File size: 33,641 Bytes
f462b1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535

# Markdown-to-Video Roadmap

## Vision
- **Markdown-to-Video Generator**: Write markdown, export video—powered entirely by native web technologies
- **Markdown controls everything**: Content, timing, transitions, templates, and visual styling all defined in `.md` files
- **Self-contained architecture**: Built on Electron + native Web APIs (Canvas, MediaRecorder, Web Audio, File System)
- **Flexible slide creation**: Multiple slide break modes (`---` separators, `# H1` headers, `## H2` headers, or auto-detection)

## Core Philosophy: Markdown as Video Source
- **Input**: Markdown file with YAML frontmatter for video configuration
- **Parser**: Custom `MarkdownParser` extracts slides, metadata, and asset references
- **Renderer**: Canvas-based slide compositor using HTML/CSS → Canvas 2D API
- **Encoder**: Native MediaRecorder API generates WebM video streams today, with planned OS-level pipelines (Media Foundation, AVFoundation, GStreamer) delivering MP4/GIF output without third-party libraries
- **Export**: Files saved via secure IPC bridge with path validation

## Guiding Principles
- **Markdown-first workflow**: Deck authoring, timeline preview, and video export driven by `.md` source
- **Native APIs only**: MediaRecorder (video encoding), Canvas 2D (rendering), Web Audio (future audio mixing)
- **Preview = Export fidelity**: Same timeline engine powers live preview and final video output
- **Security-first**: All file I/O flows through `security-core.js` with path validation and rate limiting
- **Zero-config experience**: Sensible defaults with frontmatter-based overrides and shareable presentation presets

## Completed Foundation
- [x] Markdown-to-HTML pipeline in the Electron renderer.
- [x] Baseline slide templates, theming, and live preview.
- [x] Project structure separating main, renderer, and shared modules.
- [x] Refactored renderer UI (`src/renderer/index.html`) into a markdown-first workflow with restored Templates tab.
- [x] **Comprehensive Markdown Syntax Dictionary** (`markdown-syntax.js`) - 50+ patterns supporting CommonMark + GFM
- [x] **Auto-pagination System** (`slide-paginator.js`) - Intelligent slide splitting based on visual line count (max 6 lines/slide)
- [x] **Interactive Preview Controls** - Pause/resume with click, Space, P, ESC keyboard shortcuts
- [x] **Dark Blue Theme** - Complete UI redesign with cohesive color scheme (#0a1628 background, #3b82f6 primary)

## Immediate Sprint Focus (Current Work)

### Phase 1: Core Functionality (COMPLETED)
- [x] **Rebuild `src/renderer/js/app.js`** – Complete renderer controller:
  - [x]  Parse markdown via `MarkdownParser` when user clicks "Sync Markdown"
  - [x]   Extract frontmatter (template, video.*, theme.accent) and body content

  - [x]   Generate slide array with auto-calculated durations based on content density

  - [x]   Populate Timeline tab with per-slide timings, page indicators, line counts, and duration

  - [x]   Update stage preview rendering with full markdown syntax support

  - [x]   Apply selected template and accent color to CSS variables

  - [x]   Enable Preview Timeline with pause/resume controls (click, Space, P, ESC)

  - [x]   Full support for 15+ content types (H1-H6, lists, tables, blockquotes, code, HTML, etc.)

  - [x]   Continuation markers for paginated slides ("↪ continued", "continues →")

  - [x]   Page indicators in top-right corner of slides



- [x] **Extend `src/shared/markdown-parser.js`** to:

  - [x] Emit scene-level metadata including slide index, title, subtitle, and content items

  - [x] Calculate per-slide durations using heuristics (H1=2s, list items=1s each, text=0.3s per word, code=0.5s per line)

  - [x] Support frontmatter parsing for template ID, video settings, and custom metadata

  - [x] Return asset references (images from `![alt](src)` syntax) for checklist validation

  - [x] Provide `getSummary()` method returning totalSlides, paginatedSlides, estimatedDuration, and titles

  - [x] **NEW: Integration with MarkdownSyntax dictionary** for comprehensive pattern recognition

  - [x] **NEW: Auto-pagination support** with `enablePagination` and `maxLinesPerSlide` options

  - [x] **NEW: Visual line tracking** - slides include `visualLines`, `totalPages`, `pageNumber` properties



- [x] **Wire template selection bidirectionally**:

  - [x] Clicking a template card in Templates tab updates `state.template`

  - [x] Upsert `template: <id>` into markdown frontmatter via `upsertFrontmatterValue()`

  - [x] Trigger `syncMarkdown()` to refresh timeline and reapply template CSS

  - [x] Show active template name in "Active template:" hint label



- [x] **Surface validation diagnostics**:

  - [x] Show/hide `markdownDiagnostics` panel based on parse success/failure

  - [x] Display human-friendly error messages (e.g., "Missing closing frontmatter delimiter", "Invalid slide structure")

  - [x] Highlight unsynced state when editor content changes before next sync

  - [x] Clear diagnostics automatically on successful sync



### New Features Completed Beyond Original Scope



#### 1. Comprehensive Markdown Syntax Dictionary (`src/shared/markdown-syntax.js`)

- [x] **50+ regex patterns** covering CommonMark + GitHub Flavored Markdown

- [x] **Block-level syntax**: ATX headings (# to ######), Setext headings (underlines), unordered lists (-, *, +), ordered lists, task lists, code blocks (fenced and indented), tables, blockquotes, horizontal rules, HTML blocks
- [x] **Inline syntax**: bold (**text**), italic (*text*), strikethrough (~~text~~), inline code (`code`), links, images
- [x] **Special syntax**: YAML frontmatter, footnotes, math blocks (LaTeX)
- [x] **API**: `detectBlockType(line, nextLine)` and `parseInline(text)` methods
- [x] **Documentation**: `MARKDOWN_SYNTAX.md` (EN/TH) with complete syntax reference

#### 2. Auto-pagination System (`src/shared/slide-paginator.js`)
**Status**:  **Needs Integration with Presentation Rendering** - Currently standalone, not yet used in actual rendering

- [x] **Visual line calculation** with content-specific weights:
  - H1 = 2.5 lines, H2 = 2 lines, H3-H6 = 1.5-1 lines
  - List/blockquote items = 1.2 lines each
  - Code blocks = 1 line per line (more readable)
  - Tables = 2.5 (header) + rows × 0.8
  - Images = 4 lines, HTML = 3 lines
- [x] **Intelligent splitting algorithms**:
  - Balanced page distribution (30% threshold)
  - Smart block splitting for code, tables, blockquotes
  - Atomic blocks (images, HTML, HR) never split
  - Continuation markers automatically added
- [x] **API**: `applyPagination(slides, config)` returns paginated slide array
- [x] **Documentation**: `AUTO_PAGINATION.md` (EN/TH) with examples and algorithm details

**Required Work**:
- [ ] **Integrate with Smart Layout Engine**: Use line calculation logic with `ensureContentWithinBounds()`
- [ ] **Integrate with Slide Renderer**: Make slides split automatically during actual rendering, not just parsing
- [ ] **Configure via Presentation Settings**: Add `maxLinesPerSlide` to presentation-config.js
- [ ] **Work with Safe Zones**: Calculate actual available space before splitting slides

#### 3. Interactive Preview Controls
- [x] **Pause/resume mechanism**:
  - Click anywhere on preview stage to pause/resume (preview mode only)
  - Keyboard shortcuts: Space or P to toggle, ESC to stop preview
  - Promise-based waiting with 100ms polling for instant response

#### 4. Presentation Mode (PowerPoint-style Navigation)
- [x] **Manual slide navigation** with forward/back controls:
  - "Presentation Mode" button alongside main controls
  - Left/Right arrow buttons for navigation
  - Keyboard shortcuts: ← → for prev/next, Space for next, Home/End for first/last
  - Slide counter display (e.g., "1 / 15")
  - ESC to exit presentation mode
- [x] **Fullscreen support**:
  - Fullscreen button in top-right corner during presentation
  - F key toggle for fullscreen
  - Proper fullscreen styling (borderless, full viewport)
- [x] **Visual design**:
  - Semi-transparent navigation controls at bottom center
  - Circular prev/next buttons with hover effects
  - Disabled state for first/last slide boundaries
  - Backdrop blur for better readability

#### 5. Application Reset Function
- [x] **Reset Button** after Export Video
  - Reset application to initial state
  - Clear all markdown content and slides
  - Reset all settings to defaults
  - Confirmation dialog before execution
  - Automatically stop playback or presentation
  - Reset template to 'modern'
  - Clear timeline and asset checklist

#### 6. Programmer's PowerPoint - Code Editor Themes
- [x] **New Code Editor Style Themes** in templates.js:
  - **Monokai**: Classic theme with warm tones (magenta, green, cyan)
  - **Solarized Dark**: Precision colors designed for readability
  - **SynthWave '84**: Retro futuristic 80s aesthetic (hot pink, mint, yellow)
  - **Dracula**: Dark theme for night coders
  - Full syntax highlighting support with theme-specific colors
- [x] **Enhanced Content Styles** in style.css:
  - `.content-h1`: Gradient text with glow effect
  - `.content-h2`: Border-left accent with text shadow
  - `.content-blockquote`: Styled quote marks with inset shadow
  - `.content-code-block`: Top gradient border with hover animation
  - Syntax highlighting colors: keyword, string, number, comment, function, variable
- [x] **Advanced Transitions** in slide-renderer.js:
  - **Glitch**: Digital glitch effect with random offsets and hue rotation
  - **Matrix**: Digital rain effect simulation
  - **Cube**: 3D cube rotation transition
  - **Pixelate**: Blur-based pixelation effect
- [x] **CSS Animations**:
  - `@keyframes matrixScroll`: Scrolling matrix effect
  - `@keyframes glitchSkew`: Skew animation for glitch
  - `@keyframes pixelateIn`: Blur in animation
  - `@keyframes codeHighlight`: Code block hover glow
  - `@keyframes textGlow`: Heading pulsing glow effect
- [x] **Visual feedback**:
  - Pause overlay with semi-transparent backdrop (blur 8px)
  - Large pause icon with pulse animation
  - Instructions: "Paused" text + keyboard hints
  - Z-index 1000 for always-on-top display
- [x] **State management**:
  - `isPaused` boolean flag
  - `pauseResolve` function reference for promise resolution
  - Cleanup on preview stop
- [x] **Documentation**: `PREVIEW_CONTROLS.md` (EN/TH) with usage guide

#### 7. Enhanced Timeline Visualization
- [x] **Pagination indicators**: Show "[1/2]", "[2/2]" badges for multi-page slides
- [x] **Line count display**: "8 lines", "5 lines" to show content density
- [x] **Continuation indicators**: "↪ continued" for split content
- [x] **Duration display**: Accurate timing per slide with total duration

#### 8. Smart Layout Measurement & Safe Zones
- [x] Introduced shared `SMART_SAFE_ZONE` heuristics and padding helpers to derive consistent insets for measurement and stage rendering
- [x] Synced typography, screen-type classes, and scene structure between the hidden measurement stage and the live stage frame
- [x] Reused measurement-stage results to auto-scale overflowing content while keeping metadata (`data-safe-*`) available for diagnostics
- [x] Filtered preview carry-over to exclude heading blocks and rely on authored titles instead of synthetic "Slide N" labels

#### 9. Presentation Configuration System (`src/renderer/js/presentation-config.js`)
- [x] Replaced rigid template catalogue with flexible presentation settings presets (fonts, clamp sizes, colors, backgrounds, animations)
- [x] Introduced configuration API (`getCurrentConfig`, `setConfig`, `updateConfigPart`, `loadPreset`, `resetConfig`) for fine-grained control
- [x] Defined curated preset families (Default, Professional, Minimal, Creative) plus font/background/transition option catalogs
- [x] Auto-applies presentation variables to CSS custom properties (fonts, font sizes, colors, safe spacing) without external libraries
- [x] Supports JSON import/export for sharing configuration profiles across markdown decks
- [x] **Typography & Layout Controls** - Complete document formatting system:
  - [x] Font size controls (H1, H2, Body Text) with responsive clamp (min, base vw, max)
  - [x] Line height adjustments (heading, body) for optimal readability
  - [x] Paragraph spacing controls (before/after) in rem units
  - [x] Heading spacing controls (before/after) for visual hierarchy
  - [x] Indentation controls (first-line, blockquote) for document structure
  - [x] List indent and text alignment options (left, center, right, justify)
- [x] **UI & Visual Effects Configuration**:
  - [x] Preview slide opacity control (0-1 range)
  - [x] Pause overlay blur effect (px)
  - [x] Navigation button border width (px)
  - [x] Gradient backdrop effects (spread %, blur px)
- [x] **Border & Accent Width Controls**:
  - [x] Heading accent border width (H2 left border)
  - [x] Blockquote border width (left accent line)
  - [x] Image border width (frame around images)
  - [x] Link underline thickness
  - [x] Table border width (grid lines)
  - [x] Horizontal rule (HR) border width
- [x] **Single Source of Truth Architecture**:
  - [x] All default values centralized in `CONFIG_PRESETS.default.config`
  - [x] CSS variables dynamically applied via `applyConfigToDOM()`
  - [x] Live preview with instant feedback on all changes
  - [x] Bidirectional sync between UI controls and configuration
  - [x] Frontmatter persistence (save/load all settings to markdown YAML)
- [x] **Developer Experience**:
  - [x] Zero hardcoded values in CSS or JavaScript
  - [x] Maintainable: change one config value, updates everywhere
  - [x] Extensible: easy to add new styling properties
  - [x] Type-safe: clear property structure with fallback values

### Demo Files Created
- [x] `workspace/complete-syntax-demo.md` - 25 slides demonstrating all Markdown syntax patterns
- [x] `workspace/pagination-demo.md` - 20+ slides showing auto-pagination with various content lengths

## Latest Updates (October 2025)

### 10. Mode Isolation System (Exclusive Mode Switching)
**Problem Identified**: UI elements from different modes were overlapping and causing conflicts in display and functionality

**Solution** - Built a comprehensive exclusive mode switching system:

#### Mode Manager (`src/renderer/js/mode-manager.js`)
- [x] **Singleton Pattern**: Created `ModeManager` class with single instance for entire app
- [x] **3 Strictly Separated Modes**:
  - **Intro Mode**: Initial screen with no systems active (static display only)
  - **Presentation Mode**: Presentation mode with keyboard navigation + Smart Layout only
  - **Editor Mode**: Edit mode with content editable + drag & drop + Safe Zone border only

#### Robust Control System
- [x] **System Flags Tracking**: Monitors active systems (smartLayout, dragDrop, contentEditable, safeZoneBorder, etc.)
- [x] **UI Visibility Control**: 
  - `hideAllModeUI()` - Hides all UI elements from all modes
  - `showPresentationUI()` - Shows only navigation controls, exit button, fullscreen button, edit button
  - `showEditorUI()` - Shows only save button, cancel button, exit button
- [x] **Smart Layout Management**:
  - Intro Mode: `detach()` observers completely
  - Presentation Mode: `reattach()` observers for auto-adjustment
  - Editor Mode: `detach()` observers to prevent resizing during editing
- [x] **Mode Switching Flow**:
  ```javascript

  switchMode(newMode) {

    1. shutdownMode(currentMode)  // Shutdown old mode completely

    2. currentMode = newMode       // Change mode

    3. setDisplayMode(newMode)     // Update config

    4. activateMode(newMode)       // Activate new mode exclusively

    5. dispatch 'modeChanged' event

  }

  ```

#### Integration with Existing Systems
- [x] **app.js Integration**:
  - `init()`: Calls `switchToIntroMode()` instead of `setDisplayMode('intro')`
  - `startPresentationMode()`: Calls `switchToPresentationMode()`
  - `exitPresentationMode()`: Calls `switchToIntroMode()`
  - Removed all manual UI show/hide logic (Mode Manager handles it)
  
- [x] **slide-editor.js Integration**:
  - `enterEditMode()`: Calls `switchToEditorMode()`
  - `exitEditMode()`: Calls `switchToPresentationMode()`
  - `enterDragMode()`: Calls `switchToEditorMode()`
  - `exitDragMode()`: Calls `switchToPresentationMode()`
  - Removed manual Smart Layout detach/reattach (Mode Manager handles it)
  - Removed manual Safe Zone show/hide (Mode Manager handles it)

#### Smart Layout Protection
- [x] **Guard in `ensureContentWithinBounds()`**:
  ```javascript

  function ensureContentWithinBounds() {

    const modeManager = getModeManager();

    if (modeManager && !modeManager.isSystemActive('smartLayout')) {

      return; // Don't execute if Smart Layout is disabled

    }

    // ... continue with calculations

  }

  ```

#### Results
- [x] **No UI Overlap**: Each mode shows only its relevant UI elements
- [x] **No Smart Layout Interference**: Auto-sizing only works in Presentation Mode
- [x] **Safe Edit Mode**: Editing works without interference from other systems
- [x] **Single Source of Control**: `ModeManager` is the only controller for all modes

#### Documentation and Maintenance
- [x] Created `docs/TH/MODE_ISOLATION_FIX.md` with detailed fix documentation
- [x] Added code comments indicating "Mode Manager handles this - no manual control needed"
- [x] Removed redundant code from app.js and slide-editor.js

### Strict Separation of 3 Display Logic Systems

### Complete Separation of Three Display Logic Systems
**Principle**: Each display mode has completely separate logic and Safe Zone systems to prevent modifications in one area from breaking others.

#### 1. Intro Scene System (Small Preview with UI Sidebar)
- [x] **Purpose**: Display slide previews in a small area of the UI page with side control panels
- [x] **Characteristics**:
  - [x] Fixed screen size (1280x720 fallback)
  - [x] Hard-coded Safe Zone optimized for small display area
  - [x] No dynamic calculation needed due to fixed dimensions
- [x] **Core Functions** (marked LOCKED - do not modify):
  - [x] `getStagePreviewData()` - Extract slide preview data
  - [x] `renderStagePreview()` - Render preview to DOM
  - [x] `updateStagePreview()` - Update preview when slides change
- [x] **Status**: Working perfectly - do not modify or link to other modes

#### 2. Presentation Mode - Small Screen (Normal Size Presentation)
- [x] **Purpose**: Presentation mode on standard screens (not fullscreen) at 1920x1080 or smaller
- [x] **Characteristics**:
  - [x] Supports navigation with arrow keys (← →)
  - [x] Ratio-based Safe Zone calculation for standard screens
  - [x] Safe boundaries approximately 8-9% of width/height
- [x] **Color Zones**:
  - [x] **Red Zone**: Area outside screen bounds - no content allowed
  - [x] **Green Zone**: Safe area inside boundaries - content safe here
- [x] **Calculation**:
  - [x] No hard-coded pixels
  - [x] Calculated from actual screen size ratio
  - [x] Formula: `safeInset = screenDimension × SAFE_ZONE_RATIO`

#### 3. Presentation Mode - Large Screen (Full Screen Large Display)
- [x] **Purpose**: Fullscreen mode on large screens (2560x1440+) or projectors
- [x] **Characteristics**:
  - [x] Automatic fullscreen mode entry
  - [x] Smart Layout Engine measures and optimizes content for available space
  - [x] Wider Safe Zone to accommodate projector overscan
- [x] **Color Zones** (stricter than small screens):
  - [x] **Red Zone**: Danger area 10-15% from edge - absolutely no content
  - [x] **Yellow Zone**: Warning area 5-10% - content may be cut on some projectors
  - [x] **Green Zone**: Safe area 80% center - content displays confidently
- [x] **Calculation**:
  - [x] Dynamic calculation from actual screen size
  - [x] Ratio adjusts based on screen type (normal/large/ultra)
  - [x] Example formula:
    ```

    baseRatio = 0.08 (8%)

    maxRatio = 0.16 (16%)

    actualInset = clamp(screenSize × baseRatio, MIN_PIXELS, screenSize × maxRatio)

    ```


### Code Protection from Modifications
- [x] Added warning comments to all Intro Scene related functions
- [x] Used clear `@LOCKED` and `DO NOT MODIFY` tags
- [x] Separated comments into large blocks with border lines (==== lines)
- [x] Specified reasons and impacts of modifications in comments
- [x] No emojis in comments (may cause encoding issues)

### Smart Layout and Safe Zone System
- [x] Separated Safe Zone constants for each mode
- [x] Intro Scene uses hard-coded constants
- [x] Presentation Mode will create separate calculation functions
- [ ] Create `computePresentationSafeZone()` for presentation mode
- [ ] Create `computeLargeScreenSafeZone()` for large screens
- [ ] Test Safe Zone calculations on multiple screen sizes

## Outstanding Work

### Smart Layout Engine
- [ ] **Integrate Auto-pagination with Smart Layout**:
  - [ ] Use line calculation logic from `slide-paginator.js` with `ensureContentWithinBounds()`
  - [ ] Make slides split automatically during actual rendering, not just parsing
  - [ ] Calculate available space within Safe Zones before deciding to split pages
  - [ ] Add `maxLinesPerSlide` configuration to presentation-config.js
- [ ] Rebuild `layout-schema.js` with a durable LayoutNode model and accurate per-section metrics aggregation
- [ ] Feed the layout tree into `renderSlideToStage` so DOM output follows block semantics instead of raw HTML
- [ ] Extend the measurement stage to consume layout tree data and refactor line/column calculations
- [ ] Add unit tests covering smart layout behaviours (observers, smart-list balancing, layout tree diffing)

### Cross-module Coordination (Markdown → Layout → Renderer)
- [ ] Author a `layout-contract.md` document defining the shared JSON schema for slides/sections/blocks/inlines plus diagnostics
- [ ] Refine `markdown-syntax.js` so it exposes a single detection/tokenization API and stores the metadata the parser requires
- [ ] Update `markdown-parser.js` to consume that metadata and emit content items ready to map directly into layout blocks (e.g., link, inline emphasis)
- [ ] Extend `layout-schema.js` to cover additional block types (heading, link, rich inline text) with metrics the renderer can consume immediately
- [ ] Rework `app.js` to render purely from the layout tree, return measurement/diagnostic updates into the tree, and surface state changes to the UI
- [ ] Introduce a feedback loop (diagnostics channel) between measurement stage ↔ layout-schema ↔ markdown-parser so heuristics can adapt

### Timeline & Metadata Model
- [ ] Extend markdown frontmatter for per-slide timing, transitions, narration cues, and media assets.
- [ ] Generate a shared timeline model (scenes, tracks, assets) for preview and export.
- [ ] Implement validation with actionable errors for missing or invalid metadata.

### Presentation Settings System (Template Replacement) - COMPLETED
- [x] Replace template cards UI with configurable presentation presets powered by `presentation-config.js`
- [x] Round-trip presentation settings to markdown frontmatter (fonts, colors, animation choices)
- [x] Expose granular controls (font families, clamp ranges, backgrounds, borders, effects) with live preview updates
- [x] Update parser/exporter to consume presentation settings instead of legacy template identifiers
- [x] **Complete Word/Excel-style Document Formatting**:
  - [x] 11 UI controls for styling properties (borders, effects, visual elements)
  - [x] Typography controls (8 inputs for spacing, indentation, alignment)
  - [x] Font size controls (9 inputs for H1, H2, Text with min/base/max)
  - [x] Line height controls (2 inputs for heading and body)
  - [x] All settings saved to frontmatter with `presentation.styles.*` namespace
  - [x] Full English translation of all UI labels and preset descriptions

### Phase 2: Enhanced Export (Next Priority)
- [x] Browser preview consumes timeline model flawlessly with full markdown rendering
- [ ] **Improve native WebM export quality**:
  - [ ] Enhanced MediaRecorder API with frame-perfect timing control
  - [ ] Quality/bitrate configuration options (target: 1080p at 5-10 Mbps)
  - [ ] Progress reporting with per-slide render updates and percentage display
  - [ ] Abort/cancel functionality for long renders
- [ ] Add a render job manager handling queueing, progress reporting, and cancellations
- [ ] Export progress modal with real-time preview thumbnails

### Visual Enhancements
- [ ] Support slide-specific background images/videos with aspect-ratio aware cropping.
- [ ] Introduce a declarative animation DSL covering transitions, text motion, and keyframed positioning.
- [ ] **Build custom components** (no external libraries):
  - Chart renderer using Canvas 2D API
  - Syntax highlighter using regex tokenization
  - Component registry for extensible markdown → visual mappings

### Audio & Narration (Future)
- [ ] Support synchronized narration tracks sourced from audio files.
- [ ] **Mix audio using native Web Audio API**:
  - Build custom ducking algorithm for background music
  - Synchronize audio with video timeline
  - No external audio processing libraries
- [ ] Add scenario tests validating audio/video sync quality.

### Collaboration & Templates
- [ ] Ship selectable markdown + CSS template packs within the UI.
- [ ] Provide a shared asset workspace with versioned references.
- [ ] Define naming conventions and folder layout for video-safe media assets.

## Phased Implementation Plan

### Phase 1 – Timeline Core (COMPLETED)
- [x] Rebuild `app.js` to parse markdown and populate timeline UI
- [x] Extend `markdown-parser.js` with frontmatter and duration heuristics
- [x] Wire bidirectional template selection (UI ↔ frontmatter)
- [x] Surface validation diagnostics in Markdown tab
- [x] **BONUS**: Comprehensive Markdown Syntax Dictionary with 50+ patterns
- [x] **BONUS**: Auto-pagination system with visual line calculation
- [x] **BONUS**: Interactive preview controls (pause/resume, keyboard shortcuts)
- [x] **BONUS**: Enhanced timeline visualization with pagination indicators and line metrics
- [x] **BONUS**: Presentation mode with navigation controls and fullscreen support
- [x] **BONUS**: Application reset workflow and safeguarded smart layout safe zones
- [x] **BONUS**: Code editor themed styling plus advanced transitions/animations
- [x] **BONUS**: Template-free presentation configuration system with shareable presets
- [ ] Add unit tests for parsing, timing calculations, and error cases (deferred to Phase 2)

### Phase 2 – Enhanced Video Export (Next Priority)
- [ ] Improve MediaRecorder-based WebM export quality and frame timing (target: 1080p @ 5-10 Mbps)
- [x] Implement native render progress tracking with per-slide updates and percentage display
- [x] Add resolution/FPS/quality controls synced to frontmatter
- [ ] Support abort/cancel during export with cleanup and partial file deletion
- [ ] Export progress modal with live thumbnail preview
- [ ] Unit tests for markdown-syntax.js, slide-paginator.js, pause/resume mechanism
- [ ] Create integration tests for sample deck → video output

#### Native OS Encoding Roadmap (Security-first, No Third-party Libraries)
- [ ] Design shared frame extraction pipeline (HTML → RGBA buffers/PNG frames) compatible with all native encoders
- [ ] Windows: implement a sealed Media Foundation bridge that writes H.264/AAC MP4 via sandboxed worker process
- [ ] macOS: build an AVFoundation exporter (AVAssetWriter) for H.264/AAC MP4 with strict file-path validation
- [ ] Linux: integrate system GStreamer/VA-API pipeline (`appsrc → x264enc → mp4mux`) executed under security-core supervision
- [ ] Add GIF output using the same native pipelines (MF Transform, AVFoundation ImageDestination, or GStreamer gifenc)
- [ ] Instrument security hooks (path allow-list, rate limits, checksum validation) for every native encoder invocation

### Phase 3 – Audio Integration (Future)
- [ ] Parse narration file references from slide metadata
- [ ] Load and validate audio assets via secure IPC
- [ ] Mix narration + background music using Web Audio API
- [ ] Synchronize audio with video timeline during preview and export
- [ ] Add waveform visualization in Timeline tab

### Phase 4 – Visual Enhancements (Future)
- [ ] Build custom chart renderer (Canvas-based, no libraries)
- [ ] Implement syntax highlighter using regex tokenization
- [ ] Support slide-specific background images/videos
- [ ] Create declarative animation DSL for keyframe-based transitions
- [ ] Add component registry for extensible markdown → visual mappings

### Phase 5 – Stabilization & Polish (Future)
- [ ] Performance profiling and asset caching optimization
- [ ] Improve error messages with contextual fix suggestions
- [ ] Documentation refresh with video tutorials
- [ ] Ship sample markdown decks demonstrating all features

## Architecture Impact
- **[x] Extended `src/shared/markdown-parser.js`**: Emits timeline JSON with scene metadata, durations, asset references, pagination info
- **[x] NEW `src/shared/markdown-syntax.js`**: Dictionary-based pattern library with 50+ regex patterns for all CommonMark + GFM syntax
- **[x] NEW `src/shared/slide-paginator.js`**: Visual line calculation and intelligent slide splitting with content-aware algorithms
- [ ] **New `src/shared/timeline-engine.js`**: Compose timeline model, calculate timecodes, manage playback state (future)
- **[x] Updated `src/renderer/js/app.js`**: Consumes parsed markdown for preview with pause/resume, timeline population, full syntax rendering, 13 new DOM references for styling controls, frontmatter save/load for all styling properties
- **[x] Enhanced `src/renderer/js/video-renderer.js`**: Canvas-based slide rendering with full markdown support (export ready, quality enhancement pending)
- **[x] Secure asset workspace**: Standardized `workspace/` folder with demo files and emoji-cleaner.js
- **[x] NEW `src/renderer/js/presentation-config.js`**: Centralised presentation settings engine replacing fixed templates with 30+ configurable properties, CSS variable system, and frontmatter integration
- **[x] Enhanced `src/renderer/css/style.css`**: Converted all hardcoded values to CSS variables (23+ new variables), added `.slide-table`, `.slide-hr`, `.timeline-page-indicator` classes for consistent theming
- **[x] Updated `src/renderer/index.html`**: Added 30+ new UI controls organized in 3 sections (UI Effects, Border Widths, Typography), full English translation, improved help text

## Current Technology Stack (Updated)
- **Electron 28.0.0**: Desktop application framework
- **MediaRecorder API**: Native WebM video encoding (VP8/VP9 codec)
- **Planned native encoders**: Windows Media Foundation, macOS AVFoundation, Linux GStreamer/VA-API (system-provided, no third-party libraries)
- **Canvas 2D API**: Slide rendering from HTML/CSS → Canvas with full markdown syntax support
- **Tailwind CSS (local - 407KB)**: UI styling loaded from `src/renderer/vendor/tailwind.js`
- **Web Audio API** (future): Native audio mixing and ducking
- **Custom Modules**:
  - **MarkdownParser** (`src/shared/markdown-parser.js`) - Parser with frontmatter, duration heuristics, pagination integration
  - **MarkdownSyntax** (`src/shared/markdown-syntax.js`) - Pattern dictionary with 50+ regex for CommonMark + GFM
  - **SlidePaginator** (`src/shared/slide-paginator.js`) - Visual line calculation and intelligent splitting
  - **VideoRenderer** (`src/renderer/js/video-renderer.js`) - Canvas-based slide rendering
  - **PresentationConfig** (`src/renderer/js/presentation-config.js`) - Template-free configuration presets and runtime styling engine
  - **SecurityCore** (`src/shared/security-core.js`) - Path validation and rate limiting for file operations

## Quality Strategy
- [ ] Unit tests for `markdown-syntax.js` (pattern detection, inline parsing)
- [ ] Unit tests for `slide-paginator.js` (line calculation, splitting algorithms)
- [ ] Unit tests for `markdown-parser.js` (parsing, frontmatter, duration calculation, pagination integration)
- [ ] Integration tests for markdown → timeline → video workflow
- [ ] Snapshot tests for rendered HTML structures
- [ ] Manual QA checklist for export quality across resolutions/FPS
- [ ] Error handling validation (missing files, invalid frontmatter, etc.)
- [ ] Pause/resume mechanism tests (promise resolution, keyboard shortcuts)

## Documentation & Adoption
- [x] **Produce bilingual guides**: Created 6 comprehensive documentation files
  - [x] `MARKDOWN_SYNTAX.md` (EN/TH) - Complete syntax reference with examples
  - [x] `AUTO_PAGINATION.md` (EN/TH) - Pagination system guide with algorithms
  - [x] `PREVIEW_CONTROLS.md` (EN/TH) - Interactive controls usage guide
- [x] **Publish sample decks**: Created demo markdown files
  - [x] `workspace/complete-syntax-demo.md` - 25 slides demonstrating all syntax patterns
  - [x] `workspace/pagination-demo.md` - 20+ slides showing auto-pagination
- [ ] Schedule user testing sessions and collect feedback for iterative refinement
- [ ] Produce video tutorials for export workflows and troubleshooting