chahuadev commited on
Commit
f462b1c
·
verified ·
1 Parent(s): 80abd43

Upload 51 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .gitignore +74 -0
  3. .npmignore +58 -0
  4. README.md +307 -0
  5. assets/fonts/README.md +46 -0
  6. assets/fonts/fonts.css +137 -0
  7. assets/icons/icon.ico +3 -0
  8. assets/icons/icon.jpg +3 -0
  9. assets/icons/icon.png +3 -0
  10. assets/icons/icon.webp +3 -0
  11. assets/image/chahuadev-markdown-presenter.png +3 -0
  12. docs/EN/CHANGELOG.md +292 -0
  13. docs/EN/CODE_OF_CONDUCT.md +201 -0
  14. docs/EN/CONTRIBUTING.md +357 -0
  15. docs/EN/LICENSE +22 -0
  16. docs/EN/MARKDOWN_VIDEO_PLAN.md +534 -0
  17. docs/EN/SECURITY.md +74 -0
  18. docs/TH/CHANGELOG.md +171 -0
  19. docs/TH/CODE_OF_CONDUCT.md +65 -0
  20. docs/TH/CONTRIBUTING.md +135 -0
  21. docs/TH/LICENSE +17 -0
  22. docs/TH/MARKDOWN_VIDEO_PLAN.md +621 -0
  23. docs/TH/SECURITY.md +72 -0
  24. npm-runner.bat +239 -0
  25. package-lock.json +0 -0
  26. package.json +59 -0
  27. src/README.md +0 -0
  28. src/main/main.js +489 -0
  29. src/main/preload.cjs +73 -0
  30. src/main/preload.js +61 -0
  31. src/main/preload.mjs +61 -0
  32. src/renderer/css/style.css +2150 -0
  33. src/renderer/index.html +1002 -0
  34. src/renderer/js/app.js +0 -0
  35. src/renderer/js/config-storage.js +147 -0
  36. src/renderer/js/drag-drop-manager.js +830 -0
  37. src/renderer/js/mode-manager.js +459 -0
  38. src/renderer/js/presentation-config.js +2066 -0
  39. src/renderer/js/slide-editor.js +831 -0
  40. src/renderer/js/templates.js +431 -0
  41. src/renderer/js/video-renderer.js +529 -0
  42. src/renderer/vendor/tailwind.js +0 -0
  43. src/shared/README.md +97 -0
  44. src/shared/content-fingerprint.js +236 -0
  45. src/shared/layout-schema.js +363 -0
  46. src/shared/markdown-parser.js +512 -0
  47. src/shared/markdown-syntax.js +433 -0
  48. src/shared/persistent-storage.js +535 -0
  49. src/shared/security-core.js +600 -0
  50. src/shared/slide-paginator.js +362 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ assets/icons/icon.ico filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs/
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+
8
+ # Runtime data
9
+ pids
10
+ *.pid
11
+ *.seed
12
+ *.pid.lock
13
+
14
+ # Directory for instrumented libs generated by jscoverage/JSCover
15
+ lib-cov
16
+
17
+ # Coverage directory used by tools like istanbul
18
+ coverage
19
+ *.lcov
20
+
21
+ # nyc test coverage
22
+ .nyc_output
23
+
24
+ # Dependency directories
25
+ node_modules/
26
+
27
+ # Optional npm cache directory
28
+ .npm
29
+
30
+ # Optional eslint cache
31
+ .eslintcache
32
+
33
+ # Output of 'npm pack'
34
+ *.tgz
35
+
36
+ # Yarn Integrity file
37
+ .yarn-integrity
38
+
39
+ # dotenv environment variables file
40
+ .env
41
+ .env.test
42
+ .env.local
43
+ .env.*.local
44
+
45
+ # Electron build output
46
+ dist/
47
+ out/
48
+ build/
49
+
50
+ # OS files
51
+ .DS_Store
52
+ Thumbs.db
53
+ desktop.ini
54
+
55
+ # IDE files
56
+ .vscode/
57
+ .idea/
58
+ *.sublime-project
59
+ *.sublime-workspace
60
+
61
+ # Test files
62
+ test-file.js
63
+ test-results/
64
+
65
+ # Security sensitive files
66
+ private_key.pem
67
+ *.key
68
+ *.pem
69
+ checksums.json
70
+ checksums.sig
71
+
72
+ # User data
73
+ *.sqlite
74
+ *.db
.npmignore ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Development files
2
+ .gitignore
3
+ .git/
4
+ .vscode/
5
+ .idea/
6
+ *.log
7
+ npm-debug.log*
8
+ yarn-debug.log*
9
+ yarn-error.log*
10
+
11
+ # Test files and coverage
12
+ test/
13
+ coverage/
14
+ *.test.js
15
+ *.spec.js
16
+
17
+ # Build and dist files
18
+ dist/
19
+ build/
20
+ node_modules/
21
+
22
+ # OS generated files
23
+ .DS_Store
24
+ .DS_Store?
25
+ ._*
26
+ .Spotlight-V100
27
+ .Trashes
28
+ ehthumbs.db
29
+ Thumbs.db
30
+
31
+ # Temporary files
32
+ *.tmp
33
+ *.temp
34
+ *.swp
35
+ *.swo
36
+ *~
37
+
38
+ # Old electron-specific files (not needed for npm package)
39
+ emoji-cleaner.bat
40
+ emoji-cleaner.sh
41
+
42
+ # Documentation build files
43
+ docs/
44
+
45
+ # Environment files
46
+ .env
47
+ .env.local
48
+ .env.development.local
49
+ .env.test.local
50
+ .env.production.local
51
+
52
+ # Editor files
53
+ *.sublime-project
54
+ *.sublime-workspace
55
+
56
+ # Backup files
57
+ backup-*/
58
+ emoji-backup-*/
README.md ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - en
5
+ tags:
6
+ - code-analysis
7
+ - static-analysis
8
+ - javascript
9
+ - electron
10
+ - emoji-cleaner
11
+ - junk-sweeper
12
+ - plugin-management
13
+ - desktop-app
14
+ - electron-app
15
+ - security
16
+ ---
17
+ # Chahua Markdown Video Studio
18
+
19
+ ![Chahua Markdown Video Studio](assets/image/chahuadev-markdown-presenter.png)
20
+ ![Version](https://img.shields.io/badge/version-1.0.0-blue.svg)
21
+ ![Electron](https://img.shields.io/badge/electron-28.0.0-47848f.svg)
22
+
23
+ > Author every slide, timing, and presentation configuration in markdown—preview and export videos without leaving your deck.
24
+
25
+ Chahua Markdown Video Studio turns a single markdown file into a cinematic video. Frontmatter drives presentation presets, export settings, and security-sensitive metadata while the renderer timeline stays perfectly in sync between preview and export.
26
+
27
+ ---
28
+
29
+ ## Why Markdown-First?
30
+
31
+ - Single source of truth for content, timings, transitions, narration cues, and assets.
32
+ - Deterministic timeline JSON shared by the renderer and upcoming headless export pipeline.
33
+ - Presentation presets round-trip through frontmatter so writers and designers stay aligned.
34
+ - Actionable diagnostics inside the Markdown tab highlight validation issues in context.
35
+
36
+ ---
37
+
38
+ ## Key Capabilities
39
+
40
+ - Markdown editor with live sync and diagnostics (`Sync Markdown` button).
41
+ - Timeline tab showing per-slide durations, timecodes, and tracked assets.
42
+ - Export tab for resolution, FPS, and quality settings backed by frontmatter.
43
+ - Presentation settings panel (transitioning from static templates) that writes preset choices back into the deck and restyles the preview.
44
+ - Secure preload bridge (`security-core.js`) enforcing filesystem, hashing, and rate limits.
45
+
46
+ > Current focus is WebM preview/export. Legacy GIF export returns after the shared timeline engine stabilises.
47
+
48
+ ---
49
+
50
+ ## Table of Contents
51
+
52
+ - [Quick Start](#quick-start)
53
+ - [Markdown Authoring Workflow](#markdown-authoring-workflow)
54
+ - [Markdown Format Cheatsheet](#markdown-format-cheatsheet)
55
+ - [Application Layout](#application-layout)
56
+ - [Documentation](#documentation)
57
+ - [Project Structure](#project-structure)
58
+ - [Security Posture](#security-posture)
59
+ - [Development Notes](#development-notes)
60
+ - [Contributing](#contributing)
61
+ - [Credits & Contact](#credits--contact)
62
+
63
+ ---
64
+
65
+ ## Quick Start
66
+
67
+ ```bash
68
+ # Clone the repository
69
+ git clone https://github.com/chahuadev/chahuadev-markdown-presenter.git
70
+
71
+ # Enter the project
72
+ cd chahuadev-markdown-presenter
73
+
74
+ # Install dependencies
75
+ npm install
76
+
77
+ # Launch the app
78
+ npm start
79
+ ```
80
+
81
+ Optional scripts:
82
+
83
+ ```bash
84
+ npm run dev # Verbose logging
85
+ npm run build # Package the Electron app
86
+ ```
87
+
88
+ ---
89
+
90
+ ## Markdown Authoring Workflow
91
+
92
+ 1. **Open the app** with `npm start`.
93
+ 2. **Markdown tab**
94
+ - Paste or edit your deck in the editor.
95
+ - Use `Load Sample Deck` for a guided example.
96
+ - Click `Sync Markdown` to parse slides, refresh the timeline, and update the stage text.
97
+ 3. **Timeline tab**
98
+ - Review total duration and per-slide timings.
99
+ - Confirm asset checklist items (images, audio) and resolve pending markers.
100
+ 4. **Presentation Settings tab**
101
+ - Select a preset; the choice updates frontmatter (`presentation.preset` with a `template` fallback) and restyles the stage.
102
+ - Presentation Settings is the recommended system going forward; the legacy `template` field remains only so decks from earlier versions still render correctly.
103
+ 5. **Export tab**
104
+ - Adjust `video.resolution`, `video.fps`, and `video.quality`. Values sync back to frontmatter.
105
+ 6. **Preview / Export**
106
+ - `Preview Timeline` plays the parsed deck against the live stage.
107
+ - `Export Video` records a WebM through the native `VideoRenderer` and saves it securely.
108
+
109
+ ---
110
+
111
+ ## Markdown Format Cheatsheet
112
+
113
+ ```markdown
114
+ ---
115
+ presentation:
116
+ preset: professional
117
+ fonts:
118
+ heading: "'Montserrat', 'Arial', sans-serif"
119
+ colors:
120
+ accent: "#60a5fa"
121
+ animations:
122
+ slideTransition: slide
123
+ template: professional # legacy fallback for older builds
124
+ video:
125
+ resolution: 1920x1080
126
+ fps: 60
127
+ quality: 0.95
128
+ ---
129
+
130
+ # Introduction
131
+ subtitle: Markdown Video Studio
132
+ duration: 4
133
+
134
+ Welcome to the Markdown-first workflow.
135
+
136
+ ---
137
+
138
+ # Feature Highlights
139
+ duration: 6
140
+
141
+ - Native WebM encoding with MediaRecorder API
142
+ - Real-time preview and timeline visualization
143
+ - Frontmatter configuration sync
144
+ - Truly offline-first architecture
145
+
146
+ ![Feature Demo](assets/image/screenshot.png)
147
+
148
+ ---
149
+
150
+ # Conclusion
151
+ subtitle: Built with Electron + Canvas
152
+ duration: 5
153
+
154
+ Thank you for watching!
155
+ ```
156
+
157
+ **Slide Syntax:**
158
+ - Each slide separated by `---`
159
+ - `# Title` - Main heading (required)
160
+ - `subtitle: text` - Optional subtitle
161
+ - `duration: N` - Slide duration in seconds (default: 5)
162
+ - Standard Markdown: lists, **bold**, *italic*, images
163
+
164
+ **Frontmatter Options:**
165
+ - `presentation.preset:` default, professional, minimal, creative
166
+ - `presentation.fonts.heading|body|code:` Any supported font token from `presentation-config.js`
167
+ - `presentation.colors.primary|accent|background:` Hex colors (e.g. `#3b82f6`)
168
+ - `presentation.animations.slideTransition:` fade, slide, none
169
+ - `video.resolution:` 1920x1080, 1280x720, 3840x2160
170
+ - `video.fps:` 30, 60
171
+ - `video.quality:` 0.8 - 1.0
172
+ - `template:` Legacy fallback key while presets fully replace template cards
173
+
174
+ Extended directives for transitions and narration cues are outlined in `docs/EN/MARKDOWN_VIDEO_PLAN.md`.
175
+
176
+ ---
177
+
178
+ ## Application Layout
179
+
180
+ - **Stage (left panel)**: live preview of intro, timeline snapshot, and outro styled by the active preset.
181
+ - **Markdown**: editor, diagnostics panel, summary card, and quick actions (load sample, import from disk, open workspace folder).
182
+ - **Timeline**: total runtime, per-slide breakdown, and asset checklist with availability status.
183
+ - **Export**: video configuration controls bound to frontmatter.
184
+ - **Presentation Settings**: preset gallery with font/color/animation controls that keep markdown frontmatter in sync.
185
+
186
+ ---
187
+
188
+ ## Documentation
189
+
190
+ - MARKDOWN_VIDEO_PLAN: [English](docs/EN/MARKDOWN_VIDEO_PLAN.md) / [ไทย](docs/TH/MARKDOWN_VIDEO_PLAN.md) – Roadmap covering presentation presets, safe zones, and native exporter milestones.
191
+ - CHANGELOG: [English](docs/EN/CHANGELOG.md) / [ไทย](docs/TH/CHANGELOG.md) – Release history and upcoming feature checkpoints.
192
+ - CONTRIBUTING: [English](docs/EN/CONTRIBUTING.md) / [ไทย](docs/TH/CONTRIBUTING.md) – Contribution workflow, coding standards, and review expectations.
193
+ - CODE_OF_CONDUCT: [English](docs/EN/CODE_OF_CONDUCT.md) / [ไทย](docs/TH/CODE_OF_CONDUCT.md) – Community guidelines for respectful collaboration.
194
+
195
+ ---
196
+
197
+ ## Project Structure
198
+
199
+ - [.gitignore](.gitignore)
200
+ - [.npmignore](.npmignore)
201
+ - [LICENSE](LICENSE)
202
+ - [SECURITY.md](SECURITY.md)
203
+ - [package.json](package.json)
204
+ - [package-lock.json](package-lock.json)
205
+ - [npm-runner.bat](npm-runner.bat)
206
+ - [assets/](assets/)
207
+ - [fonts/](assets/fonts/)
208
+ - [fonts.css](assets/fonts/fonts.css)
209
+ - [README.md](assets/fonts/README.md)
210
+ - [icons/](assets/icons/)
211
+ - [icon.ico](assets/icons/icon.ico)
212
+ - [icon.jpg](assets/icons/icon.jpg)
213
+ - [icon.png](assets/icons/icon.png)
214
+ - [icon.webp](assets/icons/icon.webp)
215
+ - [image/](assets/image/)
216
+ - [chahuadev-markdown-presenter.png](assets/image/chahuadev-markdown-presenter.png)
217
+ - [docs/](docs/)
218
+ - [EN/](docs/EN/)
219
+ - [CHANGELOG.md](docs/EN/CHANGELOG.md)
220
+ - [CODE_OF_CONDUCT.md](docs/EN/CODE_OF_CONDUCT.md)
221
+ - [CONTRIBUTING.md](docs/EN/CONTRIBUTING.md)
222
+ - [LICENSE](docs/EN/LICENSE)
223
+ - [MARKDOWN_VIDEO_PLAN.md](docs/EN/MARKDOWN_VIDEO_PLAN.md)
224
+ - [SECURITY.md](docs/EN/SECURITY.md)
225
+ - [TH/](docs/TH/)
226
+ - [CHANGELOG.md](docs/TH/CHANGELOG.md)
227
+ - [CODE_OF_CONDUCT.md](docs/TH/CODE_OF_CONDUCT.md)
228
+ - [CONTRIBUTING.md](docs/TH/CONTRIBUTING.md)
229
+ - [LICENSE](docs/TH/LICENSE)
230
+ - [MARKDOWN_VIDEO_PLAN.md](docs/TH/MARKDOWN_VIDEO_PLAN.md)
231
+ - [SECURITY.md](docs/TH/SECURITY.md)
232
+ - [src/](src/)
233
+ - [README.md](src/README.md)
234
+ - [main/](src/main/)
235
+ - [README.md](src/main/README.md)
236
+ - [main.js](src/main/main.js)
237
+ - [preload.cjs](src/main/preload.cjs)
238
+ - [preload.js](src/main/preload.js)
239
+ - [preload.mjs](src/main/preload.mjs)
240
+ - [renderer/](src/renderer/)
241
+ - [index.html](src/renderer/index.html)
242
+ - [css/](src/renderer/css/)
243
+ - [style.css](src/renderer/css/style.css)
244
+ - [js/](src/renderer/js/)
245
+ - [app.js](src/renderer/js/app.js)
246
+ - [presentation-config.js](src/renderer/js/presentation-config.js)
247
+ - [templates.js](src/renderer/js/templates.js)
248
+ - [video-renderer.js](src/renderer/js/video-renderer.js)
249
+ - [vendor/](src/renderer/vendor/)
250
+ - [tailwind.js](src/renderer/vendor/tailwind.js)
251
+ - [shared/](src/shared/)
252
+ - [README.md](src/shared/README.md)
253
+ - [layout-schema.js](src/shared/layout-schema.js)
254
+ - [markdown-parser.js](src/shared/markdown-parser.js)
255
+ - [markdown-syntax.js](src/shared/markdown-syntax.js)
256
+ - [security-core.js](src/shared/security-core.js)
257
+ - [slide-paginator.js](src/shared/slide-paginator.js)
258
+ - [slide-renderer.js](src/shared/slide-renderer.js)
259
+ - [workspace/](workspace/)
260
+ - [.gitkeep](workspace/.gitkeep)
261
+ - [README.md](README.md)
262
+ - `node_modules/` – Installed dependencies (omitted from this list by design).
263
+
264
+ ---
265
+
266
+ ## Security Posture
267
+
268
+ - `security-core.js` blocks path traversal, enforces extension and size limits, validates hashes, and rate-limits operations.
269
+ - The **Security** button surfaces telemetry (operation count, uptime, cache stats, rate limit entries).
270
+ - Renderer access to the filesystem and export locations flows exclusively through vetted IPC handlers.
271
+
272
+ ---
273
+
274
+ ## Development Notes
275
+
276
+ - The legacy code-upload scene workflow has been retired; markdown is now the authoritative input.
277
+ - `src/renderer/js/app.js` and `src/shared/markdown-parser.js` are under active development—follow progress in `docs/EN|TH/MARKDOWN_VIDEO_PLAN.md` under Immediate Sprint Focus.
278
+ - `src/renderer/js/presentation-config.js` unifies preset management while `templates.js` remains only for backwards compatibility.
279
+ - **Current export method**: Native WebM recording using Canvas API + MediaRecorder (no external dependencies).
280
+ - **Upcoming milestones**: Enhanced timeline engine, schema validation with actionable diagnostics, and OS-native MP4/GIF exporters scoped in the roadmap documents.
281
+
282
+ ---
283
+
284
+ ## Contributing
285
+
286
+ 1. Fork the repository.
287
+ 2. Create a feature branch (`git checkout -b feature/markdown-parser-upgrade`).
288
+ 3. Update or add tests when touching the parser, renderer, or security layers.
289
+ 4. Submit a pull request summarising how your change advances the markdown-first roadmap.
290
+
291
+ Please read the roadmap documents in `docs/EN` or `docs/TH` before proposing major architectural shifts.
292
+
293
+ ---
294
+
295
+ ## Credits & Contact
296
+
297
+ Chahua Development Co., Ltd.
298
+
299
+ - Website: [chahuadev.com](https://chahuadev.com)
300
+ - Email: chahuadev@gmail.com
301
+ - GitHub: [@chahuadev](https://github.com/chahuadev)
302
+
303
+ Stars, feedback, and roadmap suggestions are always appreciated!
304
+
305
+ ---
306
+
307
+ Transform markdown into motion.
assets/fonts/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fonts
2
+
3
+ This folder contains font definitions for the application.
4
+
5
+ ## Font Strategy
6
+
7
+ We use a **system font fallback** approach instead of hosting custom font files:
8
+
9
+ ### Primary Fonts (with fallbacks)
10
+ - **Inter** → System UI fonts (-apple-system, Segoe UI, Roboto, etc.)
11
+ - **Source Code Pro** → Monospace system fonts (SF Mono, Cascadia Code, Consolas, etc.)
12
+ - **Orbitron** → Display system fonts (SF Pro Display, etc.)
13
+
14
+ ## Why System Fonts?
15
+
16
+ - ✅ **Zero bandwidth** - No font files to download
17
+ - ✅ **Instant loading** - Fonts already installed on user's system
18
+ - ✅ **Native look** - Matches OS design language
19
+ - ✅ **Offline-first** - Always available
20
+ - ✅ **Smaller package size** - No font files in distribution
21
+
22
+ ## `fonts.css`
23
+
24
+ The `fonts.css` file defines:
25
+ 1. Optional `@font-face` for custom fonts (if user has them installed)
26
+ 2. System font fallback chains for each font family
27
+ 3. CSS custom properties for easy usage
28
+
29
+ ## Adding Custom Fonts (Optional)
30
+
31
+ If you want to bundle custom fonts:
32
+
33
+ 1. Download font files (`.woff2` recommended)
34
+ 2. Place them in this folder
35
+ 3. Update `fonts.css` with proper `@font-face` declarations:
36
+
37
+ ```css
38
+ @font-face {
39
+ font-family: 'Inter';
40
+ src: url('./Inter-Regular.woff2') format('woff2');
41
+ font-weight: 400;
42
+ font-display: swap;
43
+ }
44
+ ```
45
+
46
+ **Note**: Current implementation uses system fonts only for optimal performance and offline capability.
assets/fonts/fonts.css ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Local Fonts - Self-hosted for offline capability
3
+ * Replaces Google Fonts CDN with system fonts fallback
4
+ */
5
+
6
+ /* Inter - Primary UI Font */
7
+ @font-face {
8
+ font-family: 'Inter';
9
+ font-style: normal;
10
+ font-weight: 300 800;
11
+ font-display: swap;
12
+ src: local('Inter'), local('Inter-Regular');
13
+ }
14
+
15
+ /* Source Code Pro - Monospace for code */
16
+ @font-face {
17
+ font-family: 'Source Code Pro';
18
+ font-style: normal;
19
+ font-weight: 400 700;
20
+ font-display: swap;
21
+ src: local('Source Code Pro'), local('SourceCodePro-Regular');
22
+ }
23
+
24
+ /* Roboto Mono - Alternative Monospace */
25
+ @font-face {
26
+ font-family: 'Roboto Mono';
27
+ font-style: normal;
28
+ font-weight: 400 700;
29
+ font-display: swap;
30
+ src: local('Roboto Mono'), local('RobotoMono-Regular');
31
+ }
32
+
33
+ /* Fira Code - Code Font with Ligatures */
34
+ @font-face {
35
+ font-family: 'Fira Code';
36
+ font-style: normal;
37
+ font-weight: 400 700;
38
+ font-display: swap;
39
+ src: local('Fira Code'), local('FiraCode-Regular');
40
+ }
41
+
42
+ /* Poppins - Rounded Sans-serif */
43
+ @font-face {
44
+ font-family: 'Poppins';
45
+ font-style: normal;
46
+ font-weight: 400 700;
47
+ font-display: swap;
48
+ src: local('Poppins'), local('Poppins-Regular');
49
+ }
50
+
51
+ /* Playfair Display - Elegant Serif */
52
+ @font-face {
53
+ font-family: 'Playfair Display';
54
+ font-style: normal;
55
+ font-weight: 400 700;
56
+ font-display: swap;
57
+ src: local('Playfair Display'), local('PlayfairDisplay-Regular');
58
+ }
59
+
60
+ /* Montserrat - Display Font */
61
+ @font-face {
62
+ font-family: 'Montserrat';
63
+ font-style: normal;
64
+ font-weight: 400 800;
65
+ font-display: swap;
66
+ src: local('Montserrat'), local('Montserrat-Regular');
67
+ }
68
+
69
+ /* Space Grotesk - Futuristic Font */
70
+ @font-face {
71
+ font-family: 'Space Grotesk';
72
+ font-style: normal;
73
+ font-weight: 400 700;
74
+ font-display: swap;
75
+ src: local('Space Grotesk'), local('SpaceGrotesk-Regular');
76
+ }
77
+
78
+ /* Ubuntu - Technical Font */
79
+ @font-face {
80
+ font-family: 'Ubuntu';
81
+ font-style: normal;
82
+ font-weight: 400 700;
83
+ font-display: swap;
84
+ src: local('Ubuntu'), local('Ubuntu-Regular');
85
+ }
86
+
87
+ /* Lato - Professional Font */
88
+ @font-face {
89
+ font-family: 'Lato';
90
+ font-style: normal;
91
+ font-weight: 400 700;
92
+ font-display: swap;
93
+ src: local('Lato'), local('Lato-Regular');
94
+ }
95
+
96
+ /* JetBrains Mono - Developer Font */
97
+ @font-face {
98
+ font-family: 'JetBrains Mono';
99
+ font-style: normal;
100
+ font-weight: 400 700;
101
+ font-display: swap;
102
+ src: local('JetBrains Mono'), local('JetBrainsMono-Regular');
103
+ }
104
+
105
+ /* Orbitron - Display/Header Font */
106
+ @font-face {
107
+ font-family: 'Orbitron';
108
+ font-style: normal;
109
+ font-weight: 400 900;
110
+ font-display: swap;
111
+ src: local('Orbitron'), local('Orbitron-Regular');
112
+ }
113
+
114
+ /* Fallback to system fonts if custom fonts not available */
115
+ :root {
116
+ --font-inter: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
117
+ --font-code: 'Source Code Pro', 'Fira Code', 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, monospace;
118
+ --font-display: 'Orbitron', 'Montserrat', 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
119
+ --font-serif: 'Playfair Display', Georgia, 'Times New Roman', serif;
120
+ --font-rounded: 'Poppins', 'Nunito', -apple-system, BlinkMacSystemFont, sans-serif;
121
+ --font-space: 'Space Grotesk', 'Orbitron', monospace;
122
+ --font-tech: 'Ubuntu', 'Roboto', sans-serif;
123
+ --font-corporate: 'Lato', 'Open Sans', sans-serif;
124
+ }
125
+
126
+ /* Apply fonts globally */
127
+ body {
128
+ font-family: var(--font-inter);
129
+ }
130
+
131
+ code, pre, .font-mono {
132
+ font-family: var(--font-code);
133
+ }
134
+
135
+ h1, h2, h3, .font-display {
136
+ font-family: var(--font-display);
137
+ }
assets/icons/icon.ico ADDED

Git LFS Details

  • SHA256: 030e094e1de82c3c68b0af5bf47e872e6cefe9282d21dc426ff41e4aea36e560
  • Pointer size: 132 Bytes
  • Size of remote file: 1.76 MB
assets/icons/icon.jpg ADDED

Git LFS Details

  • SHA256: 48e152bd0b9178bd88fba51cba317a398823d8fe2c8d56653843610325decffd
  • Pointer size: 130 Bytes
  • Size of remote file: 63.7 kB
assets/icons/icon.png ADDED

Git LFS Details

  • SHA256: 030e094e1de82c3c68b0af5bf47e872e6cefe9282d21dc426ff41e4aea36e560
  • Pointer size: 132 Bytes
  • Size of remote file: 1.76 MB
assets/icons/icon.webp ADDED

Git LFS Details

  • SHA256: cf4c0932c777c0360f29ee995a7c038967679209b24eaedefce50285f616a2ea
  • Pointer size: 130 Bytes
  • Size of remote file: 35.7 kB
assets/image/chahuadev-markdown-presenter.png ADDED

Git LFS Details

  • SHA256: aa358406fde2b5500ad69ff3497d6479b9933693a158506647dfbf0dfbecb08f
  • Pointer size: 131 Bytes
  • Size of remote file: 205 kB
docs/EN/CHANGELOG.md ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Planned
11
+ - Enhanced video export quality (1080p @ 5-10 Mbps)
12
+ - Export progress tracking with per-slide updates
13
+ - Resolution/FPS/quality configuration
14
+ - Abort/cancel functionality for long renders
15
+ - Unit tests for core modules
16
+ - Custom chart renderer (Canvas-based)
17
+ - Syntax highlighter using regex tokenization
18
+ - Audio integration with Web Audio API
19
+
20
+ ## [1.0.0] - 2025-10-20
21
+
22
+ ### Added
23
+
24
+ #### Core Features
25
+ - **Markdown Parser** with full CommonMark + GFM support
26
+ - 50+ regex patterns for comprehensive syntax recognition
27
+ - YAML frontmatter parsing for configuration
28
+ - Duration calculation heuristics
29
+ - Asset reference extraction
30
+
31
+ - **Auto-pagination System**
32
+ - Visual line calculation with content-specific weights
33
+ - Intelligent slide splitting (max 6 lines per slide)
34
+ - Smart block splitting for code, tables, blockquotes
35
+ - Balanced page distribution algorithm
36
+ - Continuation markers for split content
37
+
38
+ - **Interactive Preview Controls**
39
+ - Click anywhere to pause/resume
40
+ - Keyboard shortcuts: Space, P (pause/resume), ESC (stop)
41
+ - Promise-based waiting mechanism
42
+ - Visual pause overlay with instructions
43
+
44
+ - **Full Markdown Syntax Support**
45
+ - ATX headings (# to ######)
46
+ - Setext headings (underlines)
47
+ - Bold, italic, strikethrough
48
+ - Inline and fenced code blocks
49
+ - Unordered lists (-, *, +)
50
+ - Ordered lists and task lists
51
+ - Links and images
52
+ - Blockquotes
53
+ - Tables (GFM)
54
+ - Horizontal rules
55
+ - Inline HTML blocks
56
+
57
+ - **Timeline Visualization**
58
+ - Per-slide timing display
59
+ - Pagination indicators ([1/2], [2/2])
60
+ - Line count display (e.g., "6 lines")
61
+ - Continuation indicators ("↪ continued", "continues →")
62
+ - Total duration calculation
63
+
64
+ - **Video Export**
65
+ - Native WebM encoding using MediaRecorder API
66
+ - Canvas-based slide rendering
67
+ - Template support with YAML configuration
68
+ - Custom accent colors
69
+
70
+ - **User Interface**
71
+ - Dark blue theme (#0a1628 background, #3b82f6 primary)
72
+ - Three-tab layout: Markdown, Timeline, Templates
73
+ - Real-time markdown synchronization
74
+ - Validation diagnostics with error messages
75
+ - Bidirectional template selection
76
+
77
+ #### Documentation
78
+ - Complete bilingual documentation (EN/TH)
79
+ - Markdown Syntax Guide
80
+ - Auto-pagination System Guide
81
+ - Preview Controls Guide
82
+ - Architecture Document
83
+ - Development Plan/Roadmap
84
+ - Troubleshooting Guide
85
+
86
+ - Demo files
87
+ - `complete-syntax-demo.md` - 25 slides demonstrating all syntax
88
+ - `pagination-demo.md` - 20+ slides showing pagination
89
+
90
+ #### Development
91
+ - Modular architecture with ES Modules
92
+ - Security-first file operations through `security-core.js`
93
+ - Path validation and rate limiting
94
+ - Electron 28.0.0 with context isolation
95
+ - Tailwind CSS (local bundle)
96
+
97
+ ### Changed
98
+ - Reduced `maxLinesPerSlide` from 8 to 6 for better readability
99
+ - Updated visual line weights:
100
+ - H1: 2.5 lines (was 2)
101
+ - H2: 2 lines (was 1.5)
102
+ - Lists: 1.2 lines (was 1)
103
+ - Code: 1 line per line (was 0.8)
104
+ - Images: 4 lines (was 3)
105
+ - HTML: 3 lines (was 2)
106
+ - Tables: 2.5 + rows×0.8 (was 2 + rows×0.5)
107
+
108
+ ### Fixed
109
+ - Slide overflow issues with long content
110
+ - Code block splitting accuracy
111
+ - Table pagination with headers
112
+ - Blockquote continuation markers
113
+
114
+ ### Security
115
+ - Implemented file path validation
116
+ - Added rate limiting for file operations
117
+ - Enabled Electron security best practices
118
+ - Disabled Node integration in renderer process
119
+
120
+ ---
121
+
122
+ # บันทึกการเปลี่ยนแปลง
123
+
124
+ การเปลี่ยนแปลงที่สำคัญทั้งหมดของโปรเจกต์นี้จะบันทึกไว้ในไฟล์นี้
125
+
126
+ รูปแบบอิงตาม [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
127
+ และโปรเจกต์นี้ปฏิบัติตาม [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
128
+
129
+ ## [Unreleased]
130
+
131
+ ### Added
132
+ - **Presentation Mode** - PowerPoint-style manual navigation
133
+ - Dedicated "Presentation Mode" button alongside main controls
134
+ - Forward/backward navigation buttons with left/right arrows
135
+ - Keyboard shortcuts: ← → for navigation, Space for next, Home/End for first/last, ESC to exit
136
+ - Live slide counter display (e.g., "1 / 15")
137
+ - Automatic button disable at first/last slide boundaries
138
+ - **Fullscreen Support** - True fullscreen presentation experience
139
+ - Fullscreen button in top-right corner during presentation
140
+ - F key toggle for quick fullscreen access
141
+ - Proper fullscreen styling (borderless, full viewport)
142
+ - Exit fullscreen on ESC or presentation mode exit
143
+ - **Enhanced Navigation Controls**
144
+ - Semi-transparent navigation overlay at bottom center
145
+ - Circular prev/next buttons with hover effects and glow
146
+ - Backdrop blur for better readability over slide content
147
+ - Z-index layering for proper overlay stacking
148
+ - **Application Reset Function**
149
+ - "Reset" button to return app to initial state
150
+ - Clears all markdown content, slides, and timeline
151
+ - Resets all settings to defaults (template, video config, theme)
152
+ - Confirmation dialog prevents accidental resets
153
+ - Automatically stops any active playback or presentation
154
+ - Restores default intro/outro content and timeline preview
155
+ - **Programmer's PowerPoint - Code Editor Themes**
156
+ - 4 new professional code editor themes: Monokai, Solarized, SynthWave '84, Dracula
157
+ - Full syntax highlighting with theme-specific colors (keyword, string, number, comment, function, variable)
158
+ - Enhanced content styles with gradient text, glows, and shadows
159
+ - Styled blockquotes with large quote marks and inset shadows
160
+ - Code blocks with top gradient borders and hover animations
161
+ - **Advanced Slide Transitions**
162
+ - **Glitch**: Digital glitch effect with random hue rotation
163
+ - **Matrix**: Digital rain simulation effect
164
+ - **Cube**: 3D cube rotation with perspective
165
+ - **Pixelate**: Blur-based pixelation transition
166
+ - **CSS Animations Library**
167
+ - Matrix scrolling background animation
168
+ - Glitch skew effect for digital aesthetics
169
+ - Pixelate in/out animations
170
+ - Code block hover glow effect
171
+ - Heading text pulsing glow
172
+
173
+ ### วางแผนไว้
174
+ - ปรับปรุงคุณภาพการเอ็กซ์พอร์ตวิดีโอ (1080p @ 5-10 Mbps)
175
+ - ติดตามความคืบหน้าการเอ็กซ์พอร์ตพร้อมอัปเดตต่อสไลด์
176
+ - การตั้งค่าความละเอียด/FPS/คุณภาพ
177
+ - ฟังก์ชันยกเลิก/หยุดสำหรับการเรนเดอร์ยาว
178
+ - Unit tests สำหรับโมดูลหลัก
179
+ - ตัวเรนเดอร์กราฟแบบกำหนดเอง (Canvas-based)
180
+ - Syntax highlighter ใช้ regex tokenization
181
+ - การผสานเสียงด้วย Web Audio API
182
+
183
+ ---
184
+
185
+ # บันทึกการเปลี่ยนแปลง (ต่อ - ภาษาไทย)
186
+
187
+ ## [Unreleased]
188
+
189
+ ### เพิ่ม
190
+ - **โหมดนำเสนอ (Presentation Mode)** - การนำทางแบบกำหนดเองเหมือน PowerPoint
191
+ - ปุ่ม "Presentation Mode" เฉพาะข้างปุ่มควบคุมหลัก
192
+ - ปุ่มนำทางเดินหน้า/ถอยหลังพร้อมลูกศรซ้าย/ขวา
193
+ - ปุ่มลัด: ← → สำหรับนำทาง, Space สำหรับถัดไป, Home/End สำหรับแรก/สุดท้าย, ESC เพื่อออก
194
+ - แสดงตัวนับสไลด์แบบสด (เช่น "1 / 15")
195
+ - ปิดการใช้งานปุ่มอัตโนมัติที่ขอบเขตสไลด์แรก/สุดท้าย
196
+ - **รองรับเต็มจอ (Fullscreen)** - ประสบการณ์นำเสนอแบบเต็มจอจริง
197
+ - ปุ่มเต็มจอที่มุมบนขวาขณะนำเสนอ
198
+ - กด F สลับเข้าเต็มจอได้ทันที
199
+ - สไตล์เต็มจอที่เหมาะสม (ไร้กรอบ, viewport เต็ม)
200
+ - ออกจากเต็มจอเมื่อกด ESC หรือออกจากโหมดนำเสนอ
201
+ - **ควบคุมนำทางที่ปรับปรุง**
202
+ - Overlay นำทางกึ่งโปร่งใสที่ด้านล่างกลาง
203
+ - ปุ่มวงกลม prev/next พร้อม hover effects และแสง
204
+ - Backdrop blur เพื่อการอ่านที่ดีขึ้นเหนือเนื้อหาสไลด์
205
+ - การจัดเรียง Z-index สำหรับ overlay stacking ที่เหมาะสม
206
+ - **ฟังก์ชันรีเซ็ตแอปพลิเคชัน**
207
+ - ปุ่ม "Reset" เพื่อนำแอปกลับสู่สถานะเริ่มต้น
208
+ - ล้างเนื้อหา markdown, สไลด์ และไทม์ไลน์ทั้งหมด
209
+ - รีเซ็ตการตั้งค่าทั้งหมดเป็นค่าเริ่มต้น (template, video config, theme)
210
+ - กล่องยืนยันป้องกันการรีเซ็ตโดยไม่ตั้งใจ
211
+ - หยุดการเล่นหรือนำเสนอที่ใช้งานอยู่อัตโนมัติ
212
+ - คืนค่าเนื้อหา intro/outro และพรีวิวไทม์ไลน์เริ่มต้น
213
+ - **PowerPoint สำหรับโปรแกรมเมอร์ - Code Editor Themes**
214
+ - เทมเพลต code editor 4 แบบใหม่: Monokai, Solarized, SynthWave '84, Dracula
215
+ - Syntax highlighting เต็มรูปแบบพร้อมสีเฉพาะ theme (keyword, string, number, comment, function, variable)
216
+ - Content styles ที่ปรับปรุงพร้อม gradient text, เรือง และเงา
217
+ - Blockquotes มีสไตล์พร้อมเครื่องหมายคำพูดขนาดใหญ่และ inset shadows
218
+ - Code blocks พร้อม gradient borders ด้านบนและแอนิเมชัน hover
219
+ - **Slide Transitions ขั้นสูง**
220
+ - **Glitch**: เอฟเฟกต์ glitch แบบดิจิทัลพร้อม hue rotation แบบสุ่ม
221
+ - **Matrix**: เอฟเฟกต์จำลอง digital rain
222
+ - **Cube**: การหมุนแบบ cube 3D พร้อม perspective
223
+ - **Pixelate**: Transition แบบ pixelation ใช้ blur
224
+ - **ไลบรารี CSS Animations**
225
+ - แอนิเมชันพื้นหลัง Matrix scrolling
226
+ - เอฟเฟกต์ glitch skew สำหรับสุนทรียศาสตร์ดิจิทัล
227
+ - แอนิเมชัน pixelate in/out
228
+ - เอฟเฟกต์เรืองแสงพร้อม hover ของ code block
229
+ - เอฟเฟกต์เรืองแสง pulsing ของ heading text
230
+
231
+ ## [1.0.0] - 2025-10-20
232
+
233
+ ### เพิ่ม
234
+
235
+ #### ฟีเจอร์หลัก
236
+ - **Markdown Parser** พร้อมรองรับ CommonMark + GFM เต็มรูปแบบ
237
+ - รูปแบบ regex 50+ แบบสำหรับการจดจำ syntax อย่างครอบคลุม
238
+ - การแยก YAML frontmatter สำหรับการตั้งค่า
239
+ - Heuristics การคำนวณระยะเวลา
240
+ - การแยกการอ้างอิง asset
241
+
242
+ - **ระบบแบ่งหน้าอัตโนมัติ**
243
+ - การคำนวณบรรทัดแบบ visual พร้อมน้ำหนักเฉพาะเนื้อหา
244
+ - การแบ่งสไลด์อัจฉริยะ (สูงสุด 6 บรรทัดต่อสไลด์)
245
+ - การแบ่งบล็อกอัจฉริยะสำหรับ code, tables, blockquotes
246
+ - อัลกอริทึมกระจายหน้าแบบสมดุล
247
+ - เครื่องหมายต่อเนื่องสำหรับเนื้อหาที่แบ่ง
248
+
249
+ - **การควบคุมพรีวิวแบบโต้ตอบ**
250
+ - คลิกที่ใดก็ได้เพื่อหยุด/เล่นต่อ
251
+ - ปุ่มลัด: Space, P (หยุด/เล่นต่อ), ESC (หยุด)
252
+ - กลไกการรอแบบ promise-based
253
+ - Overlay หยุดด้วยคำแนะนำ
254
+
255
+ - **รองรับ Markdown Syntax เต็มรูปแบบ**
256
+ - ATX headings (# ถึง ######)
257
+ - Setext headings (ขีดเส้นใต้)
258
+ - ตัวหนา, ตัวเอียง, ขีดฆ่า
259
+ - โค้ดบล็อกแบบ inline และ fenced
260
+ - รายการไม่มีลำดับ (-, *, +)
261
+ - รายการมีลำดับและ task lists
262
+ - ลิงก์และรูปภาพ
263
+ - Blockquotes
264
+ - ตาราง (GFM)
265
+ - เส้นแนวนอน
266
+ - บล็อก HTML แบบ inline
267
+
268
+ ### เปลี่ยนแปลง
269
+ - ลด `maxLinesPerSlide` จาก 8 เป็น 6 เพื่อให้อ่านง่ายขึ้น
270
+ - อัปเดตน้ำหนักบรรทัดแบบ visual:
271
+ - H1: 2.5 บรรทัด (เดิม 2)
272
+ - H2: 2 บรรทัด (เดิม 1.5)
273
+ - Lists: 1.2 บรรทัด (เดิม 1)
274
+ - Code: 1 บรรทัดต่อบรรทัด (เดิม 0.8)
275
+ - Images: 4 บรรทัด (เดิม 3)
276
+ - HTML: 3 บรรทัด (เดิม 2)
277
+ - Tables: 2.5 + rows×0.8 (เดิม 2 + rows×0.5)
278
+
279
+ ### แก้ไข
280
+ - ปัญหาสไลด์ล้นจอกับเนื้อหายาว
281
+ - ความแม่นยำการแบ่ง code block
282
+ - การแบ่งหน้าตารางพร้อม headers
283
+ - เครื่องหมายต่อเนื่อง blockquote
284
+
285
+ ### ความปลอดภัย
286
+ - ใช้งานการตรวจสอบ file path
287
+ - เพิ่ม rate limiting สำหรับการดำเนินการไฟล์
288
+ - เปิดใช้งานแนวทางปฏิบัติที่ดีที่สุดด้านความปลอดภัยของ Electron
289
+ - ปิด Node integration ใน renderer process
290
+
291
+ [Unreleased]: https://github.com/chahuadev/chahuadev-markdown-presenter/compare/v1.0.0...HEAD
292
+ [1.0.0]: https://github.com/chahuadev/chahuadev-markdown-presenter/releases/tag/v1.0.0
docs/EN/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT EMAIL].
64
+
65
+ All complaints will be reviewed and investigated promptly and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ ## Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ ### 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ ### 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series of
87
+ actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or permanent
94
+ ban.
95
+
96
+ ### 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ ### 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within the
114
+ community.
115
+
116
+ ## Attribution
117
+
118
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119
+ version 2.1, available at
120
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121
+
122
+ Community Impact Guidelines were inspired by
123
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124
+
125
+ For answers to common questions about this code of conduct, see the FAQ at
126
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127
+ [https://www.contributor-covenant.org/translations][translations].
128
+
129
+ [homepage]: https://www.contributor-covenant.org
130
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131
+ [Mozilla CoC]: https://github.com/mozilla/diversity
132
+ [FAQ]: https://www.contributor-covenant.org/faq
133
+ [translations]: https://www.contributor-covenant.org/translations
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
+ ความคิดเห็น คอมมิต โค้ด การแก้ไข wiki ปัญหา และการมีส่วนร่วมอื่นๆ
181
+ ที่ไม่สอดคล้องกับจรรยาบรรณนี้ และจะสื่อสารเหตุผลในการตัดสินใจดูแล
182
+ เมื่อเหมาะสม
183
+
184
+ ## การบังคับใช้
185
+
186
+ กรณีพฤติกรรมที่ไม่เหมาะสมสามารถรายงานไปยังผู้นำชุมชนที่รับผิดชอบการบังคับใช้ที่
187
+ [INSERT CONTACT EMAIL]
188
+
189
+ ข้อร้องเรียนทั้งหมดจะได้รับการตรวจสอบและสอบสวนอย่างรวดเร็วและยุติธรรม
190
+
191
+ ผู้นำชุมชนทั้งหมดมีหน้าที่เคารพความเป็นส่วนตัวและความปลอดภัย
192
+ ของผู้รายงานเหตุการณ์ใดๆ
193
+
194
+ ## การระบุแหล่งที่มา
195
+
196
+ จรรยาบรรณนี้ดัดแปลงมาจาก [Contributor Covenant][homepage]
197
+ เวอร์ชัน 2.1 มีอยู่ที่
198
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]
199
+
200
+ [homepage]: https://www.contributor-covenant.org
201
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
docs/EN/CONTRIBUTING.md ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to Chahuadev Markdown Presenter
2
+
3
+ First off, thank you for considering contributing to Chahuadev Markdown Presenter! It's people like you that make this project such a great tool.
4
+
5
+ [English](#english) | [ไทย](#thai)
6
+
7
+ ---
8
+
9
+ ## English
10
+
11
+ ### Code of Conduct
12
+
13
+ This project and everyone participating in it is governed by our [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code.
14
+
15
+ ### How Can I Contribute?
16
+
17
+ #### Reporting Bugs
18
+
19
+ Before creating bug reports, please check the [existing issues](https://github.com/chahuadev/chahuadev-markdown-presenter/issues) to avoid duplicates.
20
+
21
+ **When you create a bug report, please include:**
22
+
23
+ - **Clear title and description**
24
+ - **Steps to reproduce** the issue
25
+ - **Expected behavior** vs **actual behavior**
26
+ - **Screenshots** if applicable
27
+ - **Environment details**:
28
+ - OS version (Windows/macOS/Linux)
29
+ - Node.js version (`node --version`)
30
+ - Electron version
31
+ - Application version
32
+
33
+ **Example bug report:**
34
+
35
+ ```markdown
36
+ **Title:** Auto-pagination fails with code blocks over 10 lines
37
+
38
+ **Description:**
39
+ When a Markdown file contains a code block with more than 10 lines,
40
+ the auto-pagination system crashes.
41
+
42
+ **Steps to Reproduce:**
43
+ 1. Create a markdown file with a code block > 10 lines
44
+ 2. Click "Sync Markdown"
45
+ 3. Observe error in console
46
+
47
+ **Expected:**
48
+ Code block should be split across multiple slides
49
+
50
+ **Actual:**
51
+ Application crashes with TypeError
52
+
53
+ **Environment:**
54
+ - OS: Windows 11
55
+ - Node: v18.16.0
56
+ - Electron: 28.0.0
57
+ ```
58
+
59
+ #### Suggesting Enhancements
60
+
61
+ Enhancement suggestions are tracked as GitHub issues. When creating an enhancement suggestion:
62
+
63
+ - **Use a clear and descriptive title**
64
+ - **Provide detailed description** of the suggested enhancement
65
+ - **Explain why this enhancement would be useful**
66
+ - **List alternative solutions** you've considered
67
+
68
+ #### Pull Requests
69
+
70
+ **Process:**
71
+
72
+ 1. **Fork** the repository
73
+ 2. **Create a branch** from `main`:
74
+ ```bash
75
+ git checkout -b feature/your-feature-name
76
+ ```
77
+ 3. **Make your changes** with clear commit messages
78
+ 4. **Test thoroughly** - ensure all existing functionality works
79
+ 5. **Update documentation** if needed
80
+ 6. **Submit a pull request** with:
81
+ - Clear description of changes
82
+ - Reference to related issues
83
+ - Screenshots/GIFs for UI changes
84
+
85
+ **Commit Message Guidelines:**
86
+
87
+ ```
88
+ type(scope): subject
89
+
90
+ body (optional)
91
+
92
+ footer (optional)
93
+ ```
94
+
95
+ **Types:**
96
+ - `feat`: New feature
97
+ - `fix`: Bug fix
98
+ - `docs`: Documentation changes
99
+ - `style`: Code style changes (formatting, semicolons, etc.)
100
+ - `refactor`: Code refactoring
101
+ - `test`: Adding or updating tests
102
+ - `chore`: Maintenance tasks
103
+
104
+ **Examples:**
105
+ ```
106
+ feat(pagination): add configurable max lines per slide
107
+
108
+ fix(parser): handle empty code blocks correctly
109
+
110
+ docs(readme): update installation instructions
111
+ ```
112
+
113
+ ### Development Setup
114
+
115
+ #### Prerequisites
116
+
117
+ - Node.js 18.0.0+
118
+ - npm 8.0.0+
119
+ - Git
120
+
121
+ #### Getting Started
122
+
123
+ ```bash
124
+ # Clone your fork
125
+ git clone https://github.com/YOUR_USERNAME/chahuadev-markdown-presenter.git
126
+
127
+ # Navigate to directory
128
+ cd chahuadev-markdown-presenter
129
+
130
+ # Add upstream remote
131
+ git remote add upstream https://github.com/chahuadev/chahuadev-markdown-presenter.git
132
+
133
+ # Install dependencies
134
+ npm install
135
+
136
+ # Start development
137
+ npm start
138
+ ```
139
+
140
+ #### Project Structure
141
+
142
+ ```
143
+ src/
144
+ ├── main/ # Electron main process
145
+ ├── renderer/ # UI and frontend logic
146
+ └── shared/ # Shared modules (parser, paginator, etc.)
147
+ ```
148
+
149
+ #### Key Files
150
+
151
+ - **`src/shared/markdown-parser.js`** - Markdown parsing logic
152
+ - **`src/shared/slide-paginator.js`** - Auto-pagination algorithm
153
+ - **`src/renderer/js/app.js`** - Main application controller
154
+ - **`src/renderer/js/video-renderer.js`** - Video export logic
155
+
156
+ ### Coding Standards
157
+
158
+ #### JavaScript Style
159
+
160
+ - Use **ES6+ features** (const/let, arrow functions, template literals)
161
+ - Use **ES Modules** (`import`/`export`)
162
+ - **2 spaces** for indentation
163
+ - **Semicolons** required
164
+ - **Single quotes** for strings (except template literals)
165
+
166
+ #### Code Comments
167
+
168
+ ```javascript
169
+ /**
170
+ * Calculate visual lines for a content item
171
+ * @param {Object} item - Content item with type and content
172
+ * @returns {number} Number of visual lines
173
+ */
174
+ export function calculateVisualLines(item) {
175
+ // Implementation
176
+ }
177
+ ```
178
+
179
+ #### Error Handling
180
+
181
+ ```javascript
182
+ try {
183
+ const result = await parseMarkdown(content);
184
+ return result;
185
+ } catch (error) {
186
+ console.error('Failed to parse markdown:', error);
187
+ throw new Error(`Markdown parsing failed: ${error.message}`);
188
+ }
189
+ ```
190
+
191
+ ### Testing
192
+
193
+ ```bash
194
+ # Run tests (when implemented)
195
+ npm test
196
+
197
+ # Run linter
198
+ npm run lint
199
+ ```
200
+
201
+ **Test Guidelines:**
202
+ - Write unit tests for new features
203
+ - Ensure tests pass before submitting PR
204
+ - Include test cases for edge cases
205
+
206
+ ### Documentation
207
+
208
+ When adding new features:
209
+
210
+ 1. **Update relevant documentation** in `docs/`
211
+ 2. **Add examples** to demonstrate usage
212
+ 3. **Update README.md** if user-facing changes
213
+ 4. **Write bilingual docs** (EN + TH) when possible
214
+
215
+ ### Questions?
216
+
217
+ - Open an issue with the `question` label
218
+ - Join discussions in existing issues
219
+ - Check [documentation](docs/) first
220
+
221
+ ---
222
+
223
+ ## Thai
224
+
225
+ ### จรรยาบรรณ
226
+
227
+ โปรเจกต์นี้และทุกคนที่เข้าร่วมอยู่ภายใต้ [จรรยาบรรณ](CODE_OF_CONDUCT.md) ของเรา การเข้าร่วมหมายความว่าคุณยอมรับจรรยาบรรณนี้
228
+
229
+ ### ฉันสามารถมีส่วนร่วมได้อย่างไร?
230
+
231
+ #### รายงานบั๊ก
232
+
233
+ ก่อนสร้างรายงานบั๊ก โปรดตรวจสอบ [issues ที่มีอยู่](https://github.com/chahuadev/chahuadev-markdown-presenter/issues) เพื่อหลีกเลี่ยงการซ้ำซ้อน
234
+
235
+ **เมื่อสร้างรายงานบั๊ก โปรดระบุ:**
236
+
237
+ - **หัวข้อและคำอธิบายที่ชัดเจน**
238
+ - **ขั้นตอนการทำซ้ำ** ปัญหา
239
+ - **พฤติกรรมที่คาดหวัง** กับ **พฤติกรรมจริง**
240
+ - **ภาพหน้าจอ** ถ้ามี
241
+ - **รายละเอียดสภาพแวดล้อม**:
242
+ - เวอร์ชัน OS (Windows/macOS/Linux)
243
+ - เวอร์ชัน Node.js (`node --version`)
244
+ - เวอร์ชัน Electron
245
+ - เวอร์ชันแอปพลิเคชัน
246
+
247
+ #### แนะนำการปรับปรุง
248
+
249
+ การแนะนำการปรับปรุงจะถูกติดตามเป็น GitHub issues เมื่อสร้างข้อเสนอแนะ:
250
+
251
+ - **ใช้หัวข้อที่ชัดเจนและอธิบายได้**
252
+ - **ให้คำอธิบายโดยละเอียด** ของการปรับปรุงที่แนะนำ
253
+ - **อธิบายว่าทำไมการปรับปรุงนี้มีประโยชน์**
254
+ - **แสดงทางเลือกอื่น** ที่คุณพิจารณา
255
+
256
+ #### Pull Requests
257
+
258
+ **กระบวนการ:**
259
+
260
+ 1. **Fork** repository
261
+ 2. **สร้าง branch** จาก `main`:
262
+ ```bash
263
+ git checkout -b feature/ชื่อฟีเจอร์ของคุณ
264
+ ```
265
+ 3. **ทำการเปลี่ยนแปลง** พร้อม commit messages ที่ชัดเจน
266
+ 4. **ทดสอบอย่างละเอียด** - ตรวจสอบว่าฟังก์ชันทั้งหมดทำงาน
267
+ 5. **อัปเดตเอกสาร** ถ้าจำเป็น
268
+ 6. **ส่ง pull request** พร้อม:
269
+ - คำอธิบายการเปลี่ยนแปลงที่ชัดเจน
270
+ - อ้างอิงถึง issues ที่เกี่ยวข้อง
271
+ - ภาพหน้าจอ/GIFs สำหรับการเปลี่ยนแปลง UI
272
+
273
+ **แนวทาง Commit Message:**
274
+
275
+ ```
276
+ type(scope): เรื่อง
277
+
278
+ เนื้อหา (ถ้ามี)
279
+
280
+ footer (ถ้ามี)
281
+ ```
282
+
283
+ **ประเภท:**
284
+ - `feat`: ฟีเจอร์ใหม่
285
+ - `fix`: แก้บั๊ก
286
+ - `docs`: เปลี่ยนแปลงเอกสาร
287
+ - `style`: เปลี่ยนสไตล์โค้ด (formatting, semicolons, ฯลฯ)
288
+ - `refactor`: รีแฟกเตอร์โค้ด
289
+ - `test`: เพิ่มหรืออัปเดตเทสต์
290
+ - `chore`: งานบำรุงรักษา
291
+
292
+ ### การตั้งค่าการพัฒนา
293
+
294
+ #### ความต้องการเบื้องต้น
295
+
296
+ - Node.js 18.0.0+
297
+ - npm 8.0.0+
298
+ - Git
299
+
300
+ #### เริ่มต้น
301
+
302
+ ```bash
303
+ # โคลน fork ของคุณ
304
+ git clone https://github.com/YOUR_USERNAME/chahuadev-markdown-presenter.git
305
+
306
+ # เข้าไปในโฟลเดอร์
307
+ cd chahuadev-markdown-presenter
308
+
309
+ # เพิ่ม upstream remote
310
+ git remote add upstream https://github.com/chahuadev/chahuadev-markdown-presenter.git
311
+
312
+ # ติดตั้ง dependencies
313
+ npm install
314
+
315
+ # เริ่มพัฒนา
316
+ npm start
317
+ ```
318
+
319
+ ### มาตรฐานการเขียนโค้ด
320
+
321
+ #### JavaScript Style
322
+
323
+ - ใช้ **คุณสมบัติ ES6+** (const/let, arrow functions, template literals)
324
+ - ใช้ **ES Modules** (`import`/`export`)
325
+ - **2 spaces** สำหรับ indentation
326
+ - **Semicolons** จำเป็น
327
+ - **Single quotes** สำหรับ strings (ยกเว้น template literals)
328
+
329
+ ### การทดสอบ
330
+
331
+ ```bash
332
+ # รันเทสต์ (เมื่อถูกสร้าง)
333
+ npm test
334
+
335
+ # รัน linter
336
+ npm run lint
337
+ ```
338
+
339
+ ### เอกสาร
340
+
341
+ เมื่อเพิ่มฟีเจอร์ใหม่:
342
+
343
+ 1. **อัปเดตเอกสารที่เกี่ยวข้อง** ใน `docs/`
344
+ 2. **เพิ่มตัวอย่าง** เพื่อแสดงการใช้งาน
345
+ 3. **อัปเดต README.md** ถ้ามีการเปลี่ยนแปลงที่ผู้ใช้เห็น
346
+ 4. **เขียนเอกสารสองภาษา** (EN + TH) เมื่อเป็นไปได้
347
+
348
+ ### มีคำถาม?
349
+
350
+ - เปิด issue พร้อมป้ายกำกับ `question`
351
+ - เข้าร่วมการสนทนาใน issues ที่มีอยู่
352
+ - ตรวจสอบ [เอกสาร](docs/) ก่อน
353
+
354
+ ---
355
+
356
+ Thank you for contributing! 🎉
357
+ ขอบคุณสำหรับการมีส่วนร่วม! 🎉
docs/EN/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Chahua Development Co., Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
docs/EN/MARKDOWN_VIDEO_PLAN.md ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 
2
+ # Markdown-to-Video Roadmap
3
+
4
+ ## Vision
5
+ - **Markdown-to-Video Generator**: Write markdown, export video—powered entirely by native web technologies
6
+ - **Markdown controls everything**: Content, timing, transitions, templates, and visual styling all defined in `.md` files
7
+ - **Self-contained architecture**: Built on Electron + native Web APIs (Canvas, MediaRecorder, Web Audio, File System)
8
+ - **Flexible slide creation**: Multiple slide break modes (`---` separators, `# H1` headers, `## H2` headers, or auto-detection)
9
+
10
+ ## Core Philosophy: Markdown as Video Source
11
+ - **Input**: Markdown file with YAML frontmatter for video configuration
12
+ - **Parser**: Custom `MarkdownParser` extracts slides, metadata, and asset references
13
+ - **Renderer**: Canvas-based slide compositor using HTML/CSS → Canvas 2D API
14
+ - **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
15
+ - **Export**: Files saved via secure IPC bridge with path validation
16
+
17
+ ## Guiding Principles
18
+ - **Markdown-first workflow**: Deck authoring, timeline preview, and video export driven by `.md` source
19
+ - **Native APIs only**: MediaRecorder (video encoding), Canvas 2D (rendering), Web Audio (future audio mixing)
20
+ - **Preview = Export fidelity**: Same timeline engine powers live preview and final video output
21
+ - **Security-first**: All file I/O flows through `security-core.js` with path validation and rate limiting
22
+ - **Zero-config experience**: Sensible defaults with frontmatter-based overrides and shareable presentation presets
23
+
24
+ ## Completed Foundation
25
+ - [x] Markdown-to-HTML pipeline in the Electron renderer.
26
+ - [x] Baseline slide templates, theming, and live preview.
27
+ - [x] Project structure separating main, renderer, and shared modules.
28
+ - [x] Refactored renderer UI (`src/renderer/index.html`) into a markdown-first workflow with restored Templates tab.
29
+ - [x] **Comprehensive Markdown Syntax Dictionary** (`markdown-syntax.js`) - 50+ patterns supporting CommonMark + GFM
30
+ - [x] **Auto-pagination System** (`slide-paginator.js`) - Intelligent slide splitting based on visual line count (max 6 lines/slide)
31
+ - [x] **Interactive Preview Controls** - Pause/resume with click, Space, P, ESC keyboard shortcuts
32
+ - [x] **Dark Blue Theme** - Complete UI redesign with cohesive color scheme (#0a1628 background, #3b82f6 primary)
33
+
34
+ ## Immediate Sprint Focus (Current Work)
35
+
36
+ ### Phase 1: Core Functionality (COMPLETED)
37
+ - [x] **Rebuild `src/renderer/js/app.js`** – Complete renderer controller:
38
+ - [x] Parse markdown via `MarkdownParser` when user clicks "Sync Markdown"
39
+ - [x] Extract frontmatter (template, video.*, theme.accent) and body content
40
+ - [x] Generate slide array with auto-calculated durations based on content density
41
+ - [x] Populate Timeline tab with per-slide timings, page indicators, line counts, and duration
42
+ - [x] Update stage preview rendering with full markdown syntax support
43
+ - [x] Apply selected template and accent color to CSS variables
44
+ - [x] Enable Preview Timeline with pause/resume controls (click, Space, P, ESC)
45
+ - [x] Full support for 15+ content types (H1-H6, lists, tables, blockquotes, code, HTML, etc.)
46
+ - [x] Continuation markers for paginated slides ("↪ continued", "continues →")
47
+ - [x] Page indicators in top-right corner of slides
48
+
49
+ - [x] **Extend `src/shared/markdown-parser.js`** to:
50
+ - [x] Emit scene-level metadata including slide index, title, subtitle, and content items
51
+ - [x] Calculate per-slide durations using heuristics (H1=2s, list items=1s each, text=0.3s per word, code=0.5s per line)
52
+ - [x] Support frontmatter parsing for template ID, video settings, and custom metadata
53
+ - [x] Return asset references (images from `![alt](src)` syntax) for checklist validation
54
+ - [x] Provide `getSummary()` method returning totalSlides, paginatedSlides, estimatedDuration, and titles
55
+ - [x] **NEW: Integration with MarkdownSyntax dictionary** for comprehensive pattern recognition
56
+ - [x] **NEW: Auto-pagination support** with `enablePagination` and `maxLinesPerSlide` options
57
+ - [x] **NEW: Visual line tracking** - slides include `visualLines`, `totalPages`, `pageNumber` properties
58
+
59
+ - [x] **Wire template selection bidirectionally**:
60
+ - [x] Clicking a template card in Templates tab updates `state.template`
61
+ - [x] Upsert `template: <id>` into markdown frontmatter via `upsertFrontmatterValue()`
62
+ - [x] Trigger `syncMarkdown()` to refresh timeline and reapply template CSS
63
+ - [x] Show active template name in "Active template:" hint label
64
+
65
+ - [x] **Surface validation diagnostics**:
66
+ - [x] Show/hide `markdownDiagnostics` panel based on parse success/failure
67
+ - [x] Display human-friendly error messages (e.g., "Missing closing frontmatter delimiter", "Invalid slide structure")
68
+ - [x] Highlight unsynced state when editor content changes before next sync
69
+ - [x] Clear diagnostics automatically on successful sync
70
+
71
+ ### New Features Completed Beyond Original Scope
72
+
73
+ #### 1. Comprehensive Markdown Syntax Dictionary (`src/shared/markdown-syntax.js`)
74
+ - [x] **50+ regex patterns** covering CommonMark + GitHub Flavored Markdown
75
+ - [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
76
+ - [x] **Inline syntax**: bold (**text**), italic (*text*), strikethrough (~~text~~), inline code (`code`), links, images
77
+ - [x] **Special syntax**: YAML frontmatter, footnotes, math blocks (LaTeX)
78
+ - [x] **API**: `detectBlockType(line, nextLine)` and `parseInline(text)` methods
79
+ - [x] **Documentation**: `MARKDOWN_SYNTAX.md` (EN/TH) with complete syntax reference
80
+
81
+ #### 2. Auto-pagination System (`src/shared/slide-paginator.js`)
82
+ **Status**: **Needs Integration with Presentation Rendering** - Currently standalone, not yet used in actual rendering
83
+
84
+ - [x] **Visual line calculation** with content-specific weights:
85
+ - H1 = 2.5 lines, H2 = 2 lines, H3-H6 = 1.5-1 lines
86
+ - List/blockquote items = 1.2 lines each
87
+ - Code blocks = 1 line per line (more readable)
88
+ - Tables = 2.5 (header) + rows × 0.8
89
+ - Images = 4 lines, HTML = 3 lines
90
+ - [x] **Intelligent splitting algorithms**:
91
+ - Balanced page distribution (30% threshold)
92
+ - Smart block splitting for code, tables, blockquotes
93
+ - Atomic blocks (images, HTML, HR) never split
94
+ - Continuation markers automatically added
95
+ - [x] **API**: `applyPagination(slides, config)` returns paginated slide array
96
+ - [x] **Documentation**: `AUTO_PAGINATION.md` (EN/TH) with examples and algorithm details
97
+
98
+ **Required Work**:
99
+ - [ ] **Integrate with Smart Layout Engine**: Use line calculation logic with `ensureContentWithinBounds()`
100
+ - [ ] **Integrate with Slide Renderer**: Make slides split automatically during actual rendering, not just parsing
101
+ - [ ] **Configure via Presentation Settings**: Add `maxLinesPerSlide` to presentation-config.js
102
+ - [ ] **Work with Safe Zones**: Calculate actual available space before splitting slides
103
+
104
+ #### 3. Interactive Preview Controls
105
+ - [x] **Pause/resume mechanism**:
106
+ - Click anywhere on preview stage to pause/resume (preview mode only)
107
+ - Keyboard shortcuts: Space or P to toggle, ESC to stop preview
108
+ - Promise-based waiting with 100ms polling for instant response
109
+
110
+ #### 4. Presentation Mode (PowerPoint-style Navigation)
111
+ - [x] **Manual slide navigation** with forward/back controls:
112
+ - "Presentation Mode" button alongside main controls
113
+ - Left/Right arrow buttons for navigation
114
+ - Keyboard shortcuts: ← → for prev/next, Space for next, Home/End for first/last
115
+ - Slide counter display (e.g., "1 / 15")
116
+ - ESC to exit presentation mode
117
+ - [x] **Fullscreen support**:
118
+ - Fullscreen button in top-right corner during presentation
119
+ - F key toggle for fullscreen
120
+ - Proper fullscreen styling (borderless, full viewport)
121
+ - [x] **Visual design**:
122
+ - Semi-transparent navigation controls at bottom center
123
+ - Circular prev/next buttons with hover effects
124
+ - Disabled state for first/last slide boundaries
125
+ - Backdrop blur for better readability
126
+
127
+ #### 5. Application Reset Function
128
+ - [x] **Reset Button** after Export Video
129
+ - Reset application to initial state
130
+ - Clear all markdown content and slides
131
+ - Reset all settings to defaults
132
+ - Confirmation dialog before execution
133
+ - Automatically stop playback or presentation
134
+ - Reset template to 'modern'
135
+ - Clear timeline and asset checklist
136
+
137
+ #### 6. Programmer's PowerPoint - Code Editor Themes
138
+ - [x] **New Code Editor Style Themes** in templates.js:
139
+ - **Monokai**: Classic theme with warm tones (magenta, green, cyan)
140
+ - **Solarized Dark**: Precision colors designed for readability
141
+ - **SynthWave '84**: Retro futuristic 80s aesthetic (hot pink, mint, yellow)
142
+ - **Dracula**: Dark theme for night coders
143
+ - Full syntax highlighting support with theme-specific colors
144
+ - [x] **Enhanced Content Styles** in style.css:
145
+ - `.content-h1`: Gradient text with glow effect
146
+ - `.content-h2`: Border-left accent with text shadow
147
+ - `.content-blockquote`: Styled quote marks with inset shadow
148
+ - `.content-code-block`: Top gradient border with hover animation
149
+ - Syntax highlighting colors: keyword, string, number, comment, function, variable
150
+ - [x] **Advanced Transitions** in slide-renderer.js:
151
+ - **Glitch**: Digital glitch effect with random offsets and hue rotation
152
+ - **Matrix**: Digital rain effect simulation
153
+ - **Cube**: 3D cube rotation transition
154
+ - **Pixelate**: Blur-based pixelation effect
155
+ - [x] **CSS Animations**:
156
+ - `@keyframes matrixScroll`: Scrolling matrix effect
157
+ - `@keyframes glitchSkew`: Skew animation for glitch
158
+ - `@keyframes pixelateIn`: Blur in animation
159
+ - `@keyframes codeHighlight`: Code block hover glow
160
+ - `@keyframes textGlow`: Heading pulsing glow effect
161
+ - [x] **Visual feedback**:
162
+ - Pause overlay with semi-transparent backdrop (blur 8px)
163
+ - Large pause icon with pulse animation
164
+ - Instructions: "Paused" text + keyboard hints
165
+ - Z-index 1000 for always-on-top display
166
+ - [x] **State management**:
167
+ - `isPaused` boolean flag
168
+ - `pauseResolve` function reference for promise resolution
169
+ - Cleanup on preview stop
170
+ - [x] **Documentation**: `PREVIEW_CONTROLS.md` (EN/TH) with usage guide
171
+
172
+ #### 7. Enhanced Timeline Visualization
173
+ - [x] **Pagination indicators**: Show "[1/2]", "[2/2]" badges for multi-page slides
174
+ - [x] **Line count display**: "8 lines", "5 lines" to show content density
175
+ - [x] **Continuation indicators**: "↪ continued" for split content
176
+ - [x] **Duration display**: Accurate timing per slide with total duration
177
+
178
+ #### 8. Smart Layout Measurement & Safe Zones
179
+ - [x] Introduced shared `SMART_SAFE_ZONE` heuristics and padding helpers to derive consistent insets for measurement and stage rendering
180
+ - [x] Synced typography, screen-type classes, and scene structure between the hidden measurement stage and the live stage frame
181
+ - [x] Reused measurement-stage results to auto-scale overflowing content while keeping metadata (`data-safe-*`) available for diagnostics
182
+ - [x] Filtered preview carry-over to exclude heading blocks and rely on authored titles instead of synthetic "Slide N" labels
183
+
184
+ #### 9. Presentation Configuration System (`src/renderer/js/presentation-config.js`)
185
+ - [x] Replaced rigid template catalogue with flexible presentation settings presets (fonts, clamp sizes, colors, backgrounds, animations)
186
+ - [x] Introduced configuration API (`getCurrentConfig`, `setConfig`, `updateConfigPart`, `loadPreset`, `resetConfig`) for fine-grained control
187
+ - [x] Defined curated preset families (Default, Professional, Minimal, Creative) plus font/background/transition option catalogs
188
+ - [x] Auto-applies presentation variables to CSS custom properties (fonts, font sizes, colors, safe spacing) without external libraries
189
+ - [x] Supports JSON import/export for sharing configuration profiles across markdown decks
190
+ - [x] **Typography & Layout Controls** - Complete document formatting system:
191
+ - [x] Font size controls (H1, H2, Body Text) with responsive clamp (min, base vw, max)
192
+ - [x] Line height adjustments (heading, body) for optimal readability
193
+ - [x] Paragraph spacing controls (before/after) in rem units
194
+ - [x] Heading spacing controls (before/after) for visual hierarchy
195
+ - [x] Indentation controls (first-line, blockquote) for document structure
196
+ - [x] List indent and text alignment options (left, center, right, justify)
197
+ - [x] **UI & Visual Effects Configuration**:
198
+ - [x] Preview slide opacity control (0-1 range)
199
+ - [x] Pause overlay blur effect (px)
200
+ - [x] Navigation button border width (px)
201
+ - [x] Gradient backdrop effects (spread %, blur px)
202
+ - [x] **Border & Accent Width Controls**:
203
+ - [x] Heading accent border width (H2 left border)
204
+ - [x] Blockquote border width (left accent line)
205
+ - [x] Image border width (frame around images)
206
+ - [x] Link underline thickness
207
+ - [x] Table border width (grid lines)
208
+ - [x] Horizontal rule (HR) border width
209
+ - [x] **Single Source of Truth Architecture**:
210
+ - [x] All default values centralized in `CONFIG_PRESETS.default.config`
211
+ - [x] CSS variables dynamically applied via `applyConfigToDOM()`
212
+ - [x] Live preview with instant feedback on all changes
213
+ - [x] Bidirectional sync between UI controls and configuration
214
+ - [x] Frontmatter persistence (save/load all settings to markdown YAML)
215
+ - [x] **Developer Experience**:
216
+ - [x] Zero hardcoded values in CSS or JavaScript
217
+ - [x] Maintainable: change one config value, updates everywhere
218
+ - [x] Extensible: easy to add new styling properties
219
+ - [x] Type-safe: clear property structure with fallback values
220
+
221
+ ### Demo Files Created
222
+ - [x] `workspace/complete-syntax-demo.md` - 25 slides demonstrating all Markdown syntax patterns
223
+ - [x] `workspace/pagination-demo.md` - 20+ slides showing auto-pagination with various content lengths
224
+
225
+ ## Latest Updates (October 2025)
226
+
227
+ ### 10. Mode Isolation System (Exclusive Mode Switching)
228
+ **Problem Identified**: UI elements from different modes were overlapping and causing conflicts in display and functionality
229
+
230
+ **Solution** - Built a comprehensive exclusive mode switching system:
231
+
232
+ #### Mode Manager (`src/renderer/js/mode-manager.js`)
233
+ - [x] **Singleton Pattern**: Created `ModeManager` class with single instance for entire app
234
+ - [x] **3 Strictly Separated Modes**:
235
+ - **Intro Mode**: Initial screen with no systems active (static display only)
236
+ - **Presentation Mode**: Presentation mode with keyboard navigation + Smart Layout only
237
+ - **Editor Mode**: Edit mode with content editable + drag & drop + Safe Zone border only
238
+
239
+ #### Robust Control System
240
+ - [x] **System Flags Tracking**: Monitors active systems (smartLayout, dragDrop, contentEditable, safeZoneBorder, etc.)
241
+ - [x] **UI Visibility Control**:
242
+ - `hideAllModeUI()` - Hides all UI elements from all modes
243
+ - `showPresentationUI()` - Shows only navigation controls, exit button, fullscreen button, edit button
244
+ - `showEditorUI()` - Shows only save button, cancel button, exit button
245
+ - [x] **Smart Layout Management**:
246
+ - Intro Mode: `detach()` observers completely
247
+ - Presentation Mode: `reattach()` observers for auto-adjustment
248
+ - Editor Mode: `detach()` observers to prevent resizing during editing
249
+ - [x] **Mode Switching Flow**:
250
+ ```javascript
251
+ switchMode(newMode) {
252
+ 1. shutdownMode(currentMode) // Shutdown old mode completely
253
+ 2. currentMode = newMode // Change mode
254
+ 3. setDisplayMode(newMode) // Update config
255
+ 4. activateMode(newMode) // Activate new mode exclusively
256
+ 5. dispatch 'modeChanged' event
257
+ }
258
+ ```
259
+
260
+ #### Integration with Existing Systems
261
+ - [x] **app.js Integration**:
262
+ - `init()`: Calls `switchToIntroMode()` instead of `setDisplayMode('intro')`
263
+ - `startPresentationMode()`: Calls `switchToPresentationMode()`
264
+ - `exitPresentationMode()`: Calls `switchToIntroMode()`
265
+ - Removed all manual UI show/hide logic (Mode Manager handles it)
266
+
267
+ - [x] **slide-editor.js Integration**:
268
+ - `enterEditMode()`: Calls `switchToEditorMode()`
269
+ - `exitEditMode()`: Calls `switchToPresentationMode()`
270
+ - `enterDragMode()`: Calls `switchToEditorMode()`
271
+ - `exitDragMode()`: Calls `switchToPresentationMode()`
272
+ - Removed manual Smart Layout detach/reattach (Mode Manager handles it)
273
+ - Removed manual Safe Zone show/hide (Mode Manager handles it)
274
+
275
+ #### Smart Layout Protection
276
+ - [x] **Guard in `ensureContentWithinBounds()`**:
277
+ ```javascript
278
+ function ensureContentWithinBounds() {
279
+ const modeManager = getModeManager();
280
+ if (modeManager && !modeManager.isSystemActive('smartLayout')) {
281
+ return; // Don't execute if Smart Layout is disabled
282
+ }
283
+ // ... continue with calculations
284
+ }
285
+ ```
286
+
287
+ #### Results
288
+ - [x] **No UI Overlap**: Each mode shows only its relevant UI elements
289
+ - [x] **No Smart Layout Interference**: Auto-sizing only works in Presentation Mode
290
+ - [x] **Safe Edit Mode**: Editing works without interference from other systems
291
+ - [x] **Single Source of Control**: `ModeManager` is the only controller for all modes
292
+
293
+ #### Documentation and Maintenance
294
+ - [x] Created `docs/TH/MODE_ISOLATION_FIX.md` with detailed fix documentation
295
+ - [x] Added code comments indicating "Mode Manager handles this - no manual control needed"
296
+ - [x] Removed redundant code from app.js and slide-editor.js
297
+
298
+ ### Strict Separation of 3 Display Logic Systems
299
+
300
+ ### Complete Separation of Three Display Logic Systems
301
+ **Principle**: Each display mode has completely separate logic and Safe Zone systems to prevent modifications in one area from breaking others.
302
+
303
+ #### 1. Intro Scene System (Small Preview with UI Sidebar)
304
+ - [x] **Purpose**: Display slide previews in a small area of the UI page with side control panels
305
+ - [x] **Characteristics**:
306
+ - [x] Fixed screen size (1280x720 fallback)
307
+ - [x] Hard-coded Safe Zone optimized for small display area
308
+ - [x] No dynamic calculation needed due to fixed dimensions
309
+ - [x] **Core Functions** (marked LOCKED - do not modify):
310
+ - [x] `getStagePreviewData()` - Extract slide preview data
311
+ - [x] `renderStagePreview()` - Render preview to DOM
312
+ - [x] `updateStagePreview()` - Update preview when slides change
313
+ - [x] **Status**: Working perfectly - do not modify or link to other modes
314
+
315
+ #### 2. Presentation Mode - Small Screen (Normal Size Presentation)
316
+ - [x] **Purpose**: Presentation mode on standard screens (not fullscreen) at 1920x1080 or smaller
317
+ - [x] **Characteristics**:
318
+ - [x] Supports navigation with arrow keys (← →)
319
+ - [x] Ratio-based Safe Zone calculation for standard screens
320
+ - [x] Safe boundaries approximately 8-9% of width/height
321
+ - [x] **Color Zones**:
322
+ - [x] **Red Zone**: Area outside screen bounds - no content allowed
323
+ - [x] **Green Zone**: Safe area inside boundaries - content safe here
324
+ - [x] **Calculation**:
325
+ - [x] No hard-coded pixels
326
+ - [x] Calculated from actual screen size ratio
327
+ - [x] Formula: `safeInset = screenDimension × SAFE_ZONE_RATIO`
328
+
329
+ #### 3. Presentation Mode - Large Screen (Full Screen Large Display)
330
+ - [x] **Purpose**: Fullscreen mode on large screens (2560x1440+) or projectors
331
+ - [x] **Characteristics**:
332
+ - [x] Automatic fullscreen mode entry
333
+ - [x] Smart Layout Engine measures and optimizes content for available space
334
+ - [x] Wider Safe Zone to accommodate projector overscan
335
+ - [x] **Color Zones** (stricter than small screens):
336
+ - [x] **Red Zone**: Danger area 10-15% from edge - absolutely no content
337
+ - [x] **Yellow Zone**: Warning area 5-10% - content may be cut on some projectors
338
+ - [x] **Green Zone**: Safe area 80% center - content displays confidently
339
+ - [x] **Calculation**:
340
+ - [x] Dynamic calculation from actual screen size
341
+ - [x] Ratio adjusts based on screen type (normal/large/ultra)
342
+ - [x] Example formula:
343
+ ```
344
+ baseRatio = 0.08 (8%)
345
+ maxRatio = 0.16 (16%)
346
+ actualInset = clamp(screenSize × baseRatio, MIN_PIXELS, screenSize × maxRatio)
347
+ ```
348
+
349
+ ### Code Protection from Modifications
350
+ - [x] Added warning comments to all Intro Scene related functions
351
+ - [x] Used clear `@LOCKED` and `DO NOT MODIFY` tags
352
+ - [x] Separated comments into large blocks with border lines (==== lines)
353
+ - [x] Specified reasons and impacts of modifications in comments
354
+ - [x] No emojis in comments (may cause encoding issues)
355
+
356
+ ### Smart Layout and Safe Zone System
357
+ - [x] Separated Safe Zone constants for each mode
358
+ - [x] Intro Scene uses hard-coded constants
359
+ - [x] Presentation Mode will create separate calculation functions
360
+ - [ ] Create `computePresentationSafeZone()` for presentation mode
361
+ - [ ] Create `computeLargeScreenSafeZone()` for large screens
362
+ - [ ] Test Safe Zone calculations on multiple screen sizes
363
+
364
+ ## Outstanding Work
365
+
366
+ ### Smart Layout Engine
367
+ - [ ] **Integrate Auto-pagination with Smart Layout**:
368
+ - [ ] Use line calculation logic from `slide-paginator.js` with `ensureContentWithinBounds()`
369
+ - [ ] Make slides split automatically during actual rendering, not just parsing
370
+ - [ ] Calculate available space within Safe Zones before deciding to split pages
371
+ - [ ] Add `maxLinesPerSlide` configuration to presentation-config.js
372
+ - [ ] Rebuild `layout-schema.js` with a durable LayoutNode model and accurate per-section metrics aggregation
373
+ - [ ] Feed the layout tree into `renderSlideToStage` so DOM output follows block semantics instead of raw HTML
374
+ - [ ] Extend the measurement stage to consume layout tree data and refactor line/column calculations
375
+ - [ ] Add unit tests covering smart layout behaviours (observers, smart-list balancing, layout tree diffing)
376
+
377
+ ### Cross-module Coordination (Markdown → Layout → Renderer)
378
+ - [ ] Author a `layout-contract.md` document defining the shared JSON schema for slides/sections/blocks/inlines plus diagnostics
379
+ - [ ] Refine `markdown-syntax.js` so it exposes a single detection/tokenization API and stores the metadata the parser requires
380
+ - [ ] Update `markdown-parser.js` to consume that metadata and emit content items ready to map directly into layout blocks (e.g., link, inline emphasis)
381
+ - [ ] Extend `layout-schema.js` to cover additional block types (heading, link, rich inline text) with metrics the renderer can consume immediately
382
+ - [ ] Rework `app.js` to render purely from the layout tree, return measurement/diagnostic updates into the tree, and surface state changes to the UI
383
+ - [ ] Introduce a feedback loop (diagnostics channel) between measurement stage ↔ layout-schema ↔ markdown-parser so heuristics can adapt
384
+
385
+ ### Timeline & Metadata Model
386
+ - [ ] Extend markdown frontmatter for per-slide timing, transitions, narration cues, and media assets.
387
+ - [ ] Generate a shared timeline model (scenes, tracks, assets) for preview and export.
388
+ - [ ] Implement validation with actionable errors for missing or invalid metadata.
389
+
390
+ ### Presentation Settings System (Template Replacement) - COMPLETED
391
+ - [x] Replace template cards UI with configurable presentation presets powered by `presentation-config.js`
392
+ - [x] Round-trip presentation settings to markdown frontmatter (fonts, colors, animation choices)
393
+ - [x] Expose granular controls (font families, clamp ranges, backgrounds, borders, effects) with live preview updates
394
+ - [x] Update parser/exporter to consume presentation settings instead of legacy template identifiers
395
+ - [x] **Complete Word/Excel-style Document Formatting**:
396
+ - [x] 11 UI controls for styling properties (borders, effects, visual elements)
397
+ - [x] Typography controls (8 inputs for spacing, indentation, alignment)
398
+ - [x] Font size controls (9 inputs for H1, H2, Text with min/base/max)
399
+ - [x] Line height controls (2 inputs for heading and body)
400
+ - [x] All settings saved to frontmatter with `presentation.styles.*` namespace
401
+ - [x] Full English translation of all UI labels and preset descriptions
402
+
403
+ ### Phase 2: Enhanced Export (Next Priority)
404
+ - [x] Browser preview consumes timeline model flawlessly with full markdown rendering
405
+ - [ ] **Improve native WebM export quality**:
406
+ - [ ] Enhanced MediaRecorder API with frame-perfect timing control
407
+ - [ ] Quality/bitrate configuration options (target: 1080p at 5-10 Mbps)
408
+ - [ ] Progress reporting with per-slide render updates and percentage display
409
+ - [ ] Abort/cancel functionality for long renders
410
+ - [ ] Add a render job manager handling queueing, progress reporting, and cancellations
411
+ - [ ] Export progress modal with real-time preview thumbnails
412
+
413
+ ### Visual Enhancements
414
+ - [ ] Support slide-specific background images/videos with aspect-ratio aware cropping.
415
+ - [ ] Introduce a declarative animation DSL covering transitions, text motion, and keyframed positioning.
416
+ - [ ] **Build custom components** (no external libraries):
417
+ - Chart renderer using Canvas 2D API
418
+ - Syntax highlighter using regex tokenization
419
+ - Component registry for extensible markdown → visual mappings
420
+
421
+ ### Audio & Narration (Future)
422
+ - [ ] Support synchronized narration tracks sourced from audio files.
423
+ - [ ] **Mix audio using native Web Audio API**:
424
+ - Build custom ducking algorithm for background music
425
+ - Synchronize audio with video timeline
426
+ - No external audio processing libraries
427
+ - [ ] Add scenario tests validating audio/video sync quality.
428
+
429
+ ### Collaboration & Templates
430
+ - [ ] Ship selectable markdown + CSS template packs within the UI.
431
+ - [ ] Provide a shared asset workspace with versioned references.
432
+ - [ ] Define naming conventions and folder layout for video-safe media assets.
433
+
434
+ ## Phased Implementation Plan
435
+
436
+ ### Phase 1 – Timeline Core (COMPLETED)
437
+ - [x] Rebuild `app.js` to parse markdown and populate timeline UI
438
+ - [x] Extend `markdown-parser.js` with frontmatter and duration heuristics
439
+ - [x] Wire bidirectional template selection (UI ↔ frontmatter)
440
+ - [x] Surface validation diagnostics in Markdown tab
441
+ - [x] **BONUS**: Comprehensive Markdown Syntax Dictionary with 50+ patterns
442
+ - [x] **BONUS**: Auto-pagination system with visual line calculation
443
+ - [x] **BONUS**: Interactive preview controls (pause/resume, keyboard shortcuts)
444
+ - [x] **BONUS**: Enhanced timeline visualization with pagination indicators and line metrics
445
+ - [x] **BONUS**: Presentation mode with navigation controls and fullscreen support
446
+ - [x] **BONUS**: Application reset workflow and safeguarded smart layout safe zones
447
+ - [x] **BONUS**: Code editor themed styling plus advanced transitions/animations
448
+ - [x] **BONUS**: Template-free presentation configuration system with shareable presets
449
+ - [ ] Add unit tests for parsing, timing calculations, and error cases (deferred to Phase 2)
450
+
451
+ ### Phase 2 – Enhanced Video Export (Next Priority)
452
+ - [ ] Improve MediaRecorder-based WebM export quality and frame timing (target: 1080p @ 5-10 Mbps)
453
+ - [x] Implement native render progress tracking with per-slide updates and percentage display
454
+ - [x] Add resolution/FPS/quality controls synced to frontmatter
455
+ - [ ] Support abort/cancel during export with cleanup and partial file deletion
456
+ - [ ] Export progress modal with live thumbnail preview
457
+ - [ ] Unit tests for markdown-syntax.js, slide-paginator.js, pause/resume mechanism
458
+ - [ ] Create integration tests for sample deck → video output
459
+
460
+ #### Native OS Encoding Roadmap (Security-first, No Third-party Libraries)
461
+ - [ ] Design shared frame extraction pipeline (HTML → RGBA buffers/PNG frames) compatible with all native encoders
462
+ - [ ] Windows: implement a sealed Media Foundation bridge that writes H.264/AAC MP4 via sandboxed worker process
463
+ - [ ] macOS: build an AVFoundation exporter (AVAssetWriter) for H.264/AAC MP4 with strict file-path validation
464
+ - [ ] Linux: integrate system GStreamer/VA-API pipeline (`appsrc → x264enc → mp4mux`) executed under security-core supervision
465
+ - [ ] Add GIF output using the same native pipelines (MF Transform, AVFoundation ImageDestination, or GStreamer gifenc)
466
+ - [ ] Instrument security hooks (path allow-list, rate limits, checksum validation) for every native encoder invocation
467
+
468
+ ### Phase 3 – Audio Integration (Future)
469
+ - [ ] Parse narration file references from slide metadata
470
+ - [ ] Load and validate audio assets via secure IPC
471
+ - [ ] Mix narration + background music using Web Audio API
472
+ - [ ] Synchronize audio with video timeline during preview and export
473
+ - [ ] Add waveform visualization in Timeline tab
474
+
475
+ ### Phase 4 – Visual Enhancements (Future)
476
+ - [ ] Build custom chart renderer (Canvas-based, no libraries)
477
+ - [ ] Implement syntax highlighter using regex tokenization
478
+ - [ ] Support slide-specific background images/videos
479
+ - [ ] Create declarative animation DSL for keyframe-based transitions
480
+ - [ ] Add component registry for extensible markdown → visual mappings
481
+
482
+ ### Phase 5 – Stabilization & Polish (Future)
483
+ - [ ] Performance profiling and asset caching optimization
484
+ - [ ] Improve error messages with contextual fix suggestions
485
+ - [ ] Documentation refresh with video tutorials
486
+ - [ ] Ship sample markdown decks demonstrating all features
487
+
488
+ ## Architecture Impact
489
+ - **[x] Extended `src/shared/markdown-parser.js`**: Emits timeline JSON with scene metadata, durations, asset references, pagination info
490
+ - **[x] NEW `src/shared/markdown-syntax.js`**: Dictionary-based pattern library with 50+ regex patterns for all CommonMark + GFM syntax
491
+ - **[x] NEW `src/shared/slide-paginator.js`**: Visual line calculation and intelligent slide splitting with content-aware algorithms
492
+ - [ ] **New `src/shared/timeline-engine.js`**: Compose timeline model, calculate timecodes, manage playback state (future)
493
+ - **[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
494
+ - **[x] Enhanced `src/renderer/js/video-renderer.js`**: Canvas-based slide rendering with full markdown support (export ready, quality enhancement pending)
495
+ - **[x] Secure asset workspace**: Standardized `workspace/` folder with demo files and emoji-cleaner.js
496
+ - **[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
497
+ - **[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
498
+ - **[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
499
+
500
+ ## Current Technology Stack (Updated)
501
+ - **Electron 28.0.0**: Desktop application framework
502
+ - **MediaRecorder API**: Native WebM video encoding (VP8/VP9 codec)
503
+ - **Planned native encoders**: Windows Media Foundation, macOS AVFoundation, Linux GStreamer/VA-API (system-provided, no third-party libraries)
504
+ - **Canvas 2D API**: Slide rendering from HTML/CSS → Canvas with full markdown syntax support
505
+ - **Tailwind CSS (local - 407KB)**: UI styling loaded from `src/renderer/vendor/tailwind.js`
506
+ - **Web Audio API** (future): Native audio mixing and ducking
507
+ - **Custom Modules**:
508
+ - **MarkdownParser** (`src/shared/markdown-parser.js`) - Parser with frontmatter, duration heuristics, pagination integration
509
+ - **MarkdownSyntax** (`src/shared/markdown-syntax.js`) - Pattern dictionary with 50+ regex for CommonMark + GFM
510
+ - **SlidePaginator** (`src/shared/slide-paginator.js`) - Visual line calculation and intelligent splitting
511
+ - **VideoRenderer** (`src/renderer/js/video-renderer.js`) - Canvas-based slide rendering
512
+ - **PresentationConfig** (`src/renderer/js/presentation-config.js`) - Template-free configuration presets and runtime styling engine
513
+ - **SecurityCore** (`src/shared/security-core.js`) - Path validation and rate limiting for file operations
514
+
515
+ ## Quality Strategy
516
+ - [ ] Unit tests for `markdown-syntax.js` (pattern detection, inline parsing)
517
+ - [ ] Unit tests for `slide-paginator.js` (line calculation, splitting algorithms)
518
+ - [ ] Unit tests for `markdown-parser.js` (parsing, frontmatter, duration calculation, pagination integration)
519
+ - [ ] Integration tests for markdown → timeline → video workflow
520
+ - [ ] Snapshot tests for rendered HTML structures
521
+ - [ ] Manual QA checklist for export quality across resolutions/FPS
522
+ - [ ] Error handling validation (missing files, invalid frontmatter, etc.)
523
+ - [ ] Pause/resume mechanism tests (promise resolution, keyboard shortcuts)
524
+
525
+ ## Documentation & Adoption
526
+ - [x] **Produce bilingual guides**: Created 6 comprehensive documentation files
527
+ - [x] `MARKDOWN_SYNTAX.md` (EN/TH) - Complete syntax reference with examples
528
+ - [x] `AUTO_PAGINATION.md` (EN/TH) - Pagination system guide with algorithms
529
+ - [x] `PREVIEW_CONTROLS.md` (EN/TH) - Interactive controls usage guide
530
+ - [x] **Publish sample decks**: Created demo markdown files
531
+ - [x] `workspace/complete-syntax-demo.md` - 25 slides demonstrating all syntax patterns
532
+ - [x] `workspace/pagination-demo.md` - 20+ slides showing auto-pagination
533
+ - [ ] Schedule user testing sessions and collect feedback for iterative refinement
534
+ - [ ] Produce video tutorials for export workflows and troubleshooting
docs/EN/SECURITY.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ We release patches for security vulnerabilities. Which versions are eligible for receiving such patches depends on the CVSS v3.0 Rating:
6
+
7
+ | Version | Supported |
8
+ | ------- | ------------------ |
9
+ | 1.0.x | :white_check_mark: |
10
+ | < 1.0 | :x: |
11
+
12
+ ## Reporting a Vulnerability
13
+
14
+ **Please do not report security vulnerabilities through public GitHub issues.**
15
+
16
+ Instead, please report them via email to: **[INSERT SECURITY EMAIL]**
17
+
18
+ You should receive a response within 48 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
19
+
20
+ Please include the following information (as much as you can provide) to help us better understand the nature and scope of the possible issue:
21
+
22
+ * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
23
+ * Full paths of source file(s) related to the manifestation of the issue
24
+ * The location of the affected source code (tag/branch/commit or direct URL)
25
+ * Any special configuration required to reproduce the issue
26
+ * Step-by-step instructions to reproduce the issue
27
+ * Proof-of-concept or exploit code (if possible)
28
+ * Impact of the issue, including how an attacker might exploit the issue
29
+
30
+ This information will help us triage your report more quickly.
31
+
32
+ ## Preferred Languages
33
+
34
+ We prefer all communications to be in English or Thai.
35
+
36
+ ## Security Update Process
37
+
38
+ 1. **Report received** - We acknowledge receipt within 48 hours
39
+ 2. **Investigation** - We investigate and validate the vulnerability
40
+ 3. **Fix development** - We develop and test a fix
41
+ 4. **Security advisory** - We publish a security advisory if needed
42
+ 5. **Release** - We release a patched version
43
+ 6. **Disclosure** - We publicly disclose the vulnerability after the fix is released
44
+
45
+ ## Known Security Considerations
46
+
47
+ ### File System Access
48
+
49
+ This application requires file system access to:
50
+ - Read Markdown files
51
+ - Write exported video files
52
+ - Access workspace directory
53
+
54
+ **Mitigations:**
55
+ - All file operations go through `security-core.js` with path validation
56
+ - Rate limiting prevents abuse
57
+ - User consent required for file operations
58
+
59
+ ### Electron Security
60
+
61
+ We follow Electron security best practices:
62
+ - Context isolation enabled
63
+ - Node integration disabled in renderer
64
+ - Preload scripts for IPC communication
65
+ - Content Security Policy enforced
66
+
67
+ ### Third-Party Dependencies
68
+
69
+ We regularly:
70
+ - Update dependencies to latest secure versions
71
+ - Run `npm audit` to check for vulnerabilities
72
+ - Review dependency licenses and security advisories
73
+
74
+ ---
docs/TH/CHANGELOG.md ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # บันทึกการเปลี่ยนแปลง
2
+
3
+ การเปลี่ยนแปลงที่สำคัญทั้งหมดของโปรเจกต์นี้จะบันทึกไว้ในไฟล์นี้
4
+
5
+ รูปแบบอิงตาม [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
6
+ และโปรเจกต์นี้ปฏิบัติตาม [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+ - **Presentation Mode** - PowerPoint-style manual navigation
12
+ - Dedicated "Presentation Mode" button alongside main controls
13
+ - Forward/backward navigation buttons with left/right arrows
14
+ - Keyboard shortcuts: ← → for navigation, Space for next, Home/End for first/last, ESC to exit
15
+ - Live slide counter display (e.g., "1 / 15")
16
+ - Automatic button disable at first/last slide boundaries
17
+ - **Fullscreen Support** - True fullscreen presentation experience
18
+ - Fullscreen button in top-right corner during presentation
19
+ - F key toggle for quick fullscreen access
20
+ - Proper fullscreen styling (borderless, full viewport)
21
+ - Exit fullscreen on ESC or presentation mode exit
22
+ - **Enhanced Navigation Controls**
23
+ - Semi-transparent navigation overlay at bottom center
24
+ - Circular prev/next buttons with hover effects and glow
25
+ - Backdrop blur for better readability over slide content
26
+ - Z-index layering for proper overlay stacking
27
+ - **Application Reset Function**
28
+ - "Reset" button to return app to initial state
29
+ - Clears all markdown content, slides, and timeline
30
+ - Resets all settings to defaults (template, video config, theme)
31
+ - Confirmation dialog prevents accidental resets
32
+ - Automatically stops any active playback or presentation
33
+ - Restores default intro/outro content and timeline preview
34
+ - **Programmer's PowerPoint - Code Editor Themes**
35
+ - 4 new professional code editor themes: Monokai, Solarized, SynthWave '84, Dracula
36
+ - Full syntax highlighting with theme-specific colors (keyword, string, number, comment, function, variable)
37
+ - Enhanced content styles with gradient text, glows, and shadows
38
+ - Styled blockquotes with large quote marks and inset shadows
39
+ - Code blocks with top gradient borders and hover animations
40
+ - **Advanced Slide Transitions**
41
+ - **Glitch**: Digital glitch effect with random hue rotation
42
+ - **Matrix**: Digital rain simulation effect
43
+ - **Cube**: 3D cube rotation with perspective
44
+ - **Pixelate**: Blur-based pixelation transition
45
+ - **CSS Animations Library**
46
+ - Matrix scrolling background animation
47
+ - Glitch skew effect for digital aesthetics
48
+ - Pixelate in/out animations
49
+ - Code block hover glow effect
50
+ - Heading text pulsing glow
51
+
52
+ ### วางแผนไว้
53
+ - ปรับปรุงคุณภาพการเอ็กซ์พอร์ตวิดีโอ (1080p @ 5-10 Mbps)
54
+ - ติดตามความคืบหน้าการเอ็กซ์พอร์ตพร้อมอัปเดตต่อสไลด์
55
+ - การตั้งค่าความละเอียด/FPS/คุณภาพ
56
+ - ฟังก์ชันยกเลิก/หยุดสำหรับการเรนเดอร์ยาว
57
+ - Unit tests สำหรับโมดูลหลัก
58
+ - ตัวเรนเดอร์กราฟแบบกำหนดเอง (Canvas-based)
59
+ - Syntax highlighter ใช้ regex tokenization
60
+ - การผสานเสียงด้วย Web Audio API
61
+
62
+ ---
63
+
64
+ # บันทึกการเปลี่ยนแปลง (ต่อ - ภาษาไทย)
65
+
66
+ ## [Unreleased]
67
+
68
+ ### เพิ่ม
69
+ - **โหมดนำเสนอ (Presentation Mode)** - การนำทางแบบกำหนดเองเหมือน PowerPoint
70
+ - ปุ่ม "Presentation Mode" เฉพาะข้างปุ่มควบคุมหลัก
71
+ - ปุ่มนำทางเดินหน้า/ถอยหลังพร้อมลูกศรซ้าย/ขวา
72
+ - ปุ่มลัด: ← → สำหรับนำทาง, Space สำหรับถัดไป, Home/End สำหรับแรก/สุดท้าย, ESC เพื่อออก
73
+ - แสดงตัวนับสไลด์แบบสด (เช่น "1 / 15")
74
+ - ปิดการใช้งานปุ่มอัตโนมัติที่ขอบเขตสไลด์แรก/สุดท้าย
75
+ - **รองรับเต็มจอ (Fullscreen)** - ประสบการณ์นำเสนอแบบเต็มจอจริง
76
+ - ปุ่มเต็มจอที่มุมบนขวาขณะนำเสนอ
77
+ - กด F สลับเข้าเต็มจอได้ทันที
78
+ - สไตล์เต็มจอที่เหมาะสม (ไร้กรอบ, viewport เต็ม)
79
+ - ออกจากเต็มจอเมื่อกด ESC หรือออกจากโหมดนำเสนอ
80
+ - **ควบคุมนำทางที่ปรับปรุง**
81
+ - Overlay นำทางกึ่งโปร่งใสที่ด้านล่างกลาง
82
+ - ปุ่มวงกลม prev/next พร้อม hover effects และแสง
83
+ - Backdrop blur เพื่อการอ่านที่ดีขึ้นเหนือเนื้อหาสไลด์
84
+ - การจัดเรียง Z-index สำหรับ overlay stacking ที่เหมาะสม
85
+ - **ฟังก์ชันรีเซ็ตแอปพลิเคชัน**
86
+ - ปุ่ม "Reset" เพื่อนำแอปกลับสู่สถานะเริ่มต้น
87
+ - ล้างเนื้อหา markdown, สไลด์ และไทม์ไลน์ทั้งหมด
88
+ - รีเซ็ตการตั้งค่าทั้งหมดเป็นค่าเริ่มต้น (template, video config, theme)
89
+ - กล่องยืนยันป้องกันการรีเซ็ตโดยไม่ตั้งใจ
90
+ - หยุดการเล่นหรือนำเสนอที่ใช้งานอยู่อัตโนมัติ
91
+ - คืนค่าเนื้อหา intro/outro และพรีวิวไทม์ไลน์เริ่มต้น
92
+ - **PowerPoint สำหรับโปรแกรมเมอร์ - Code Editor Themes**
93
+ - เทมเพลต code editor 4 แบบใหม่: Monokai, Solarized, SynthWave '84, Dracula
94
+ - Syntax highlighting เต็มรูปแบบพร้อมสีเฉพาะ theme (keyword, string, number, comment, function, variable)
95
+ - Content styles ที่ปรับปรุงพร้อม gradient text, เรือง และเงา
96
+ - Blockquotes มีสไตล์พร้อมเครื่องหมายคำพูดขนาดใหญ่และ inset shadows
97
+ - Code blocks พร้อม gradient borders ด้านบนและแอนิเมชัน hover
98
+ - **Slide Transitions ขั้นสูง**
99
+ - **Glitch**: เอฟเฟกต์ glitch แบบดิจิทัลพร้อม hue rotation แบบสุ่ม
100
+ - **Matrix**: เอฟเฟกต์จำลอง digital rain
101
+ - **Cube**: การหมุนแบบ cube 3D พร้อม perspective
102
+ - **Pixelate**: Transition แบบ pixelation ใช้ blur
103
+ - **ไลบรารี CSS Animations**
104
+ - แอนิเมชันพื้นหลัง Matrix scrolling
105
+ - เอฟเฟกต์ glitch skew สำหรับสุนทรียศาสตร์ดิจิทัล
106
+ - แอนิเมชัน pixelate in/out
107
+ - เอฟเฟกต์เรืองแสงพร้อม hover ของ code block
108
+ - เอฟเฟกต์เรืองแสง pulsing ของ heading text
109
+
110
+ ## [1.0.0] - 2025-10-20
111
+
112
+ ### เพิ่ม
113
+
114
+ #### ฟีเจอร์หลัก
115
+ - **Markdown Parser** พร้อมรองรับ CommonMark + GFM เต็มรูปแบบ
116
+ - รูปแบบ regex 50+ แบบสำหรับการจดจำ syntax อย่างครอบคลุม
117
+ - การแยก YAML frontmatter สำหรับการตั้งค่า
118
+ - Heuristics การคำนวณระยะเวลา
119
+ - การแยกการอ้างอิง asset
120
+
121
+ - **ระบบแบ่งหน้าอัตโนมัติ**
122
+ - การคำนวณบรรทัดแบบ visual พร้อมน้ำหนักเฉพาะเนื้อหา
123
+ - การแบ่งสไลด์อัจฉริยะ (สูงสุด 6 บรรทัดต่อสไลด์)
124
+ - การแบ่งบล็อกอัจฉริยะสำหรับ code, tables, blockquotes
125
+ - อัลกอริทึมกระจายหน้าแบบสมดุล
126
+ - เครื่องหมายต่อเนื่องสำหรับเนื้อหาที่แบ่ง
127
+
128
+ - **การควบคุมพรีวิวแบบโต้ตอบ**
129
+ - คลิกที่ใดก็ได้เพื่อหยุด/เล่นต่อ
130
+ - ปุ่มลัด: Space, P (หยุด/เล่นต่อ), ESC (หยุด)
131
+ - กลไกการรอแบบ promise-based
132
+ - Overlay หยุดด้วยคำแนะนำ
133
+
134
+ - **รองรับ Markdown Syntax เต็มรูปแบบ**
135
+ - ATX headings (# ถึง ######)
136
+ - Setext headings (ขีดเส้นใต้)
137
+ - ตัวหนา, ตัวเอียง, ขีดฆ่า
138
+ - โค้ดบล็อกแบบ inline และ fenced
139
+ - รายการไม่มีลำดับ (-, *, +)
140
+ - รา��การมีลำดับและ task lists
141
+ - ลิงก์และรูปภาพ
142
+ - Blockquotes
143
+ - ตาราง (GFM)
144
+ - เส้นแนวนอน
145
+ - บล็อก HTML แบบ inline
146
+
147
+ ### เปลี่ยนแปลง
148
+ - ลด `maxLinesPerSlide` จาก 8 เป็น 6 เพื่อให้อ่านง่ายขึ้น
149
+ - อัปเดตน้ำหนักบรรทัดแบบ visual:
150
+ - H1: 2.5 บรรทัด (เดิม 2)
151
+ - H2: 2 บรรทัด (เดิม 1.5)
152
+ - Lists: 1.2 บรรทัด (เดิม 1)
153
+ - Code: 1 บรรทัดต่อบรรทัด (เดิม 0.8)
154
+ - Images: 4 บรรทัด (เดิม 3)
155
+ - HTML: 3 บรรทัด (เดิม 2)
156
+ - Tables: 2.5 + rows×0.8 (เดิม 2 + rows×0.5)
157
+
158
+ ### แก้ไข
159
+ - ปัญหาสไลด์ล้นจอกับเนื้อหายาว
160
+ - ความแม่นยำการแบ่ง code block
161
+ - การแบ่งหน้าตารางพร้อม headers
162
+ - เครื่องหมายต่อเนื่อง blockquote
163
+
164
+ ### ความปลอดภัย
165
+ - ใช้งานการตรวจสอบ file path
166
+ - เพิ่ม rate limiting สำหรับการดำเนินการไฟล์
167
+ - เปิดใช้งานแนวทางปฏิบัติที่ดีที่สุดด้านความปลอดภัยของ Electron
168
+ - ปิด Node integration ใน renderer process
169
+
170
+ [Unreleased]: https://github.com/chahuadev/chahuadev-markdown-presenter/compare/v1.0.0...HEAD
171
+ [1.0.0]: https://github.com/chahuadev/chahuadev-markdown-presenter/releases/tag/v1.0.0
docs/TH/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ความคิดเห็น คอมมิต โค้ด การแก้ไข wiki ปัญหา และการมีส่วนร่วมอื่นๆ
45
+ ที่ไม่สอดคล้องกับจรรยาบรรณนี้ และจะสื่อสารเหตุผลใ��การตัดสินใจดูแล
46
+ เมื่อเหมาะสม
47
+
48
+ ## การบังคับใช้
49
+
50
+ กรณีพฤติกรรมที่ไม่เหมาะสมสามารถรายงานไปยังผู้นำชุมชนที่รับผิดชอบการบังคับใช้ที่
51
+ [INSERT CONTACT EMAIL]
52
+
53
+ ข้อร้องเรียนทั้งหมดจะได้รับการตรวจสอบและสอบสวนอย่างรวดเร็วและยุติธรรม
54
+
55
+ ผู้นำชุมชนทั้งหมดมีหน้าที่เคารพความเป็นส่วนตัวและความปลอดภัย
56
+ ของผู้รายงานเหตุการณ์ใดๆ
57
+
58
+ ## การระบุแหล่งที่มา
59
+
60
+ จรรยาบรรณนี้ดัดแปลงมาจาก [Contributor Covenant][homepage]
61
+ เวอร์ชัน 2.1 มีอยู่ที่
62
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]
63
+
64
+ [homepage]: https://www.contributor-covenant.org
65
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
docs/TH/CONTRIBUTING.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Thai
2
+
3
+ ### จรรยาบรรณ
4
+
5
+ โปรเจกต์นี้และทุกคนที่เข้าร่วมอยู่ภายใต้ [จรรยาบรรณ](CODE_OF_CONDUCT.md) ของเรา การเข้าร่วมหมายความว่าคุณยอมรับจรรยาบรรณนี้
6
+
7
+ ### ฉันสามารถมีส่วนร่วมได้อย่างไร?
8
+
9
+ #### รายงานบั๊ก
10
+
11
+ ก่อนสร้างรายงานบั๊ก โปรดตรวจสอบ [issues ที่มีอยู่](https://github.com/chahuadev/chahuadev-markdown-presenter/issues) เพื่อหลีกเลี่ยงการซ้ำซ้อน
12
+
13
+ **เมื่อสร้างรายงานบั๊ก โปรดระบุ:**
14
+
15
+ - **หัวข้อและคำอธิบายที่ชัดเจน**
16
+ - **ขั้นตอนการทำซ้ำ** ปัญหา
17
+ - **พฤติกรรมที่คาดหวัง** กับ **พฤติกรรมจริง**
18
+ - **ภาพหน้าจอ** ถ้ามี
19
+ - **รายละเอียดสภาพแวดล้อม**:
20
+ - เวอร์ชัน OS (Windows/macOS/Linux)
21
+ - เวอร์ชัน Node.js (`node --version`)
22
+ - เวอร์ชัน Electron
23
+ - เวอร์ชันแอปพลิเคชัน
24
+
25
+ #### แนะนำการปรับปรุง
26
+
27
+ การแนะนำการปรับปรุงจะถูกติดตามเป็น GitHub issues เมื่อสร้างข้อเสนอแนะ:
28
+
29
+ - **ใช้หัวข้อที่ชัดเจนและอธิบายได้**
30
+ - **ให้คำอธิบายโดยละเอียด** ของการปรับปรุงที่แนะนำ
31
+ - **อธิบายว่าทำไมการปรับปรุงนี้มีประโยชน์**
32
+ - **แสดงทางเลือกอื่น** ที่คุณพิจารณา
33
+
34
+ #### Pull Requests
35
+
36
+ **กระบวนการ:**
37
+
38
+ 1. **Fork** repository
39
+ 2. **สร้าง branch** จาก `main`:
40
+ ```bash
41
+ git checkout -b feature/ชื่อฟีเจอร์ของคุณ
42
+ ```
43
+ 3. **ทำการเปลี่ยนแปลง** พร้อม commit messages ที่ชัดเจน
44
+ 4. **ทดสอบอย่างละเอียด** - ตรวจสอบว่าฟังก์ชันทั้งหมดทำงาน
45
+ 5. **อัปเดตเอกสาร** ถ้าจำเป็น
46
+ 6. **ส่ง pull request** พร้อม:
47
+ - คำอธิบายการเปลี่ยนแปลงที่ชัดเจน
48
+ - อ้างอิงถึง issues ที่เกี่ยวข้อง
49
+ - ภาพหน้าจอ/GIFs สำหรับการเปลี่ยนแปลง UI
50
+
51
+ **แนวทาง Commit Message:**
52
+
53
+ ```
54
+ type(scope): เรื่อง
55
+
56
+ เนื้อหา (ถ้ามี)
57
+
58
+ footer (ถ้ามี)
59
+ ```
60
+
61
+ **ประเภท:**
62
+ - `feat`: ฟีเจอร์ใหม่
63
+ - `fix`: แก้บั๊ก
64
+ - `docs`: เปลี่ยนแปลงเอกสาร
65
+ - `style`: เปลี่ยนสไตล์โค้ด (formatting, semicolons, ฯลฯ)
66
+ - `refactor`: รีแฟกเตอร์โค้ด
67
+ - `test`: เพิ่มหรืออัปเดตเทสต์
68
+ - `chore`: งานบำรุงรักษา
69
+
70
+ ### การตั้งค่าการพัฒนา
71
+
72
+ #### ความต้องการเบื้องต้น
73
+
74
+ - Node.js 18.0.0+
75
+ - npm 8.0.0+
76
+ - Git
77
+
78
+ #### เริ่มต้น
79
+
80
+ ```bash
81
+ # โคลน fork ของคุณ
82
+ git clone https://github.com/YOUR_USERNAME/chahuadev-markdown-presenter.git
83
+
84
+ # เข้าไปในโฟลเดอร์
85
+ cd chahuadev-markdown-presenter
86
+
87
+ # เพิ่ม upstream remote
88
+ git remote add upstream https://github.com/chahuadev/chahuadev-markdown-presenter.git
89
+
90
+ # ติดตั้ง dependencies
91
+ npm install
92
+
93
+ # เริ่มพัฒนา
94
+ npm start
95
+ ```
96
+
97
+ ### มาตรฐานการเขียนโค้ด
98
+
99
+ #### JavaScript Style
100
+
101
+ - ใช้ **คุณสมบัติ ES6+** (const/let, arrow functions, template literals)
102
+ - ใช้ **ES Modules** (`import`/`export`)
103
+ - **2 spaces** สำหรับ indentation
104
+ - **Semicolons** จำเป็น
105
+ - **Single quotes** สำหรับ strings (ยกเว้น template literals)
106
+
107
+ ### การทดสอบ
108
+
109
+ ```bash
110
+ # รันเทสต์ (เมื่อถูกสร้าง)
111
+ npm test
112
+
113
+ # รัน linter
114
+ npm run lint
115
+ ```
116
+
117
+ ### เอกสาร
118
+
119
+ เมื่อเพิ่มฟีเจอร์ใหม่:
120
+
121
+ 1. **อัปเดตเอกสารที่เกี่ยวข้อง** ใน `docs/`
122
+ 2. **เพิ่มตัวอย่าง** เพื่อแสดงการใช้งาน
123
+ 3. **อัปเดต README.md** ถ้ามีการเปลี่ยนแปลงที่ผู้ใช้เห็น
124
+ 4. **เขียนเอกสารสองภาษา** (EN + TH) เมื่อเป็นไปได้
125
+
126
+ ### มีคำถาม?
127
+
128
+ - เปิด issue พร้อมป้ายกำกับ `question`
129
+ - เข้าร่วมการสนทนาใน issues ที่มีอยู่
130
+ - ตรวจสอบ [เอกสาร](docs/) ก่อน
131
+
132
+ ---
133
+
134
+ Thank you for contributing! 🎉
135
+ ขอบคุณสำหรับการมีส่วนร่วม! 🎉
docs/TH/LICENSE ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ใบอนุญาต MIT
2
+
3
+ ลิขสิทธิ์ (c) 2025 บริษัท ชาฮัว ดีเวลลอปเมนท์ จำกัด
4
+
5
+ อนุญาตให้บุคคลใดก็ตามที่ได้รับสำเนาซอฟต์แวร์นี้และไฟล์เอกสารประกอบที่เกี่ยวข้อง ("ซอฟต์แวร์")
6
+ ใช้งานซอฟต์แวร์นี้ได้โดยไม่มีค่าใช้จ่ายใดๆ รวมถึงแต่ไม่จำกัดเพียงสิทธิ์ในการใช้
7
+ คัดลอก แก้ไข ผสาน เผยแพร่ แจกจ่าย อนุญาตให้ใช้สิทธิ์ช่วง และ/หรือขายสำเนาซอฟต์แวร์
8
+ และอนุญาตให้บุคคลที่ได้รับซอฟต์แวร์นี้ดำเนินการดังกล่าวได้ ภายใต้เงื่อนไขดังต่อไปนี้:
9
+
10
+ ประกาศลิขสิทธิ์ข้างต้นและประกาศการอนุญาตนี้จะรวมอยู่ในสำเนาหรือส่วนสำคัญของซอฟต์แวร์ทั้งหมด
11
+
12
+ ซอฟต์แวร์นี้ให้บริการ "ตามสภาพ" โดยไม่มีการรับประกันใดๆ ทั้งสิ้น ไม่ว่าโดยชัดแจ้งหรือโดยนัย
13
+ รวมถึงแต่ไม่จำกัดเพียงการรับประกันความสามารถในการขาย ความเหมาะสมสำหรับวัตถุประสงค์เฉพาะ
14
+ และการไม่ละเมิดสิทธิ์ ไม่ว่าในกรณีใด ผู้เขียนหรือผู้ถือลิขสิทธิ์จะไม่รับผิดชอบต่อการเรียกร้อง ความเสียหาย
15
+ หรือความรับผิดอื่นใด ไม่ว่าจะเป็นการฟ้องร้องตามสัญญา การละเมิด หรืออื่นใด ที่เกิดขึ้นจาก
16
+ จาก หรือเกี่ยวข้องกับซอฟต์แวร์ หรือการใช้งานหรือการดำเนินการอื่นใดใน
17
+ ซอฟต์แวร์
docs/TH/MARKDOWN_VIDEO_PLAN.md ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # แผนพัฒนา Markdown-to-Video
2
+
3
+ ## วิสัยทัศน์
4
+ - **Markdown-to-Video Generator**: เขียน Markdown แล้วเอ็กซ์พอร์ตเป็นวิดีโอ—ใช้เทคโนโลยีเว็บดั้งเดิมทั้งหมด
5
+ - **Markdown ควบคุมทุกอย่าง**: เนื้อหา เวลา ทรานซิชัน เทมเพลต และสไตล์ภาพกำหนดทั้งหมดในไฟล์ `.md`
6
+ - **สถาปัตยกรรมแบบครบวงจร**: สร้างบน Electron + Web APIs ดั้งเดิม (Canvas, MediaRecorder, Web Audio, File System)
7
+
8
+ ## หลักการหลัก: Markdown คือแหล่งต้นทางวิดีโอ
9
+ - **อินพุต**: ไฟล์ Markdown พร้อม YAML frontmatter สำหรับการตั้งค่าวิดีโอ
10
+ - **ตัวแยกส่วน**: `MarkdownParser` แยกสไลด์ ข้อมูลเมทา และอ้างอิงแอสเซ็ต
11
+ - **ตัวเรนเดอร์**: ตัวประกอบสไลด์บน Canvas จาก HTML/CSS → Canvas 2D API
12
+ - **ตัวเข้ารหัส**: MediaRecorder API สร้างสตรีมวิดีโอ WebM (ปัจจุบัน) พร้อมแผนใช้ตัวเข้ารหัสระดับระบบปฏิบัติการ (Media Foundation, AVFoundation, GStreamer) เพื่อสร้าง MP4/GIF โดยไม่พึ่งไลบรารีภายนอก
13
+ - **ตัวเอ็กซ์พอร์ต**: บันทึกไฟล์ผ่าน IPC bridge ที่มีการตรวจสอบความปลอดภัย
14
+
15
+ ## หลักการชี้นำ
16
+ - **Workflow แบบ Markdown-first**: การเขียนเด็ค พรีวิวไทม์ไลน์ และเอ็กซ์พอร์ตวิดีโอขับเคลื่อนด้วยไฟล์ `.md`
17
+ - **ใช้ Native APIs เท่านั้น**: MediaRecorder (เข้ารหัสวิดีโอ), Canvas 2D (เรนเดอร์), Web Audio (ผสมเสียงในอนาคต)
18
+ - **พรีวิว = เอ็กซ์พอร์ต**: ไทม์ไลน์เอ็นจินเดียวกันขับเคลื่อนทั้งพรีวิวสดและเอาต์พุตสุดท้าย
19
+ - **ความปลอดภัยสำคัญ**: การเข้าถึงไฟล์ทั้งหมดผ่าน `security-core.js` พร้อมตรวจสอบ path และจำกัดอัตรา
20
+ - **ใช้งานได้ทันที**: ค่าเริ่มต้นที่เหมาะสมพร้อม preset การนำเสนอที่ปรับแต่ง/แชร์ผ่าน frontmatter ได้
21
+
22
+ ## งานที่ทำแล้ว
23
+ - [x] ระบบแปลง Markdown → HTML สำหรับ renderer ของ Electron
24
+ - [x] เทมเพลตพื้นฐาน การสลับธีม และพรีวิวแบบเรียลไทม์
25
+ - [x] ออกแบบโครงสร้างโปรเจกต์รองรับการแยก main/renderer/shared
26
+ - [x] รีแฟกเตอร์ UI renderer (`src/renderer/index.html`) ให้เป็น workflow แบบ Markdown-first พร้อมแท็บ Templates
27
+ - [x] **พจนานุกรม Markdown Syntax ครบถ้วน** (`markdown-syntax.js`) - รองรับ 50+ รูปแบบ CommonMark + GFM
28
+ - [x] **ระบบแบ่งหน้าอัตโนมัติ** (`slide-paginator.js`) - แบ่งสไลด์อัจฉริยะตามจำนวนบรรทัดแสดงผล (สูงสุด 6 บรรทัด/สไลด์)
29
+ - [x] **ควบคุมพรีวิวแบบโต้ตอบ** - หยุด/เล่นต่อด้วยคลิก, ปุ่ม Space, P, ESC
30
+ - [x] **ธีมสีน้ำเงินเข้ม** - UI ครบชุดสีที่สอดคล้องกัน (พื้นหลัง #0a1628, หลัก #3b82f6)
31
+
32
+ ## เฟส 1: ฟังก์ชันหลัก ([x] เสร็จสมบูรณ์)
33
+
34
+ ### งานหลักที่เสร็จแล้ว
35
+ - [x] **เขียน `src/renderer/js/app.js` ใหม่** – Controller ครบถ้วน:
36
+ - [x] แยก markdown ผ่าน `MarkdownParser` เมื่อคลิก "Sync Markdown"
37
+ - [x] แยก frontmatter (template, video.*, theme.accent) และเนื้อหา
38
+ - [x] สร้างอาร์เรย์สไลด์พร้อ��คำนวณเวลาอัตโนมัติตามความหนาแน่นเนื้อหา
39
+ - [x] เติมข้อมูลแท็บ Timeline พร้อมเวลาต่อสไลด์, ตัวบ่งชี้หน้า, จำนวนบรรทัด, ระยะเวลา
40
+ - [x] อัปเดตการเรนเดอร์พรีวิวเวทีพร้อมรองรับ markdown syntax เต็มรูปแบบ
41
+ - [x] ใช้เทมเพลตและสีที่เลือกกับตัวแปร CSS
42
+ - [x] เปิดใช้งาน Preview Timeline พร้อมควบคุมหยุด/เล่นต่อ (คลิก, Space, P, ESC)
43
+ - [x] รองรับเนื้อหา 15+ ประเภท (H1-H6, lists, tables, blockquotes, code, HTML, ฯลฯ)
44
+ - [x] เครื่องหมายต่อเนื่องสำหรับสไลด์ที่แบ่ง ("↪ continued", "continues →")
45
+ - [x] ตัวบ่งชี้หน้าที่มุมบนขวาของสไลด์
46
+
47
+ - [x] **ขยาย `src/shared/markdown-parser.js`** เพื่อ:
48
+ - [x] ปล่อยข้อมูลเมทาระดับฉาก รวมถึง index, title, subtitle, และ content items
49
+ - [x] คำนวณระยะเวลาต่อสไลด์ใช้ heuristics (H1=2s, list=1s แต่ละรายการ, text=0.3s ต่อคำ, code=0.5s ต่อบรรทัด)
50
+ - [x] รองรับการแยก frontmatter สำหรับ template ID, video settings, และข้อมูลเมทากำหนดเอง
51
+ - [x] ส่งคืนการอ้างอิง asset (ภาพจาก `![alt](src)`) สำหรับตรวจสอบ checklist
52
+ - [x] มีเมธอด `getSummary()` ส่งคืน totalSlides, paginatedSlides, estimatedDuration, และ titles
53
+ - [x] **ใหม่: ผสานกับพจนานุกรม MarkdownSyntax** สำหรับจดจำรูปแบบอย่างครอบคลุม
54
+ - [x] **ใหม่: รองรับแบ่งหน้าอัตโนมัติ** พร้อมตัวเลือก `enablePagination` และ `maxLinesPerSlide`
55
+ - [x] **ใหม่: ติดตามบรรทัดแบบ visual** - สไลด์มี properties `visualLines`, `totalPages`, `pageNumber`
56
+
57
+ - [x] **ผูกการเลือกเทมเพลตแบบสองทาง**:
58
+ - [x] คลิกการ์ดเทมเพลตในแท็บ Templates อัปเดต `state.template`
59
+ - [x] Upsert `template: <id>` เข้า frontmatter ผ่าน `upsertFrontmatterValue()`
60
+ - [x] เรียก `syncMarkdown()` เพื่อรีเฟรช timeline และใช้ CSS เทมเพลตใหม่
61
+ - [x] แสดงชื่อเทมเพลตที่ใช้งานในฉลาก "Active template:"
62
+
63
+ - [x] **แสดงการวินิจฉัยความถูกต้อง**:
64
+ - [x] แสดง/ซ่อนแผง `markdownDiagnostics` ตามความสำเร็จ/ล้มเหลวของการแยกส่วน
65
+ - [x] แสดงข้อความผิดพลาดที่เป็นมิตร (เช่น "ไม่มี frontmatter delimiter ปิด", "โครงสร้างสไลด์ไม่ถูกต้อง")
66
+ - [x] เน้นสถานะยังไม่ซิงก์เมื่อเนื้อหาเอดิเตอร์เปลี่ยนก่อนซิงก์ครั้งต่อไป
67
+ - [x] ล้างการวินิจฉัยอัตโนมัติเมื่อซิงก์สำเร็จ
68
+
69
+ ### ฟีเจอร์ใหม่ที่เสร็จนอกเหนือจากแผนเดิม
70
+
71
+ #### 1. พจนานุกรม Markdown Syntax ครบถ้วน (`src/shared/markdown-syntax.js`)
72
+ - [x] **รูปแบบ regex 50+ แบบ** ครอบคลุม CommonMark + GitHub Flavored Markdown
73
+ - [x] **Block-level syntax**: ATX headings (# ถึง ######), Setext headings (ขีดเส้นใต้), unordered lists (-, *, +), ordered lists, task lists, code blocks (fenced และ indented), tables, blockquotes, horizontal rules, HTML blocks
74
+ - [x] **Inline syntax**: bold (**text**), italic (*text*), strikethrough (~~text~~), inline code (`code`), links, images
75
+ - [x] **Special syntax**: YAML frontmatter, footnotes, math blocks (LaTeX)
76
+ - [x] **API**: เมธอด `detectBlockType(line, nextLine)` และ `parseInline(text)`
77
+ - [x] **เอกสาร**: `MARKDOWN_SYNTAX.md` (EN/TH) พร้อมคู่มือ syntax ครบถ้วน
78
+
79
+ #### 2. ระบบแบ่งหน้าอัตโนมัติ (`src/shared/slide-paginator.js`)
80
+ **สถานะ**: **ต้องผสานเข้า Presentation Rendering** - ตอนนี้แยกออกมาต่างหาก ยังไม่ได้ใช้งานจริง
81
+
82
+ - [x] **การคำนวณบรรทัดแบบ visual** พร้อมน้ำหนักเฉพาะเนื้อหา:
83
+ - H1 = 2.5 บรรทัด, H2 = 2 บรรทัด, H3-H6 = 1.5-1 บรรทัด
84
+ - List/blockquote items = 1.2 บรรทัดต่อรายการ
85
+ - Code blocks = 1 บรรทัดต่อบรรทัด (อ่านง่ายขึ้น)
86
+ - Tables = 2.5 (header) + rows × 0.8
87
+ - Images = 4 บรรทัด, HTML = 3 บรรทัด
88
+ - [x] **อัลกอริทึมแบ่งอัจฉริยะ**:
89
+ - กระจายหน้าแบบสมดุล (threshold 30%)
90
+ - แบ่งบล็อกอัจฉริยะสำหรับ code, tables, blockquotes
91
+ - บล็อกแบบ atomic (images, HTML, HR) ไม่แบ่ง
92
+ - เครื่องหมายต่อเนื่องเพิ่มอัตโนมัติ
93
+ - [x] **API**: `applyPagination(slides, config)` ส่งคืนอาร์เรย์สไลด์ที่แบ่งหน้าแล้ว
94
+ - [x] **เอกสาร**: `AUTO_PAGINATION.md` (EN/TH) พร้อมตัวอย่างและรายละเอียดอัลกอริทึม
95
+
96
+ **งานที่ต้องทำ**:
97
+ - [ ] **ผสานเข้า Smart Layout Engine**: ใช้ logic การคำนวณบรรทัดร่วมกับ `ensureContentWithinBounds()`
98
+ - [ ] **ผสานเข้า Slide Renderer**: ทำให้สไลด์แบ่งอัตโนมัติตอน render จริง ไม่ใช่แค่ตอน parse
99
+ - [ ] **ตั้งค่าผ่าน Presentation Config**: เพิ่ม `maxLinesPerSlide` ลงใน presentation settings
100
+ - [ ] **ใช้กับ Safe Zone**: คำนวณพื้นที่ว่างจริงก่อนแบ่งสไลด์
101
+
102
+ #### 3. ควบคุมพรีวิวแบบโต้ตอบ
103
+ - [x] **กลไกหยุด/เล่นต่อ**:
104
+ - คลิกที่ใดก็ได้บนเวทีพรีวิวเพื่อหยุด/เล่นต่อ (โหมดพรีวิวเท่านั้น)
105
+ - ปุ่มลัด: Space หรือ P สลับ, ESC หยุดพรีวิว
106
+ - การรอแบบ promise-based พร้อม polling 100ms เพื่อตอบสนองทันที
107
+ - [x] **ฟีดแบ็กภาพ**:
108
+ - Overlay หยุดพร้อม backdrop กึ่งโปร่งใส (blur 8px)
109
+ - ไอคอนหยุดขนาดใหญ่ ⏸ พร้อมแอนิเมชัน pulse
110
+ - คำแนะนำ: ข้อความ "Paused" + คำใบ้ปุ่มลัด
111
+ - Z-index 1000 เพื่อแสดงบนสุดเสมอ
112
+ - [x] **การจัดการสถานะ**:
113
+ - แฟล็ก boolean `isPaused`
114
+ - ฟังก์ชันอ้างอิง `pauseResolve` สำหรับ promise resolution
115
+ - ทำความสะอาดเมื่อหยุดพรีวิว
116
+ - [x] **เอกสาร**: `PREVIEW_CONTROLS.md` (EN/TH) พร้อมคู่มือการใช้งาน
117
+
118
+ #### 4. โหมดนำเสนอ (Presentation Mode) แบบ PowerPoint
119
+ - [x] **การนำทางสไลด์แบบกำหนดเอง** พร้อมควบคุมเดินหน้า/ถอยหลัง:
120
+ - ปุ่ม "Presentation Mode" ข้างปุ่มควบคุมหลัก
121
+ - ปุ่มลูกศร ← → สำหรับนำทางไปข้างหน้า/ข้างหลัง
122
+ - ปุ่มลัด: ← → สำหรับ prev/next, Space สำหรับ next, Home/End สำหรับ first/last
123
+ - แสดงตัวนับสไลด์ (เช่น "1 / 15")
124
+ - ESC เพื่อออกจากโหมดนำเสนอ
125
+ - [x] **รองรับเต็มจอ (Fullscreen)**:
126
+ - ปุ่มเต็มจอที่มุมบนขวาขณะนำเสนอ
127
+ - กด F สลับเต็มจอ
128
+ - สไตล์เต็มจอที่เหมาะสม (ไร้กรอบ, viewport เต็ม)
129
+ - [x] **ดีไซน์ภาพ**:
130
+ - ควบคุมนำทางกึ่งโปร่งใสที่ด้านล่างกลาง
131
+ - ปุ่มวงกลม prev/next พร้อม hover effects
132
+ - สถานะปิดการใช้งานสำหรับขอบเขตสไลด์แรก/สุด��้าย
133
+ - Backdrop blur เพื่อการอ่านที่ดีขึ้น
134
+
135
+ #### 5. ฟังก์ชันรีเซ็ตแอปพลิเคชัน
136
+ - [x] **ปุ่ม Reset** ต่อจาก Export Video
137
+ - รีเซ็ตแอปกลับสู่สถานะเริ่มต้น
138
+ - ล้างเนื้อหา markdown และสไลด์ทั้งหมด
139
+ - รีเซ็ตการตั้งค่ากลับเป็นค่าเริ่มต้น
140
+ - ยืนยันก่อนดำเนินการ (confirmation dialog)
141
+ - หยุดการเล่นหรือนำเสนออัตโนมัติ
142
+ - รีเซ็ตเทมเพลตเป็น 'modern'
143
+ - เคลียร์ไทม์ไลน์และ asset checklist
144
+
145
+ #### 6. PowerPoint สำหรับโปรแกรมเมอร์ - Code Editor Themes
146
+ - [x] **Theme ใหม่สไตล์ Code Editor** ใน templates.js:
147
+ - **Monokai**: Theme คลาสสิก ใช้สี warm tones (magenta, green, cyan)
148
+ - **Solarized Dark**: Precision colors designed for readability
149
+ - **SynthWave '84**: Retro futuristic 80s aesthetic (hot pink, mint, yellow)
150
+ - **Dracula**: Dark theme สำหรับคนเขียนโค้ดตอนกลางคืน
151
+ - รองรับ syntax highlighting พร้อม theme-specific colors
152
+ - [x] **Enhanced Content Styles** ใน style.css:
153
+ - `.content-h1`: Gradient text with glow effect
154
+ - `.content-h2`: Border-left accent with text shadow
155
+ - `.content-blockquote`: Styled quote marks with inset shadow
156
+ - `.content-code-block`: Top gradient border with hover animation
157
+ - Syntax highlighting colors: keyword, string, number, comment, function, variable
158
+ - [x] **Advanced Transitions** ใน slide-renderer.js:
159
+ - **Glitch**: Digital glitch effect พร้อม random offsets และ hue rotation
160
+ - **Matrix**: Digital rain effect simulation
161
+ - **Cube**: 3D cube rotation transition
162
+ - **Pixelate**: Blur-based pixelation effect
163
+ - [x] **CSS Animations**:
164
+ - `@keyframes matrixScroll`: Scrolling matrix effect
165
+ - `@keyframes glitchSkew`: Skew animation for glitch
166
+ - `@keyframes pixelateIn`: Blur in animation
167
+ - `@keyframes codeHighlight`: Code block hover glow
168
+ - `@keyframes textGlow`: Heading pulsing glow effect
169
+
170
+ #### 7. การแสดงภาพไทม์ไลน์ปรับปรุง
171
+ - [x] **ตัวบ่งชี้การแบ่งหน้า**: แสดง badges "[1/2]", "[2/2]" สำหรับสไลด์หลายหน้า
172
+ - [x] **แสดงจำนวนบรรทัด**: "8 lines", "5 lines" เพื่อแสดงความหนาแน่นเนื้อหา
173
+ - [x] **ตัวบ่งชี้ต่อเนื่อง**: "↪ continued" สำหรับเนื้อหาที่แบ่ง
174
+ - [x] **แสดงระยะเวลา**: เวลาที่แม่นยำต่อสไลด์พร้อมระยะเวลารวม
175
+
176
+ #### 8. ระบบวัดผลและขอบปลอดภัยของ Smart Layout
177
+ - [x] เพิ่ม heuristic `SMART_SAFE_ZONE` และ helper padding เพื่อให้ measurement stage กับเวทีจริงใช้อินเสตต์เดียวกัน
178
+ - [x] ซิงก์ฟอนต์ คลาส screen-type และโครงสร้างซีนของ measurement stage ให้ตรงกับเวทีจริงทุกโหมดหน้าจอ
179
+ - [x] ใช้ผลการวัดซ้ำในการสเกลคอนเทนต์หลังเรนเดอร์ พร้อมเผยค่า `data-safe-*` สำหรับการตรวจสอบ
180
+ - [x] กรอง heading จากสไลด์ถัดไปเมื่อดึงคอนเทนต์มาพรีวิว และพึ่งพาหัวข้อที่ผู้ใช้เขียนแทน “Slide N” แบบสร้างเอง
181
+
182
+ #### 9. ระบบตั้งค่าการนำเสนอ (`src/renderer/js/presentation-config.js`)
183
+ - [x] ปรับแนวคิดเทมเพลตเดิมให้เป็นชุด preset แบบยืดหยุ่น (ฟอนต์ ขนาด clamp สี พื้นหลัง แอนิเมชัน)
184
+ - [x] มี API จัดการคอนฟิก (`getCurrentConfig`, `setConfig`, `updateConfigPart`, `loadPreset`, `resetConfig`) ให้ควบคุมได้ละเอียด
185
+ - [x] รวม preset หลัก (Default, Professional, Minimal, Creative) พร้อมตัวเลือกฟอนต์/พื้นหลัง/ทรานซิชันที่คัดสรรไว้
186
+ - [x] ใช้งานค่า config กับ CSS custom properties โดยอัตโนมัติ โดยไม่พึ่งไลบรารีภายนอก
187
+ - [x] รองรับการส่งออก/นำเข้า JSON เพื่อแชร์โปรไฟล์การนำเสนอระหว่างเด็ค Markdown
188
+
189
+ ### ไฟล์ตัวอย่างที่สร้าง
190
+ - [x] `workspace/complete-syntax-demo.md` - 25 สไลด์แสดงรูปแบบ Markdown syntax ทั้งหมด
191
+ - [x] `workspace/pagination-demo.md` - 20+ สไลด์แสดงการแบ่งหน้าอัตโนมัติพร้อมความยาวเนื้อหาหลากหลาย
192
+
193
+ ## อัปเดตล่าสุด (ตุลาคม 2025)
194
+
195
+ ### 10. ระบบแยกโหมดการทำงานอย่างเด็ดขาด (Mode Isolation System)
196
+ **ปัญหาที่พบ**: UI elements จากโหมดต่างๆ ทำงานทับซ้อนกัน ทำให้เกิดความขัดแย้งและข้อผิดพลาดการแสดงผล
197
+
198
+ **การแก้ไข** - สร้างระบบควบคุมโหมดแบบ exclusive mode switching:
199
+
200
+ #### Mode Manager (`src/renderer/js/mode-manager.js`)
201
+ - [x] **Singleton Pattern**: สร้าง `ModeManager` class เพียง instance เดียวสำหรับทั้งแอป
202
+ - [x] **3 โหมดแยกกันอย่างเด็ดขาด**:
203
+ - **Intro Mode**: หน้าเริ่มต้น ไม่มีระบบใดทำงาน (static display only)
204
+ - **Presentation Mode**: โหมดนำเสนอ เปิดเฉพาะ keyboard navigation + Smart Layout
205
+ - **Editor Mode**: โหมดแก้ไข เปิดเฉพาะ content editable + drag & drop + Safe Zone border
206
+
207
+ #### ระบบควบคุมที่รัดกุม
208
+ - [x] **System Flags Tracking**: ติดตาม active systems (smartLayout, dragDrop, contentEditable, safeZoneBorder, etc.)
209
+ - [x] **UI Visibility Control**:
210
+ - `hideAllModeUI()` - ซ่อน UI elements ทั้งหมด
211
+ - `showPresentationUI()` - แสดงเฉพาะ navigation controls, exit button, fullscreen button, edit button
212
+ - `showEditorUI()` - แสดงเฉพาะ save button, cancel button, exit button
213
+ - [x] **Smart Layout Management**:
214
+ - Intro Mode: `detach()` observers อย่างเด็ดขาด
215
+ - Presentation Mode: `reattach()` observers สำหรับ auto-adjustment
216
+ - Editor Mode: `detach()` observers เพื่อป้องกันการปรับขนาดขณะแก้ไข
217
+ - [x] **Mode Switching Flow**:
218
+ ```javascript
219
+ switchMode(newMode) {
220
+ 1. shutdownMode(currentMode) // ปิดโหมดเดิมทั้งหมด
221
+ 2. currentMode = newMode // เปลี่ยนโหมด
222
+ 3. setDisplayMode(newMode) // อัปเดต config
223
+ 4. activateMode(newMode) // เปิดโหมดใหม่เท่านั้น
224
+ 5. dispatch 'modeChanged' event
225
+ }
226
+ ```
227
+
228
+ #### การผสานรวมกับระบบเดิม
229
+ - [x] **app.js Integration**:
230
+ - `init()`: เรียก `switchToIntroMode()` แทน `setDisplayMode('intro')`
231
+ - `startPresentationMode()`: เรียก `switchToPresentationMode()`
232
+ - `exitPresentationMode()`: เรียก `switchToIntroMode()`
233
+ - ลบการ manual show/hide UI elements ทั้งหมด (Mode Manager จัดการให้)
234
+
235
+ - [x] **slide-editor.js Integration**:
236
+ - `enterEditMode()`: เรียก `switchToEditorMode()`
237
+ - `exitEditMode()`: เรียก `switchToPresentationMode()`
238
+ - `enterDragMode()`: เรียก `switchToEditorMode()`
239
+ - `exitDragMode()`: เรียก `switchToPresentationMode()`
240
+ - ลบการ manual Smart Layout detach/reattach (Mode Manager จัดการให้)
241
+ - ลบการ manual Safe Zone show/hide (Mode Manager จัดการให้)
242
+
243
+ #### การป้องกัน Smart Layout ทำงานในโหมดที่ไม่ควร
244
+ - [x] **Guard in `ensureContentWithinBounds()`**:
245
+ ```javascript
246
+ function ensureContentWithinBounds() {
247
+ const modeManager = getModeManager();
248
+ if (modeManager && !modeManager.isSystemActive('smartLayout')) {
249
+ return; // ห้ามทำงานถ้า Smart Layout ปิดอยู่
250
+ }
251
+ // ... คำนวณและปรับขนาดต่อ
252
+ }
253
+ ```
254
+
255
+ #### ผลลัพธ์
256
+ - [x] **ไม่มีการทับซ้อนของ UI**: แต่ละโหมดแสดง UI elements ที่เกี่ยวข้องเท่านั้น
257
+ - [x] **ไม่มี Smart Layout รบกวน**: ระบบปรับขนาดทำงานเฉพาะ Presentation Mode
258
+ - [x] **Edit Mode ปลอดภัย**: แก้ไขได้โดยไม่มีระบบอื่นมาขัดขวาง
259
+ - [x] **Single Source of Control**: `ModeManager` เป็นจุดเดียวที่ควบคุมโหมดทั้งหมด
260
+
261
+ #### เอกสารและการบำรุงรักษา
262
+ - [x] สร้างเอกสาร `docs/TH/MODE_ISOLATION_FIX.md` พร้อมรายละเอียดการแก้ไข
263
+ - [x] คอมเมนต์ในโค้ดชี้แจงว่า "Mode Manager จัดการแล้ว ไม่ต้อง manual control"
264
+ - [x] ลบโค้ดซ้ำซ้อนออกจาก app.js และ slide-editor.js
265
+
266
+ ### ระบบแยกโลจิกทั้ง 3 ส่วนอย่างเด็ดขาด
267
+ **หลักการ**: แต่ละโหมดการแสดงผลมีโลจิกและระบบ Safe Zone แยกกันโดยสิ้นเชิง เพื่อป้องกันการแก้ไขส่วนหนึ่งทำให้ส่วนอื่นเสียหาย
268
+
269
+ #### 1. ระบบ Intro Scene (จอพรีวิวขนาดเล็กพร้อม UI Sidebar)
270
+ - [x] **วัตถุประสงค์**: แสดงตัวอย่างสไลด์ในพื้นที่เล็กของหน้า UI พร้อมแถบควบคุมด้านข้าง
271
+ - [x] **คุณสมบัติ**:
272
+ - [x] ขนาดหน้าจอคงที่ (1280x720 fallback)
273
+ - [x] Safe Zone แบบ hard-coded เหมาะสำหรับพื้นที่แสดงผลเล็ก
274
+ - [x] ไม่ต้องคำนวณแบบ dynamic เพราะพื้นที่แน่นอน
275
+ - [x] **ฟังก์ชันหลัก** (ทำเครื่องหมาย LOCKED - ห้ามแก้ไข):
276
+ - [x] `getStagePreviewData()` - ดึงข้อมูลตัวอย่างสไลด์
277
+ - [x] `renderStagePreview()` - เรนเดอร์พรีวิวลงใน DOM
278
+ - [x] `updateStagePreview()` - อัปเดตพรีวิวเมื่อสไลด์เปลี่ยน
279
+ - [x] **สถานะ**: ทำงานสมบูรณ์แล้ว - ห้ามแก้ไขหรือเชื่อมโยงกับโหมดอื่น
280
+
281
+ #### 2. ระบบ Presentation Mode - Small Screen (จอนำเสนอขนาดปกติ)
282
+ - [x] **วัตถุประสงค์**: โหมดนำเสนอบนจอปกติ (ไม่ fullscreen) ขนาด 1920x1080 หรือเล็กกว่า
283
+ - [x] **คุณสมบัติ**:
284
+ - [x] รองรับการนำทางด้วยปุ่มลูกศร (← →)
285
+ - [x] คำนวณ Safe Zone แบบ ratio-based สำหรับหน้าจอปกติ
286
+ - [x] ขอบปลอดภัย (Safe Zone) ประมาณ 8-9% ของความกว้าง/สูง
287
+ - [x] **โซนสี**:
288
+ - [x] **Red Zone**: พื้นที่นอกขอบหน้าจอ - ห้ามวางเนื้อหา
289
+ - [x] **Green Zone**: พื้นที่ปลอดภัยภายในขอบ - วางเนื้อหาได้อย่างปลอดภัย
290
+ - [x] **การคำนวณ**:
291
+ - [x] ไม่ใช้ hard-coded pixels
292
+ - [x] คำนวณจาก ratio ของขนาดหน้าจอจริง
293
+ - [x] สูตร: `safeInset = screenDimension × SAFE_ZONE_RATIO`
294
+
295
+ #### 3. ระบบ Presentation Mode - Large Screen (จอนำเสนอขนาดใหญ่เต็มจอ)
296
+ - [x] **วัตถุประสงค์**: โหมด fullscreen บนจอขนาดใหญ่ (2560x1440 ขึ้นไป) หรือโปรเจคเตอร์
297
+ - [x] **คุณสมบัติ**:
298
+ - [x] เข้าสู่ fullscreen mode อัตโนมัติ
299
+ - [x] Smart Layout Engine วัดและจัดเนื้อหาให้เหมาะสมกับพื้นที่
300
+ - [x] Safe Zone กว้างขึ้นเพื่อรองรับการ overscan ของโปรเจคเตอร์
301
+ - [x] **โซนสี** (เข้มงวดกว่าจอเล็ก):
302
+ - [x] **Red Zone**: พื้นที่อันตราย 10-15% จากขอบ - ห้ามวางเนื้อหาเด็ดขาด
303
+ - [x] **Yellow Zone**: พื้นที่เตือน 5-10% - วางได้แต่อาจถูกตัดบนโปรเจคเตอร์บางรุ่น
304
+ - [x] **Green Zone**: พื้นที่ปลอดภัย 80% กลางจอ - วางเนื้��หาได้อย่างสบายใจ
305
+ - [x] **การคำนวณ**:
306
+ - [x] คำนวณแบบ dynamic จากขนาดหน้าจอจริง
307
+ - [x] ปรับ ratio ตามประเภทจอ (normal/large/ultra)
308
+ - [x] ตัวอย่างสูตร:
309
+ ```
310
+ baseRatio = 0.08 (8%)
311
+ maxRatio = 0.16 (16%)
312
+ actualInset = clamp(screenSize × baseRatio, MIN_PIXELS, screenSize × maxRatio)
313
+ ```
314
+
315
+ ### การป้องกันโค้ดจากการแก้ไข
316
+ - [x] เพิ่มคอมเมนต์เตือนทุกฟังก์ชันที่เกี่ยวข้องกับ Intro Scene
317
+ - [x] ใช้แท็ก `@LOCKED` และ `DO NOT MODIFY` ชัดเจน
318
+ - [x] แยกคอมเมนต์ออกเป็นบล็อกใหญ่ด้วยเส้นขอบ (==== lines)
319
+ - [x] ระบุเหตุผลและผลกระทบของการแก้ไขในคอมเมนต์
320
+ - [x] ไม่ใช้อิโมจิในคอมเมนต์ (อาจทำให้เกิดปัญหา encoding)
321
+
322
+ ### Smart Layout และ Safe Zone System
323
+ - [x] แยก Safe Zone constants สำหรับแต่ละโหมด
324
+ - [x] Intro Scene ใช้ constants แบบ hard-coded
325
+ - [x] Presentation Mode จะสร้างฟังก์ชันคำนวณแยกต่างหาก
326
+ - [ ] สร้างฟังก์ชัน `computePresentationSafeZone()` สำหรับโหมดนำเสนอ
327
+ - [ ] สร้างฟังก์ชัน `computeLargeScreenSafeZone()` สำหรับจอใหญ่
328
+ - [ ] ทดสอบการคำนวณ Safe Zone บนจอหลายขนาด
329
+
330
+ ## งานที่ต้องทำต่อ
331
+
332
+ ### เครื่องมือจัดวางอัจฉริยะ (Smart Layout)
333
+ - [ ] **ผสาน Auto-pagination เข้า Smart Layout**:
334
+ - [ ] ใช้ logic การคำนวณบรรทัดจาก `slide-paginator.js` ร่วมกับ `ensureContentWithinBounds()`
335
+ - [ ] ทำให้สไลด์แบ่งอัตโนมัติตอน render จริง ไม่ใช่แค่ตอน parse
336
+ - [ ] คำนวณพื้นที่ว่างภายใน Safe Zone ก่อนตัดสินใจแบ่งหน้า
337
+ - [ ] เพิ่มการตั้งค่า `maxLinesPerSlide` ใน presentation-config.js
338
+ - [ ] สร้าง `layout-schema.js` เวอร์ชันใหม่ที่นิยามโครงสร้าง LayoutNode และการรวม metrics แบบชัดเจน
339
+ - [ ] ผูก layout tree กับกระบวนการ `renderSlideToStage` ให้เรนเดอร์ DOM ตามบล็อกแทนการใช้ HTML ดิบ
340
+ - [ ] ปรับ measurement stage ให้ใช้ข้อมูลจาก layout tree พร้อม refactor การคำนวณบรรทัด/คอลัมน์
341
+ - [ ] เพิ่ม unit tests สำหรับ smart layout (measurement observers, smart-list balancing, layout tree diff)
342
+
343
+ ### ระบบประสานงานระหว่างโมดูล Markdown → Layout → Renderer
344
+ - [ ] สร้างเอกสาร `layout-contract.md` ระบุ schema JSON กลางสำหรับ slide/section/block/inline พร้อม diagnostics
345
+ - [ ] ปรับ `markdown-syntax.js` ให้ปล่อย API เดียว (detect + inline tokenize) และบันทึก metadata ที่ parser ต้องใช้
346
+ - [ ] ปรับ `markdown-parser.js` ให้ใช้ metadata นั้น สร้าง content item ที่พร้อม map ไปยัง layout block (เช่น link, inline emphasis)
347
+ - [ ] อัปเดต `layout-schema.js` ให้รองรับ block ชนิดใหม่ (heading, link, inline rich text) พร้อม metrics ที่ renderer ใช้งานได้ทันที
348
+ - [ ] ปรับ `app.js` ให้ใช้ layout tree ทั้งหมดในการเรนเดอร์, ส่งผล measurement/diagnostics กลับเข้า tree, และเผยสถานะต่อ UI
349
+ - [ ] เพิ่ม feedback loop (diagnostics channel) ระหว่าง measurement stage ↔ layout-schema ↔ markdown-parser เพื่อให้ heuristics เรียนรู้ได้
350
+
351
+ ### โมเดลไทม์ไลน์และข้อมูลเมทาดาทา
352
+ - [ ] เพิ่ม schema ฟรอนต์แมตเตอร์และอินไลน์ directive สำหรับเวลา ทรานซิชัน คิวบรรยาย และแอสเซ็ต
353
+ - [ ] สร้างโมเดลไทม์ไลน์กลาง (JSON) ใช้งานร่วมกันระหว่าง renderer และ pipeline เอ็กซ์พอร์ต
354
+ - [ ] ตรวจสอบความถูกต้องของเมทาดาทาพร้อมผลักข้อความผิดพลาดเข้าสู่ diagnostics ของ UI
355
+
356
+ ### 9. ระบบตั้งค่าการนำเสนอ (เสร็จสมบูรณ์ ✅)
357
+ - [x] **วัตถุประสงค์**: ระบบปรับแต่งรูปลักษณ์แบบ Word/Excel พร้อมการประสานงานแบบสองทาง (UI ↔ Config ↔ Frontmatter ↔ CSS)
358
+ - [x] **สถาปัตยกรรม**: แทนที่ระบบเทมเพลตแบบตายตัวด้วย configuration engine แบบไดนามิก พร้อมระบบตัวแปร CSS
359
+
360
+ #### การควบคุมการจัดพิมพ์และเลย์เอาต์
361
+ 1. **การตั้งค่าฟอนต์** (9 อินพุต)
362
+ - [x] ช่วงขนาดฟอนต์แบบ responsive: H1 min/base/max, H2 min/base/max, Text min/base/max
363
+ - [x] ระบบ CSS `clamp()` อัตโนมัติสำหรับการปรับขนาดฟอนต์ตามหน้าจอ
364
+ - [x] หน่วยที่รองรับ: px, rem, em
365
+
366
+ 2. **การตั้งค่า Line Height** (2 อินพุต)
367
+ - [x] ระยะบรรทัดของ heading (default: 1.2)
368
+ - [x] ระยะบรรทัดของ body text (default: 1.6)
369
+ - [x] หน่วยที่รองรับ: ไม่มีหน่วย, em
370
+
371
+ 3. **การตั้งค่าการจัดวรรคตอน** (8 อินพุต)
372
+ - [x] ระยะห่างหน้าหลังพารากราฟ (px)
373
+ - [x] ระยะห่างหน้าหลังหัวข้อ (px)
374
+ - [x] การเยื้องบรรทัดแรก (px)
375
+ - [x] การเยื้องรายการ/ซ้ำซ้อน (px)
376
+ - [x] การจัดข้อความ (left, center, right, justify)
377
+
378
+ 4. **การตั้งค่าสี** (2 อินพุต)
379
+ - [x] สีหลัก (Accent Color) พร้อม picker สี
380
+ - [x] สีพื้นหลัง gradient
381
+
382
+ #### การตั้งค่า UI และเอฟเฟกต์ภาพ
383
+ - [x] **Preview Overlay Opacity** - ความทึบของ overlay พรีวิว (0-100%)
384
+ - [x] **Overlay Background Blur** - ความเบลอของพื้นหลังตอนหยุด (0-20px)
385
+ - [x] **Navigation Border Width** - ความหนาเส้นขอบปุ่มนำทาง (0-5px)
386
+ - [x] **Backdrop Gradient Spread** - การกระจายของ gradient พื้นหลัง (40-80%)
387
+ - [x] **Backdrop Blur Intensity** - ความเข้มเบลอของพื้นหลัง (0-60px)
388
+
389
+ #### การตั้งค่าความกว้างขอบและเส้นเน้น
390
+ - [x] **Heading Accent Border** - เส้นเน้นใต้หัวข้อ (0-8px)
391
+ - [x] **Blockquote Left Border** - เส้นซ้าย blockquote (0-8px)
392
+ - [x] **Image Border** - กรอบรอบรูปภาพ (0-8px)
393
+ - [x] **Link Underline** - เส้นใต้ลิงก์ (0-4px)
394
+ - [x] **Table Border** - เส้นขอบตาราง (0-4px)
395
+ - [x] **Horizontal Rule** - ความหนาเส้นแบ่ง (0-6px)
396
+
397
+ #### Single Source of Truth
398
+ - [x] **CONFIG_PRESETS** ใน `presentation-config.js`:
399
+ * ค่าเริ่มต้นครบถ้วน 30+ properties
400
+ * Preset 4 แบบ: Default, Professional, Minimal, Creative
401
+ * แชร์ผ่าน frontmatter ได้
402
+
403
+ - [x] **ระบบตัวแปร CSS** (23+ ตัวแปร):
404
+ * `--preview-opacity`, `--overlay-background`, `--overlay-blur`
405
+ * `--nav-border-width`, `--nav-border-opacity`
406
+ * `--backdrop-gradient-color`, `--backdrop-gradient-spread`, `--backdrop-blur`
407
+ * `--heading-accent-border-width`, `--blockquote-border-width`, `--image-border-width`
408
+ * `--link-underline-width`, `--table-border-width`, `--hr-border-width`
409
+ * ตัวแปรฟอนต์และระยะห่างทั้งหมด
410
+
411
+ #### การประสานงานแบบสองทาง
412
+ 1. **UI → Config** (`syncUIToConfig()`)
413
+ - [x] รับค่าจากอินพุตพร้อมแปลงหน่วย (px, %, ไม่มีหน่วย)
414
+ - [x] อัปเดต `currentConfig` ทันที
415
+ - [x] เรียก `applyConfigToDOM()` เพื่อแสดงผล
416
+
417
+ 2. **Config → CSS** (`applyConfigToDOM()`)
418
+ - [x] ตั้งค่าตัวแปร CSS 23+ ตัวบน `document.documentElement`
419
+ - [x] แปลงเป็นสตริง CSS พร้อมหน่วย
420
+ - [x] อัปเดตทันทีในหน้าพรีวิว
421
+
422
+ 3. **Config → Frontmatter** (`savePresentationSettings()`)
423
+ - [x] บันทึกทุก property ลง YAML namespace `presentation.styles.*`
424
+ - [x] ตัวอย่าง: `presentation.styles.previewOpacity: 85`
425
+
426
+ 4. **Frontmatter → Config** (`loadConfigFromFrontmatter()`)
427
+ - [x] โหลดจาก YAML เมื่อเปิด markdown
428
+ - [x] merge เข้า currentConfig
429
+ - [x] เรียก `loadConfigToUI()` เพื่ออัปเดต UI
430
+
431
+ #### ประสบการณ์นักพัฒนา
432
+ - [x] **ไม่มีค่าแบบตายตัว**: ทุกอย่างอยู่ใน CONFIG_PRESETS.default.config
433
+ - [x] **ง่ายต่อการขยาย**: เพิ่ม property ที่เดียว → ใช้ได้ทุกที่
434
+ - [x] **รักษาได้ง่าย**: แก้ค่าเริ่มต้นที่เดียว → ผลทั่วทั้งระบบ
435
+ - [x] **ปลอดภัย**: ตรวจสอบค่าและหน่วยทุกจุด
436
+
437
+ #### การใช้งาน
438
+ ```yaml
439
+ ---
440
+ presentation:
441
+ preset: "professional" # หรือ "minimal", "creative"
442
+ styles:
443
+ h1FontBase: "3.5rem"
444
+ accentColor: "#3b82f6"
445
+ previewOpacity: 85
446
+ overlayBlur: 12
447
+ headingBorderWidth: 4
448
+ # ... properties อื่นๆ
449
+ ---
450
+ ```
451
+
452
+ #### รายการตรวจสอบความสมบูรณ์
453
+ - [x] 30+ UI controls ในแท็บ Presentation Settings
454
+ - [x] 4 presets ที่กำหนดไว้ล่วงหน้า
455
+ - [x] 23+ CSS variables พร้อมค่า fallback
456
+ - [x] ฟังก์ชันผูกแบบสองทาง (UI ↔ config)
457
+ - [x] การบันทึก/โหลด frontmatter สำหรับทุก property
458
+ - [x] ปุ่ม Reset ใช้ `resetConfig()` แบบกลาง
459
+ - [x] คลาส CSS สำหรับ table, hr, timeline indicators
460
+ - [x] แปลเป็นภาษาอังกฤษทั้งหมด (UI + presets + help text)
461
+ - [x] ไม่มี syntax errors ในทุกไฟล์
462
+ - [x] เอกสารครบถ้วนใน EN/TH MARKDOWN_VIDEO_PLAN.md
463
+
464
+ ### เฟส 2: ปรับปรุงเอ็กซ์พอร์ต (ความสำคัญถัดไป)
465
+ - [x] พรีวิวแบบเบราว์เซอร์ใช้โมเดลไทม์ไลน์ได้อย่างไร้ที่ติพร้อม markdown rendering เต็มรูปแบบ
466
+ - [ ] **ปรับปรุงคุณภาพการเอ็กซ์พอร์ต WebM แบบ native**:
467
+ - [ ] ปรับปรุง MediaRecorder API ให้ควบคุมเวลาแบบ frame-perfect
468
+ - [ ] ตัวเลือกการตั้งค่าคุณภาพ/bitrate (เป้าหมาย: 1080p ที่ 5-10 Mbps)
469
+ - [ ] รายงานความคืบหน้าพร้อมอัปเดตต่อสไลด์และแสดงเปอร์เซ็นต์
470
+ - [ ] ฟังก์ชันยกเลิก/หยุดสำหรับการเรนเดอร์ยาว
471
+ - [ ] บริหารวงจรเรนเดอร์ด้วยคิวงาน รายงานความคืบหน้า และการยกเลิก
472
+ - [ ] Modal ความคืบหน้าการเอ็กซ์พอร์ตพร้อมแสดง thumbnail แบบเรียลไทม์
473
+
474
+ ### การปรับแต่งภาพและแอนิเมชัน
475
+ - [ ] รองรับพื้นหลังแบบภาพ/วิดีโอต่อสไลด์พร้อมการครอปรักษาอัตราส่วน
476
+ - [ ] นิยาม DSL สำหรับทรานซิชัน แอนิเมชัน และการจัดวางแบบคีย์เฟรม
477
+ - [ ] **สร้างคอมโพเนนต์กำหนดเอง** (ไม่ใช้ไลบรารีภายนอก):
478
+ - [ ] ตัวเรนเดอร์กราฟโดยใช้ Canvas 2D API
479
+ - [ ] ตัวไฮไลต์ syntax โดยใช้ regex tokenization
480
+ - [ ] Component registry สำหรับการแมป markdown → ภาพที่ขยายได้
481
+
482
+ ### เสียงและการบรรยาย (อนาคต)
483
+ - [ ] รองรับแทร็กบรรยายที่ซิงก์กับไทม์ไลน์จากไฟล์เสียง
484
+ - [ ] **ผสมเสียงโดยใช้ Web Audio API แบบ native**:
485
+ - [ ] สร้างอัลกอริทึม ducking กำหนดเองสำหรับดนตรีพื้นหลัง
486
+ - [ ] ซิงโครไนซ์เสียงกับไทม์ไลน์วิดีโอ
487
+ - [ ] ไม่ใช้ไลบรารีประมวลผลเสียงภายนอก
488
+ - [ ] ตรวจสอบคุณภาพซิงก์เสียง-ภาพผ่านเทสต์สถานการณ์ตัวอย่าง
489
+
490
+ ### เวิร์กโฟลว์เทมเพลตและการทำงานร่วมกัน
491
+ - [ ] สร้างระบบเลือกเทมเพลต Markdown + CSS ผ่าน UI
492
+ - [ ] จัดทำพื้นที่เก็บแอสเซ็ตร่วมพร้อมการอ้างอิงเวอร์ชัน
493
+ - [ ] จัดทำมาตรฐานการตั้งชื่อไฟล์และโครงสร้างโฟลเดอร์สำหรับมีเดีย
494
+
495
+ ## แผนดำเนินงานแบบเฟส
496
+
497
+ ### เฟส 1 – แกนไทม์ไลน์ ([x] เสร็จสมบูรณ์)
498
+ - [x] เขียน `app.js` ใหม่เพื่อแยก markdown และเติมข้อมูล timeline UI
499
+ - [x] ขยาย `markdown-parser.js` พร้อม frontmatter และการคำนวณระยะเวลา
500
+ - [x] ผูกการเลือกเทมเพลตแบบสองทาง (UI ↔ frontmatter)
501
+ - [x] แสดงข้อผิดพลาดการตรวจสอบในแท็บ Markdown
502
+ - [x] **โบนัส**: พจนานุกรม Markdown Syntax ครบถ้วนพร้อม 50+ รูปแบบ
503
+ - [x] **โบนัส**: ระบบแบ่งหน้าอัตโนมัติพร้อมการคำนวณบรรทัดแบบ visual
504
+ - [x] **โบนัส**: ควบคุมพรีวิวแบบโต้ตอบ (หยุด/เล่นต่อ, ปุ่มลัด)
505
+ - [x] **โบนัส**: การแสดงภาพไทม์ไลน์ปรับปรุงพร้อมตัวบ่งชี้และจำนวนบรรทัด
506
+ - [x] **โบนัส**: โหมดนำเสนอเต็มรูปแบบพร้อมระบบนำทางและ fullscreen
507
+ - [x] **โบนัส**: เวิร์กโฟลว์รีเซ็ตและระบบ Safe Zone อัจฉริยะที่ปกป้องเนื้อหา
508
+ - [x] **โบนัส**: ธีม Code Editor พร้อมทรานซิชัน/แอนิเมชันระดับสูง
509
+ - [x] **โบนัส**: ระบบตั้งค่าการนำเสนอแบบไม่มีเทมเพลต พร้อม preset ที่แชร์ได้
510
+ - [ ] เพิ่ม unit tests สำหรับการแยกส่วน การคำนวณเวลา และกรณีผิดพลาด (เลื่อนไปเฟส 2)
511
+
512
+ ### เฟส 2 – ปรับปรุงเอ็กซ์พอร์ตวิดีโอ (ความสำคัญถัดไป)
513
+ - [ ] ปรับปรุงคุณภาพการเอ็กซ์พอร์ต WebM ด้วย MediaRecorder และเฟรมที่แม่นยำ (เป้าหมาย: 1080p @ 5-10 Mbps)
514
+ - [x] ใช้งานการติดตามความคืบหน้าแบบ native พร้อมอัปเดตต่อสไลด์และแสดงเปอร์เซ็นต์
515
+ - [x] เพิ่มตัวควบคุมความละเอียด/FPS/คุณภาพที่ซิงก์กับ frontmatter
516
+ - [ ] รองรับการยกเลิกระหว่างเอ็กซ์พอร์ตพร้อมทำความสะอาดและลบไฟล์บางส่วน
517
+ - [ ] Modal ความคืบหน้าการเอ็กซ์พอร์ตพร้อมแสดง thumbnail แบบสด
518
+ - [ ] Unit tests สำหรับ markdown-syntax.js, slide-paginator.js, กลไกหยุด/เล่นต่อ
519
+ - [ ] สร้าง integration tests สำหรับ markdown ตัวอย่าง → วิดีโอ
520
+
521
+ #### แผน Native Encoder ของระบบปฏิบัติการ (ความปลอดภัยสูง ไม่ใช้ไลบรารีภายนอก)
522
+ - [ ] ออกแบบ pipeline ดึงเฟรมกลาง (HTML → บัฟเฟอร์ RGBA/PNG) ที่ใช้ร่วมกับ encoder ทุกแพลตฟอร์ม
523
+ - [ ] Windows: สร้าง bridge Media Foundation แบบ sandbox เพื่อเขียน MP4 (H.264/AAC) ภายใต้การค��บคุมของ security-core
524
+ - [ ] macOS: พัฒนา exporter ผ่าน AVFoundation (AVAssetWriter) สำหรับ H.264/AAC พร้อมตรวจสอบเส้นทางไฟล์อย่างเข้มงวด
525
+ - [ ] Linux: เชื่อมกับ GStreamer/VA-API ที่มีในระบบ (`appsrc → x264enc → mp4mux`) โดยรันภายใต้เงื่อนไขความปลอดภัยเดียวกัน
526
+ - [ ] เพิ่มการสร้าง GIF โดยใช้ pipeline native เดียวกัน (MF Transform, AVFoundation ImageDestination หรือ GStreamer gifenc)
527
+ - [ ] ใส่ฮุคความปลอดภัยเพิ่มเติม (allow-list เส้นทาง, rate limit, ตรวจสอบ checksum) ในทุกการเรียก encoder
528
+
529
+ ### เฟส 3 – ผสานเสียง (อนาคต)
530
+ - [ ] แยกการอ้างอิงไฟล์บรรยายจากข้อมูลเมทาสไลด์
531
+ - [ ] โหลดและตรวจสอบแอสเซ็ตเสียงผ่าน IPC ที่ปลอดภัย
532
+ - [ ] ผสมบรรยาย + ดนตรีพื้นหลังโดยใช้ Web Audio API
533
+ - [ ] ซิงโครไนซ์เสียงกับไทม์ไลน์วิดีโอในพรีวิวและเอ็กซ์พอร์ต
534
+ - [ ] เพิ่มการแสดงผลคลื่นเสียงในแท็บ Timeline
535
+
536
+ ### เฟส 4 – ปรับปรุงภาพ (อนาคต)
537
+ - [ ] สร้างตัวเรนเดอร์กราฟแบบกำหนดเอง (Canvas-based ไม่มี libraries)
538
+ - [ ] ใช้งาน syntax highlighter โดยใช้ regex tokenization
539
+ - [ ] รองรับภาพ/วิดีโอพื้นหลังเฉพาะสไลด์
540
+ - [ ] สร้าง animation DSL แบบ declarative สำหรับทรานซิชันแบบ keyframe
541
+ - [ ] เพิ่ม component registry สำหรับการแมป markdown → ภาพที่ขยายได้
542
+
543
+ ### เฟส 5 – ทำให้เสถียรและปรับแต่ง (อนาคต)
544
+ - [ ] วิเคราะห์ประสิทธิภาพและเพิ่มประสิทธิภาพแคชแอสเซ็ต
545
+ - [ ] ปรับปรุงข้อความผิดพลาดพร้อมคำแนะนำแก้ไขตามบริบท
546
+ - [ ] ปรับปรุงเอกสารพร้อมวิดีโอสอน
547
+ - [ ] ส่งมอบ markdown decks ตัวอย่างที่แสดงฟีเจอร์ทั้งหมด
548
+
549
+ ## ผลกระทบด้านสถาปัตยกรรม
550
+ - **[x] ขยาย `src/shared/markdown-parser.js`**: ปล่อย timeline JSON พร้อมข้อมูลเมทาฉาก ระยะเวลา อ้างอิงแอสเซ็ต ข้อมูลการแบ่งหน้า
551
+ - **[x] สร้างใหม่ `src/shared/markdown-syntax.js`**: ไลบรารีรูปแบบแบบพจนานุกรมพร้อม 50+ regex patterns สำหรับ CommonMark + GFM ทั้งหมด
552
+ - **[x] สร้างใหม่ `src/shared/slide-paginator.js`**: การคำนวณบรรทัดแบบ visual และอัลกอริทึมแบ่งสไลด์อัจฉริยะ
553
+ - [ ] **สร้างใหม่ `src/shared/timeline-engine.js`**: ประกอบโมเดลไทม์ไลน์ คำนวณ timecodes จัดการสถานะการเล่น (อนาคต)
554
+ - **[x] อัปเดต `src/renderer/js/app.js`**:
555
+ * ใช้ markdown ที่แยกแล้วสำหรับพรีวิวพร้อมหยุด/เล่นต่อ
556
+ * เติม timeline พร้อมการเรนเดอร์ syntax เต็มรูปแบบ
557
+ * เพิ่มอ้างอิง DOM 13 ตัวสำหรับการตั้งค่าสไตล์ใหม่
558
+ * `savePresentationSettings()` บันทึก 11 properties สไตล์ลง frontmatter
559
+ * `resetApplication()` ใช้ `resetConfig()` แบบรวมศูนย์
560
+ * `buildSlideItemHtml()` ใช้คลาส `.slide-table`, `.slide-hr`
561
+ * `updateTimelineUI()` ใช้คลาส `.timeline-page-indicator`
562
+ - **[x] ปรับปรุง `src/renderer/js/video-renderer.js`**: การเรนเดอร์สไลด์บน Canvas พร้อมรองรับ markdown เต็มรูปแบบ (พร้อมเอ็กซ์พอร์ต รอปรับปรุงคุณภาพ)
563
+ - **[x] ระบบแอสเซ็ตท��่ปลอดภัย**: โฟลเดอร์ `workspace/` มาตรฐานพร้อมไฟล์ตัวอย่างและ emoji-cleaner.js
564
+ - **[x] โมดูลใหม่ `src/renderer/js/presentation-config.js`**:
565
+ * เอนจินตั้งค่าการนำเสนอแทนเทมเพลตแบบตายตัว
566
+ * `CONFIG_PRESETS` พร้อม 30+ properties, 4 presets
567
+ * `applyConfigToDOM()` ตั้งค่าตัวแปร CSS 23+ ตัวบน document.documentElement
568
+ * `loadConfigToUI()` โหลดทุกการตั้งค่ารวม 11 styling controls
569
+ * `syncUIToConfig()` ซิงก์การเปลี่ยนแปลง UI พร้อมแปลงหน่วย (px, %, ไม่มีหน่วย)
570
+ * `setupUIStylesListeners()` จัดการ input events สำหรับ 11 styling inputs
571
+ * `loadConfigFromFrontmatter()` โหลดทุก styling properties จาก YAML
572
+ * `resetConfig()` รีเซ็ตเป็นค่าเริ่มต้นแบบรวมศูนย์
573
+ - **[x] อัปเดต `src/renderer/css/style.css`**:
574
+ * แปลงค่าตายตัวทั้งหมดเป็นตัวแปร CSS
575
+ * ประกาศตัวแปร 23+ ตัวพร้อมค่า fallback
576
+ * `.pause-overlay` ใช้ `var(--overlay-background)`, `var(--overlay-blur)`
577
+ * `.nav-btn` ใช้ `var(--nav-border-width)`, rgba พร้อม `var(--nav-border-opacity)`
578
+ * `.gradient-backdrop` ใช้ `var(--backdrop-gradient-color)`, `var(--backdrop-gradient-spread)`, `var(--backdrop-blur)`
579
+ * ความกว้างเส้นขอบทั้งหมด: `var(--*-border-width)` พร้อม fallbacks
580
+ * คลาสใหม่: `.slide-table`, `.slide-hr`, `.timeline-page-indicator` พร้อมสไตล์ที่เป็นธีม
581
+ - **[x] อัปเดต `src/renderer/index.html`**:
582
+ * 30+ controls ในแท็บ Presentation Settings
583
+ * แบ่งเป็น 3 sections: UI Effects (5 inputs), Border Widths (6 inputs), Typography/Layout
584
+ * แปลเป็นภาษาอังกฤษทั้งหมด (หัวข้อ, labels, help text)
585
+ * เพิ่มข้อความช่วยเหลือแบบอธิบายสำหรับแต่ละ section
586
+
587
+ ## เทคโนโลยีที่ใช้งานปัจจุบัน (อัปเดต)
588
+ - **Electron 28.0.0**: เฟรมเวิร์กแอปพลิเคชันเดสก์ท็อป
589
+ - **MediaRecorder API**: การเข้ารหัสวิดีโอ WebM แบบ native (codec VP8/VP9)
590
+ - **ตัวเข้ารหัส native (แผน)**: Windows Media Foundation, macOS AVFoundation, Linux GStreamer/VA-API (ใช้คอมโพเนนต์จากระบบ ไม่มี dependency ภายนอก)
591
+ - **Canvas 2D API**: เรนเดอร์สไลด์จาก HTML/CSS → Canvas พร้อมรองรับ markdown syntax เต็มรูปแบบ
592
+ - **Tailwind CSS (local - 407KB)**: UI styling โหลดจาก `src/renderer/vendor/tailwind.js`
593
+ - **Web Audio API** (อนาคต): การผสมและปรับเสียงแบบ native
594
+ - **โมดูลกำหนดเอง**:
595
+ - **MarkdownParser** (`src/shared/markdown-parser.js`) - Parser พร้อม frontmatter, duration heuristics, ผสาน pagination
596
+ - **MarkdownSyntax** (`src/shared/markdown-syntax.js`) - พจนานุกรมรูปแบบพร้อม 50+ regex สำหรับ CommonMark + GFM
597
+ - **SlidePaginator** (`src/shared/slide-paginator.js`) - การคำนวณบรรทัดแบบ visual และการแบ่งอัจฉริยะ
598
+ - **VideoRenderer** (`src/renderer/js/video-renderer.js`) - การเรนเดอร์สไลด์บน Canvas
599
+ - **PresentationConfig** (`src/renderer/js/presentation-config.js`) - ระบบ preset การนำเสนอและการตั้งค่ารันไทม์แบบไม่มีเทมเพลต
600
+ - **SecurityCore** (`src/shared/security-core.js`) - ตรวจสอบ path และจำกัดอัตราสำหรับการดำเนินการไฟล์
601
+
602
+ ## กลยุทธ์คุณภาพ
603
+ - [ ] Unit tests สำหรับ `markdown-syntax.js` (การตรวจจับรูปแบบ การแยกส่วนแบบ inline)
604
+ - [ ] Unit tests สำหรับ `slide-paginator.js` (การคำนวณบรรทัด อัลกอริทึมการแบ่ง)
605
+ - [ ] Unit tests สำหรับ `markdown-parser.js` (การแยกส่วน frontmatter คำนวณระยะเวลา ผสาน pagination)
606
+ - [ ] Integration tests สำหรับ workflow markdown → ไทม์ไลน์ → วิดีโอ
607
+ - [ ] Snapshot tests สำหรับโครงสร้าง HTML ที่เรนเดอร์
608
+ - [ ] รายการตรวจสอบ QA แบบ manual สำหรับคุณภาพการเอ็กซ์พอร์ตในความละเอียด/FPS ต่างๆ
609
+ - [ ] การตรวจสอบการจัดการข้อผิดพลาด (ไฟล์หายไป frontmatter ผิดพลาด ฯลฯ)
610
+ - [ ] เทสต์กลไกหยุด/เล่นต่อ (promise resolution, ปุ่มลัด)
611
+
612
+ ## เอกสารและการนำไปใช้
613
+ - [x] **จัดทำคู่มือสองภาษา**: สร้างเอกสารครบถ้วน 6 ไฟล์
614
+ - [x] `MARKDOWN_SYNTAX.md` (EN/TH) - คู่มือ syntax ครบถ้วนพร้อมตัวอย่าง
615
+ - [x] `AUTO_PAGINATION.md` (EN/TH) - คู่มือระบบแบ่งหน้าพร้อมอัลกอริทึม
616
+ - [x] `PREVIEW_CONTROLS.md` (EN/TH) - คู่มือการใช้งานควบคุมแบบโต้ตอบ
617
+ - [x] **สร้างเด็คตัวอย่าง**: สร้างไฟล์ markdown ตัวอย่าง
618
+ - [x] `workspace/complete-syntax-demo.md` - 25 สไลด์แสดงรูปแบบ syntax ทั้งหมด
619
+ - [x] `workspace/pagination-demo.md` - 20+ สไลด์แสดงการแบ่งหน้าอัตโนมัติ
620
+ - [ ] วางแผนทดสอบกับผู้ใช้จริงและรวบรวมฟีดแบ็กเพื่อปรับปรุงต่อเนื่อง
621
+ - [ ] จัดทำวิดีโอสอนสำหรับขั้นตอนเอ็กซ์พอร์ตและแก้ไขปัญหา
docs/TH/SECURITY.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # นโยบายความปลอดภัย
2
+
3
+ ## เวอร์ชันที่รองรับ
4
+
5
+ เราปล่อยแพตช์สำหรับช่องโหว่ด้านความปลอดภัย เวอร์ชันใดที่มีสิทธิ์ได้รับแพตช์ดังกล่าวขึ้นอยู่กับการจัดอันดับ CVSS v3.0:
6
+
7
+ | เวอร์ชัน | รองรับ |
8
+ | -------- | ------------------- |
9
+ | 1.0.x | :white_check_mark: |
10
+ | < 1.0 | :x: |
11
+
12
+ ## การรายงานช่องโหว่
13
+
14
+ **โปรดอย่ารายงานช่องโหว่ด้านความปลอดภัยผ่าน GitHub issues สาธารณะ**
15
+
16
+ แทนที่จะเป็นเช่นนั้น โปรดรายงานผ่านอีเมลไปที่: **[INSERT SECURITY EMAIL]**
17
+
18
+ คุณควรได้รับการตอบกลับภายใน 48 ชั่วโมง หากคุณไม่ได้รับการตอบกลับด้วยเหตุผลบางอย่าง โปรดติดตามผ่านอีเมลเพื่อให้แน่ใจว่าเราได้รับข้อความเดิมของคุณ
19
+
20
+ โปรดรวมข้อมูลต่อไปนี้ (เท่าที่คุณสามารถให้ได้) เพื่อช่วยให้เราเข้าใจธรรมชาติและขอบเขตของปัญหาที่เป็นไปได้:
21
+
22
+ * ประเภทของปัญหา (เช่น buffer overflow, SQL injection, cross-site scripting ฯลฯ)
23
+ * เส้นทางเต็มของไฟล์ต้นฉบับที่เกี่ยวข้องกับการแสดงออกของปัญหา
24
+ * ตำแหน่งของ source code ที่ได้รับผลกระทบ (tag/branch/commit หรือ URL โดยตรง)
25
+ * การตั้งค่าพิเศษที่จำเป็นในการทำซ้ำปัญหา
26
+ * คำแนะนำทีละขั้นตอนในการทำซ้ำปัญหา
27
+ * Proof-of-concept หรือ exploit code (ถ้าเป็นไปได้)
28
+ * ผลกระทบของปัญหา รวมถึงวิธีที่ผู้โจมตีอาจใช้ประโยชน์จากปัญหา
29
+
30
+ ข้อมูลนี้จะช่วยให้เราจัดลำดับความสำคัญรายงานของคุณได้เร็วขึ้น
31
+
32
+ ## ภาษาที่ต้องการ
33
+
34
+ เราต้องการให้การสื่อสารทั้งหมดเป็นภาษาอังกฤษหรือไทย
35
+
36
+ ## กระบวนการอัปเดตความปลอดภัย
37
+
38
+ 1. **ได้รับรายงาน** - เรารับทราบการรับภายใน 48 ชั่วโมง
39
+ 2. **การสอบสวน** - เราสอบสวนและตรวจสอบความถูกต้องของช่องโหว่
40
+ 3. **การพัฒนาการแก้ไข** - เราพัฒนาและทดสอบการแก้ไข
41
+ 4. **คำแนะนำด้านความปลอดภัย** - เราเผยแพร่คำแนะนำด้านความปลอดภัยถ้าจำเป็น
42
+ 5. **ปล่อย** - เราปล่อยเวอร์ชันที่แพตช์แล้ว
43
+ 6. **การเปิดเผย** - เราเปิดเผยช่องโหว่สาธารณะหลังจากปล่อยการแก้ไขแล้ว
44
+
45
+ ## ข้อพิจารณาด้านความปลอดภัยที่ทราบ
46
+
47
+ ### การเข้าถึงระบบไฟล์
48
+
49
+ แอปพลิเคชันนี้ต้องการการเข้าถึงระบบไฟล์เพื่อ:
50
+ - อ่านไฟล์ Markdown
51
+ - เขียนไฟล์วิดีโอที่เอ็กซ์พอร์ต
52
+ - เข้าถึงโฟลเดอร์ workspace
53
+
54
+ **การบรรเทา:**
55
+ - การดำเนินการไฟล์ทั้งหมดผ่าน `security-core.js` พร้อมการตรวจสอบ path
56
+ - Rate limiting ป้องกันการใช้งานในทางที่ผิด
57
+ - ต้องได้รับความยินยอมจากผู้ใช้สำหรับการดำเนินการไฟล์
58
+
59
+ ### ความปลอดภัย Electron
60
+
61
+ เราปฏิบัติตามแนวทางปฏิบัติที่ดีที่สุดด้านความปลอดภัยของ Electron:
62
+ - เปิดใช้งาน context isolation
63
+ - ปิด Node integration ใน renderer
64
+ - Preload scripts สำหรับการสื่อสาร IPC
65
+ - บังคับใช้ Content Security Policy
66
+
67
+ ### Dependencies จากบุคคลที่สาม
68
+
69
+ เราทำสม่ำเสมอ:
70
+ - อัปเดต dependencies เป็นเวอร์ชันที่ปลอดภัยล่าสุด
71
+ - รัน `npm audit` เพื่อตรวจสอบช่องโหว่
72
+ - ตรวจสอบใบอนุญาตและคำแนะนำด้านความปลอดภัยของ dependency
npm-runner.bat ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ chcp 65001 > nul
3
+ color 0A
4
+ title Chahua Video Builder - Task Runner
5
+
6
+ echo.
7
+
8
+ :MENU
9
+ cls
10
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
11
+ echo ║ 🎬 Chahua Video Builder Toolkit ║
12
+ echo ║ Version 1.0.0 ║
13
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
14
+ echo.
15
+ echo.
16
+ echo --- Common Tasks ---
17
+ echo [1] npm install (ติดตั้ง Dependencies - Electron only)
18
+ echo [2] npm start (เปิดแอพพลิเคชัน Video Builder)
19
+ echo [3] npm run dev (เปิดแอพพลิเคชันพร้อม DevTools)
20
+ echo.
21
+ echo --- Build & Package ---
22
+ echo [4] npm run build (Build ทุกแพลตฟอร์ม)
23
+ echo [5] npm run build:win (Build สำหรับ Windows เท่านั้น)
24
+ echo [6] npm run build:mac (Build สำหรับ macOS เท่านั้น)
25
+ echo [7] npm run build:linux (Build สำหรับ Linux เท่านั้น)
26
+ echo.
27
+ echo --- Utilities ---
28
+ echo [8] Open Workspace (เปิดโฟลเดอร์ workspace/)
29
+ echo [9] Open VS Code (เปิดโปรเจ็กต์ใน VS Code)
30
+ echo.
31
+ echo [0] Exit (ออกจากโปรแกรม)
32
+ echo.
33
+ echo ===================================================
34
+ echo.
35
+
36
+ :: รับ Input จากผู้ใช้
37
+ set /p "CHOICE=เลือกหมายเลข (0-9) และกด Enter: "
38
+
39
+ :: ตรวจสอบตัวเลือก
40
+ if "%CHOICE%"=="1" goto INSTALL
41
+ if "%CHOICE%"=="2" goto START
42
+ if "%CHOICE%"=="3" goto DEV
43
+ if "%CHOICE%"=="4" goto BUILD
44
+ if "%CHOICE%"=="5" goto BUILD_WIN
45
+ if "%CHOICE%"=="6" goto BUILD_MAC
46
+ if "%CHOICE%"=="7" goto BUILD_LINUX
47
+ if "%CHOICE%"=="8" goto OPEN_WORKSPACE
48
+ if "%CHOICE%"=="9" goto OPEN_CODE
49
+ if "%CHOICE%"=="0" goto EXIT
50
+
51
+ :: ถ้าพิมพ์ผิด
52
+ echo.
53
+ echo ❌ ตัวเลือกไม่ถูกต้อง กรุณาลองใหม่อีกครั้ง
54
+ echo.
55
+ pause
56
+ goto MENU
57
+
58
+
59
+ :: =================================
60
+ :: ## Action Sections ##
61
+ :: =================================
62
+
63
+ :INSTALL
64
+ cls
65
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
66
+ echo ║ 📦 Installing Dependencies ║
67
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
68
+ echo.
69
+ echo Installing Electron and electron-builder (only dependencies)...
70
+ echo.
71
+ call npm install
72
+ echo.
73
+ if %ERRORLEVEL% EQU 0 (
74
+ echo ✅ Installation completed successfully!
75
+ ) else (
76
+ echo ❌ Installation failed! Error code: %ERRORLEVEL%
77
+ )
78
+ echo.
79
+ pause
80
+ goto MENU
81
+
82
+ :START
83
+ cls
84
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
85
+ echo ║ 🚀 Starting Video Builder App ║
86
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
87
+ echo.
88
+ echo Launching Chahua Video Builder...
89
+ echo Press Ctrl+C to stop the application.
90
+ echo.
91
+ call npm start
92
+ echo.
93
+ echo.
94
+ echo ✅ Application closed.
95
+ pause
96
+ goto MENU
97
+
98
+ :DEV
99
+ cls
100
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
101
+ echo ║ 🔧 Starting Development Mode (with DevTools) ║
102
+ echo ╚════════════════════════════════════════════════════════════════════════════════���
103
+ echo.
104
+ echo Launching with Developer Tools enabled...
105
+ echo Press Ctrl+C to stop the application.
106
+ echo.
107
+ call npm run dev
108
+ echo.
109
+ echo.
110
+ echo ✅ Development session ended.
111
+ pause
112
+ goto MENU
113
+
114
+ :BUILD
115
+ cls
116
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
117
+ echo ║ 🏗️ Building for All Platforms ║
118
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
119
+ echo.
120
+ echo Building Windows (NSIS), macOS (DMG), and Linux (AppImage)...
121
+ echo This may take several minutes...
122
+ echo.
123
+ call npm run build
124
+ echo.
125
+ if %ERRORLEVEL% EQU 0 (
126
+ echo ✅ Build completed successfully!
127
+ echo 📁 Output: dist/ folder
128
+ ) else (
129
+ echo ❌ Build failed! Error code: %ERRORLEVEL%
130
+ )
131
+ echo.
132
+ pause
133
+ goto MENU
134
+
135
+ :BUILD_WIN
136
+ cls
137
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
138
+ echo ║ 🪟 Building for Windows Only ║
139
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
140
+ echo.
141
+ echo Building Windows installer (NSIS)...
142
+ echo Output format: .exe installer
143
+ echo.
144
+ call npm run build:win
145
+ echo.
146
+ if %ERRORLEVEL% EQU 0 (
147
+ echo ✅ Windows build completed successfully!
148
+ echo 📁 Output: dist/ folder
149
+ echo 📦 Installer ready for distribution
150
+ ) else (
151
+ echo ❌ Build failed! Error code: %ERRORLEVEL%
152
+ )
153
+ echo.
154
+ pause
155
+ goto MENU
156
+
157
+ :BUILD_MAC
158
+ cls
159
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
160
+ echo ║ 🍎 Building for macOS Only ║
161
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
162
+ echo.
163
+ echo Building macOS installer (DMG)...
164
+ echo ⚠️ Note: macOS builds work best on macOS systems
165
+ echo.
166
+ call npm run build:mac
167
+ echo.
168
+ if %ERRORLEVEL% EQU 0 (
169
+ echo ✅ macOS build completed successfully!
170
+ echo 📁 Output: dist/ folder
171
+ ) else (
172
+ echo ❌ Build failed! Error code: %ERRORLEVEL%
173
+ )
174
+ echo.
175
+ pause
176
+ goto MENU
177
+
178
+ :BUILD_LINUX
179
+ cls
180
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
181
+ echo ║ 🐧 Building for Linux Only ║
182
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
183
+ echo.
184
+ echo Building Linux installer (AppImage)...
185
+ echo.
186
+ call npm run build:linux
187
+ echo.
188
+ if %ERRORLEVEL% EQU 0 (
189
+ echo ✅ Linux build completed successfully!
190
+ echo 📁 Output: dist/ folder
191
+ ) else (
192
+ echo ❌ Build failed! Error code: %ERRORLEVEL%
193
+ )
194
+ echo.
195
+ pause
196
+ goto MENU
197
+
198
+ :OPEN_WORKSPACE
199
+ cls
200
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
201
+ echo ║ 📂 Opening Workspace Folder ║
202
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
203
+ echo.
204
+ echo Opening workspace/ folder for your code files...
205
+ echo.
206
+ if exist "workspace" (
207
+ explorer workspace
208
+ echo ✅ Workspace folder opened!
209
+ ) else (
210
+ echo ❌ Workspace folder not found!
211
+ echo Creating workspace folder...
212
+ mkdir workspace
213
+ echo ✅ Created workspace folder!
214
+ explorer workspace
215
+ )
216
+ echo.
217
+ timeout /t 2 /nobreak > nul
218
+ goto MENU
219
+
220
+ :OPEN_CODE
221
+ cls
222
+ echo ╔════════════════════════════════════════════════════════════════════════════════╗
223
+ echo ║ 💻 Opening in VS Code ║
224
+ echo ╚════════════════════════════════════════════════════════════════════════════════╝
225
+ echo.
226
+ echo Opening current project in Visual Studio Code...
227
+ echo.
228
+ code .
229
+ if %ERRORLEVEL% EQU 0 (
230
+ echo ✅ VS Code opened successfully!
231
+ ) else (
232
+ echo ❌ Could not open VS Code. Is it installed?
233
+ )
234
+ echo.
235
+ timeout /t 2 /nobreak > nul
236
+ goto MENU
237
+
238
+ :EXIT
239
+ exit /b
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "chahuadev-markdown-presenter",
3
+ "version": "2.0.0",
4
+ "description": "Transform Markdown into Professional Video Presentations - PowerPoint-style slides with animations and transitions. Truly offline-first, zero external dependencies.",
5
+ "main": "src/main/main.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "start": "electron .",
9
+ "dev": "electron . --enable-logging",
10
+ "build": "electron-builder",
11
+ "build:win": "electron-builder --win",
12
+ "build:mac": "electron-builder --mac",
13
+ "build:linux": "electron-builder --linux"
14
+ },
15
+ "keywords": [
16
+ "electron",
17
+ "markdown",
18
+ "presentation",
19
+ "chahuadev",
20
+ "markdown-to-video",
21
+ "slides",
22
+ "powerpoint",
23
+ "webm",
24
+ "gif",
25
+ "native",
26
+ "zero-dependencies"
27
+ ],
28
+ "author": "Chahua Development Co., Ltd.",
29
+ "license": "MIT",
30
+ "devDependencies": {
31
+ "electron": "^28.0.0",
32
+ "electron-builder": "^24.9.1"
33
+ },
34
+ "build": {
35
+ "appId": "com.chahuadev.markdownpresenter",
36
+ "productName": "Chahua Markdown Presenter",
37
+ "directories": {
38
+ "output": "dist"
39
+ },
40
+ "files": [
41
+ "**/*",
42
+ "!**/*.md",
43
+ "!dist",
44
+ "!node_modules"
45
+ ],
46
+ "win": {
47
+ "target": "nsis",
48
+ "icon": "icon.ico"
49
+ },
50
+ "mac": {
51
+ "target": "dmg",
52
+ "icon": "icon.icns"
53
+ },
54
+ "linux": {
55
+ "target": "AppImage",
56
+ "icon": "icon.png"
57
+ }
58
+ }
59
+ }
src/README.md ADDED
Binary file (66 Bytes). View file
 
src/main/main.js ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Main Process
3
+ // 100% Native Implementation - No External Dependencies
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ import { app, BrowserWindow, ipcMain, dialog } from 'electron';
11
+ import path from 'node:path';
12
+ import url from 'node:url';
13
+ import fs from 'node:fs/promises';
14
+ import { createReadStream, createWriteStream } from 'node:fs';
15
+ import crypto from 'node:crypto';
16
+
17
+ const appDir = path.dirname(url.fileURLToPath(import.meta.url));
18
+ const rootDir = path.join(appDir, '..', '..');
19
+
20
+ // ══════════════════════════════════════════════════════════════════════════════
21
+ // Security Manager Integration
22
+ // ══════════════════════════════════════════════════════════════════════════════
23
+
24
+ let SecurityManager;
25
+ let securityInstance;
26
+
27
+ async function initializeSecurity() {
28
+ try {
29
+ const securityModule = await import('../shared/security-core.js');
30
+ SecurityManager = securityModule.SecurityManager;
31
+ securityInstance = new SecurityManager({
32
+ EXTRA_ALLOWED_DIRS: [
33
+ app.getPath('documents'),
34
+ app.getPath('downloads'),
35
+ path.join(rootDir, 'workspace'),
36
+ path.join(rootDir, 'examples')
37
+ ]
38
+ });
39
+ console.log('[Security] Security system initialized');
40
+ console.log('[Security] Whitelisted folders:', [
41
+ 'Documents',
42
+ 'Downloads',
43
+ path.join(rootDir, 'workspace'),
44
+ path.join(rootDir, 'examples')
45
+ ]);
46
+ } catch (error) {
47
+ console.error('[Security] Failed to initialize security:', error);
48
+ }
49
+ }
50
+
51
+ // ══════════════════════════════════════════════════════════════════════════════
52
+ // Window Management
53
+ // ══════════════════════════════════════════════════════════════════════════════
54
+
55
+ const createWindow = async () => {
56
+ const win = new BrowserWindow({
57
+ width: 1600,
58
+ height: 1000,
59
+ minWidth: 1200,
60
+ minHeight: 700,
61
+ backgroundColor: '#020617',
62
+ autoHideMenuBar: true,
63
+ show: false,
64
+ webPreferences: {
65
+ preload: path.join(appDir, 'preload.cjs'),
66
+ contextIsolation: true,
67
+ nodeIntegration: false,
68
+ sandbox: false,
69
+ webSecurity: true
70
+ }
71
+ });
72
+
73
+ win.once('ready-to-show', () => {
74
+ win.show();
75
+ });
76
+
77
+ await win.loadFile(path.join(rootDir, 'src', 'renderer', 'index.html'));
78
+
79
+ // Dev tools in development mode
80
+ if (process.env.NODE_ENV === 'development') {
81
+ win.webContents.openDevTools();
82
+ }
83
+
84
+ return win;
85
+ };
86
+
87
+ // ══════════════════════════════════════════════════════════════════════════════
88
+ // IPC Handlers - File Operations
89
+ // ══════════════════════════════════════════════════════════════════════════════
90
+
91
+ ipcMain.handle('file:selectFile', async () => {
92
+ try {
93
+ const result = await dialog.showOpenDialog({
94
+ title: 'Select Code File',
95
+ defaultPath: path.join(rootDir, 'workspace'),
96
+ properties: ['openFile'],
97
+ filters: [
98
+ { name: 'Code Files', extensions: ['js', 'ts', 'jsx', 'tsx', 'vue', 'svelte', 'py', 'java', 'cpp', 'c', 'cs', 'go', 'rs', 'rb', 'php'] },
99
+ { name: 'Web Files', extensions: ['html', 'css', 'scss', 'sass', 'less'] },
100
+ { name: 'Config Files', extensions: ['json', 'yml', 'yaml', 'toml', 'xml'] },
101
+ { name: 'All Files', extensions: ['*'] }
102
+ ]
103
+ });
104
+
105
+ if (result.canceled || result.filePaths.length === 0) {
106
+ return { success: false, canceled: true };
107
+ }
108
+
109
+ const filePath = result.filePaths[0];
110
+
111
+ // Security validation
112
+ if (securityInstance) {
113
+ const validation = await securityInstance.secureReadFile(filePath);
114
+ return {
115
+ success: true,
116
+ filePath: validation.filePath,
117
+ content: validation.content,
118
+ size: validation.size,
119
+ hash: validation.hash
120
+ };
121
+ } else {
122
+ // Fallback without security
123
+ const content = await fs.readFile(filePath, 'utf-8');
124
+ return {
125
+ success: true,
126
+ filePath,
127
+ content,
128
+ size: content.length
129
+ };
130
+ }
131
+ } catch (error) {
132
+ console.error('[File] Error selecting file:', error);
133
+ return {
134
+ success: false,
135
+ error: error.message
136
+ };
137
+ }
138
+ });
139
+
140
+ ipcMain.handle('file:readFile', async (event, filePath) => {
141
+ try {
142
+ if (securityInstance) {
143
+ const validation = await securityInstance.secureReadFile(filePath);
144
+ return {
145
+ success: true,
146
+ content: validation.content,
147
+ size: validation.size,
148
+ hash: validation.hash
149
+ };
150
+ } else {
151
+ const content = await fs.readFile(filePath, 'utf-8');
152
+ return {
153
+ success: true,
154
+ content,
155
+ size: content.length
156
+ };
157
+ }
158
+ } catch (error) {
159
+ console.error('[File] Error reading file:', error);
160
+ return {
161
+ success: false,
162
+ error: error.message
163
+ };
164
+ }
165
+ });
166
+
167
+ // ══════════════════════════════════════════════════════════════════════════════
168
+ // IPC Handlers - Markdown Operations
169
+ // ══════════════════════════════════════════════════════════════════════════════
170
+
171
+ ipcMain.handle('markdown:openFile', async () => {
172
+ try {
173
+ const result = await dialog.showOpenDialog({
174
+ title: 'Open Markdown File',
175
+ defaultPath: path.join(rootDir, 'workspace'),
176
+ properties: ['openFile'],
177
+ filters: [
178
+ { name: 'Markdown Files', extensions: ['md', 'markdown'] },
179
+ { name: 'Text Files', extensions: ['txt'] },
180
+ { name: 'All Files', extensions: ['*'] }
181
+ ]
182
+ });
183
+
184
+ if (result.canceled || result.filePaths.length === 0) {
185
+ return { success: false, canceled: true };
186
+ }
187
+
188
+ const filePath = result.filePaths[0];
189
+
190
+ // Security validation
191
+ if (securityInstance) {
192
+ const validation = await securityInstance.secureReadFile(filePath);
193
+ return {
194
+ success: true,
195
+ filePath: validation.filePath,
196
+ content: validation.content,
197
+ size: validation.size,
198
+ hash: validation.hash
199
+ };
200
+ } else {
201
+ const content = await fs.readFile(filePath, 'utf-8');
202
+ return {
203
+ success: true,
204
+ filePath,
205
+ content,
206
+ size: content.length
207
+ };
208
+ }
209
+ } catch (error) {
210
+ console.error('[Markdown] Error opening file:', error);
211
+ return {
212
+ success: false,
213
+ error: error.message
214
+ };
215
+ }
216
+ });
217
+
218
+ ipcMain.handle('workspace:open', async () => {
219
+ try {
220
+ const workspacePath = path.join(rootDir, 'workspace');
221
+
222
+ // Ensure workspace folder exists
223
+ try {
224
+ await fs.access(workspacePath);
225
+ } catch {
226
+ await fs.mkdir(workspacePath, { recursive: true });
227
+ }
228
+
229
+ // Open in system file explorer
230
+ const { shell } = await import('electron');
231
+ await shell.openPath(workspacePath);
232
+
233
+ return { success: true, path: workspacePath };
234
+ } catch (error) {
235
+ console.error('[Workspace] Error opening workspace:', error);
236
+ return {
237
+ success: false,
238
+ error: error.message
239
+ };
240
+ }
241
+ });
242
+
243
+ // ══════════════════════════════════════════════════════════════════════════════
244
+ // IPC Handlers - Video Operations
245
+ // ══════════════════════════════════════════════════════════════════════════════
246
+
247
+ ipcMain.handle('video:saveVideo', async (event, { blob, format, filename }) => {
248
+ try {
249
+ const result = await dialog.showSaveDialog({
250
+ title: 'Save Video File',
251
+ defaultPath: path.join(rootDir, 'workspace', filename || `chahua-video-${Date.now()}.${format}`),
252
+ filters: [
253
+ { name: 'WebM Video', extensions: ['webm'] },
254
+ { name: 'All Files', extensions: ['*'] }
255
+ ]
256
+ });
257
+
258
+ if (result.canceled) {
259
+ return { success: false, canceled: true };
260
+ }
261
+
262
+ // Convert base64 to buffer
263
+ const buffer = Buffer.from(blob.split(',')[1], 'base64');
264
+ await fs.writeFile(result.filePath, buffer);
265
+
266
+ return {
267
+ success: true,
268
+ filePath: result.filePath,
269
+ size: buffer.length
270
+ };
271
+ } catch (error) {
272
+ console.error('[Video] Error saving video:', error);
273
+ return {
274
+ success: false,
275
+ error: error.message
276
+ };
277
+ }
278
+ });
279
+
280
+ ipcMain.handle('video:saveGIF', async (event, { frames, filename }) => {
281
+ try {
282
+ const result = await dialog.showSaveDialog({
283
+ title: 'Save GIF File',
284
+ defaultPath: path.join(rootDir, 'workspace', filename || `chahua-video-${Date.now()}.gif`),
285
+ filters: [
286
+ { name: 'GIF Files', extensions: ['gif'] },
287
+ { name: 'All Files', extensions: ['*'] }
288
+ ]
289
+ });
290
+
291
+ if (result.canceled) {
292
+ return { success: false, canceled: true };
293
+ }
294
+
295
+ // Simple GIF encoding (native implementation)
296
+ const gifBuffer = await encodeGIF(frames);
297
+ await fs.writeFile(result.filePath, gifBuffer);
298
+
299
+ return {
300
+ success: true,
301
+ filePath: result.filePath,
302
+ size: gifBuffer.length
303
+ };
304
+ } catch (error) {
305
+ console.error('[Video] Error saving GIF:', error);
306
+ return {
307
+ success: false,
308
+ error: error.message
309
+ };
310
+ }
311
+ });
312
+
313
+ // ══════════════════════════════════════════════════════════════════════════════
314
+ // Native GIF Encoder (Simple Implementation)
315
+ // ══════════════════════════════════════════════════════════════════════════════
316
+
317
+ async function encodeGIF(frames) {
318
+ // GIF Header
319
+ const header = Buffer.from('GIF89a', 'ascii');
320
+
321
+ // Logical Screen Descriptor
322
+ const width = frames[0].width || 1920;
323
+ const height = frames[0].height || 1080;
324
+ const lsd = Buffer.alloc(7);
325
+ lsd.writeUInt16LE(width, 0);
326
+ lsd.writeUInt16LE(height, 2);
327
+ lsd[4] = 0xF7; // Global color table flag
328
+ lsd[5] = 0x00; // Background color
329
+ lsd[6] = 0x00; // Aspect ratio
330
+
331
+ // Simple color table (256 colors)
332
+ const colorTable = Buffer.alloc(768);
333
+ for (let i = 0; i < 256; i++) {
334
+ colorTable[i * 3] = i;
335
+ colorTable[i * 3 + 1] = i;
336
+ colorTable[i * 3 + 2] = i;
337
+ }
338
+
339
+ // Application Extension for looping
340
+ const appExt = Buffer.from([
341
+ 0x21, 0xFF, 0x0B,
342
+ 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45,
343
+ 0x32, 0x2E, 0x30,
344
+ 0x03, 0x01, 0x00, 0x00, 0x00
345
+ ]);
346
+
347
+ const frameBuffers = [];
348
+
349
+ for (const frame of frames) {
350
+ // Graphics Control Extension
351
+ const gce = Buffer.from([
352
+ 0x21, 0xF9, 0x04,
353
+ 0x04, // Disposal method
354
+ 0x0A, 0x00, // Delay time (100ms)
355
+ 0x00, // Transparent color
356
+ 0x00
357
+ ]);
358
+
359
+ // Image Descriptor
360
+ const imgDesc = Buffer.alloc(10);
361
+ imgDesc[0] = 0x2C;
362
+ imgDesc.writeUInt16LE(0, 1); // Left
363
+ imgDesc.writeUInt16LE(0, 3); // Top
364
+ imgDesc.writeUInt16LE(width, 5); // Width
365
+ imgDesc.writeUInt16LE(height, 7); // Height
366
+ imgDesc[9] = 0x00;
367
+
368
+ // Image data (simplified - just use the frame data as-is)
369
+ const imageData = Buffer.from(frame.data || []);
370
+
371
+ frameBuffers.push(Buffer.concat([gce, imgDesc, imageData]));
372
+ }
373
+
374
+ // Trailer
375
+ const trailer = Buffer.from([0x3B]);
376
+
377
+ return Buffer.concat([header, lsd, colorTable, appExt, ...frameBuffers, trailer]);
378
+ }
379
+
380
+ // ══════════════════════════════════════════════════════════════════════════════
381
+ // IPC Handlers - Security Operations
382
+ // ══════════════════════════════════════════════════════════════════════════════
383
+
384
+ ipcMain.handle('security:getStats', async () => {
385
+ try {
386
+ if (securityInstance) {
387
+ return {
388
+ success: true,
389
+ stats: securityInstance.getSecurityStats()
390
+ };
391
+ }
392
+ return { success: false, error: 'Security not initialized' };
393
+ } catch (error) {
394
+ return { success: false, error: error.message };
395
+ }
396
+ });
397
+
398
+ ipcMain.handle('security:exportLog', async () => {
399
+ try {
400
+ if (securityInstance) {
401
+ const log = securityInstance.exportSecurityLog();
402
+
403
+ const result = await dialog.showSaveDialog({
404
+ title: 'Export Security Log',
405
+ defaultPath: path.join(rootDir, 'workspace', `security-log-${Date.now()}.json`),
406
+ filters: [
407
+ { name: 'JSON Files', extensions: ['json'] },
408
+ { name: 'All Files', extensions: ['*'] }
409
+ ]
410
+ });
411
+
412
+ if (result.canceled) {
413
+ return { success: false, canceled: true };
414
+ }
415
+
416
+ await fs.writeFile(result.filePath, JSON.stringify(log, null, 2));
417
+
418
+ return {
419
+ success: true,
420
+ filePath: result.filePath
421
+ };
422
+ }
423
+ return { success: false, error: 'Security not initialized' };
424
+ } catch (error) {
425
+ return { success: false, error: error.message };
426
+ }
427
+ });
428
+
429
+ // ══════════════════════════════════════════════════════════════════════════════
430
+ // IPC Handlers - System Operations
431
+ // ══════════════════════════════════════════════════════════════════════════════
432
+
433
+ ipcMain.handle('system:ping', () => {
434
+ return {
435
+ timestamp: Date.now(),
436
+ version: app.getVersion(),
437
+ platform: process.platform
438
+ };
439
+ });
440
+
441
+ ipcMain.handle('system:getInfo', () => {
442
+ return {
443
+ appVersion: app.getVersion(),
444
+ electronVersion: process.versions.electron,
445
+ nodeVersion: process.versions.node,
446
+ platform: process.platform,
447
+ arch: process.arch,
448
+ paths: {
449
+ documents: app.getPath('documents'),
450
+ downloads: app.getPath('downloads'),
451
+ workspace: path.join(rootDir, 'workspace'),
452
+ examples: path.join(rootDir, 'examples'),
453
+ root: rootDir
454
+ }
455
+ };
456
+ });
457
+
458
+ // ══════════════════════════════════════════════════════════════════════════════
459
+ // App Initialization
460
+ // ══════════════════════════════════════════════════════════════════════════════
461
+
462
+ app.whenReady().then(async () => {
463
+ await initializeSecurity();
464
+ createWindow();
465
+
466
+ app.on('activate', () => {
467
+ if (BrowserWindow.getAllWindows().length === 0) {
468
+ createWindow();
469
+ }
470
+ });
471
+ });
472
+
473
+ app.on('window-all-closed', () => {
474
+ if (process.platform !== 'darwin') {
475
+ app.quit();
476
+ }
477
+ });
478
+
479
+ // ══════════════════════════════════════════════════════════════════════════════
480
+ // Error Handling
481
+ // ══════════════════════════════════════════════════════════════════════════════
482
+
483
+ process.on('uncaughtException', (error) => {
484
+ console.error('[Main] Uncaught Exception:', error);
485
+ });
486
+
487
+ process.on('unhandledRejection', (reason, promise) => {
488
+ console.error('[Main] Unhandled Rejection at:', promise, 'reason:', reason);
489
+ });
src/main/preload.cjs ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Preload Script
3
+ // Secure Bridge between Main and Renderer Process
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ const { contextBridge, ipcRenderer } = require('electron');
11
+
12
+ console.log('[Preload] Preload script loaded successfully');
13
+
14
+ // ══════════════════════════════════════════════════════════════════════════════
15
+ // Exposed API to Renderer Process
16
+ // ══════════════════════════════════════════════════════════════════════════════
17
+
18
+ contextBridge.exposeInMainWorld('chahuaVideo', {
19
+ // ════════════════════════════════════════════════════════════════════════════
20
+ // File Operations
21
+ // ════════════════════════════════════════════════════════════════════════════
22
+
23
+ selectFile: () => ipcRenderer.invoke('file:selectFile'),
24
+
25
+ readFile: (filePath) => ipcRenderer.invoke('file:readFile', filePath),
26
+
27
+ // ════════════════════════════════════════════════════════════════════════════
28
+ // Markdown Operations
29
+ // ════════════════════════════════════════════════════════════════════════════
30
+
31
+ openMarkdownFile: () => ipcRenderer.invoke('markdown:openFile'),
32
+
33
+ openWorkspaceFolder: () => ipcRenderer.invoke('workspace:open'),
34
+
35
+ // ════════════════════════════════════════════════════════════════════════════
36
+ // Video Operations
37
+ // ════════════════════════════════════════════════════════════════════════════
38
+
39
+ saveVideo: (data) => ipcRenderer.invoke('video:saveVideo', data),
40
+
41
+ saveGIF: (data) => ipcRenderer.invoke('video:saveGIF', data),
42
+
43
+ // ════════════════════════════════════════════════════════════════════════════
44
+ // Security Operations
45
+ // ════════════════════════════════════════════════════════════════════════════
46
+
47
+ getSecurityStats: () => ipcRenderer.invoke('security:getStats'),
48
+
49
+ exportSecurityLog: () => ipcRenderer.invoke('security:exportLog'),
50
+
51
+ // ════════════════════════════════════════════════════════════════════════════
52
+ // System Operations
53
+ // ════════════════════════════════════════════════════════════════════════════
54
+
55
+ ping: () => ipcRenderer.invoke('system:ping'),
56
+
57
+ getSystemInfo: () => ipcRenderer.invoke('system:getInfo'),
58
+
59
+ // ════════════════════════════════════════════════════════════════════════════
60
+ // Version Info
61
+ // ════════════════════════════════════════════════════════════════════════════
62
+
63
+ version: '1.0.0',
64
+
65
+ platform: process.platform
66
+ });
67
+
68
+ console.log('[Preload] chahuaVideo API exposed to window object');
69
+ console.log('[Preload] API includes:', [
70
+ 'selectFile', 'readFile', 'openMarkdownFile', 'openWorkspaceFolder',
71
+ 'saveVideo', 'saveGIF', 'getSecurityStats', 'exportSecurityLog',
72
+ 'ping', 'getSystemInfo', 'version', 'platform'
73
+ ]);
src/main/preload.js ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Preload Script
3
+ // Secure Bridge between Main and Renderer Process
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ import { contextBridge, ipcRenderer } from 'electron';
11
+
12
+ console.log('[Preload] Preload script loaded successfully');
13
+
14
+ // ══════════════════════════════════════════════════════════════════════════════
15
+ // Exposed API to Renderer Process
16
+ // ══════════════════════════════════════════════════════════════════════════════
17
+
18
+ contextBridge.exposeInMainWorld('chahuaVideo', {
19
+ // ════════════════════════════════════════════════════════════════════════════
20
+ // File Operations
21
+ // ════════════════════════════════════════════════════════════════════════════
22
+
23
+ selectFile: () => ipcRenderer.invoke('file:selectFile'),
24
+
25
+ readFile: (filePath) => ipcRenderer.invoke('file:readFile', filePath),
26
+
27
+ // ════════════════════════════════════════════════════════════════════════════
28
+ // Video Operations
29
+ // ════════════════════════════════════════════════════════════════════════════
30
+
31
+ saveVideo: (data) => ipcRenderer.invoke('video:saveVideo', data),
32
+
33
+ saveGIF: (data) => ipcRenderer.invoke('video:saveGIF', data),
34
+
35
+ // ════════════════════════════════════════════════════════════════════════════
36
+ // Security Operations
37
+ // ════════════════════════════════════════════════════════════════════════════
38
+
39
+ getSecurityStats: () => ipcRenderer.invoke('security:getStats'),
40
+
41
+ exportSecurityLog: () => ipcRenderer.invoke('security:exportLog'),
42
+
43
+ // ════════════════════════════════════════════════════════════════════════════
44
+ // System Operations
45
+ // ════════════════════════════════════════════════════════════════════════════
46
+
47
+ ping: () => ipcRenderer.invoke('system:ping'),
48
+
49
+ getSystemInfo: () => ipcRenderer.invoke('system:getInfo'),
50
+
51
+ // ════════════════════════════════════════════════════════════════════════════
52
+ // Version Info
53
+ // ════════════════════════════════════════════════════════════════════════════
54
+
55
+ version: '1.0.0',
56
+
57
+ platform: process.platform
58
+ });
59
+
60
+ console.log('[Preload] chahuaVideo API exposed to window object');
61
+ console.log('[Preload] Available methods:', Object.keys(window.chahuaVideo || {}));
src/main/preload.mjs ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Preload Script (ES Module)
3
+ // Secure Bridge between Main and Renderer Process
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ import { contextBridge, ipcRenderer } from 'electron';
11
+
12
+ console.log('[Preload] Preload script loaded successfully');
13
+
14
+ // ══════════════════════════════════════════════════════════════════════════════
15
+ // Exposed API to Renderer Process
16
+ // ══════════════════════════════════════════════════════════════════════════════
17
+
18
+ contextBridge.exposeInMainWorld('chahuaVideo', {
19
+ // ════════════════════════════════════════════════════════════════════════════
20
+ // File Operations
21
+ // ════════════════════════════════════════════════════════════════════════════
22
+
23
+ selectFile: () => ipcRenderer.invoke('file:selectFile'),
24
+
25
+ readFile: (filePath) => ipcRenderer.invoke('file:readFile', filePath),
26
+
27
+ // ════════════════════════════════════════════════════════════════════════════
28
+ // Video Operations
29
+ // ════════════════════════════════════════════════════════════════════════════
30
+
31
+ saveVideo: (data) => ipcRenderer.invoke('video:saveVideo', data),
32
+
33
+ saveGIF: (data) => ipcRenderer.invoke('video:saveGIF', data),
34
+
35
+ // ════════════════════════════════════════════════════════════════════════════
36
+ // Security Operations
37
+ // ════════════════════════════════════════════════════════════════════════════
38
+
39
+ getSecurityStats: () => ipcRenderer.invoke('security:getStats'),
40
+
41
+ exportSecurityLog: () => ipcRenderer.invoke('security:exportLog'),
42
+
43
+ // ════════════════════════════════════════════════════════════════════════════
44
+ // System Operations
45
+ // ════════════════════════════════════════════════════════════════════════════
46
+
47
+ ping: () => ipcRenderer.invoke('system:ping'),
48
+
49
+ getSystemInfo: () => ipcRenderer.invoke('system:getInfo'),
50
+
51
+ // ════════════════════════════════════════════════════════════════════════════
52
+ // Version Info
53
+ // ════════════════════════════════════════════════════════════════════════════
54
+
55
+ version: '1.0.0',
56
+
57
+ platform: process.platform
58
+ });
59
+
60
+ console.log('[Preload] chahuaVideo API exposed to window object');
61
+ console.log('[Preload] Available methods:', Object.keys(window.chahuaVideo || {}));
src/renderer/css/style.css ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ══════════════════════════════════════════════════════════════════════════════
2
+ Chahua Video Builder - Main Stylesheet
3
+ Professional Edition - Clean and Modern Design
4
+ ══════════════════════════════════════════════════════════════════════════════
5
+ Company: Chahua Development Co., Ltd.
6
+ Version: 1.0.0
7
+ License: MIT
8
+ ══════════════════════════════════════════════════════════════════════════════ */
9
+
10
+ /* ════════════════════════════════════════════════════════════════════════════
11
+ CSS Variables (Design Tokens)
12
+ ════════════════════════════════════════════════════════════════════════════ */
13
+
14
+ :root {
15
+ /* Primary Colors - Dark Blue Theme */
16
+ --accent-color: #3b82f6;
17
+ --color-primary: #3b82f6;
18
+ --color-secondary: #06b6d4;
19
+
20
+ /* Background Colors */
21
+ --color-background: #0a1628;
22
+ --color-surface: #132337;
23
+ --color-surface-hover: #1a2f47;
24
+ --color-border: #1e3a5f;
25
+
26
+ /* Text Colors */
27
+ --color-text: #e2e8f0;
28
+ --color-text-secondary: #94a3b8;
29
+ --color-text-muted: #64748b;
30
+
31
+ /* Accent Colors */
32
+ --color-cyan: #06b6d4;
33
+ --color-blue: #3b82f6;
34
+ --color-success: #10b981;
35
+ --color-warning: #f59e0b;
36
+ --color-error: #ef4444;
37
+
38
+ /* Fonts */
39
+ --font-primary: 'Inter', sans-serif;
40
+ --font-code: 'Source Code Pro', monospace;
41
+
42
+ /* Layout */
43
+ --border-radius: 0.75rem;
44
+ --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2);
45
+ --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.3);
46
+ --content-spacing: 1.5rem;
47
+
48
+ /* UI Elements (will be overridden by presentation-config.js) */
49
+ --preview-opacity: 0.68;
50
+ --overlay-background: rgba(10, 22, 40, 0.85);
51
+ --overlay-blur: 8px;
52
+
53
+ /* Page Indicator (will be overridden by presentation-config.js) */
54
+ --page-indicator-top: 16px;
55
+ --page-indicator-right: 16px;
56
+ --page-indicator-font-size: 0.875rem;
57
+ --page-indicator-opacity: 0.7;
58
+ --page-indicator-padding-x: 12px;
59
+ --page-indicator-padding-y: 4px;
60
+ --page-indicator-bg-color: rgba(22, 78, 99, 0.5);
61
+ --page-indicator-text-color: #a5f3fc;
62
+ --nav-border-width: 2px;
63
+ --nav-border-opacity: 0.5;
64
+
65
+ /* Borders & Accents */
66
+ --heading-accent-border-width: 4px;
67
+ --blockquote-border-width: 4px;
68
+ --image-border-width: 2px;
69
+ --link-underline-width: 2px;
70
+ --table-border-width: 1px;
71
+ --hr-border-width: 2px;
72
+
73
+ /* Effects */
74
+ --backdrop-gradient-color: rgba(59, 130, 246, 0.15);
75
+ --backdrop-gradient-spread: 70%;
76
+ --backdrop-blur: 60px;
77
+ }
78
+
79
+ /* ════════════════════════════════════════════════════════════════════════════
80
+ Base Styles
81
+ ════════════════════════════════════════════════════════════════════════════ */
82
+
83
+ * {
84
+ margin: 0;
85
+ padding: 0;
86
+ box-sizing: border-box;
87
+ }
88
+
89
+ body {
90
+ font-family: var(--font-primary);
91
+ background-color: var(--color-background);
92
+ color: var(--color-text);
93
+ overflow-x: hidden;
94
+ }
95
+
96
+ /* ════════════════════════════════════════════════════════════════════════════
97
+ Video Stage Components
98
+ ════════════════════════════════════════════════════════════════════════════ */
99
+
100
+ .stage-frame {
101
+ position: relative;
102
+ width: 100%;
103
+ padding-top: 56.25%; /* 16:9 aspect ratio */
104
+ border-radius: var(--border-radius);
105
+ overflow: hidden;
106
+ background: var(--color-surface);
107
+ border: 1px solid var(--color-border);
108
+ box-shadow: var(--shadow-lg);
109
+ }
110
+
111
+ #stage {
112
+ position: absolute;
113
+ inset: 0;
114
+ width: 100%;
115
+ height: 100%;
116
+ background-color: var(--color-surface);
117
+ overflow: hidden;
118
+ }
119
+
120
+ /* ════════════════════════════════════════════════════════════════════════════
121
+ Smart Layout Enhancements
122
+ ════════════════════════════════════════════════════════════════════════════ */
123
+
124
+ .smart-layout-root .smart-list {
125
+ list-style: none;
126
+ padding: 0;
127
+ margin: 0 0 var(--content-spacing);
128
+ column-gap: 2.5rem;
129
+ }
130
+
131
+ .smart-layout-root .smart-list li {
132
+ margin-left: 2rem;
133
+ margin-bottom: 0.85rem;
134
+ line-height: var(--line-height-body, 1.45);
135
+ }
136
+
137
+ .smart-layout-root .smart-list.smart-balanced,
138
+ .smart-layout-root .smart-list.smart-balanced-three {
139
+ column-fill: balance;
140
+ }
141
+
142
+ .smart-layout-root .smart-list.smart-balanced {
143
+ column-count: 2;
144
+ }
145
+
146
+ .smart-layout-root .smart-list.smart-balanced-three {
147
+ column-count: 3;
148
+ }
149
+
150
+ .smart-layout-root .smart-list.smart-balanced li,
151
+ .smart-layout-root .smart-list.smart-balanced-three li {
152
+ break-inside: avoid;
153
+ margin-left: 1.25rem !important;
154
+ }
155
+
156
+ .smart-layout-root .smart-list.has-preview li[data-preview="true"] {
157
+ opacity: var(--preview-opacity);
158
+ }
159
+
160
+ /* ════════════════════════════════════════════════════════════════════════════
161
+ Pause Overlay
162
+ ════════════════════════════════════════════════════════════════════════════ */
163
+
164
+ .pause-overlay {
165
+ position: absolute;
166
+ inset: 0;
167
+ display: flex;
168
+ align-items: center;
169
+ justify-content: center;
170
+ background-color: var(--overlay-background, rgba(10, 22, 40, 0.85));
171
+ backdrop-filter: blur(var(--overlay-blur, 8px));
172
+ z-index: 1000;
173
+ transition: opacity 0.3s ease;
174
+ }
175
+
176
+ .pause-overlay.hidden {
177
+ display: none;
178
+ }
179
+
180
+ .pause-indicator {
181
+ text-align: center;
182
+ animation: pulse-pause 2s ease-in-out infinite;
183
+ }
184
+
185
+ .pause-icon {
186
+ font-size: 6rem;
187
+ margin-bottom: 1rem;
188
+ filter: drop-shadow(0 4px 12px rgba(59, 130, 246, 0.5));
189
+ }
190
+
191
+ .pause-text {
192
+ font-size: 2rem;
193
+ font-weight: bold;
194
+ color: var(--color-primary);
195
+ text-transform: uppercase;
196
+ letter-spacing: 0.2em;
197
+ margin-bottom: 0.5rem;
198
+ }
199
+
200
+ .pause-hint {
201
+ font-size: 1rem;
202
+ color: var(--color-text-secondary);
203
+ opacity: 0.8;
204
+ }
205
+
206
+ @keyframes pulse-pause {
207
+ 0%, 100% {
208
+ opacity: 1;
209
+ transform: scale(1);
210
+ }
211
+ 50% {
212
+ opacity: 0.7;
213
+ transform: scale(1.05);
214
+ }
215
+ }
216
+
217
+ /* ════════════════════════════════════════════════════════════════════════════
218
+ Navigation Controls (Presentation Mode)
219
+ ════════════════════════════════════════════════════════════════════════════ */
220
+
221
+ .nav-controls {
222
+ position: absolute;
223
+ bottom: 2rem;
224
+ left: 50%;
225
+ transform: translateX(-50%);
226
+ display: flex;
227
+ align-items: center;
228
+ gap: 1rem;
229
+ z-index: 900;
230
+ transition: opacity 0.3s ease;
231
+ }
232
+
233
+ .nav-controls.hidden {
234
+ display: none;
235
+ }
236
+
237
+ .nav-btn {
238
+ display: flex;
239
+ align-items: center;
240
+ justify-content: center;
241
+ width: 3rem;
242
+ height: 3rem;
243
+ background: var(--color-surface, rgba(19, 35, 55, 0.9));
244
+ border: var(--nav-border-width, 2px) solid rgba(59, 130, 246, var(--nav-border-opacity, 0.5));
245
+ border-radius: 50%;
246
+ color: var(--color-primary);
247
+ cursor: pointer;
248
+ transition: all 0.2s ease;
249
+ backdrop-filter: blur(10px);
250
+ }
251
+
252
+ .nav-btn:hover:not(:disabled) {
253
+ background: rgba(59, 130, 246, 0.2);
254
+ border-color: var(--color-primary);
255
+ transform: scale(1.1);
256
+ box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
257
+ }
258
+
259
+ .nav-btn:disabled {
260
+ opacity: 0.3;
261
+ cursor: not-allowed;
262
+ border-color: rgba(100, 116, 139, 0.3);
263
+ }
264
+
265
+ .nav-arrow {
266
+ font-size: 1.5rem;
267
+ font-weight: bold;
268
+ }
269
+
270
+ .slide-counter {
271
+ padding: 0.5rem 1rem;
272
+ background: rgba(19, 35, 55, 0.9);
273
+ border: 2px solid rgba(59, 130, 246, 0.5);
274
+ border-radius: var(--border-radius);
275
+ color: var(--color-text);
276
+ font-size: 0.875rem;
277
+ font-weight: 600;
278
+ backdrop-filter: blur(10px);
279
+ min-width: 5rem;
280
+ text-align: center;
281
+ }
282
+
283
+ /* ════════════════════════════════════════════════════════════════════════════
284
+ Fullscreen Button
285
+ ════════════════════════════════════════════════════════════════════════════ */
286
+
287
+ .fullscreen-btn {
288
+ position: absolute;
289
+ top: 1rem;
290
+ right: 1rem;
291
+ display: flex;
292
+ align-items: center;
293
+ justify-content: center;
294
+ width: 2.5rem;
295
+ height: 2.5rem;
296
+ background: rgba(19, 35, 55, 0.9);
297
+ border: 2px solid rgba(59, 130, 246, 0.5);
298
+ border-radius: 0.5rem;
299
+ color: var(--color-primary);
300
+ cursor: pointer;
301
+ transition: all 0.2s ease;
302
+ backdrop-filter: blur(10px);
303
+ z-index: 900;
304
+ }
305
+
306
+ .fullscreen-btn:hover {
307
+ background: rgba(59, 130, 246, 0.2);
308
+ border-color: var(--color-primary);
309
+ transform: scale(1.1);
310
+ box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
311
+ }
312
+
313
+ .fullscreen-btn.hidden {
314
+ display: none;
315
+ }
316
+
317
+ .fullscreen-icon {
318
+ font-size: 1.25rem;
319
+ }
320
+
321
+ /* Exit Presentation Mode Button */
322
+ .exit-presentation-btn {
323
+ position: absolute;
324
+ top: 1rem;
325
+ right: 7.5rem;
326
+ display: flex;
327
+ align-items: center;
328
+ justify-content: center;
329
+ width: 2.5rem;
330
+ height: 2.5rem;
331
+ background: rgba(239, 68, 68, 0.9);
332
+ border: 2px solid rgba(248, 113, 113, 0.5);
333
+ border-radius: 0.5rem;
334
+ color: white;
335
+ cursor: pointer;
336
+ transition: all 0.2s ease;
337
+ backdrop-filter: blur(10px);
338
+ z-index: 900;
339
+ }
340
+
341
+ .exit-presentation-btn:hover {
342
+ background: rgba(239, 68, 68, 1);
343
+ border-color: rgba(248, 113, 113, 0.8);
344
+ transform: scale(1.1);
345
+ box-shadow: 0 4px 12px rgba(239, 68, 68, 0.5);
346
+ }
347
+
348
+ .exit-presentation-btn.hidden {
349
+ display: none;
350
+ }
351
+
352
+ .exit-presentation-btn svg {
353
+ display: block;
354
+ }
355
+
356
+ /* Stop Preview Button */
357
+ .stop-preview-btn,
358
+ .stop-export-btn {
359
+ position: absolute;
360
+ top: 1rem;
361
+ right: 11rem;
362
+ display: flex;
363
+ align-items: center;
364
+ justify-content: center;
365
+ width: 2.5rem;
366
+ height: 2.5rem;
367
+ background: rgba(251, 191, 36, 0.9);
368
+ border: 2px solid rgba(252, 211, 77, 0.5);
369
+ border-radius: 0.5rem;
370
+ color: #1e293b;
371
+ cursor: pointer;
372
+ transition: all 0.2s ease;
373
+ backdrop-filter: blur(10px);
374
+ z-index: 900;
375
+ }
376
+
377
+ .stop-preview-btn:hover,
378
+ .stop-export-btn:hover {
379
+ background: rgba(251, 191, 36, 1);
380
+ border-color: rgba(252, 211, 77, 0.8);
381
+ transform: scale(1.1);
382
+ box-shadow: 0 4px 12px rgba(251, 191, 36, 0.5);
383
+ }
384
+
385
+ .stop-preview-btn.hidden,
386
+ .stop-export-btn.hidden {
387
+ display: none;
388
+ }
389
+
390
+ .stop-preview-btn svg,
391
+ .stop-export-btn svg {
392
+ display: block;
393
+ }
394
+
395
+ /* ════════════════════════════════════════════════════════════════════════════
396
+ Slide Edit Controls
397
+ ════════════════════════════════════════════════════════════════════════════ */
398
+
399
+ /* Edit Slide Button (Pencil Icon) */
400
+ .edit-slide-btn {
401
+ position: absolute;
402
+ top: 1rem;
403
+ right: 4.5rem;
404
+ z-index: 900;
405
+ display: flex;
406
+ align-items: center;
407
+ justify-content: center;
408
+ width: 2.5rem;
409
+ height: 2.5rem;
410
+ background: rgba(59, 130, 246, 0.9);
411
+ backdrop-filter: blur(10px);
412
+ border: 2px solid rgba(96, 165, 250, 0.5);
413
+ border-radius: 0.5rem;
414
+ color: white;
415
+ cursor: pointer;
416
+ transition: all 0.2s ease;
417
+ }
418
+
419
+ .edit-slide-btn:hover {
420
+ background: rgba(59, 130, 246, 1);
421
+ border-color: rgba(96, 165, 250, 0.8);
422
+ transform: scale(1.1);
423
+ box-shadow: 0 4px 12px rgba(59, 130, 246, 0.5);
424
+ }
425
+
426
+ .edit-slide-btn.active {
427
+ background: rgba(16, 185, 129, 0.9);
428
+ border-color: rgba(52, 211, 153, 0.5);
429
+ }
430
+
431
+ .edit-slide-btn.active:hover {
432
+ background: rgba(16, 185, 129, 1);
433
+ box-shadow: 0 4px 12px rgba(16, 185, 129, 0.5);
434
+ }
435
+
436
+ .edit-slide-btn svg {
437
+ display: block;
438
+ }
439
+
440
+ /* Save Slide Button */
441
+ .save-slide-btn {
442
+ position: absolute;
443
+ top: 1rem;
444
+ right: 8rem;
445
+ z-index: 900;
446
+ display: flex;
447
+ align-items: center;
448
+ justify-content: center;
449
+ width: 2.5rem;
450
+ height: 2.5rem;
451
+ background: rgba(16, 185, 129, 0.9);
452
+ backdrop-filter: blur(10px);
453
+ border: 2px solid rgba(52, 211, 153, 0.5);
454
+ border-radius: 0.5rem;
455
+ color: white;
456
+ cursor: pointer;
457
+ transition: all 0.2s ease;
458
+ animation: slideInRight 0.3s ease-out;
459
+ }
460
+
461
+ .save-slide-btn:hover {
462
+ background: rgba(16, 185, 129, 1);
463
+ border-color: rgba(52, 211, 153, 0.8);
464
+ transform: scale(1.1);
465
+ box-shadow: 0 4px 12px rgba(16, 185, 129, 0.5);
466
+ }
467
+
468
+ .save-slide-btn svg {
469
+ display: block;
470
+ }
471
+
472
+ /* Cancel Edit Button */
473
+ .cancel-edit-btn {
474
+ position: absolute;
475
+ top: 1rem;
476
+ right: 11.5rem;
477
+ z-index: 900;
478
+ display: flex;
479
+ align-items: center;
480
+ justify-content: center;
481
+ width: 2.5rem;
482
+ height: 2.5rem;
483
+ background: rgba(239, 68, 68, 0.9);
484
+ backdrop-filter: blur(10px);
485
+ border: 2px solid rgba(248, 113, 113, 0.5);
486
+ border-radius: 0.5rem;
487
+ color: white;
488
+ cursor: pointer;
489
+ transition: all 0.2s ease;
490
+ animation: slideInRight 0.3s ease-out;
491
+ }
492
+
493
+ .cancel-edit-btn:hover {
494
+ background: rgba(239, 68, 68, 1);
495
+ border-color: rgba(248, 113, 113, 0.8);
496
+ transform: scale(1.1);
497
+ box-shadow: 0 4px 12px rgba(239, 68, 68, 0.5);
498
+ }
499
+
500
+ .cancel-edit-btn svg {
501
+ display: block;
502
+ }
503
+
504
+ @keyframes slideInRight {
505
+ from {
506
+ opacity: 0;
507
+ transform: translateX(20px);
508
+ }
509
+ to {
510
+ opacity: 1;
511
+ transform: translateX(0);
512
+ }
513
+ }
514
+
515
+ /* Editable Slide Content */
516
+ .slide-editable [contenteditable="true"] {
517
+ outline: 2px dashed rgba(59, 130, 246, 0.5);
518
+ outline-offset: 4px;
519
+ border-radius: 0.375rem;
520
+ padding: 0.5rem;
521
+ min-height: 2rem;
522
+ transition: all 0.2s ease;
523
+ cursor: text;
524
+ }
525
+
526
+ .slide-editable [contenteditable="true"]:hover {
527
+ outline-color: rgba(59, 130, 246, 0.8);
528
+ background: rgba(59, 130, 246, 0.05);
529
+ }
530
+
531
+ .slide-editable [contenteditable="true"]:focus {
532
+ outline: 2px solid rgba(59, 130, 246, 1);
533
+ outline-offset: 4px;
534
+ background: rgba(59, 130, 246, 0.1);
535
+ }
536
+
537
+ .slide-editable [contenteditable="true"]:empty:before {
538
+ content: attr(data-placeholder);
539
+ color: rgba(148, 163, 184, 0.5);
540
+ font-style: italic;
541
+ }
542
+
543
+ /* Edit Mode Indicator */
544
+ .edit-mode-indicator {
545
+ position: absolute;
546
+ top: 1rem;
547
+ left: 1rem;
548
+ z-index: 900;
549
+ background: rgba(59, 130, 246, 0.95);
550
+ backdrop-filter: blur(10px);
551
+ border: 2px solid rgba(96, 165, 250, 0.5);
552
+ border-radius: 0.5rem;
553
+ padding: 0.5rem 1rem;
554
+ color: white;
555
+ font-size: 0.875rem;
556
+ font-weight: 600;
557
+ letter-spacing: 0.05em;
558
+ text-transform: uppercase;
559
+ animation: pulse 2s ease-in-out infinite;
560
+ }
561
+
562
+ @keyframes pulse {
563
+ 0%, 100% {
564
+ opacity: 1;
565
+ }
566
+ 50% {
567
+ opacity: 0.8;
568
+ }
569
+ }
570
+
571
+ /* ═══════════════════════════════════════════════════════════════════════════
572
+ DRAG & DROP SYSTEM STYLES
573
+ ═══════════════════════════════════════════════════════════════════════════ */
574
+
575
+ /* Draggable content */
576
+ .draggable-content {
577
+ cursor: move;
578
+ position: absolute !important;
579
+ user-select: none;
580
+ -webkit-user-select: none;
581
+ -moz-user-select: none;
582
+ -ms-user-select: none;
583
+ transition: box-shadow 0.2s ease, transform 0.1s ease;
584
+ pointer-events: auto;
585
+ }
586
+
587
+ .draggable-content:hover {
588
+ box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
589
+ }
590
+
591
+ .draggable-content.is-dragging {
592
+ cursor: grabbing !important;
593
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
594
+ transform: scale(1.02);
595
+ z-index: 9999 !important;
596
+ opacity: 0.9;
597
+ user-select: none !important;
598
+ -webkit-user-select: none !important;
599
+ pointer-events: none;
600
+ }
601
+
602
+ /* ป้องกันการ select ทั้ง stage ขณะลาก */
603
+ .stage-dragging {
604
+ user-select: none !important;
605
+ -webkit-user-select: none !important;
606
+ cursor: grabbing !important;
607
+ }
608
+
609
+ .stage-dragging * {
610
+ pointer-events: none !important;
611
+ }
612
+
613
+ /* Drag handle */
614
+ .drag-handle {
615
+ position: absolute;
616
+ left: -30px;
617
+ top: 50%;
618
+ transform: translateY(-50%);
619
+ width: 24px;
620
+ height: 24px;
621
+ background: rgba(59, 130, 246, 0.9);
622
+ border-radius: 6px;
623
+ display: flex;
624
+ align-items: center;
625
+ justify-content: center;
626
+ cursor: grab;
627
+ opacity: 0;
628
+ transition: opacity 0.2s ease, background 0.2s ease;
629
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
630
+ }
631
+
632
+ .draggable-content:hover .drag-handle {
633
+ opacity: 1;
634
+ }
635
+
636
+ .drag-handle:hover {
637
+ background: rgba(59, 130, 246, 1);
638
+ }
639
+
640
+ .drag-handle:active {
641
+ cursor: grabbing;
642
+ }
643
+
644
+ .drag-handle svg {
645
+ color: white;
646
+ fill: currentColor;
647
+ }
648
+
649
+ /* Position locked */
650
+ .position-locked {
651
+ cursor: not-allowed !important;
652
+ }
653
+
654
+ .position-locked .drag-handle {
655
+ background: rgba(156, 163, 175, 0.9);
656
+ cursor: not-allowed;
657
+ }
658
+
659
+ .position-locked:hover {
660
+ box-shadow: 0 0 0 2px rgba(156, 163, 175, 0.3);
661
+ }
662
+
663
+ /* Outside safe zone warning */
664
+ .outside-safe-zone {
665
+ box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.6) !important;
666
+ animation: shake 0.3s ease;
667
+ }
668
+
669
+ @keyframes shake {
670
+ 0%, 100% { transform: translateX(0); }
671
+ 25% { transform: translateX(-4px); }
672
+ 75% { transform: translateX(4px); }
673
+ }
674
+
675
+ /* ═══════════════════════════════════════════════════════════════════════════
676
+ SAFE ZONE OVERLAY STYLES - กรอบสีแดงบังคับ
677
+ ═══════════════════════════════════════════════════════════════════════════ */
678
+
679
+ .safe-zone-overlay {
680
+ position: fixed;
681
+ top: 0;
682
+ left: 0;
683
+ right: 0;
684
+ bottom: 0;
685
+ pointer-events: none;
686
+ z-index: 8888;
687
+ opacity: 1;
688
+ }
689
+
690
+ .safe-zone-overlay.hidden {
691
+ opacity: 0;
692
+ pointer-events: none;
693
+ }
694
+
695
+ /* Safe zone borders - กรอบสีแดงบาง */
696
+ .safe-zone-border {
697
+ position: fixed;
698
+ background: transparent;
699
+ pointer-events: none;
700
+ }
701
+
702
+ .safe-zone-top,
703
+ .safe-zone-bottom {
704
+ height: 1px;
705
+ background: rgba(239, 68, 68, 0.8);
706
+ box-shadow: 0 0 4px rgba(239, 68, 68, 0.5);
707
+ }
708
+
709
+ .safe-zone-left,
710
+ .safe-zone-right {
711
+ width: 1px;
712
+ background: rgba(239, 68, 68, 0.8);
713
+ box-shadow: 0 0 4px rgba(239, 68, 68, 0.5);
714
+ }
715
+
716
+ /* เอฟเฟกต์เมื่อลากใกล้ขอบ */
717
+ .safe-zone-overlay.warning .safe-zone-border {
718
+ background: rgba(239, 68, 68, 1);
719
+ animation: pulse-red 0.5s ease infinite;
720
+ }
721
+
722
+ @keyframes pulse-red {
723
+ 0%, 100% {
724
+ opacity: 1;
725
+ filter: brightness(1);
726
+ }
727
+ 50% {
728
+ opacity: 0.7;
729
+ filter: brightness(1.5);
730
+ }
731
+ }
732
+
733
+ /* ═══════════════════════════════════════════════════════════════════════════
734
+ POSITION CONTROLS UI
735
+ ═══════════════════════════════════════════════════════════════════════════ */
736
+
737
+ .position-controls {
738
+ position: fixed;
739
+ bottom: 2rem;
740
+ left: 2rem;
741
+ background: rgba(17, 24, 39, 0.95);
742
+ backdrop-filter: blur(10px);
743
+ border-radius: 12px;
744
+ padding: 1rem;
745
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
746
+ border: 1px solid rgba(255, 255, 255, 0.1);
747
+ z-index: 9000;
748
+ display: flex;
749
+ gap: 0.5rem;
750
+ transition: all 0.3s ease;
751
+ }
752
+
753
+ .position-controls.hidden {
754
+ opacity: 0;
755
+ pointer-events: none;
756
+ transform: translateY(20px);
757
+ }
758
+
759
+ .position-control-btn {
760
+ width: 40px;
761
+ height: 40px;
762
+ background: rgba(59, 130, 246, 0.1);
763
+ border: 1px solid rgba(59, 130, 246, 0.3);
764
+ border-radius: 8px;
765
+ color: rgba(59, 130, 246, 1);
766
+ cursor: pointer;
767
+ display: flex;
768
+ align-items: center;
769
+ justify-content: center;
770
+ transition: all 0.2s ease;
771
+ padding: 0;
772
+ }
773
+
774
+ .position-control-btn:hover {
775
+ background: rgba(59, 130, 246, 0.2);
776
+ border-color: rgba(59, 130, 246, 0.5);
777
+ transform: translateY(-2px);
778
+ }
779
+
780
+ .position-control-btn:active {
781
+ transform: translateY(0);
782
+ }
783
+
784
+ .position-control-btn.active {
785
+ background: rgba(59, 130, 246, 0.3);
786
+ border-color: rgba(59, 130, 246, 0.6);
787
+ }
788
+
789
+ .position-control-btn svg {
790
+ width: 20px;
791
+ height: 20px;
792
+ }
793
+
794
+ /* Position indicator */
795
+ .position-indicator {
796
+ position: fixed;
797
+ top: 1rem;
798
+ left: 50%;
799
+ transform: translateX(-50%);
800
+ background: rgba(17, 24, 39, 0.95);
801
+ backdrop-filter: blur(10px);
802
+ border-radius: 8px;
803
+ padding: 0.5rem 1rem;
804
+ font-size: 0.875rem;
805
+ color: rgba(156, 163, 175, 1);
806
+ font-family: 'Courier New', monospace;
807
+ z-index: 9000;
808
+ pointer-events: none;
809
+ opacity: 0;
810
+ transition: opacity 0.2s ease;
811
+ }
812
+
813
+ .position-indicator.show {
814
+ opacity: 1;
815
+ }
816
+
817
+ .fullscreen-btn.hidden,
818
+ .exit-presentation-btn.hidden,
819
+ .stop-preview-btn.hidden,
820
+ .stop-export-btn.hidden,
821
+ .edit-slide-btn.hidden,
822
+ .save-slide-btn.hidden,
823
+ .cancel-edit-btn.hidden {
824
+ display: none;
825
+ }
826
+
827
+ /* Fullscreen mode adjustments */
828
+ .stage-frame:fullscreen {
829
+ border-radius: 0;
830
+ padding-top: 0;
831
+ }
832
+
833
+ .stage-frame:fullscreen #stage {
834
+ width: 100vw;
835
+ height: 100vh;
836
+ }
837
+
838
+ .stage-frame:-webkit-full-screen {
839
+ border-radius: 0;
840
+ padding-top: 0;
841
+ }
842
+
843
+ .stage-frame:-webkit-full-screen #stage {
844
+ width: 100vw;
845
+ height: 100vh;
846
+ }
847
+
848
+ .stage-frame:-moz-full-screen {
849
+ border-radius: 0;
850
+ padding-top: 0;
851
+ }
852
+
853
+ .stage-frame:-moz-full-screen #stage {
854
+ width: 100vw;
855
+ height: 100vh;
856
+ }
857
+
858
+ .stage-frame:-ms-fullscreen {
859
+ border-radius: 0;
860
+ padding-top: 0;
861
+ }
862
+
863
+ .stage-frame:-ms-fullscreen #stage {
864
+ width: 100vw;
865
+ height: 100vh;
866
+ }
867
+
868
+ /* ════════════════════════════════════════════════════════════════════════════
869
+ Scene Styles
870
+ ════════════════════════════════════════════════════════════════════════════ */
871
+
872
+ .scene {
873
+ position: absolute;
874
+ inset: 0;
875
+ display: flex;
876
+ flex-direction: column;
877
+ justify-content: center;
878
+ align-items: center;
879
+ padding: 0;
880
+ opacity: 0;
881
+ transform: translateY(35px) scale(0.96);
882
+ transition: opacity 0.6s ease, transform 0.6s ease;
883
+ pointer-events: none;
884
+ overflow: hidden;
885
+ box-sizing: border-box;
886
+ word-break: break-word;
887
+ hyphens: auto;
888
+ }
889
+
890
+ .scene.active {
891
+ opacity: 1;
892
+ transform: translateY(0) scale(1);
893
+ pointer-events: auto;
894
+ }
895
+
896
+ .scene > * {
897
+ max-width: 100%;
898
+ word-wrap: break-word;
899
+ overflow-wrap: break-word;
900
+ word-break: break-word;
901
+ }
902
+
903
+ .scene .slide-content {
904
+ max-height: 100%;
905
+ max-width: 100%;
906
+ overflow: hidden;
907
+ display: flex;
908
+ flex-direction: column;
909
+ gap: 1.5rem;
910
+ text-align: var(--text-align, left);
911
+ line-height: var(--line-height-body, 1.7);
912
+ }
913
+
914
+ #stage.screen-large .scene,
915
+ #stage.screen-ultra .scene {
916
+ justify-content: flex-start;
917
+ align-items: flex-start;
918
+ padding: 0;
919
+ }
920
+
921
+ #stage.screen-ultra .scene {
922
+ padding: 0;
923
+ }
924
+
925
+ #stage.screen-large [data-scene="body"] h1,
926
+ #smartMeasurementStage.screen-large [data-scene="body"] h1,
927
+ #stage.screen-ultra [data-scene="body"] h1,
928
+ #smartMeasurementStage.screen-ultra [data-scene="body"] h1 {
929
+ font-size: var(--font-size-h1, clamp(2.5rem, 5vw, 4.5rem));
930
+ max-width: 100%;
931
+ }
932
+
933
+ #stage.screen-large [data-scene="body"] h2,
934
+ #smartMeasurementStage.screen-large [data-scene="body"] h2,
935
+ #stage.screen-ultra [data-scene="body"] h2,
936
+ #smartMeasurementStage.screen-ultra [data-scene="body"] h2 {
937
+ font-size: var(--font-size-h2, clamp(2rem, 4vw, 3.5rem));
938
+ max-width: 100%;
939
+ }
940
+
941
+ #stage.screen-large [data-scene="body"] h3,
942
+ #smartMeasurementStage.screen-large [data-scene="body"] h3,
943
+ #stage.screen-ultra [data-scene="body"] h3,
944
+ #smartMeasurementStage.screen-ultra [data-scene="body"] h3 {
945
+ font-size: var(--font-size-h3, clamp(1.75rem, 3vw, 2.75rem));
946
+ max-width: 100%;
947
+ }
948
+
949
+ #stage.screen-large [data-scene="body"] p,
950
+ #smartMeasurementStage.screen-large [data-scene="body"] p,
951
+ #stage.screen-large [data-scene="body"] li,
952
+ #smartMeasurementStage.screen-large [data-scene="body"] li,
953
+ #stage.screen-ultra [data-scene="body"] p,
954
+ #smartMeasurementStage.screen-ultra [data-scene="body"] p,
955
+ #stage.screen-ultra [data-scene="body"] li,
956
+ #smartMeasurementStage.screen-ultra [data-scene="body"] li {
957
+ font-size: var(--font-size-text, clamp(1.25rem, 2vw, 2rem));
958
+ line-height: var(--line-height-body, 1.6);
959
+ max-width: 100%;
960
+ }
961
+
962
+ #stage.screen-ultra [data-scene="body"] p,
963
+ #smartMeasurementStage.screen-ultra [data-scene="body"] p,
964
+ #stage.screen-ultra [data-scene="body"] li,
965
+ #smartMeasurementStage.screen-ultra [data-scene="body"] li {
966
+ font-size: var(--font-size-text, clamp(1.5rem, 2.2vw, 2.2rem));
967
+ max-width: 100%;
968
+ }
969
+
970
+ /* สำหรับหน้าจอใหญ่ ให้จัดเนื้อหาชิดซ้ายแทนกึ่งกลาง */
971
+ #stage.screen-large .smart-layout-root,
972
+ #stage.screen-ultra .smart-layout-root {
973
+ align-items: flex-start;
974
+ }
975
+
976
+ #stage.screen-large .slide-heading,
977
+ #stage.screen-ultra .slide-heading {
978
+ text-align: left;
979
+ margin-left: 0;
980
+ margin-right: 0;
981
+ max-width: 95%;
982
+ }
983
+
984
+ #stage.screen-large .slide-text,
985
+ #stage.screen-ultra .slide-text {
986
+ text-align: left;
987
+ margin-left: 0;
988
+ margin-right: 0;
989
+ max-width: 92%;
990
+ }
991
+
992
+ #stage.screen-large .smart-list,
993
+ #stage.screen-ultra .smart-list {
994
+ margin-left: 0;
995
+ margin-right: 0;
996
+ max-width: 92%;
997
+ }
998
+
999
+ #stage.screen-large .slide-blockquote,
1000
+ #stage.screen-ultra .slide-blockquote {
1001
+ margin-left: 0;
1002
+ margin-right: 0;
1003
+ max-width: 90%;
1004
+ }
1005
+
1006
+ #stage.screen-large .slide-code,
1007
+ #stage.screen-ultra .slide-code {
1008
+ margin-left: 0;
1009
+ margin-right: 0;
1010
+ max-width: 95%;
1011
+ }
1012
+
1013
+ #stage.screen-large .slide-image,
1014
+ #stage.screen-ultra .slide-image {
1015
+ margin-left: 0;
1016
+ margin-right: auto;
1017
+ max-width: 85%;
1018
+ }
1019
+
1020
+ [data-preview="true"],
1021
+ .preview-block {
1022
+ opacity: var(--preview-opacity);
1023
+ border-top: 1px dashed rgba(96, 165, 250, 0.35);
1024
+ padding-top: calc(var(--content-spacing) * 1.1);
1025
+ margin-top: calc(var(--content-spacing) * 1.2);
1026
+ }
1027
+
1028
+ .preview-block:first-child {
1029
+ border-top: none;
1030
+ padding-top: 0;
1031
+ margin-top: 0;
1032
+ }
1033
+
1034
+ .preview-block hr,
1035
+ hr.preview-block {
1036
+ border-color: rgba(96, 165, 250, 0.35);
1037
+ }
1038
+
1039
+ .gradient-backdrop {
1040
+ position: absolute;
1041
+ inset: -20%;
1042
+ background: radial-gradient(
1043
+ circle at center,
1044
+ var(--backdrop-gradient-color, rgba(59, 130, 246, 0.15)),
1045
+ transparent var(--backdrop-gradient-spread, 70%)
1046
+ );
1047
+ filter: blur(var(--backdrop-blur, 60px));
1048
+ opacity: 0.6;
1049
+ }
1050
+
1051
+ /* ════════════════════════════════════════════════════════════════════════════
1052
+ Typography - Paragraph & Text Styles
1053
+ ════════════════════════════════════════════════════════════════════════════ */
1054
+
1055
+ p {
1056
+ margin-top: var(--paragraph-spacing-before, 0.5rem);
1057
+ margin-bottom: var(--paragraph-spacing-after, 1rem);
1058
+ line-height: var(--line-height-body, 1.7);
1059
+ text-align: var(--text-align, left);
1060
+ text-indent: var(--indent-first-line, 0);
1061
+ }
1062
+
1063
+ .content-text p {
1064
+ color: var(--color-text);
1065
+ font-size: var(--font-size-text, 1rem);
1066
+ }
1067
+
1068
+ /* ════════════════════════════════════════════════════════════════════════════
1069
+ Code Block Styles
1070
+ ════════════════════════════════════════════════════════════════════════════ */
1071
+
1072
+ .code-block {
1073
+ font-family: var(--font-code);
1074
+ white-space: pre-wrap;
1075
+ background: var(--color-surface);
1076
+ border: 1px solid var(--color-border);
1077
+ border-radius: var(--border-radius);
1078
+ padding: 1.75rem;
1079
+ color: var(--color-text);
1080
+ box-shadow: var(--shadow);
1081
+ max-width: 100%;
1082
+ overflow-x: auto;
1083
+ position: relative;
1084
+ line-height: 1.6;
1085
+ }
1086
+
1087
+ .code-block::before {
1088
+ content: '';
1089
+ position: absolute;
1090
+ top: 0;
1091
+ left: 0;
1092
+ right: 0;
1093
+ height: 2px;
1094
+ background: var(--gradient);
1095
+ }
1096
+
1097
+ /* Syntax Highlighting with Theme Variables */
1098
+ .code-syntax .keyword,
1099
+ .code-block .keyword {
1100
+ color: var(--syntax-keyword, #f87171);
1101
+ font-weight: 600;
1102
+ }
1103
+
1104
+ .code-syntax .string,
1105
+ .code-block .string {
1106
+ color: var(--syntax-string, #34d399);
1107
+ }
1108
+
1109
+ .code-syntax .comment,
1110
+ .code-block .comment {
1111
+ color: var(--syntax-comment, #6b7280);
1112
+ font-style: italic;
1113
+ opacity: 0.8;
1114
+ }
1115
+
1116
+ .code-syntax .function,
1117
+ .code-block .function {
1118
+ color: var(--syntax-function, #60a5fa);
1119
+ font-weight: 500;
1120
+ }
1121
+
1122
+ .code-syntax .number,
1123
+ .code-block .number {
1124
+ color: var(--syntax-number, #fbbf24);
1125
+ }
1126
+
1127
+ .code-syntax .variable,
1128
+ .code-block .variable {
1129
+ color: var(--syntax-variable, #a78bfa);
1130
+ }
1131
+
1132
+ /* Enhanced Content Styles with Typography Controls */
1133
+ .content-h1 h1,
1134
+ .content-h2 h2,
1135
+ .content-h3 h3,
1136
+ .content-h4 h4,
1137
+ .content-h5 h5,
1138
+ .content-h6 h6 {
1139
+ margin-top: var(--heading-spacing-before, 1.5rem);
1140
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1141
+ line-height: var(--line-height-heading, 1.3);
1142
+ text-align: var(--text-align, left);
1143
+ }
1144
+
1145
+ .content-h1 h1 {
1146
+ color: var(--color-primary);
1147
+ text-shadow: 0 0 20px var(--color-primary), 0 4px 12px rgba(0, 0, 0, 0.3);
1148
+ font-size: var(--font-size-h1, clamp(2rem, 5vw, 3.5rem));
1149
+ font-weight: 800;
1150
+ letter-spacing: -0.02em;
1151
+ background: linear-gradient(135deg, var(--color-primary), var(--color-secondary));
1152
+ -webkit-background-clip: text;
1153
+ -webkit-text-fill-color: transparent;
1154
+ background-clip: text;
1155
+ max-width: 100%;
1156
+ word-wrap: break-word;
1157
+ }
1158
+
1159
+ .content-h2 h2 {
1160
+ color: var(--color-secondary);
1161
+ text-shadow: 0 0 15px var(--color-secondary);
1162
+ font-size: var(--font-size-h2, clamp(1.75rem, 4vw, 2.75rem));
1163
+ font-weight: 700;
1164
+ border-left: var(--heading-accent-border-width, 4px) solid var(--color-primary);
1165
+ padding-left: 1.5rem;
1166
+ max-width: 100%;
1167
+ word-wrap: break-word;
1168
+ }
1169
+
1170
+ .content-h3 h3 {
1171
+ color: var(--color-accent);
1172
+ font-size: var(--font-size-h3, clamp(1.5rem, 3vw, 2rem));
1173
+ font-weight: 600;
1174
+ max-width: 100%;
1175
+ word-wrap: break-word;
1176
+ }
1177
+
1178
+ .content-blockquote blockquote {
1179
+ border-left: var(--blockquote-border-width, 4px) solid var(--color-accent);
1180
+ padding-left: var(--indent-blockquote, 1.5rem);
1181
+ margin: 1.5rem 0;
1182
+ font-style: italic;
1183
+ color: var(--color-text-secondary);
1184
+ background: rgba(var(--color-surface), 0.3);
1185
+ padding: 1.5rem;
1186
+ border-radius: var(--border-radius);
1187
+ box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.2);
1188
+ }
1189
+
1190
+ .content-blockquote blockquote::before {
1191
+ content: '"';
1192
+ font-size: 4rem;
1193
+ color: var(--color-accent);
1194
+ opacity: 0.3;
1195
+ position: absolute;
1196
+ margin-left: -2rem;
1197
+ margin-top: -1rem;
1198
+ }
1199
+
1200
+ .content-list-item ul,
1201
+ .content-numbered-item ol {
1202
+ margin-left: var(--list-indent, 2rem);
1203
+ line-height: var(--line-height-body, 1.8);
1204
+ }
1205
+
1206
+ .content-list-item li,
1207
+ .content-numbered-item li {
1208
+ margin-bottom: 0.75rem;
1209
+ color: var(--color-text);
1210
+ text-align: var(--text-align, left);
1211
+ }
1212
+
1213
+ .content-list-item li::marker {
1214
+ color: var(--color-primary);
1215
+ font-size: 1.2em;
1216
+ }
1217
+
1218
+ /* Task List Styling */
1219
+ .content-task-list li {
1220
+ list-style: none;
1221
+ margin-left: -1.5rem;
1222
+ }
1223
+
1224
+ .content-task-list li::before {
1225
+ content: '☐';
1226
+ color: var(--color-accent);
1227
+ font-size: 1.5em;
1228
+ margin-right: 0.75rem;
1229
+ }
1230
+
1231
+ .content-task-list li.checked::before {
1232
+ content: '☑';
1233
+ color: var(--color-primary);
1234
+ }
1235
+
1236
+ /* Image Styling */
1237
+ .content-image img {
1238
+ border-radius: var(--border-radius);
1239
+ box-shadow: var(--shadow);
1240
+ max-width: 100%;
1241
+ height: auto;
1242
+ border: 2px solid var(--color-primary);
1243
+ }
1244
+
1245
+ /* Link Styling */
1246
+ .content-link a {
1247
+ color: var(--color-primary);
1248
+ text-decoration: none;
1249
+ border-bottom: 2px solid var(--color-primary);
1250
+ padding-bottom: 2px;
1251
+ transition: all 0.3s ease;
1252
+ }
1253
+
1254
+ .content-link a:hover {
1255
+ color: var(--color-secondary);
1256
+ border-bottom-color: var(--color-secondary);
1257
+ text-shadow: 0 0 10px var(--color-secondary);
1258
+ }
1259
+
1260
+ /* ════════════════════════════════════════════════════════════════════════════
1261
+ Typography Components
1262
+ ════════════════════════════════════════════════════════════════════════════ */
1263
+
1264
+ .badge {
1265
+ letter-spacing: 0.35em;
1266
+ font-size: 0.65rem;
1267
+ text-transform: uppercase;
1268
+ color: rgba(255, 255, 255, 0.6);
1269
+ font-weight: 600;
1270
+ }
1271
+
1272
+ /* ════════════════════════════════════════════════════════════════════════════
1273
+ Button Styles
1274
+ ════════════════════════════════════════════════════════════════════════════ */
1275
+
1276
+ .btn-primary {
1277
+ background: var(--color-primary);
1278
+ color: #fff;
1279
+ padding: 0.75rem 1.5rem;
1280
+ border-radius: var(--border-radius);
1281
+ font-weight: 600;
1282
+ border: none;
1283
+ cursor: pointer;
1284
+ transition: all 0.2s ease;
1285
+ box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
1286
+ }
1287
+
1288
+ .btn-primary:hover:not(:disabled) {
1289
+ background: #2563eb;
1290
+ box-shadow: 0 4px 8px rgba(59, 130, 246, 0.4);
1291
+ }
1292
+
1293
+ .btn-primary:disabled {
1294
+ opacity: 0.5;
1295
+ cursor: not-allowed;
1296
+ }
1297
+
1298
+ .btn-secondary {
1299
+ background: var(--color-surface);
1300
+ border: 1px solid var(--color-border);
1301
+ color: var(--color-text);
1302
+ padding: 0.75rem 1.5rem;
1303
+ border-radius: var(--border-radius);
1304
+ font-weight: 500;
1305
+ cursor: pointer;
1306
+ transition: all 0.2s ease;
1307
+ }
1308
+
1309
+ .btn-secondary:hover:not(:disabled) {
1310
+ border-color: var(--color-primary);
1311
+ background: var(--color-surface-hover);
1312
+ }
1313
+
1314
+ .btn-secondary:disabled {
1315
+ opacity: 0.5;
1316
+ cursor: not-allowed;
1317
+ }
1318
+
1319
+ .btn-tertiary {
1320
+ background: transparent;
1321
+ border: 1px solid var(--color-border);
1322
+ color: var(--color-text-secondary);
1323
+ padding: 0.5rem 1rem;
1324
+ border-radius: var(--border-radius);
1325
+ font-weight: 500;
1326
+ font-size: 0.875rem;
1327
+ cursor: pointer;
1328
+ transition: all 0.2s ease;
1329
+ }
1330
+
1331
+ .btn-tertiary:hover:not(:disabled) {
1332
+ border-color: var(--color-cyan);
1333
+ color: var(--color-cyan);
1334
+ background: rgba(6, 182, 212, 0.1);
1335
+ }
1336
+
1337
+ /* Reset Button - Warning Style */
1338
+ #resetBtn {
1339
+ border-color: rgba(239, 68, 68, 0.3);
1340
+ color: #ef4444;
1341
+ }
1342
+
1343
+ #resetBtn:hover:not(:disabled) {
1344
+ border-color: var(--color-error);
1345
+ background: rgba(239, 68, 68, 0.1);
1346
+ color: #ef4444;
1347
+ }
1348
+
1349
+ /* ════════════════════════════════════════════════════════════════════════════
1350
+ Configuration Panel Styles
1351
+ ═════��══════════════════════════════════════════════════════════════════════ */
1352
+
1353
+ .config-panel {
1354
+ background: var(--color-surface);
1355
+ backdrop-filter: blur(10px);
1356
+ border: 1px solid var(--color-border);
1357
+ }
1358
+
1359
+ .config-panel input,
1360
+ .config-panel textarea,
1361
+ .config-panel select {
1362
+ background: var(--color-background);
1363
+ border: 1px solid var(--color-border);
1364
+ color: var(--color-text);
1365
+ border-radius: var(--border-radius);
1366
+ padding: 0.5rem 0.75rem;
1367
+ width: 100%;
1368
+ font-family: inherit;
1369
+ transition: all 0.2s ease;
1370
+ }
1371
+
1372
+ .config-panel textarea {
1373
+ font-family: var(--font-code);
1374
+ resize: vertical;
1375
+ }
1376
+
1377
+ .config-panel input:focus,
1378
+ .config-panel textarea:focus,
1379
+ .config-panel select:focus {
1380
+ outline: none;
1381
+ border-color: var(--color-primary);
1382
+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
1383
+ }
1384
+
1385
+ /* ════════════════════════════════════════════════════════════════════════════
1386
+ Status & Progress Components
1387
+ ════════════════════════════════════════════════════════════════════════════ */
1388
+
1389
+ .status-pill {
1390
+ display: inline-flex;
1391
+ align-items: center;
1392
+ gap: 0.5rem;
1393
+ font-size: 0.75rem;
1394
+ letter-spacing: 0.05em;
1395
+ border-radius: 999px;
1396
+ background: var(--color-surface);
1397
+ border: 1px solid var(--color-border);
1398
+ padding: 0.5rem 1rem;
1399
+ font-weight: 600;
1400
+ text-transform: uppercase;
1401
+ color: var(--color-text-secondary);
1402
+ }
1403
+
1404
+ .status-pill.online::before {
1405
+ content: '';
1406
+ display: block;
1407
+ width: 0.5rem;
1408
+ height: 0.5rem;
1409
+ border-radius: 999px;
1410
+ background: var(--color-success);
1411
+ animation: pulse 2s ease-in-out infinite;
1412
+ }
1413
+
1414
+ .status-pill.recording::before {
1415
+ content: '';
1416
+ display: block;
1417
+ width: 0.5rem;
1418
+ height: 0.5rem;
1419
+ border-radius: 999px;
1420
+ background: var(--color-error);
1421
+ animation: pulse 1s ease-in-out infinite;
1422
+ }
1423
+
1424
+ @keyframes pulse {
1425
+ 0%, 100% {
1426
+ opacity: 1;
1427
+ }
1428
+ 50% {
1429
+ opacity: 0.5;
1430
+ }
1431
+ }
1432
+
1433
+ .pulse {
1434
+ animation: pulse 2s ease-in-out infinite;
1435
+ }
1436
+
1437
+ /* ════════════════════════════════════════════════════════════════════════════
1438
+ Advanced Transition Animations
1439
+ ════════════════════════════════════════════════════════════════════════════ */
1440
+
1441
+ @keyframes matrixScroll {
1442
+ 0% {
1443
+ background-position: 0% 0%;
1444
+ }
1445
+ 100% {
1446
+ background-position: 0% 200%;
1447
+ }
1448
+ }
1449
+
1450
+ @keyframes glitchSkew {
1451
+ 0% {
1452
+ transform: skew(0deg);
1453
+ }
1454
+ 25% {
1455
+ transform: skew(2deg);
1456
+ }
1457
+ 50% {
1458
+ transform: skew(-2deg);
1459
+ }
1460
+ 75% {
1461
+ transform: skew(1deg);
1462
+ }
1463
+ 100% {
1464
+ transform: skew(0deg);
1465
+ }
1466
+ }
1467
+
1468
+ @keyframes pixelateIn {
1469
+ 0% {
1470
+ filter: blur(20px);
1471
+ opacity: 0;
1472
+ }
1473
+ 50% {
1474
+ filter: blur(10px);
1475
+ }
1476
+ 100% {
1477
+ filter: blur(0px);
1478
+ opacity: 1;
1479
+ }
1480
+ }
1481
+
1482
+ @keyframes scanline {
1483
+ 0% {
1484
+ transform: translateY(-100%);
1485
+ }
1486
+ 100% {
1487
+ transform: translateY(100%);
1488
+ }
1489
+ }
1490
+
1491
+ /* Code Block Enhanced Animations */
1492
+ @keyframes codeHighlight {
1493
+ 0%, 100% {
1494
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
1495
+ }
1496
+ 50% {
1497
+ box-shadow: 0 8px 32px var(--color-primary), 0 0 40px rgba(var(--color-primary), 0.3);
1498
+ }
1499
+ }
1500
+
1501
+ .code-block:hover {
1502
+ animation: codeHighlight 2s ease-in-out infinite;
1503
+ }
1504
+
1505
+ /* Heading Glow Effects */
1506
+ @keyframes textGlow {
1507
+ 0%, 100% {
1508
+ text-shadow: 0 0 10px var(--color-primary), 0 0 20px var(--color-primary);
1509
+ }
1510
+ 50% {
1511
+ text-shadow: 0 0 20px var(--color-primary), 0 0 40px var(--color-primary), 0 0 60px var(--color-secondary);
1512
+ }
1513
+ }
1514
+
1515
+ .content-h1 h1:hover,
1516
+ .content-h2 h2:hover {
1517
+ animation: textGlow 1.5s ease-in-out infinite;
1518
+ }
1519
+
1520
+ .progress-bar {
1521
+ width: 100%;
1522
+ height: 0.5rem;
1523
+ background: var(--color-surface);
1524
+ border: 1px solid var(--color-border);
1525
+ border-radius: 999px;
1526
+ overflow: hidden;
1527
+ }
1528
+
1529
+ .progress-bar-fill {
1530
+ height: 100%;
1531
+ background: var(--color-primary);
1532
+ border-radius: 999px;
1533
+ transition: width 0.3s ease;
1534
+ }
1535
+
1536
+ /* ════════════════════════════════════════════════════════════════════════════
1537
+ Template Card Styles
1538
+ ════════════════════════════════════════════════════════════════════════════ */
1539
+
1540
+ .template-card {
1541
+ background: var(--color-surface);
1542
+ border: 2px solid var(--color-border);
1543
+ border-radius: var(--border-radius);
1544
+ padding: 1rem;
1545
+ cursor: pointer;
1546
+ transition: all 0.2s ease;
1547
+ }
1548
+
1549
+ .template-card:hover {
1550
+ border-color: var(--color-cyan);
1551
+ box-shadow: 0 0 0 1px var(--color-cyan);
1552
+ }
1553
+
1554
+ .template-card.active {
1555
+ border-color: var(--color-primary);
1556
+ background: rgba(59, 130, 246, 0.1);
1557
+ box-shadow: 0 0 0 1px var(--color-primary);
1558
+ }
1559
+
1560
+ /* ════════════════════════════════════════════════════════════════════════════
1561
+ File Upload Zone
1562
+ ════════════════════════════════════════════════════════════════════════════ */
1563
+
1564
+ .file-upload-zone {
1565
+ border: 2px dashed var(--color-border);
1566
+ border-radius: var(--border-radius);
1567
+ padding: 2rem;
1568
+ text-align: center;
1569
+ cursor: pointer;
1570
+ transition: all 0.2s ease;
1571
+ background: var(--color-surface);
1572
+ }
1573
+
1574
+ .file-upload-zone:hover {
1575
+ border-color: var(--color-cyan);
1576
+ background: rgba(6, 182, 212, 0.05);
1577
+ }
1578
+
1579
+ .file-upload-zone.dragging {
1580
+ border-color: var(--color-primary);
1581
+ background: rgba(59, 130, 246, 0.1);
1582
+ }
1583
+
1584
+ /* ════════════════════════════════════════════════════════════════════════════
1585
+ Security Badge
1586
+ ════════════════════════════════════════════════════════════════════════════ */
1587
+
1588
+ .security-badge {
1589
+ display: inline-flex;
1590
+ align-items: center;
1591
+ gap: 0.5rem;
1592
+ background: rgba(16, 185, 129, 0.1);
1593
+ color: #10b981;
1594
+ padding: 0.25rem 0.75rem;
1595
+ border-radius: 0.5rem;
1596
+ font-size: 0.75rem;
1597
+ font-weight: 600;
1598
+ }
1599
+
1600
+ .security-badge::before {
1601
+ content: '';
1602
+ }
1603
+
1604
+ /* ════════════════════════════════════════════════════════════════════════════
1605
+ Tab System
1606
+ ════════════════════════════════════════════════════════════════════════════ */
1607
+
1608
+ .tab-button {
1609
+ padding: 0.75rem 1.5rem;
1610
+ background: transparent;
1611
+ border: none;
1612
+ color: var(--color-text-secondary);
1613
+ font-weight: 500;
1614
+ cursor: pointer;
1615
+ border-bottom: 2px solid transparent;
1616
+ transition: all 0.3s ease;
1617
+ }
1618
+
1619
+ .tab-button.active {
1620
+ color: var(--color-primary);
1621
+ border-bottom-color: var(--color-primary);
1622
+ }
1623
+
1624
+ .tab-content {
1625
+ display: none;
1626
+ }
1627
+
1628
+ .tab-content.active {
1629
+ display: block;
1630
+ }
1631
+
1632
+ /* ════════════════════════════════════════════════════════════════════════════
1633
+ Slide Content Structured Styles - ใช้กับเนื้อหาจาก Markdown
1634
+ ════════════════════════════════════════════════════════════════════════════ */
1635
+
1636
+ .smart-layout-root {
1637
+ display: flex;
1638
+ flex-direction: column;
1639
+ align-items: center;
1640
+ width: 100%;
1641
+ max-width: 100%;
1642
+ gap: 1.5rem;
1643
+ padding: 0;
1644
+ }
1645
+
1646
+ .slide-heading {
1647
+ text-align: center;
1648
+ width: 100%;
1649
+ max-width: 100%;
1650
+ margin-left: auto;
1651
+ margin-right: auto;
1652
+ word-wrap: break-word;
1653
+ overflow-wrap: break-word;
1654
+ word-break: break-word;
1655
+ line-height: var(--line-height-heading, 1.3);
1656
+ hyphens: auto;
1657
+ }
1658
+
1659
+ .slide-h1 {
1660
+ font-size: var(--font-size-h1, clamp(1.75rem, 4.5vw, 3rem));
1661
+ font-weight: 800;
1662
+ margin-top: var(--heading-spacing-before, 1.5rem);
1663
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1664
+ color: var(--color-primary);
1665
+ text-shadow: 0 0 20px var(--color-primary);
1666
+ background: linear-gradient(135deg, var(--color-primary), var(--color-secondary));
1667
+ -webkit-background-clip: text;
1668
+ -webkit-text-fill-color: transparent;
1669
+ background-clip: text;
1670
+ max-width: 100%;
1671
+ }
1672
+
1673
+ .slide-h2 {
1674
+ font-size: var(--font-size-h2, clamp(1.5rem, 3.5vw, 2.5rem));
1675
+ font-weight: 700;
1676
+ margin-top: var(--heading-spacing-before, 1.5rem);
1677
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1678
+ color: var(--color-secondary);
1679
+ text-shadow: 0 0 15px var(--color-secondary);
1680
+ max-width: 100%;
1681
+ }
1682
+
1683
+ .slide-h3 {
1684
+ font-size: var(--font-size-h3, clamp(1.25rem, 2.75vw, 1.9rem));
1685
+ font-weight: 600;
1686
+ margin-top: var(--heading-spacing-before, 1.5rem);
1687
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1688
+ color: var(--color-cyan);
1689
+ max-width: 100%;
1690
+ }
1691
+
1692
+ .slide-h4 {
1693
+ font-size: clamp(1.25rem, 2.5vw, 1.75rem);
1694
+ font-weight: 600;
1695
+ margin-top: var(--heading-spacing-before, 1.5rem);
1696
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1697
+ }
1698
+
1699
+ .slide-h5 {
1700
+ font-size: clamp(1.1rem, 2vw, 1.5rem);
1701
+ font-weight: 600;
1702
+ margin-top: var(--heading-spacing-before, 1.5rem);
1703
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1704
+ }
1705
+
1706
+ .slide-h6 {
1707
+ font-size: clamp(1rem, 1.5vw, 1.25rem);
1708
+ font-weight: 500;
1709
+ margin-top: var(--heading-spacing-before, 1.5rem);
1710
+ margin-bottom: var(--heading-spacing-after, 0.75rem);
1711
+ }
1712
+
1713
+ .slide-text,
1714
+ .slide-text p {
1715
+ font-size: var(--font-size-text, clamp(1.1rem, 1.8vw, 1.6rem));
1716
+ line-height: var(--line-height-body, 1.7);
1717
+ margin-top: var(--paragraph-spacing-before, 0.5rem);
1718
+ margin-bottom: var(--paragraph-spacing-after, 1rem);
1719
+ text-align: var(--text-align, center);
1720
+ text-indent: var(--indent-first-line, 0);
1721
+ max-width: 100%;
1722
+ margin-left: auto;
1723
+ margin-right: auto;
1724
+ color: var(--color-text);
1725
+ word-break: break-word;
1726
+ overflow-wrap: break-word;
1727
+ }
1728
+
1729
+ .slide-text-preview {
1730
+ font-size: clamp(1rem, 1.6vw, 1.4rem);
1731
+ color: var(--color-text-secondary);
1732
+ font-style: italic;
1733
+ opacity: 0.8;
1734
+ }
1735
+
1736
+ .smart-list {
1737
+ width: 100%;
1738
+ max-width: 100%;
1739
+ margin-left: auto;
1740
+ margin-right: auto;
1741
+ padding-left: var(--list-indent, 1.5rem);
1742
+ list-style: none;
1743
+ }
1744
+
1745
+ .slide-list-item {
1746
+ font-size: var(--font-size-text, clamp(1.1rem, 1.8vw, 1.6rem));
1747
+ line-height: var(--line-height-body, 1.7);
1748
+ margin-bottom: 0.75rem;
1749
+ padding-left: var(--list-indent, 1.5rem);
1750
+ text-indent: calc(-1 * var(--list-indent, 1.5rem));
1751
+ color: var(--color-text);
1752
+ word-break: break-word;
1753
+ overflow-wrap: break-word;
1754
+ }
1755
+
1756
+ .slide-blockquote {
1757
+ border-left: var(--blockquote-border-width, 4px) solid var(--color-cyan);
1758
+ padding-left: var(--indent-blockquote, 1.5rem);
1759
+ padding-top: 1rem;
1760
+ padding-bottom: 1rem;
1761
+ margin-left: var(--indent-blockquote, 1.5rem);
1762
+ margin-top: var(--paragraph-spacing-before, 0.5rem);
1763
+ margin-bottom: var(--paragraph-spacing-after, 1rem);
1764
+ font-style: italic;
1765
+ font-size: clamp(1.25rem, 2vw, 1.75rem);
1766
+ line-height: var(--line-height-body, 1.7);
1767
+ color: var(--color-text-secondary);
1768
+ background: rgba(19, 35, 55, 0.3);
1769
+ border-radius: 0.5rem;
1770
+ max-width: 85%;
1771
+ }
1772
+
1773
+ .slide-code {
1774
+ max-width: 90%;
1775
+ margin-left: auto;
1776
+ margin-right: auto;
1777
+ margin-top: var(--paragraph-spacing-before, 0.5rem);
1778
+ margin-bottom: var(--paragraph-spacing-after, 1rem);
1779
+ }
1780
+
1781
+ .slide-code .code-block {
1782
+ font-family: var(--font-code, 'Source Code Pro', monospace);
1783
+ font-size: var(--font-size-code, clamp(0.9rem, 1.5vw, 1.1rem));
1784
+ line-height: 1.5;
1785
+ }
1786
+
1787
+ .slide-image {
1788
+ max-width: 80%;
1789
+ height: auto;
1790
+ border-radius: 0.75rem;
1791
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
1792
+ margin-left: auto;
1793
+ margin-right: auto;
1794
+ display: block;
1795
+ margin-bottom: 1rem;
1796
+ border: var(--image-border-width, 2px) solid var(--color-primary);
1797
+ }
1798
+
1799
+ .slide-link {
1800
+ color: var(--color-cyan);
1801
+ text-decoration: underline;
1802
+ text-decoration-thickness: var(--link-underline-width, 2px);
1803
+ font-size: clamp(1.25rem, 2vw, 1.75rem);
1804
+ transition: all 0.2s ease;
1805
+ }
1806
+
1807
+ .slide-link:hover {
1808
+ color: var(--color-secondary);
1809
+ text-shadow: 0 0 10px var(--color-secondary);
1810
+ }
1811
+
1812
+ /* ════════════════════════════════════════════════════════════════════════════
1813
+ Table & HR Styles
1814
+ ════════════════════════════════════════════════════════════════════════════ */
1815
+
1816
+ .slide-table {
1817
+ width: 100%;
1818
+ border-collapse: collapse;
1819
+ margin-bottom: 1rem;
1820
+ border: var(--table-border-width, 1px) solid var(--color-accent);
1821
+ }
1822
+
1823
+ .slide-table th {
1824
+ border: var(--table-border-width, 1px) solid var(--color-accent);
1825
+ padding: 1rem;
1826
+ background-color: var(--color-accent);
1827
+ color: white;
1828
+ font-weight: 600;
1829
+ text-align: left;
1830
+ }
1831
+
1832
+ .slide-table td {
1833
+ border: var(--table-border-width, 1px) solid var(--color-accent);
1834
+ padding: 0.75rem 1rem;
1835
+ color: var(--color-text);
1836
+ }
1837
+
1838
+ .slide-table tr:nth-child(even) {
1839
+ background-color: rgba(var(--color-surface), 0.3);
1840
+ }
1841
+
1842
+ .slide-hr {
1843
+ border: 0;
1844
+ border-top: var(--hr-border-width, 2px) solid var(--color-accent);
1845
+ margin: 1.5rem 0;
1846
+ opacity: 0.7;
1847
+ }
1848
+
1849
+ /* ════════════════════════════════════════════════════════════════════════════
1850
+ Timeline Page Indicator
1851
+ ════════════════════════════════════════════════════════════════════════════ */
1852
+
1853
+ .timeline-page-indicator {
1854
+ font-size: 0.75rem;
1855
+ padding: 0.125rem 0.5rem;
1856
+ background-color: var(--color-accent);
1857
+ color: var(--color-text);
1858
+ border-radius: 0.25rem;
1859
+ opacity: 0.8;
1860
+ }
1861
+
1862
+ /* Slide Page Indicator (on stage) */
1863
+ .slide-page-indicator {
1864
+ position: absolute;
1865
+ top: var(--page-indicator-top, 16px);
1866
+ right: var(--page-indicator-right, 16px);
1867
+ font-size: var(--page-indicator-font-size, 0.875rem);
1868
+ opacity: var(--page-indicator-opacity, 0.7);
1869
+ z-index: 100;
1870
+ }
1871
+
1872
+ .slide-page-indicator span {
1873
+ display: inline-block;
1874
+ padding: var(--page-indicator-padding-y, 4px) var(--page-indicator-padding-x, 12px);
1875
+ background-color: var(--page-indicator-bg-color, rgba(22, 78, 99, 0.5));
1876
+ color: var(--page-indicator-text-color, #a5f3fc);
1877
+ border-radius: 0.375rem;
1878
+ }
1879
+
1880
+ /* ════════════════════════════════════════════════════════════════════════════
1881
+ Collapsible Settings Sections
1882
+ ════════════════════════════════════════════════════════════════════════════ */
1883
+
1884
+ .settings-section summary {
1885
+ list-style: none;
1886
+ transition: color 0.15s ease;
1887
+ user-select: none;
1888
+ cursor: pointer;
1889
+ }
1890
+
1891
+ .settings-section summary::-webkit-details-marker {
1892
+ display: none;
1893
+ }
1894
+
1895
+ .settings-section summary > span:first-child {
1896
+ display: inline-block;
1897
+ transition: transform 0.15s ease;
1898
+ font-size: 0.7em;
1899
+ }
1900
+
1901
+ .settings-section[open] summary > span:first-child {
1902
+ transform: rotate(90deg);
1903
+ }
1904
+
1905
+ .settings-section summary:hover {
1906
+ color: #e2e8f0;
1907
+ }
1908
+
1909
+ /* ════════════════════════════════════════════════════════════════════════════
1910
+ Responsive Design
1911
+ ════════════════════════════════════════════════════════════════════════════ */
1912
+
1913
+ @media (max-width: 768px) {
1914
+ .stage-frame {
1915
+ padding-top: 75%; /* Adjusted for mobile */
1916
+ }
1917
+
1918
+ .scene {
1919
+ padding: 1.5rem;
1920
+ }
1921
+
1922
+ .code-block {
1923
+ padding: 1rem;
1924
+ font-size: 0.875rem;
1925
+ }
1926
+
1927
+ .smart-layout-root {
1928
+ gap: 1rem;
1929
+ }
1930
+
1931
+ .slide-heading,
1932
+ .slide-text,
1933
+ .smart-list,
1934
+ .slide-blockquote,
1935
+ .slide-code {
1936
+ max-width: 95%;
1937
+ }
1938
+ }
1939
+
1940
+
1941
+ @media (max-width: 640px) {
1942
+ .btn-primary,
1943
+ .btn-secondary {
1944
+ padding: 0.625rem 1.25rem;
1945
+ font-size: 0.875rem;
1946
+ }
1947
+ }
1948
+
1949
+ /* ═══════════════════════════════════════════════════════════════════════════
1950
+ EXIT CONFIRMATION DIALOG
1951
+ ═══════════════════════════════════════════════════════════════════════════ */
1952
+
1953
+ .exit-confirmation-dialog {
1954
+ position: fixed;
1955
+ top: 0;
1956
+ left: 0;
1957
+ width: 100%;
1958
+ height: 100%;
1959
+ z-index: 10000;
1960
+ display: flex;
1961
+ align-items: center;
1962
+ justify-content: center;
1963
+ }
1964
+
1965
+ .exit-confirmation-overlay {
1966
+ position: absolute;
1967
+ top: 0;
1968
+ left: 0;
1969
+ width: 100%;
1970
+ height: 100%;
1971
+ background: rgba(0, 0, 0, 0.6);
1972
+ backdrop-filter: blur(4px);
1973
+ animation: fadeIn 0.15s ease;
1974
+ }
1975
+
1976
+ .exit-confirmation-content {
1977
+ position: relative;
1978
+ background: #1e293b;
1979
+ border-radius: 8px;
1980
+ padding: 1.25rem;
1981
+ max-width: 380px;
1982
+ width: 90%;
1983
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
1984
+ border: 1px solid rgba(255, 255, 255, 0.1);
1985
+ animation: slideUp 0.2s ease;
1986
+ }
1987
+
1988
+ .exit-confirmation-header {
1989
+ margin-bottom: 1rem;
1990
+ }
1991
+
1992
+ .exit-confirmation-header h3 {
1993
+ margin: 0;
1994
+ font-size: 1.125rem;
1995
+ font-weight: 600;
1996
+ color: #f1f5f9;
1997
+ }
1998
+
1999
+ .exit-confirmation-body {
2000
+ margin-bottom: 1.25rem;
2001
+ color: #cbd5e1;
2002
+ line-height: 1.5;
2003
+ font-size: 0.875rem;
2004
+ }
2005
+
2006
+ .exit-confirmation-body p {
2007
+ margin: 0.5rem 0;
2008
+ }
2009
+
2010
+ .exit-confirmation-body .warning-text {
2011
+ color: #fbbf24;
2012
+ font-weight: 500;
2013
+ }
2014
+
2015
+ .exit-confirmation-footer {
2016
+ display: flex;
2017
+ gap: 0.5rem;
2018
+ }
2019
+
2020
+ .exit-confirmation-footer button {
2021
+ flex: 1;
2022
+ padding: 0.5rem 0.75rem;
2023
+ border: 1px solid rgba(255, 255, 255, 0.1);
2024
+ border-radius: 6px;
2025
+ font-size: 0.8125rem;
2026
+ font-weight: 500;
2027
+ cursor: pointer;
2028
+ transition: all 0.15s ease;
2029
+ }
2030
+
2031
+ .btn-exit-save {
2032
+ background: rgba(59, 130, 246, 0.2);
2033
+ color: #60a5fa;
2034
+ border-color: rgba(59, 130, 246, 0.3);
2035
+ }
2036
+
2037
+ .btn-exit-save:hover {
2038
+ background: rgba(59, 130, 246, 0.3);
2039
+ border-color: rgba(59, 130, 246, 0.5);
2040
+ }
2041
+
2042
+ .btn-exit-discard {
2043
+ background: rgba(239, 68, 68, 0.2);
2044
+ color: #f87171;
2045
+ border-color: rgba(239, 68, 68, 0.3);
2046
+ }
2047
+
2048
+ .btn-exit-discard:hover {
2049
+ background: rgba(239, 68, 68, 0.3);
2050
+ border-color: rgba(239, 68, 68, 0.5);
2051
+ }
2052
+
2053
+ .btn-exit-cancel {
2054
+ background: rgba(71, 85, 105, 0.2);
2055
+ color: #cbd5e1;
2056
+ border-color: rgba(255, 255, 255, 0.1);
2057
+ }
2058
+
2059
+ .btn-exit-cancel:hover {
2060
+ background: rgba(71, 85, 105, 0.3);
2061
+ border-color: rgba(255, 255, 255, 0.15);
2062
+ }
2063
+
2064
+ @keyframes fadeIn {
2065
+ from { opacity: 0; }
2066
+ to { opacity: 1; }
2067
+ }
2068
+
2069
+ @keyframes slideUp {
2070
+ from {
2071
+ opacity: 0;
2072
+ transform: translateY(10px);
2073
+ }
2074
+ to {
2075
+ opacity: 1;
2076
+ transform: translateY(0);
2077
+ }
2078
+ }
2079
+
2080
+ /* ════════════════════════════════════════════════════════════════════════════
2081
+ Markdown Drop Zone
2082
+ ════════════════════════════════════════════════════════════════════════════ */
2083
+
2084
+ .markdown-drop-zone {
2085
+ position: relative;
2086
+ }
2087
+
2088
+ .markdown-drop-zone textarea {
2089
+ width: 100%;
2090
+ transition: all 0.2s ease;
2091
+ }
2092
+
2093
+ .markdown-drop-zone.drag-over textarea {
2094
+ opacity: 0.3;
2095
+ pointer-events: none;
2096
+ }
2097
+
2098
+ .markdown-drop-zone .drop-overlay {
2099
+ position: absolute;
2100
+ inset: 0;
2101
+ display: flex;
2102
+ align-items: center;
2103
+ justify-content: center;
2104
+ background: rgba(10, 22, 40, 0.95);
2105
+ border: 2px dashed var(--color-primary);
2106
+ border-radius: var(--border-radius);
2107
+ backdrop-filter: blur(8px);
2108
+ z-index: 10;
2109
+ pointer-events: none;
2110
+ }
2111
+
2112
+ .markdown-drop-zone.drag-over .drop-overlay {
2113
+ display: flex;
2114
+ }
2115
+
2116
+ .drop-overlay.hidden {
2117
+ display: none;
2118
+ }
2119
+
2120
+ .drop-content {
2121
+ text-align: center;
2122
+ animation: slideUp 0.3s ease;
2123
+ }
2124
+
2125
+ .drop-icon {
2126
+ font-size: 4rem;
2127
+ margin-bottom: 1rem;
2128
+ animation: bounce 0.6s ease infinite;
2129
+ }
2130
+
2131
+ .drop-text {
2132
+ font-size: 1.25rem;
2133
+ font-weight: 600;
2134
+ color: var(--color-text);
2135
+ margin-bottom: 0.5rem;
2136
+ }
2137
+
2138
+ .drop-hint {
2139
+ font-size: 0.875rem;
2140
+ color: var(--color-text-secondary);
2141
+ }
2142
+
2143
+ @keyframes bounce {
2144
+ 0%, 100% {
2145
+ transform: translateY(0);
2146
+ }
2147
+ 50% {
2148
+ transform: translateY(-10px);
2149
+ }
2150
+ }
src/renderer/index.html ADDED
@@ -0,0 +1,1002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Chahua Markdown Video Studio</title>
7
+
8
+ <!-- Local Stylesheets (Offline-first) -->
9
+ <script src="./vendor/tailwind.js"></script>
10
+ <link rel="stylesheet" href="../../assets/fonts/fonts.css">
11
+ <link rel="stylesheet" href="./css/style.css">
12
+ </head>
13
+ <body>
14
+ <main class="min-h-screen flex flex-col lg:flex-row gap-6 p-4 lg:p-8">
15
+ <!-- Left Panel - Video Stage -->
16
+ <section class="flex-1 flex flex-col gap-6">
17
+ <!-- Header -->
18
+ <header class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
19
+ <div>
20
+ <h1 class="text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
21
+ Markdown Video Studio
22
+ </h1>
23
+ <p class="text-slate-400 mt-1 flex items-center gap-2">
24
+ Markdown-first authoring · Unified timeline engine
25
+ <span class="security-badge">Enterprise Security</span>
26
+ </p>
27
+ </div>
28
+ <div class="flex items-center gap-3">
29
+ <span id="statusPill" class="status-pill online">Ready</span>
30
+ <button id="securityBtn" class="btn-secondary px-3 py-2 text-sm" title="View Security Stats">
31
+ Security
32
+ </button>
33
+ </div>
34
+ </header>
35
+
36
+ <!-- Video Stage -->
37
+ <div class="stage-frame" id="stageFrame">
38
+ <div id="stage">
39
+ <!-- Pause Overlay -->
40
+ <div id="pauseOverlay" class="pause-overlay hidden">
41
+ <div class="pause-indicator">
42
+ <div class="pause-icon">⏸</div>
43
+ <div class="pause-text">PAUSED</div>
44
+ <div class="pause-hint">Click or press Space to resume</div>
45
+ <div class="pause-hint" style="margin-top: 0.5rem; opacity: 0.6;">Press ESC to stop</div>
46
+ </div>
47
+ </div>
48
+
49
+ <!-- Navigation Controls -->
50
+ <div id="navControls" class="nav-controls hidden">
51
+ <button id="prevSlideBtn" class="nav-btn nav-btn-prev" title="Previous Slide (←)">
52
+ <span class="nav-arrow">←</span>
53
+ </button>
54
+ <button id="nextSlideBtn" class="nav-btn nav-btn-next" title="Next Slide (→)">
55
+ <span class="nav-arrow">→</span>
56
+ </button>
57
+ <div id="slideCounter" class="slide-counter">1 / 1</div>
58
+ </div>
59
+
60
+ <!-- Exit Presentation Mode Button -->
61
+ <button id="exitPresentationBtn" class="exit-presentation-btn hidden" title="Exit Presentation Mode (ESC)">
62
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
63
+ <line x1="18" y1="6" x2="6" y2="18"></line>
64
+ <line x1="6" y1="6" x2="18" y2="18"></line>
65
+ </svg>
66
+ </button>
67
+
68
+ <!-- Stop Preview Button -->
69
+ <button id="stopPreviewBtn" class="stop-preview-btn hidden" title="Stop Preview">
70
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
71
+ <rect x="6" y="6" width="12" height="12"></rect>
72
+ </svg>
73
+ </button>
74
+
75
+ <!-- Stop Export Button -->
76
+ <button id="stopExportBtn" class="stop-export-btn hidden" title="Stop Export">
77
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
78
+ <rect x="6" y="6" width="12" height="12"></rect>
79
+ </svg>
80
+ </button>
81
+
82
+ <!-- Fullscreen Button -->
83
+ <button id="fullscreenBtn" class="fullscreen-btn hidden" title="Toggle Fullscreen (F)">
84
+ <span class="fullscreen-icon">⛶</span>
85
+ </button>
86
+
87
+ <!-- Slide Edit Button (Presentation Mode) -->
88
+ <button id="editSlideBtn" class="edit-slide-btn hidden" title="Edit Current Slide (E)">
89
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
90
+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
91
+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
92
+ </svg>
93
+ </button>
94
+
95
+ <!-- Save Slide Edit Button (shown after editing) -->
96
+ <button id="saveSlideBtn" class="save-slide-btn hidden" title="Save Slide Changes (Ctrl+S)">
97
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
98
+ <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
99
+ <polyline points="17 21 17 13 7 13 7 21"></polyline>
100
+ <polyline points="7 3 7 8 15 8"></polyline>
101
+ </svg>
102
+ </button>
103
+
104
+ <!-- Cancel Edit Button -->
105
+ <button id="cancelEditBtn" class="cancel-edit-btn hidden" title="Cancel Changes (ESC)">
106
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
107
+ <line x1="18" y1="6" x2="6" y2="18"></line>
108
+ <line x1="6" y1="6" x2="18" y2="18"></line>
109
+ </svg>
110
+ </button>
111
+
112
+ <!-- Position Controls -->
113
+ <div id="positionControls" class="position-controls hidden">
114
+ <button id="toggleSafeZoneBtn" class="position-control-btn" title="แสดง/ซ่อน Safe Zone">
115
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
116
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
117
+ <path d="M3 9h18M9 21V9"></path>
118
+ </svg>
119
+ </button>
120
+ <button id="toggleSnapGridBtn" class="position-control-btn" title="Snap to Grid">
121
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
122
+ <circle cx="12" cy="12" r="1"></circle>
123
+ <circle cx="12" cy="6" r="1"></circle>
124
+ <circle cx="12" cy="18" r="1"></circle>
125
+ <circle cx="6" cy="12" r="1"></circle>
126
+ <circle cx="18" cy="12" r="1"></circle>
127
+ <circle cx="6" cy="6" r="1"></circle>
128
+ <circle cx="6" cy="18" r="1"></circle>
129
+ <circle cx="18" cy="6" r="1"></circle>
130
+ <circle cx="18" cy="18" r="1"></circle>
131
+ </svg>
132
+ </button>
133
+ <button id="resetPositionsBtn" class="position-control-btn" title="รีเซ็ตตำแหน่งทั้งหมด">
134
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
135
+ <polyline points="1 4 1 10 7 10"></polyline>
136
+ <polyline points="23 20 23 14 17 14"></polyline>
137
+ <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"></path>
138
+ </svg>
139
+ </button>
140
+ <button id="exportSettingsBtn" class="position-control-btn" title="ส่งออกการตั้งค่า">
141
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
142
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
143
+ <polyline points="7 10 12 15 17 10"></polyline>
144
+ <line x1="12" y1="15" x2="12" y2="3"></line>
145
+ </svg>
146
+ </button>
147
+ </div>
148
+
149
+ <!-- Position Indicator -->
150
+ <div id="positionIndicator" class="position-indicator">
151
+ X: <span id="posX">0</span> | Y: <span id="posY">0</span>
152
+ </div>
153
+
154
+ <div class="gradient-backdrop"></div>
155
+
156
+ <div id="slideContainer" class="flex flex-col gap-12">
157
+ <div class="scene active" data-scene="intro">
158
+ <span class="badge">intro</span>
159
+ <h2 data-bind="intro.title" class="text-4xl md:text-6xl font-bold mt-4 text-center max-w-3xl">
160
+ Markdown Video Studio
161
+ </h2>
162
+ <p data-bind="intro.subtitle" class="text-lg md:text-2xl text-slate-300 mt-6 text-center max-w-2xl">
163
+ Define every slide, timing, and asset straight from your markdown deck.
164
+ </p>
165
+ <div class="mt-10 flex flex-wrap items-center justify-center gap-3 text-xs uppercase tracking-wider text-slate-400">
166
+ <span> Markdown-driven timeline</span>
167
+ <span> Unified preview & export</span>
168
+ <span> Extensible components</span>
169
+ </div>
170
+ </div>
171
+
172
+ <div class="scene" data-scene="body">
173
+ <span class="badge">timeline</span>
174
+ <div class="w-full max-w-4xl mx-auto bg-slate-900/60 rounded-2xl border border-slate-800/70 p-6">
175
+ <h3 class="text-2xl font-semibold text-slate-300 mb-4">Live Timeline</h3>
176
+ <ul id="timelinePreview" class="space-y-3 text-slate-200 text-sm">
177
+ <li class="flex items-start justify-between gap-3">
178
+ <span class="font-semibold">Slide 1 · Intro</span>
179
+ <span class="opacity-70">00:00 → 00:05</span>
180
+ </li>
181
+ <li class="flex items-start justify-between gap-3">
182
+ <span class="font-semibold">Slide 2 · Agenda</span>
183
+ <span class="opacity-70">00:05 → 00:15</span>
184
+ </li>
185
+ <li class="flex items-start justify-between gap-3">
186
+ <span class="font-semibold">Slide 3 · Demo</span>
187
+ <span class="opacity-70">00:15 → 00:35</span>
188
+ </li>
189
+ </ul>
190
+ <p class="text-xs text-slate-500 mt-4">
191
+ Timeline updates whenever the markdown deck changes.
192
+ </p>
193
+ </div>
194
+ </div>
195
+
196
+ <div class="scene" data-scene="outro">
197
+ <div class="flex flex-col items-center text-center gap-6 max-w-3xl mx-auto">
198
+ <span class="badge">outro</span>
199
+ <h3 data-bind="outro.title" class="text-4xl md:text-5xl font-bold">
200
+ Render from Markdown
201
+ </h3>
202
+ <p data-bind="outro.tagline" class="text-slate-300 text-lg md:text-xl">
203
+ Export consistent videos without ever leaving your markdown workflow.
204
+ </p>
205
+ <div class="flex gap-4 mt-4">
206
+ <span class="px-6 py-3 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 text-white font-semibold">
207
+ Powered by Timeline Engine
208
+ </span>
209
+ </div>
210
+ </div>
211
+ </div>
212
+ </div>
213
+ </div>
214
+ </div>
215
+
216
+ <!-- Controls -->
217
+ <div class="flex flex-wrap items-center gap-3">
218
+ <button id="syncMarkdownBtn" class="btn-secondary">
219
+ Sync Markdown
220
+ </button>
221
+ <button id="presentationModeBtn" class="btn-primary">
222
+ Presentation Mode
223
+ </button>
224
+ <button id="previewBtn" class="btn-primary">
225
+ Preview Timeline
226
+ </button>
227
+ <button id="recordWebMBtn" class="btn-primary">
228
+ Export Video
229
+ </button>
230
+ <button id="resetBtn" class="btn-secondary" title="Reset to initial state">
231
+ Reset
232
+ </button>
233
+ </div>
234
+
235
+ <!-- Progress Bar -->
236
+ <div id="progressContainer" class="hidden">
237
+ <div class="progress-bar">
238
+ <div id="progressBar" class="progress-bar-fill" style="width: 0%"></div>
239
+ </div>
240
+ <p id="progressText" class="text-sm text-slate-400 mt-2">Processing...</p>
241
+ </div>
242
+
243
+ <!-- Status Log -->
244
+ <div id="statusLog" class="text-sm text-slate-400 bg-slate-900/60 border border-slate-800/60 rounded-xl px-4 py-3">
245
+ <strong>Ready:</strong> Configure your video and click render to start.
246
+ </div>
247
+ </section>
248
+
249
+ <!-- Right Panel - Configuration -->
250
+ <aside class="config-panel w-full lg:w-96 xl:w-[32rem] rounded-2xl p-6 space-y-6 overflow-y-auto max-h-[92vh]">
251
+ <!-- Tabs -->
252
+ <div class="flex border-b border-slate-700">
253
+ <button class="tab-button" data-tab="markdown">Markdown</button>
254
+ <button class="tab-button" data-tab="timeline">Timeline</button>
255
+ <button class="tab-button" data-tab="export">Export</button>
256
+ <button class="tab-button" data-tab="presentation">Settings</button>
257
+ </div>
258
+
259
+ <!-- Tab: Markdown -->
260
+ <div class="tab-content active" data-tab-content="markdown">
261
+ <section class="space-y-4">
262
+ <header>
263
+ <h3 class="text-base font-semibold text-white">Markdown Deck</h3>
264
+ <p class="text-xs text-slate-400 mt-1">Author your timeline, scenes, and narration directly in markdown.</p>
265
+ </header>
266
+ <div class="flex flex-wrap gap-2">
267
+ <button id="loadMarkdownSample" class="btn-tertiary text-xs px-3 py-2">Load Sample Deck</button>
268
+ <button id="importMarkdownBtn" class="btn-tertiary text-xs px-3 py-2">Import Markdown</button>
269
+ <button id="openWorkspaceBtn" class="btn-tertiary text-xs px-3 py-2">Open Workspace Folder</button>
270
+ </div>
271
+ <label class="block">
272
+ <span class="text-sm text-slate-300 mb-2 block">Markdown Source</span>
273
+ <div id="markdownDropZone" class="markdown-drop-zone">
274
+ <textarea id="markdownEditor" rows="18" class="w-full font-mono text-sm" placeholder="---\ntitle: Launch Update\nslides:\n - id: intro\n duration: 5s\n transition: fade\n content: |\n # Chahua Markdown Video Studio\n Elevate your markdown into motion\n---"></textarea>
275
+ <div class="drop-overlay hidden">
276
+ <div class="drop-content">
277
+ <div class="drop-icon"></div>
278
+ <div class="drop-text">Drop Markdown file here</div>
279
+ <div class="drop-hint">Supports .md, .markdown, .txt</div>
280
+ </div>
281
+ </div>
282
+ </div>
283
+ </label>
284
+ <div id="markdownDiagnostics" class="hidden text-xs bg-slate-800/40 border border-slate-600/40 text-slate-300 rounded-lg p-3"></div>
285
+ <div id="markdownSummary" class="text-xs text-slate-400 bg-slate-800/60 border border-slate-700/60 rounded-lg p-3">
286
+ Awaiting markdown sync.
287
+ </div>
288
+ </section>
289
+ </div>
290
+
291
+ <!-- Tab: Timeline -->
292
+ <div class="tab-content" data-tab-content="timeline">
293
+ <section class="space-y-4">
294
+ <header>
295
+ <h3 class="text-base font-semibold text-white">Timeline Overview</h3>
296
+ <p class="text-xs text-slate-400 mt-1">Review parsed scenes, tracks, and media assets.</p>
297
+ </header>
298
+ <div class="bg-slate-900/60 border border-slate-800/60 rounded-xl p-4 space-y-3">
299
+ <div class="flex items-center justify-between text-xs text-slate-400">
300
+ <span>Total Duration</span>
301
+ <span id="timelineTotal">00:00</span>
302
+ </div>
303
+ <div class="divide-y divide-slate-800" id="timelineSceneList">
304
+ <div class="py-3 flex flex-col gap-1">
305
+ <div class="flex items-center justify-between text-sm text-slate-200">
306
+ <span>Slide 1 · Intro</span>
307
+ <span>5s</span>
308
+ </div>
309
+ <p class="text-xs text-slate-500">transition: fade · narration: none</p>
310
+ </div>
311
+ <div class="py-3 flex flex-col gap-1">
312
+ <div class="flex items-center justify-between text-sm text-slate-200">
313
+ <span>Slide 2 · Agenda</span>
314
+ <span>10s</span>
315
+ </div>
316
+ <p class="text-xs text-slate-500">transition: slide-left · narration: intro.mp3</p>
317
+ </div>
318
+ </div>
319
+ </div>
320
+ <section class="space-y-3">
321
+ <h4 class="text-sm font-semibold text-white">Asset Checklist</h4>
322
+ <ul id="assetChecklist" class="space-y-2 text-xs text-slate-400 bg-slate-900/60 border border-slate-800/60 rounded-xl p-3">
323
+ <li class="flex items-center justify-between">
324
+ <span>intro-bg.png</span>
325
+ <span class="status-pill pending">pending</span>
326
+ </li>
327
+ <li class="flex items-center justify-between">
328
+ <span>voiceover/intro.mp3</span>
329
+ <span class="status-pill online">available</span>
330
+ </li>
331
+ </ul>
332
+ </section>
333
+ </section>
334
+ </div>
335
+
336
+ <!-- Tab: Export -->
337
+ <div class="tab-content" data-tab-content="export">
338
+ <section class="space-y-4">
339
+ <header>
340
+ <h3 class="text-base font-semibold text-white">Export Settings</h3>
341
+ <p class="text-xs text-slate-400 mt-1">Applied to both preview renderer and headless export jobs.</p>
342
+ </header>
343
+ <label class="block">
344
+ <span class="text-sm text-slate-300 mb-2 block">Resolution</span>
345
+ <select data-config="video.resolution" class="w-full">
346
+ <option value="1920x1080">1920x1080 (Full HD)</option>
347
+ <option value="1280x720">1280x720 (HD)</option>
348
+ <option value="3840x2160">3840x2160 (4K)</option>
349
+ </select>
350
+ </label>
351
+ <label class="block">
352
+ <span class="text-sm text-slate-300 mb-2 block">Frame Rate (FPS)</span>
353
+ <select data-config="video.fps" class="w-full">
354
+ <option value="30">30 FPS</option>
355
+ <option value="60" selected>60 FPS</option>
356
+ <option value="120">120 FPS</option>
357
+ </select>
358
+ </label>
359
+ <label class="block">
360
+ <span class="text-sm text-slate-300 mb-2 block">Quality</span>
361
+ <input type="range" min="0.1" max="1" step="0.05" data-config="video.quality" value="0.95" class="w-full">
362
+ <span id="qualityValue" class="text-xs text-slate-400">95%</span>
363
+ </label>
364
+ <label class="block">
365
+ <span class="text-sm text-slate-300 mb-2 block">Accent Color</span>
366
+ <input type="color" data-config="theme.accent" value="#60a5fa" class="w-full h-12">
367
+ </label>
368
+ <div class="border-t border-slate-700 pt-4 space-y-3 text-xs text-slate-400">
369
+ <div class="flex items-center justify-between">
370
+ <span>Estimated Render Time</span>
371
+ <span id="renderEta">—</span>
372
+ </div>
373
+ <div class="flex items-center justify-between">
374
+ <span>Headless Renderer</span>
375
+ <span id="rendererBackend">Pending selection</span>
376
+ </div>
377
+ </div>
378
+ </section>
379
+ </div>
380
+
381
+ <!-- Tab: Presentation Settings -->
382
+ <div class="tab-content" data-tab-content="presentation">
383
+ <section class="space-y-4">
384
+ <header>
385
+ <h3 class="text-base font-semibold text-white">Presentation Settings</h3>
386
+ <p class="text-xs text-slate-400 mt-1">Configure fonts, colors, and animations. Settings are automatically saved to localStorage.</p>
387
+ </header>
388
+
389
+ <!-- Settings Legend -->
390
+ <div class="bg-slate-800/30 border border-slate-700/40 rounded-lg p-3 space-y-2">
391
+ <h4 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
392
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
393
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
394
+ </svg>
395
+ Settings Legend
396
+ </h4>
397
+ <div class="grid grid-cols-2 gap-2 text-xs">
398
+ <div class="flex items-center gap-2">
399
+ <div class="w-3 h-3 bg-slate-500/50 rounded-sm"></div>
400
+ <span class="text-slate-300">Slide Content</span>
401
+ </div>
402
+ <div class="flex items-center gap-2">
403
+ <div class="w-3 h-3 bg-slate-600/50 rounded-sm"></div>
404
+ <span class="text-slate-300">UI Elements</span>
405
+ </div>
406
+ </div>
407
+ <p class="text-xs text-slate-400 pt-1">
408
+ <span class="font-semibold text-slate-300">Content</span> settings affect slide content (text, headings, lists).
409
+ <span class="font-semibold text-slate-300">UI</span> settings affect UI (navigation, overlays).
410
+ </p>
411
+ </div>
412
+
413
+ <!-- Preset Selector -->
414
+ <div class="space-y-2 pb-2">
415
+ <label class="block text-sm font-medium text-slate-300">Preset</label>
416
+ <select id="presetSelector" class="w-full px-3 py-2 bg-slate-900/60 border border-slate-700/60 rounded-lg text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
417
+ <option value="default">Default</option>
418
+ <option value="professional">Professional</option>
419
+ <option value="minimal">Minimal</option>
420
+ <option value="creative">Creative</option>
421
+ </select>
422
+ <p class="text-xs text-slate-500">Load a preset to quickly configure all settings below.</p>
423
+ </div>
424
+
425
+ <!-- Configuration Management -->
426
+ <div class="space-y-2 pb-3 border-b border-slate-800/60">
427
+ <label class="block text-sm font-medium text-slate-300">Configuration</label>
428
+ <div class="grid grid-cols-3 gap-2">
429
+ <button id="exportConfigBtn" class="px-3 py-2 bg-slate-800/40 hover:bg-slate-700/50 border border-slate-600/40 rounded-lg text-slate-300 text-xs font-medium transition-colors flex items-center justify-center gap-2">
430
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
431
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
432
+ </svg>
433
+ Export
434
+ </button>
435
+ <button id="importConfigBtn" class="px-3 py-2 bg-slate-800/40 hover:bg-slate-700/50 border border-slate-600/40 rounded-lg text-slate-300 text-xs font-medium transition-colors flex items-center justify-center gap-2">
436
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
437
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
438
+ </svg>
439
+ Import
440
+ </button>
441
+ <button id="resetConfigBtn" class="px-3 py-2 bg-slate-800/40 hover:bg-slate-700/50 border border-slate-600/40 rounded-lg text-slate-300 text-xs font-medium transition-colors flex items-center justify-center gap-2">
442
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
443
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
444
+ </svg>
445
+ Reset
446
+ </button>
447
+ </div>
448
+ <p class="text-xs text-slate-500">
449
+ Your settings are automatically saved to localStorage. Export creates a JSON backup file.
450
+ </p>
451
+ </div>
452
+
453
+ <!-- Font Settings (Collapsible) -->
454
+ <details class="settings-section border-t border-slate-800/60 pt-3" open>
455
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
456
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
457
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
458
+ </svg>
459
+ <span>Fonts</span>
460
+ </summary>
461
+ <div class="space-y-3 pl-5">
462
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
463
+ <span class="font-semibold text-slate-300">Applies to:</span> All headings (H1-H6), body text, and code blocks in slides
464
+ </p>
465
+
466
+ <div class="space-y-2">
467
+ <label class="block text-xs font-medium text-slate-400">Heading Font <span class="text-slate-600">(H1, H2, H3)</span></label>
468
+ <select id="fontHeading" class="w-full px-3 py-2 bg-slate-900/60 border border-slate-700/60 rounded-lg text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
469
+ <!-- Options populated by JS -->
470
+ </select>
471
+ </div>
472
+
473
+ <div class="space-y-2">
474
+ <label class="block text-xs font-medium text-slate-400">Body Font <span class="text-slate-600">(Paragraphs, Lists)</span></label>
475
+ <select id="fontBody" class="w-full px-3 py-2 bg-slate-900/60 border border-slate-700/60 rounded-lg text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
476
+ <!-- Options populated by JS -->
477
+ </select>
478
+ </div>
479
+
480
+ <div class="space-y-2">
481
+ <label class="block text-xs font-medium text-slate-400">Code Font <span class="text-slate-600">(Code Blocks)</span></label>
482
+ <select id="fontCode" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
483
+ <!-- Options populated by JS -->
484
+ </select>
485
+ </div>
486
+ </div>
487
+ </details>
488
+
489
+ <!-- Color Settings (Collapsible) -->
490
+ <details class="settings-section border-t border-slate-800/60 pt-3">
491
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
492
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
493
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
494
+ </svg>
495
+ <span>Colors</span>
496
+ </summary>
497
+ <div class="space-y-3 pl-5">
498
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
499
+ <span class="font-semibold text-slate-300">Applies to:</span> Headings, links, accents, background, and all text colors in slides
500
+ </p>
501
+
502
+ <div class="grid grid-cols-2 gap-3">
503
+ <div class="space-y-2">
504
+ <label class="block text-xs font-medium text-slate-400">Primary <span class="text-slate-600">(H1, Links)</span></label>
505
+ <input type="color" id="colorPrimary" class="w-full h-10 bg-slate-900/60 border border-slate-700/60 rounded-lg cursor-pointer">
506
+ </div>
507
+ <div class="space-y-2">
508
+ <label class="block text-xs font-medium text-slate-400">Accent <span class="text-slate-600">(Highlights)</span></label>
509
+ <input type="color" id="colorAccent" class="w-full h-10 bg-slate-900/60 border border-slate-700/60 rounded-lg cursor-pointer">
510
+ </div>
511
+ <div class="space-y-2">
512
+ <label class="block text-xs font-medium text-slate-400">Background <span class="text-slate-600">(Slide BG)</span></label>
513
+ <input type="color" id="colorBackground" class="w-full h-10 bg-slate-900/60 border border-slate-700/60 rounded-lg cursor-pointer">
514
+ </div>
515
+ <div class="space-y-2">
516
+ <label class="block text-xs font-medium text-slate-400">Text <span class="text-slate-600">(Body Text)</span></label>
517
+ <input type="color" id="colorText" class="w-full h-10 bg-slate-900/60 border border-slate-700/60 rounded-lg cursor-pointer">
518
+ </div>
519
+ </div>
520
+ </div>
521
+ </details>
522
+
523
+ <!-- Animations (Collapsible) -->
524
+ <details class="settings-section border-t border-slate-800/60 pt-3">
525
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
526
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
527
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
528
+ </svg>
529
+ <span>Animations <span class="text-xs font-normal text-slate-500">(Slide Content)</span></span>
530
+ </summary>
531
+ <div class="space-y-3 pl-5">
532
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
533
+ <span class="font-semibold text-slate-300">Applies to:</span> Slide transitions and animation timing
534
+ </p>
535
+
536
+ <div class="space-y-2">
537
+ <label class="block text-xs font-medium text-slate-400">Slide Transition</label>
538
+ <select id="animationTransition" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
539
+ <option value="fade">Fade</option>
540
+ <option value="slide">Slide</option>
541
+ <option value="none">None</option>
542
+ </select>
543
+ </div>
544
+
545
+ <div class="space-y-2">
546
+ <label class="block text-xs font-medium text-slate-400">Duration (seconds)</label>
547
+ <input type="number" id="animationDuration" min="0.1" max="2" step="0.1" value="0.6" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
548
+ </div>
549
+ </div>
550
+ </details>
551
+
552
+ <!-- UI & Visual Effects (Collapsible) -->
553
+ <details class="settings-section border-t border-slate-800/60 pt-3">
554
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
555
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
556
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
557
+ </svg>
558
+ <span>UI & Visual Effects</span>
559
+ </summary>
560
+ <div class="space-y-3 pl-5">
561
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
562
+ <span class="font-semibold text-slate-300">Applies to:</span> UI elements (navigation, overlays, backdrops) - NOT slide content
563
+ </p>
564
+ <h4 class="text-sm font-semibold text-slate-300">UI & Visual Effects</h4>
565
+ <p class="text-xs text-slate-500">Control overlay, navigation, and backdrop effects</p>
566
+
567
+ <!-- Preview Opacity -->
568
+ <div class="space-y-2">
569
+ <label class="block text-xs font-medium text-slate-400">Preview Slide Opacity</label>
570
+ <input type="number" id="previewOpacity" min="0" max="1" step="0.05" value="0.68" class="w-full px-3 py-2 bg-slate-900/60 border border-slate-700/60 rounded-lg text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
571
+ <p class="text-xs text-slate-500">Opacity of next slide preview (0-1)</p>
572
+ </div>
573
+
574
+ <!-- Overlay Settings -->
575
+ <div class="space-y-2">
576
+ <label class="block text-xs font-medium text-slate-400">Pause Overlay</label>
577
+ <div class="grid grid-cols-2 gap-2">
578
+ <div>
579
+ <label class="block text-xs text-slate-500 mb-1">Blur (px)</label>
580
+ <input type="number" id="overlayBlur" min="0" max="20" step="1" value="8" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
581
+ </div>
582
+ <div>
583
+ <label class="block text-xs text-slate-500 mb-1">Border Width (px)</label>
584
+ <input type="number" id="navBorderWidth" min="1" max="5" step="1" value="2" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
585
+ </div>
586
+ </div>
587
+ </div>
588
+
589
+ <!-- Backdrop Effects -->
590
+ <div class="space-y-2">
591
+ <label class="block text-xs font-medium text-slate-400">Gradient Backdrop Effect</label>
592
+ <div class="grid grid-cols-2 gap-2">
593
+ <div>
594
+ <label class="block text-xs text-slate-500 mb-1">Spread (%)</label>
595
+ <input type="number" id="backdropSpread" min="50" max="100" step="5" value="70" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
596
+ </div>
597
+ <div>
598
+ <label class="block text-xs text-slate-500 mb-1">Blur (px)</label>
599
+ <input type="number" id="backdropBlur" min="0" max="100" step="10" value="60" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
600
+ </div>
601
+ </div>
602
+ </div>
603
+ </div>
604
+ </details>
605
+
606
+ <!-- Border & Accent Widths (Collapsible) -->
607
+ <details class="settings-section border-t border-slate-800/60 pt-3">
608
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
609
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
610
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
611
+ </svg>
612
+ <span>Border & Accent Widths</span>
613
+ </summary>
614
+ <div class="space-y-3 pl-5">
615
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
616
+ <span class="font-semibold text-slate-300">Applies to:</span> Border thickness of headings, blockquotes, images, tables, and links in slides
617
+ </p>
618
+
619
+ <div class="grid grid-cols-2 gap-3">
620
+ <div class="space-y-2">
621
+ <label class="block text-xs font-medium text-slate-400">Heading Border</label>
622
+ <input type="number" id="headingBorderWidth" min="1" max="8" step="1" value="4" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
623
+ </div>
624
+ <div class="space-y-2">
625
+ <label class="block text-xs font-medium text-slate-400">Blockquote Border</label>
626
+ <input type="number" id="blockquoteBorderWidth" min="1" max="8" step="1" value="4" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
627
+ </div>
628
+ <div class="space-y-2">
629
+ <label class="block text-xs font-medium text-slate-400">Image Border</label>
630
+ <input type="number" id="imageBorderWidth" min="0" max="6" step="1" value="2" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
631
+ </div>
632
+ <div class="space-y-2">
633
+ <label class="block text-xs font-medium text-slate-400">Link Underline</label>
634
+ <input type="number" id="linkUnderlineWidth" min="1" max="5" step="1" value="2" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
635
+ </div>
636
+ <div class="space-y-2">
637
+ <label class="block text-xs font-medium text-slate-400">Table Border</label>
638
+ <input type="number" id="tableBorderWidth" min="1" max="4" step="1" value="1" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
639
+ </div>
640
+ <div class="space-y-2">
641
+ <label class="block text-xs font-medium text-slate-400">HR Border</label>
642
+ <input type="number" id="hrBorderWidth" min="1" max="5" step="1" value="2" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
643
+ </div>
644
+ </div>
645
+ </div>
646
+ </details>
647
+
648
+ <!-- Font Sizes (Collapsible) -->
649
+ <details class="settings-section border-t border-slate-800/60 pt-3">
650
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
651
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
652
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
653
+ </svg>
654
+ <span>Font Sizes</span>
655
+ </summary>
656
+ <div class="space-y-3 pl-5">
657
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
658
+ <span class="font-semibold text-slate-300">Applies to:</span> All heading and text sizes in slide content
659
+ </p>
660
+ <p class="text-xs text-slate-500">Adjust responsive font sizes using clamp(min, base vw, max)</p>
661
+
662
+ <!-- H1 Size -->
663
+ <div class="space-y-2">
664
+ <label class="block text-xs font-medium text-slate-400">H1 Heading (rem)</label>
665
+ <div class="grid grid-cols-3 gap-2">
666
+ <div>
667
+ <label class="block text-xs text-slate-500 mb-1">Min</label>
668
+ <input type="number" id="fontSizeH1Min" min="1" max="5" step="0.25" value="1.75" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
669
+ </div>
670
+ <div>
671
+ <label class="block text-xs text-slate-500 mb-1">Base vw</label>
672
+ <input type="number" id="fontSizeH1Base" min="1" max="10" step="0.5" value="4.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
673
+ </div>
674
+ <div>
675
+ <label class="block text-xs text-slate-500 mb-1">Max</label>
676
+ <input type="number" id="fontSizeH1Max" min="1" max="8" step="0.25" value="3" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
677
+ </div>
678
+ </div>
679
+ </div>
680
+
681
+ <!-- H2 Size -->
682
+ <div class="space-y-2">
683
+ <label class="block text-xs font-medium text-slate-400">H2 Heading (rem)</label>
684
+ <div class="grid grid-cols-3 gap-2">
685
+ <div>
686
+ <label class="block text-xs text-slate-500 mb-1">Min</label>
687
+ <input type="number" id="fontSizeH2Min" min="1" max="4" step="0.25" value="1.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
688
+ </div>
689
+ <div>
690
+ <label class="block text-xs text-slate-500 mb-1">Base vw</label>
691
+ <input type="number" id="fontSizeH2Base" min="1" max="8" step="0.5" value="3.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
692
+ </div>
693
+ <div>
694
+ <label class="block text-xs text-slate-500 mb-1">Max</label>
695
+ <input type="number" id="fontSizeH2Max" min="1" max="6" step="0.25" value="2.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
696
+ </div>
697
+ </div>
698
+ </div>
699
+
700
+ <!-- Body Text Size -->
701
+ <div class="space-y-2">
702
+ <label class="block text-xs font-medium text-slate-400">Body Text (rem)</label>
703
+ <div class="grid grid-cols-3 gap-2">
704
+ <div>
705
+ <label class="block text-xs text-slate-500 mb-1">Min</label>
706
+ <input type="number" id="fontSizeTextMin" min="0.8" max="3" step="0.1" value="1.1" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
707
+ </div>
708
+ <div>
709
+ <label class="block text-xs text-slate-500 mb-1">Base vw</label>
710
+ <input type="number" id="fontSizeTextBase" min="1" max="5" step="0.2" value="1.8" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
711
+ </div>
712
+ <div>
713
+ <label class="block text-xs text-slate-500 mb-1">Max</label>
714
+ <input type="number" id="fontSizeTextMax" min="0.8" max="4" step="0.1" value="1.6" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
715
+ </div>
716
+ </div>
717
+ </div>
718
+
719
+ <!-- Line Height -->
720
+ <div class="space-y-2">
721
+ <label class="block text-xs font-medium text-slate-400">Line Height</label>
722
+ <div class="grid grid-cols-2 gap-2">
723
+ <div>
724
+ <label class="block text-xs text-slate-500 mb-1">Heading</label>
725
+ <input type="number" id="lineHeightHeading" min="1" max="2.5" step="0.05" value="1.3" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
726
+ </div>
727
+ <div>
728
+ <label class="block text-xs text-slate-500 mb-1">Body</label>
729
+ <input type="number" id="lineHeightBody" min="1" max="3" step="0.05" value="1.7" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
730
+ </div>
731
+ </div>
732
+ </div>
733
+ </div>
734
+ </details>
735
+
736
+ <!-- Typography & Layout (Collapsible) -->
737
+ <details class="settings-section border-t border-slate-800/60 pt-3">
738
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
739
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
740
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
741
+ </svg>
742
+ <span>Typography & Layout</span>
743
+ </summary>
744
+ <div class="space-y-3 pl-5">
745
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
746
+ <span class="font-semibold text-slate-300">Applies to:</span> Spacing, indentation, and alignment of slide content
747
+ </p>
748
+ <h4 class="text-sm font-semibold text-slate-300">Typography & Layout</h4>
749
+ <p class="text-xs text-slate-500">Control paragraph spacing, indentation, and text alignment</p>
750
+
751
+ <!-- Paragraph Spacing -->
752
+ <div class="space-y-2">
753
+ <label class="block text-xs font-medium text-slate-400">Paragraph Spacing</label>
754
+ <div class="grid grid-cols-2 gap-2">
755
+ <div>
756
+ <label class="block text-xs text-slate-500 mb-1">Before (rem)</label>
757
+ <input type="number" id="paragraphBefore" min="0" max="3" step="0.25" value="0.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
758
+ </div>
759
+ <div>
760
+ <label class="block text-xs text-slate-500 mb-1">After (rem)</label>
761
+ <input type="number" id="paragraphAfter" min="0" max="3" step="0.25" value="1" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
762
+ </div>
763
+ </div>
764
+ </div>
765
+
766
+ <!-- Heading Spacing -->
767
+ <div class="space-y-2">
768
+ <label class="block text-xs font-medium text-slate-400">Heading Spacing</label>
769
+ <div class="grid grid-cols-2 gap-2">
770
+ <div>
771
+ <label class="block text-xs text-slate-500 mb-1">Before (rem)</label>
772
+ <input type="number" id="headingBefore" min="0" max="4" step="0.25" value="1.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
773
+ </div>
774
+ <div>
775
+ <label class="block text-xs text-slate-500 mb-1">After (rem)</label>
776
+ <input type="number" id="headingAfter" min="0" max="3" step="0.25" value="0.75" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
777
+ </div>
778
+ </div>
779
+ </div>
780
+
781
+ <!-- Indentation -->
782
+ <div class="space-y-2">
783
+ <label class="block text-xs font-medium text-slate-400">Indentation (rem)</label>
784
+ <div class="grid grid-cols-2 gap-2">
785
+ <div>
786
+ <label class="block text-xs text-slate-500 mb-1">First Line</label>
787
+ <input type="number" id="indentFirst" min="0" max="3" step="0.25" value="0" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
788
+ </div>
789
+ <div>
790
+ <label class="block text-xs text-slate-500 mb-1">Blockquote</label>
791
+ <input type="number" id="indentBlockquote" min="0" max="4" step="0.25" value="1.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
792
+ </div>
793
+ </div>
794
+ </div>
795
+
796
+ <!-- List Indent & Text Align -->
797
+ <div class="grid grid-cols-2 gap-3">
798
+ <div class="space-y-2">
799
+ <label class="block text-xs font-medium text-slate-400">List Indent (rem)</label>
800
+ <input type="number" id="listIndent" min="0" max="4" step="0.25" value="1.5" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
801
+ </div>
802
+ <div class="space-y-2">
803
+ <label class="block text-xs font-medium text-slate-400">Text Align</label>
804
+ <select id="textAlign" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
805
+ <option value="left">Left</option>
806
+ <option value="center">Center</option>
807
+ <option value="right">Right</option>
808
+ <option value="justify">Justify</option>
809
+ </select>
810
+ </div>
811
+ </div>
812
+ </div>
813
+ </details>
814
+
815
+ <!-- Page Indicator Settings (Collapsible) -->
816
+ <details class="settings-section border-t border-slate-800/60 pt-3">
817
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
818
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
819
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
820
+ </svg>
821
+ <span>Page Indicator</span>
822
+ </summary>
823
+ <div class="space-y-3 pl-5">
824
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
825
+ <span class="font-semibold text-slate-300">Applies to:</span> Page numbers display (e.g., "1 / 3") - UI element only
826
+ </p>
827
+
828
+ <div class="grid grid-cols-2 gap-3">
829
+ <div class="space-y-2">
830
+ <label class="block text-xs font-medium text-slate-400">Position Top (px)</label>
831
+ <input type="number" id="pageIndicatorTop" min="0" max="100" step="4" value="16" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
832
+ </div>
833
+ <div class="space-y-2">
834
+ <label class="block text-xs font-medium text-slate-400">Position Right (px)</label>
835
+ <input type="number" id="pageIndicatorRight" min="0" max="100" step="4" value="16" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
836
+ </div>
837
+ <div class="space-y-2">
838
+ <label class="block text-xs font-medium text-slate-400">Font Size (rem)</label>
839
+ <input type="number" id="pageIndicatorFontSize" min="0.5" max="2" step="0.125" value="0.875" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
840
+ </div>
841
+ <div class="space-y-2">
842
+ <label class="block text-xs font-medium text-slate-400">Opacity (0-1)</label>
843
+ <input type="number" id="pageIndicatorOpacity" min="0" max="1" step="0.05" value="0.7" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
844
+ </div>
845
+ <div class="space-y-2">
846
+ <label class="block text-xs font-medium text-slate-400">Padding X (px)</label>
847
+ <input type="number" id="pageIndicatorPaddingX" min="0" max="40" step="2" value="12" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
848
+ </div>
849
+ <div class="space-y-2">
850
+ <label class="block text-xs font-medium text-slate-400">Padding Y (px)</label>
851
+ <input type="number" id="pageIndicatorPaddingY" min="0" max="20" step="2" value="4" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
852
+ </div>
853
+ <div class="space-y-2 col-span-2">
854
+ <label class="block text-xs font-medium text-slate-400">Background Color (rgba)</label>
855
+ <input type="text" id="pageIndicatorBgColor" value="rgba(22, 78, 99, 0.5)" placeholder="rgba(22, 78, 99, 0.5)" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
856
+ </div>
857
+ <div class="space-y-2 col-span-2">
858
+ <label class="block text-xs font-medium text-slate-400">Text Color (hex)</label>
859
+ <input type="color" id="pageIndicatorTextColor" value="#a5f3fc" class="w-full h-10 bg-slate-900/60 border border-slate-700/60 rounded cursor-pointer">
860
+ </div>
861
+ </div>
862
+ </div>
863
+ </details>
864
+
865
+ <!-- Smart List Column Settings (Collapsible) -->
866
+ <details class="settings-section border-t border-slate-800/60 pt-3">
867
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
868
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
869
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
870
+ </svg>
871
+ <span>Smart List Columns</span>
872
+ </summary>
873
+ <div class="space-y-3 pl-5">
874
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
875
+ <span class="font-semibold text-slate-300">Applies to:</span> Lists in slide content - automatic column layout on large screens
876
+ </p>
877
+
878
+ <div class="space-y-3">
879
+ <div class="space-y-2">
880
+ <label class="block text-xs font-medium text-slate-400">2-Column Threshold (items)</label>
881
+ <input type="number" id="smartListTwoColumn" min="3" max="20" step="1" value="6" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
882
+ <p class="text-xs text-slate-500 mt-1">Lists with this many items or more will display in 2 columns</p>
883
+ </div>
884
+ <div class="space-y-2">
885
+ <label class="block text-xs font-medium text-slate-400">3-Column Threshold (items)</label>
886
+ <input type="number" id="smartListThreeColumn" min="6" max="30" step="1" value="12" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
887
+ <p class="text-xs text-slate-500 mt-1">Lists with this many items or more will display in 3 columns</p>
888
+ </div>
889
+ </div>
890
+
891
+ <div class="text-xs text-slate-400 bg-slate-800/30 border border-slate-700/40 rounded-lg p-2.5 mt-3">
892
+ <span class="font-semibold text-slate-300">Note:</span> Column layout only applies on large screens and in presentation mode.
893
+ </div>
894
+ </div>
895
+ </details>
896
+
897
+ <!-- Content Layout & Positioning (Collapsible) -->
898
+ <details class="settings-section border-t border-slate-800/60 pt-3">
899
+ <summary class="text-sm font-semibold text-slate-300 cursor-pointer hover:text-slate-200 flex items-center gap-2 pb-3">
900
+ <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
901
+ <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"/>
902
+ </svg>
903
+ <span>Content Layout & Positioning</span>
904
+ </summary>
905
+ <div class="space-y-3 pl-5">
906
+ <p class="text-xs text-slate-500 bg-slate-800/30 border border-slate-700/40 rounded p-2">
907
+ <span class="font-semibold text-slate-300">Applies to:</span> Slide content padding and alignment on different screen sizes
908
+ </p>
909
+
910
+ <!-- Content Padding -->
911
+ <div class="space-y-2">
912
+ <label class="block text-xs font-medium text-slate-400">Content Padding (px)</label>
913
+ <div class="grid grid-cols-3 gap-2">
914
+ <div>
915
+ <label class="block text-xs text-slate-500 mb-1">Small</label>
916
+ <input type="number" id="contentPaddingSmall" min="0" max="100" step="4" value="40" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
917
+ </div>
918
+ <div>
919
+ <label class="block text-xs text-slate-500 mb-1">Large</label>
920
+ <input type="number" id="contentPaddingLarge" min="0" max="120" step="4" value="48" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
921
+ </div>
922
+ <div>
923
+ <label class="block text-xs text-slate-500 mb-1">Ultra</label>
924
+ <input type="number" id="contentPaddingUltra" min="0" max="150" step="4" value="64" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
925
+ </div>
926
+ </div>
927
+ <p class="text-xs text-slate-500 mt-1">Padding around slide content for different screen sizes</p>
928
+ </div>
929
+
930
+ <!-- Content Alignment -->
931
+ <div class="space-y-2">
932
+ <label class="block text-xs font-medium text-slate-400">Content Alignment</label>
933
+ <div class="grid grid-cols-2 gap-2">
934
+ <div>
935
+ <label class="block text-xs text-slate-500 mb-1">Horizontal</label>
936
+ <select id="contentAlignHorizontal" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
937
+ <option value="flex-start">Left (Start)</option>
938
+ <option value="center" selected>Center</option>
939
+ <option value="flex-end">Right (End)</option>
940
+ </select>
941
+ </div>
942
+ <div>
943
+ <label class="block text-xs text-slate-500 mb-1">Vertical</label>
944
+ <select id="contentAlignVertical" class="w-full px-2 py-1.5 bg-slate-900/60 border border-slate-700/60 rounded text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-slate-500/50">
945
+ <option value="flex-start">Top (Start)</option>
946
+ <option value="center" selected>Center</option>
947
+ <option value="flex-end">Bottom (End)</option>
948
+ </select>
949
+ </div>
950
+ </div>
951
+ <p class="text-xs text-slate-500 mt-1">How content is aligned on large screens and in presentation mode</p>
952
+ </div>
953
+
954
+ <div class="text-xs text-slate-400 bg-slate-800/30 border border-slate-700/40 rounded-lg p-2.5 mt-3">
955
+ <span class="font-semibold text-slate-300">Tip:</span> Use center/center for traditional presentations, or flex-start/flex-start for document-style layouts.
956
+ </div>
957
+ </div>
958
+ </details>
959
+
960
+ <!-- Action Buttons -->
961
+ <div class="flex gap-3 border-t border-slate-800/60 pt-4 mt-4">
962
+ <button id="saveSettingsBtn" class="flex-1 px-4 py-2.5 bg-slate-700 hover:bg-slate-600 text-white font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-slate-500/50 flex items-center justify-center gap-2">
963
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
964
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"/>
965
+ </svg>
966
+ Save Settings
967
+ </button>
968
+ <button id="resetSettingsBtn" class="flex-1 px-4 py-2.5 bg-slate-800/50 hover:bg-slate-700/60 border border-slate-600/40 text-slate-300 font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-slate-500/50 flex items-center justify-center gap-2">
969
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
970
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
971
+ </svg>
972
+ Reset to Default
973
+ </button>
974
+ </div>
975
+
976
+ <!-- Status -->
977
+ <div class="text-xs text-slate-400 bg-slate-800/30 border border-slate-700/40 rounded-lg p-3">
978
+ <span class="font-semibold text-slate-300">Live Preview:</span> All changes apply <strong class="text-slate-200">instantly</strong> as you adjust settings!
979
+ <br>
980
+ <span class="text-slate-500 mt-1 block">Tip: Hover over any setting to see highlighted elements on stage.</span>
981
+ <br>
982
+ <span class="text-slate-500 mt-1 block"> Click "Save to Frontmatter" to persist settings to your markdown file.</span>
983
+ </div>
984
+
985
+ <!-- Legacy Template Support -->
986
+ <details class="border-t border-slate-800/60 pt-4">
987
+ <summary class="text-xs font-medium text-slate-400 cursor-pointer hover:text-slate-300">Legacy Template Support</summary>
988
+ <div class="mt-3 space-y-2">
989
+ <p class="text-xs text-slate-500">For backward compatibility with older decks using <code class="text-slate-400">template:</code> field.</p>
990
+ <div id="templatesContainer" class="grid grid-cols-2 gap-2 mt-2"></div>
991
+ </div>
992
+ </details>
993
+ </section>
994
+ </div>
995
+ </aside>
996
+ </main>
997
+
998
+ <!-- External Scripts -->
999
+ <script type="module" src="./js/app.js"></script>
1000
+ </body>
1001
+ </html>
1002
+
src/renderer/js/app.js ADDED
The diff for this file is too large to render. See raw diff
 
src/renderer/js/config-storage.js ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Configuration Storage Manager
3
+ * บันทึกและโหลดการตั้งค่าจาก localStorage และไฟล์ JSON
4
+ */
5
+
6
+ const CONFIG_STORAGE_KEY = 'chahua-presentation-config';
7
+ const CONFIG_FILE_NAME = 'presentation-config.json';
8
+
9
+ export class ConfigStorage {
10
+ /**
11
+ * บันทึกการตั้งค่าลง localStorage
12
+ */
13
+ static saveToLocalStorage(config) {
14
+ try {
15
+ const configJson = JSON.stringify(config, null, 2);
16
+ localStorage.setItem(CONFIG_STORAGE_KEY, configJson);
17
+ console.log('[ConfigStorage] Saved to localStorage');
18
+ return true;
19
+ } catch (error) {
20
+ console.error('[ConfigStorage] Failed to save to localStorage:', error);
21
+ return false;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * โหลดการตั้งค่าจาก localStorage
27
+ */
28
+ static loadFromLocalStorage() {
29
+ try {
30
+ const configJson = localStorage.getItem(CONFIG_STORAGE_KEY);
31
+ if (!configJson) {
32
+ console.log('[ConfigStorage] No saved config in localStorage');
33
+ return null;
34
+ }
35
+
36
+ const config = JSON.parse(configJson);
37
+ console.log('[ConfigStorage] Loaded from localStorage');
38
+ return config;
39
+ } catch (error) {
40
+ console.error('[ConfigStorage] Failed to load from localStorage:', error);
41
+ return null;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * ลบการตั้งค่าจาก localStorage
47
+ */
48
+ static clearLocalStorage() {
49
+ try {
50
+ localStorage.removeItem(CONFIG_STORAGE_KEY);
51
+ console.log('[ConfigStorage] Cleared localStorage');
52
+ return true;
53
+ } catch (error) {
54
+ console.error('[ConfigStorage] Failed to clear localStorage:', error);
55
+ return false;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Export การตั้งค่าเป็นไฟล์ JSON
61
+ */
62
+ static async exportToFile(config, fileName = CONFIG_FILE_NAME) {
63
+ try {
64
+ const configJson = JSON.stringify(config, null, 2);
65
+ const blob = new Blob([configJson], { type: 'application/json' });
66
+
67
+ // Create download link
68
+ const url = URL.createObjectURL(blob);
69
+ const a = document.createElement('a');
70
+ a.href = url;
71
+ a.download = fileName;
72
+ a.click();
73
+
74
+ URL.revokeObjectURL(url);
75
+ console.log('[ConfigStorage] Exported to file:', fileName);
76
+ return true;
77
+ } catch (error) {
78
+ console.error('[ConfigStorage] Failed to export to file:', error);
79
+ return false;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Import การตั้งค่าจากไฟล์ JSON
85
+ */
86
+ static async importFromFile() {
87
+ return new Promise((resolve, reject) => {
88
+ const input = document.createElement('input');
89
+ input.type = 'file';
90
+ input.accept = '.json';
91
+
92
+ input.onchange = async (e) => {
93
+ try {
94
+ const file = e.target.files[0];
95
+ if (!file) {
96
+ resolve(null);
97
+ return;
98
+ }
99
+
100
+ const text = await file.text();
101
+ const config = JSON.parse(text);
102
+
103
+ console.log('[ConfigStorage] Imported from file:', file.name);
104
+ resolve(config);
105
+ } catch (error) {
106
+ console.error('[ConfigStorage] Failed to import from file:', error);
107
+ reject(error);
108
+ }
109
+ };
110
+
111
+ input.click();
112
+ });
113
+ }
114
+
115
+ /**
116
+ * บันทึกการตั้งค่าอัตโนมัติ (debounced)
117
+ */
118
+ static autoSave(config, delay = 1000) {
119
+ if (this.autoSaveTimeout) {
120
+ clearTimeout(this.autoSaveTimeout);
121
+ }
122
+
123
+ this.autoSaveTimeout = setTimeout(() => {
124
+ this.saveToLocalStorage(config);
125
+ }, delay);
126
+ }
127
+
128
+ /**
129
+ * ตรวจสอบว่ามีการตั้งค่าที่บันทึกไว้หรือไม่
130
+ */
131
+ static hasSavedConfig() {
132
+ return localStorage.getItem(CONFIG_STORAGE_KEY) !== null;
133
+ }
134
+
135
+ /**
136
+ * รีเซ็ตการตั้งค่าทั้งหมด
137
+ */
138
+ static reset() {
139
+ this.clearLocalStorage();
140
+ if (this.autoSaveTimeout) {
141
+ clearTimeout(this.autoSaveTimeout);
142
+ }
143
+ }
144
+ }
145
+
146
+ // Auto-save timeout reference
147
+ ConfigStorage.autoSaveTimeout = null;
src/renderer/js/drag-drop-manager.js ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Drag & Drop Manager with Safe Zone System
3
+ *
4
+ * จัดการการลากย้ายบรรทัดข้อความใน Presentation Mode
5
+ * พร้อมระบบเตือนเมื่อลากออกนอกโซนปลอดภัย
6
+ *
7
+ * @author Chahua Development Co., Ltd.
8
+ * @version 2.2.0
9
+ */
10
+
11
+ import { ContentFingerprint } from '../../shared/content-fingerprint.js';
12
+ import { SAFE_ZONE_CONFIG, computeSafeZoneMargins, getSafeZoneConfig } from './presentation-config.js';
13
+
14
+ export class DragDropManager {
15
+ constructor() {
16
+ this.isDragging = false;
17
+ this.currentDragElement = null;
18
+ this.dragStartX = 0;
19
+ this.dragStartY = 0;
20
+ this.elementStartX = 0;
21
+ this.elementStartY = 0;
22
+ this.dragOffsetX = 0;
23
+ this.dragOffsetY = 0;
24
+
25
+ // Bound event handlers
26
+ this.boundMouseMove = null;
27
+ this.boundMouseUp = null;
28
+
29
+ // Safe zone settings - อ่านจาก presentation-config.js
30
+ this.showSafeZone = false;
31
+ this.safeZoneElement = null;
32
+
33
+ // Snap to grid
34
+ this.snapToGrid = false;
35
+ this.gridSize = 10;
36
+
37
+ // Z-index management
38
+ this.maxZIndex = 1000;
39
+
40
+ // Position storage
41
+ this.positions = new Map(); // fingerprint -> {x, y, zIndex, locked}
42
+
43
+ this.init();
44
+ }
45
+
46
+ init() {
47
+ this.createSafeZoneOverlay();
48
+ this.setupGlobalEventListeners();
49
+
50
+ // Listen for Safe Zone config updates
51
+ window.addEventListener('safeZoneConfigUpdated', () => {
52
+ console.log('[DragDrop] Safe Zone config updated, refreshing overlay...');
53
+ this.updateSafeZoneBorders();
54
+ });
55
+ }
56
+
57
+ /**
58
+ * สร้าง overlay แสดงโซนปลอดภัย (กรอบสีแดงบังคับ)
59
+ */
60
+ createSafeZoneOverlay() {
61
+ this.safeZoneElement = document.createElement('div');
62
+ this.safeZoneElement.className = 'safe-zone-overlay';
63
+ this.safeZoneElement.innerHTML = `
64
+ <div class="safe-zone-border safe-zone-top"></div>
65
+ <div class="safe-zone-border safe-zone-right"></div>
66
+ <div class="safe-zone-border safe-zone-bottom"></div>
67
+ <div class="safe-zone-border safe-zone-left"></div>
68
+ `;
69
+ document.body.appendChild(this.safeZoneElement);
70
+
71
+ // แสดง Safe Zone ตลอดเวลาในโหมดแก้ไข
72
+ this.showSafeZone = true;
73
+ }
74
+
75
+ /**
76
+ * Setup global event listeners
77
+ */
78
+ setupGlobalEventListeners() {
79
+ // Prevent default drag behavior
80
+ document.addEventListener('dragstart', (e) => {
81
+ if (e.target.classList.contains('draggable-content')) {
82
+ e.preventDefault();
83
+ }
84
+ });
85
+ }
86
+
87
+ /**
88
+ * เปิดใช้งาน drag & drop สำหรับ slide ปัจจุบัน
89
+ *
90
+ * @param {HTMLElement} sceneElement
91
+ */
92
+ enableDragging(sceneElement) {
93
+ if (!sceneElement) return;
94
+
95
+ const elements = sceneElement.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote');
96
+
97
+ elements.forEach((element, index) => {
98
+ this.makeDraggable(element, index);
99
+ });
100
+
101
+ // แสดง Safe Zone ทันทีเมื่อเข้าโหมดแก้ไข
102
+ this.showSafeZoneOverlay();
103
+
104
+ // ป้องกัน click events ระหว่างลาก
105
+ this.preventClickPropagation = (e) => {
106
+ if (this.isDragging) {
107
+ e.stopPropagation();
108
+ e.preventDefault();
109
+ }
110
+ };
111
+
112
+ sceneElement.addEventListener('click', this.preventClickPropagation, true);
113
+ sceneElement.addEventListener('mousedown', this.preventClickPropagation, true);
114
+ }
115
+
116
+ /**
117
+ * ปิดใช้งาน drag & drop
118
+ *
119
+ * @param {HTMLElement} sceneElement
120
+ */
121
+ disableDragging(sceneElement) {
122
+ if (!sceneElement) return;
123
+
124
+ const elements = sceneElement.querySelectorAll('.draggable-content');
125
+
126
+ elements.forEach(element => {
127
+ this.makeNonDraggable(element);
128
+ });
129
+
130
+ this.hideSafeZoneOverlay();
131
+
132
+ // ลบ event listeners
133
+ if (this.preventClickPropagation) {
134
+ sceneElement.removeEventListener('click', this.preventClickPropagation, true);
135
+ sceneElement.removeEventListener('mousedown', this.preventClickPropagation, true);
136
+ this.preventClickPropagation = null;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * ทำให้ element ลากได้
142
+ *
143
+ * @param {HTMLElement} element
144
+ * @param {number} index
145
+ */
146
+ makeDraggable(element, index) {
147
+ // เพิ่ม class และ attributes
148
+ element.classList.add('draggable-content');
149
+ element.setAttribute('data-drag-index', index);
150
+
151
+ // สร้าง fingerprint
152
+ const fingerprint = ContentFingerprint.generateStable(element);
153
+ element.setAttribute('data-fingerprint', fingerprint.primary);
154
+
155
+ // โหลด position ที่บันทึกไว้
156
+ const savedPosition = this.positions.get(fingerprint.primary);
157
+ if (savedPosition) {
158
+ this.applyPosition(element, savedPosition);
159
+ } else {
160
+ // บันทึก position เริ่มต้น
161
+ this.saveInitialPosition(element, fingerprint.primary);
162
+ }
163
+
164
+ // ถ้า locked ไม่ต้องเพิ่ม event listeners
165
+ if (savedPosition?.locked) {
166
+ element.classList.add('position-locked');
167
+ return;
168
+ }
169
+
170
+ // เพิ่ม drag handle
171
+ this.addDragHandle(element);
172
+
173
+ // Event listeners
174
+ element.addEventListener('mousedown', this.handleMouseDown.bind(this));
175
+ }
176
+
177
+ /**
178
+ * เพิ่ม drag handle (ไอคอนมือจับ)
179
+ *
180
+ * @param {HTMLElement} element
181
+ */
182
+ addDragHandle(element) {
183
+ const handle = document.createElement('div');
184
+ handle.className = 'drag-handle';
185
+ handle.innerHTML = `
186
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
187
+ <circle cx="9" cy="5" r="1"></circle>
188
+ <circle cx="9" cy="12" r="1"></circle>
189
+ <circle cx="9" cy="19" r="1"></circle>
190
+ <circle cx="15" cy="5" r="1"></circle>
191
+ <circle cx="15" cy="12" r="1"></circle>
192
+ <circle cx="15" cy="19" r="1"></circle>
193
+ </svg>
194
+ `;
195
+ handle.title = 'ลากเพื่อย้ายตำแหน่ง';
196
+ element.style.position = 'relative';
197
+ element.insertBefore(handle, element.firstChild);
198
+ }
199
+
200
+ /**
201
+ * ลบการ draggable
202
+ *
203
+ * @param {HTMLElement} element
204
+ */
205
+ makeNonDraggable(element) {
206
+ element.classList.remove('draggable-content', 'position-locked');
207
+ element.removeAttribute('data-drag-index');
208
+ element.removeAttribute('data-fingerprint');
209
+
210
+ // ลบ drag handle
211
+ const handle = element.querySelector('.drag-handle');
212
+ if (handle) {
213
+ handle.remove();
214
+ }
215
+
216
+ // ลบ event listeners
217
+ element.removeEventListener('mousedown', this.handleMouseDown.bind(this));
218
+ }
219
+
220
+ /**
221
+ * Handle mouse down
222
+ *
223
+ * @param {MouseEvent} e
224
+ */
225
+ handleMouseDown(e) {
226
+ // ถ้าคลิกที่ drag handle หรือ element เอง
227
+ const target = e.currentTarget;
228
+
229
+ // ถ้า locked ไม่ให้ลาก
230
+ if (target.classList.contains('position-locked')) {
231
+ return;
232
+ }
233
+
234
+ // เริ่ม drag
235
+ this.isDragging = true;
236
+ this.currentDragElement = target;
237
+
238
+ // บันทึกตำแหน่งเริ่มต้น
239
+ this.dragStartX = e.clientX;
240
+ this.dragStartY = e.clientY;
241
+
242
+ const rect = target.getBoundingClientRect();
243
+ this.elementStartX = rect.left;
244
+ this.elementStartY = rect.top;
245
+ this.dragOffsetX = e.clientX - rect.left;
246
+ this.dragOffsetY = e.clientY - rect.top;
247
+
248
+ // เพิ่ม class
249
+ target.classList.add('is-dragging');
250
+
251
+ // เพิ่ม class ให้ stage เพื่อป้องกัน select
252
+ const stage = document.getElementById('stage');
253
+ if (stage) {
254
+ stage.classList.add('stage-dragging');
255
+ }
256
+
257
+ // Bring to front
258
+ this.bringToFront(target);
259
+
260
+ // แสดง safe zone
261
+ if (this.showSafeZone) {
262
+ this.showSafeZoneOverlay();
263
+ }
264
+
265
+ // Global listeners - ใช้ arrow function เพื่อรักษา context
266
+ this.boundMouseMove = this.handleMouseMove.bind(this);
267
+ this.boundMouseUp = this.handleMouseUp.bind(this);
268
+
269
+ document.addEventListener('mousemove', this.boundMouseMove, true);
270
+ document.addEventListener('mouseup', this.boundMouseUp, true);
271
+
272
+ // ป้องกันการ select text
273
+ e.preventDefault();
274
+ e.stopPropagation();
275
+ return false;
276
+ }
277
+
278
+ /**
279
+ * Handle mouse move
280
+ *
281
+ * @param {MouseEvent} e
282
+ */
283
+ handleMouseMove(e) {
284
+ if (!this.isDragging || !this.currentDragElement) return;
285
+
286
+ // ป้องกันการเปลี่ยนหน้า
287
+ e.preventDefault();
288
+ e.stopPropagation();
289
+
290
+ // คำนวณตำแหน่งใหม่ (viewport coordinates)
291
+ let clientX = e.clientX - this.dragOffsetX;
292
+ let clientY = e.clientY - this.dragOffsetY;
293
+
294
+ // จำกัดให้อยู่ภายใน Safe Zone (ไม่ใช่แค่ stage)
295
+ const stage = document.getElementById('stage');
296
+ if (stage) {
297
+ const stageRect = stage.getBoundingClientRect();
298
+ const elementRect = this.currentDragElement.getBoundingClientRect();
299
+
300
+ // อ่านค่า Safe Zone margins จาก stage (คำนวณจาก SMART_SAFE_ZONE แล้ว)
301
+ const margins = this.getSafeZoneMargins();
302
+
303
+ // ขอบเขตของ Safe Zone (viewport coordinates)
304
+ const minClientX = stageRect.left + margins.left;
305
+ const maxClientX = stageRect.right - margins.right - elementRect.width;
306
+ const minClientY = stageRect.top + margins.top;
307
+ const maxClientY = stageRect.bottom - margins.bottom - elementRect.height;
308
+
309
+ // จำกัดตำแหน่งให้อยู่ใน Safe Zone เท่านั้น
310
+ clientX = Math.max(minClientX, Math.min(clientX, maxClientX));
311
+ clientY = Math.max(minClientY, Math.min(clientY, maxClientY));
312
+ }
313
+
314
+ // Snap to grid (ใช้ viewport coordinates)
315
+ if (this.snapToGrid) {
316
+ clientX = Math.round(clientX / this.gridSize) * this.gridSize;
317
+ clientY = Math.round(clientY / this.gridSize) * this.gridSize;
318
+ }
319
+
320
+ // ใช้ตำแหน่งใหม่ (ใช้ fixed positioning เพื่อให้ตรงกับ clientX/Y)
321
+ this.currentDragElement.style.position = 'fixed';
322
+ this.currentDragElement.style.left = `${clientX}px`;
323
+ this.currentDragElement.style.top = `${clientY}px`;
324
+
325
+ // เช็คว่าอยู่ในโซนปลอดภัยหรือไม่ (จะต้อง true เสมอเพราะเราจำกัดแล้ว)
326
+ const isInSafeZone = this.checkSafeZone(clientX, clientY, this.currentDragElement);
327
+
328
+ if (!isInSafeZone) {
329
+ this.currentDragElement.classList.add('outside-safe-zone');
330
+ this.highlightSafeZoneBorder();
331
+ } else {
332
+ this.currentDragElement.classList.remove('outside-safe-zone');
333
+ this.unhighlightSafeZoneBorder();
334
+ }
335
+
336
+ return false;
337
+ }
338
+
339
+ /**
340
+ * Handle mouse up
341
+ *
342
+ * @param {MouseEvent} e
343
+ */
344
+ handleMouseUp(e) {
345
+ if (!this.isDragging || !this.currentDragElement) return;
346
+
347
+ // ป้องกันการเปลี่ยนหน้า
348
+ e.preventDefault();
349
+ e.stopPropagation();
350
+
351
+ const element = this.currentDragElement;
352
+
353
+ // ลบ class
354
+ element.classList.remove('is-dragging', 'outside-safe-zone');
355
+ this.unhighlightSafeZoneBorder();
356
+
357
+ // ลบ class จาก stage
358
+ const stage = document.getElementById('stage');
359
+ if (stage) {
360
+ stage.classList.remove('stage-dragging');
361
+ }
362
+
363
+ // บันทึกตำแหน่งใหม่
364
+ const fingerprint = element.getAttribute('data-fingerprint');
365
+ const rect = element.getBoundingClientRect();
366
+
367
+ this.positions.set(fingerprint, {
368
+ x: rect.left,
369
+ y: rect.top,
370
+ zIndex: parseInt(element.style.zIndex) || 1000,
371
+ locked: false,
372
+ timestamp: Date.now()
373
+ });
374
+
375
+ // Reset
376
+ this.isDragging = false;
377
+ this.currentDragElement = null;
378
+
379
+ // ลบ global listeners - ใช้ bound functions
380
+ if (this.boundMouseMove) {
381
+ document.removeEventListener('mousemove', this.boundMouseMove, true);
382
+ this.boundMouseMove = null;
383
+ }
384
+ if (this.boundMouseUp) {
385
+ document.removeEventListener('mouseup', this.boundMouseUp, true);
386
+ this.boundMouseUp = null;
387
+ }
388
+
389
+ // ซ่อน safe zone ถ้าไม่ได้เปิดค้างไว้
390
+ if (!this.showSafeZone) {
391
+ this.hideSafeZoneOverlay();
392
+ }
393
+
394
+ // Trigger save event
395
+ this.dispatchPositionChanged(fingerprint);
396
+
397
+ return false;
398
+ }
399
+
400
+ /**
401
+ * อ่านค่า Safe Zone margins จาก presentation-config.js
402
+ *
403
+ * @returns {Object} { top, right, bottom, left }
404
+ */
405
+ getSafeZoneMargins() {
406
+ const stage = document.getElementById('stage');
407
+ if (!stage) {
408
+ // ใช้ค่าจาก config
409
+ return computeSafeZoneMargins();
410
+ }
411
+
412
+ const stageRect = stage.getBoundingClientRect();
413
+ return computeSafeZoneMargins(stageRect);
414
+ }
415
+
416
+ /**
417
+ * เช็คว่าอยู่ในโซนปลอดภัยหรือไม่
418
+ *
419
+ * @param {number} x
420
+ * @param {number} y
421
+ * @param {HTMLElement} element
422
+ * @returns {boolean}
423
+ */
424
+ checkSafeZone(x, y, element) {
425
+ // ใช้ stage เป็นขอบเขต
426
+ const stage = document.getElementById('stage');
427
+ if (!stage) return true;
428
+
429
+ const stageRect = stage.getBoundingClientRect();
430
+ const elementRect = element.getBoundingClientRect();
431
+ const width = elementRect.width;
432
+ const height = elementRect.height;
433
+
434
+ // อ่านค่า Safe Zone margins จาก stage
435
+ const margins = this.getSafeZoneMargins();
436
+
437
+ // คำนวณจากขอบ stage
438
+ const minX = stageRect.left + margins.left;
439
+ const maxX = stageRect.right - margins.right - width;
440
+ const minY = stageRect.top + margins.top;
441
+ const maxY = stageRect.bottom - margins.bottom - height;
442
+
443
+ // เช็คว่าอยู่ในโซนหรือไม่
444
+ const inHorizontal = (x >= minX) && (x <= maxX);
445
+ const inVertical = (y >= minY) && (y <= maxY);
446
+
447
+ return inHorizontal && inVertical;
448
+ }
449
+
450
+ /**
451
+ * แสดง safe zone overlay
452
+ */
453
+ showSafeZoneOverlay() {
454
+ if (!this.safeZoneElement) {
455
+ console.warn('[DragDrop] Safe zone element not found');
456
+ return;
457
+ }
458
+
459
+ this.safeZoneElement.classList.remove('hidden');
460
+ this.updateSafeZoneBorders();
461
+ console.log('[DragDrop] Safe zone overlay shown');
462
+ }
463
+
464
+ /**
465
+ * ซ่อน safe zone overlay
466
+ */
467
+ hideSafeZoneOverlay() {
468
+ if (!this.safeZoneElement) return;
469
+ this.safeZoneElement.classList.add('hidden');
470
+ console.log('[DragDrop] Safe zone overlay hidden');
471
+ }
472
+
473
+ /**
474
+ * อัปเดต safe zone borders (ตาม stage)
475
+ */
476
+ updateSafeZoneBorders() {
477
+ if (!this.safeZoneElement) {
478
+ console.warn('[DragDrop] Cannot update borders: safeZoneElement is null');
479
+ return;
480
+ }
481
+
482
+ // ใช้ stage เป็นขอบเขต
483
+ const stage = document.getElementById('stage');
484
+ if (!stage) {
485
+ console.warn('[DragDrop] Cannot update borders: stage not found');
486
+ return;
487
+ }
488
+
489
+ const stageRect = stage.getBoundingClientRect();
490
+ // อ่านค่า Safe Zone margins จาก stage
491
+ const margins = this.getSafeZoneMargins();
492
+
493
+ console.log('[DragDrop] Updating Safe Zone borders:', {
494
+ stageRect: { width: stageRect.width, height: stageRect.height, left: stageRect.left, top: stageRect.top },
495
+ margins: margins,
496
+ viewportSize: { width: window.innerWidth, height: window.innerHeight }
497
+ });
498
+
499
+ // คำนวณตำแหน่งจาก stage (ใช้ margins แยกแต่ละด้าน)
500
+ const topPos = stageRect.top + margins.top;
501
+ const rightPos = stageRect.right - margins.right;
502
+ const bottomPos = stageRect.bottom - margins.bottom;
503
+ const leftPos = stageRect.left + margins.left;
504
+
505
+ // อ่านค่าจาก config
506
+ const borderConfig = SAFE_ZONE_CONFIG.border;
507
+
508
+ // Top border
509
+ const top = this.safeZoneElement.querySelector('.safe-zone-top');
510
+ if (top) {
511
+ top.style.position = 'fixed';
512
+ top.style.top = `${topPos}px`;
513
+ top.style.left = `${leftPos}px`;
514
+ top.style.width = `${stageRect.width - margins.left - margins.right}px`;
515
+ top.style.height = `${borderConfig.width}px`;
516
+ top.style.backgroundColor = borderConfig.color;
517
+ top.style.boxShadow = `0 0 ${borderConfig.glowSize} ${borderConfig.glowColor}`;
518
+ top.style.zIndex = borderConfig.zIndex;
519
+ top.style.pointerEvents = 'none';
520
+ }
521
+
522
+ // Right border
523
+ const right = this.safeZoneElement.querySelector('.safe-zone-right');
524
+ if (right) {
525
+ right.style.position = 'fixed';
526
+ right.style.top = `${topPos}px`;
527
+ right.style.left = `${rightPos}px`;
528
+ right.style.height = `${stageRect.height - margins.top - margins.bottom}px`;
529
+ right.style.width = `${borderConfig.width}px`;
530
+ right.style.backgroundColor = borderConfig.color;
531
+ right.style.boxShadow = `0 0 ${borderConfig.glowSize} ${borderConfig.glowColor}`;
532
+ right.style.zIndex = borderConfig.zIndex;
533
+ right.style.pointerEvents = 'none';
534
+ }
535
+
536
+ // Bottom border
537
+ const bottom = this.safeZoneElement.querySelector('.safe-zone-bottom');
538
+ if (bottom) {
539
+ bottom.style.position = 'fixed';
540
+ bottom.style.top = `${bottomPos}px`;
541
+ bottom.style.left = `${leftPos}px`;
542
+ bottom.style.width = `${stageRect.width - margins.left - margins.right}px`;
543
+ bottom.style.height = `${borderConfig.width}px`;
544
+ bottom.style.backgroundColor = borderConfig.color;
545
+ bottom.style.boxShadow = `0 0 ${borderConfig.glowSize} ${borderConfig.glowColor}`;
546
+ bottom.style.zIndex = borderConfig.zIndex;
547
+ bottom.style.pointerEvents = 'none';
548
+ }
549
+
550
+ // Left border
551
+ const left = this.safeZoneElement.querySelector('.safe-zone-left');
552
+ if (left) {
553
+ left.style.position = 'fixed';
554
+ left.style.top = `${topPos}px`;
555
+ left.style.left = `${leftPos}px`;
556
+ left.style.height = `${stageRect.height - margins.top - margins.bottom}px`;
557
+ left.style.width = `${borderConfig.width}px`;
558
+ left.style.backgroundColor = borderConfig.color;
559
+ left.style.boxShadow = `0 0 ${borderConfig.glowSize} ${borderConfig.glowColor}`;
560
+ left.style.zIndex = borderConfig.zIndex;
561
+ left.style.pointerEvents = 'none';
562
+ }
563
+
564
+ console.log('[DragDrop] Safe Zone borders updated successfully');
565
+ }
566
+
567
+ /**
568
+ * อัปเดต corners ของ safe zone
569
+ */
570
+ updateSafeZoneCorners(stageRect, margins) {
571
+ if (!this.safeZoneElement) return;
572
+
573
+ const topPos = stageRect.top + margins.top;
574
+ const rightPos = stageRect.right - margins.right;
575
+ const bottomPos = stageRect.bottom - margins.bottom;
576
+ const leftPos = stageRect.left + margins.left;
577
+
578
+ // Top-left
579
+ const tl = this.safeZoneElement.querySelector('.safe-zone-tl');
580
+ if (tl) {
581
+ tl.style.position = 'fixed';
582
+ tl.style.top = `${topPos}px`;
583
+ tl.style.left = `${leftPos}px`;
584
+ }
585
+
586
+ // Top-right
587
+ const tr = this.safeZoneElement.querySelector('.safe-zone-tr');
588
+ if (tr) {
589
+ tr.style.position = 'fixed';
590
+ tr.style.top = `${topPos}px`;
591
+ tr.style.left = `${rightPos - 20}px`;
592
+ }
593
+
594
+ // Bottom-right
595
+ const br = this.safeZoneElement.querySelector('.safe-zone-br');
596
+ if (br) {
597
+ br.style.position = 'fixed';
598
+ br.style.top = `${bottomPos - 20}px`;
599
+ br.style.left = `${rightPos - 20}px`;
600
+ }
601
+
602
+ // Bottom-left
603
+ const bl = this.safeZoneElement.querySelector('.safe-zone-bl');
604
+ if (bl) {
605
+ bl.style.position = 'fixed';
606
+ bl.style.top = `${bottomPos - 20}px`;
607
+ bl.style.left = `${leftPos}px`;
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Highlight safe zone border (เตือนสีแดง)
613
+ */
614
+ highlightSafeZoneBorder() {
615
+ if (!this.safeZoneElement) return;
616
+ this.safeZoneElement.classList.add('warning');
617
+ }
618
+
619
+ /**
620
+ * Unhighlight safe zone border
621
+ */
622
+ unhighlightSafeZoneBorder() {
623
+ if (!this.safeZoneElement) return;
624
+ this.safeZoneElement.classList.remove('warning');
625
+ }
626
+
627
+ /**
628
+ * Bring element to front
629
+ *
630
+ * @param {HTMLElement} element
631
+ */
632
+ bringToFront(element) {
633
+ this.maxZIndex++;
634
+ element.style.zIndex = this.maxZIndex;
635
+ }
636
+
637
+ /**
638
+ * บันทึก initial position
639
+ *
640
+ * @param {HTMLElement} element
641
+ * @param {string} fingerprint
642
+ */
643
+ saveInitialPosition(element, fingerprint) {
644
+ // ตั้ง position เป็น fixed (ใช้ viewport coordinates)
645
+ const computedStyle = window.getComputedStyle(element);
646
+ if (computedStyle.position !== 'fixed' && computedStyle.position !== 'absolute') {
647
+ element.style.position = 'fixed';
648
+ }
649
+
650
+ const rect = element.getBoundingClientRect();
651
+
652
+ this.positions.set(fingerprint, {
653
+ x: rect.left,
654
+ y: rect.top,
655
+ zIndex: 1000,
656
+ locked: false,
657
+ timestamp: Date.now()
658
+ });
659
+ }
660
+
661
+ /**
662
+ * Apply position to element
663
+ *
664
+ * @param {HTMLElement} element
665
+ * @param {Object} position
666
+ */
667
+ applyPosition(element, position) {
668
+ // ใช้ fixed positioning เพื่อให้ตำแหน่งตรงกับที่บ���นทึกไว้
669
+ element.style.position = 'fixed';
670
+ element.style.left = `${position.x}px`;
671
+ element.style.top = `${position.y}px`;
672
+ element.style.zIndex = position.zIndex || 1000;
673
+
674
+ if (position.locked) {
675
+ element.classList.add('position-locked');
676
+ }
677
+ }
678
+
679
+ /**
680
+ * Lock/unlock element position
681
+ *
682
+ * @param {HTMLElement} element
683
+ * @param {boolean} locked
684
+ */
685
+ toggleLock(element, locked) {
686
+ const fingerprint = element.getAttribute('data-fingerprint');
687
+ if (!fingerprint) return;
688
+
689
+ const position = this.positions.get(fingerprint);
690
+ if (position) {
691
+ position.locked = locked;
692
+ this.positions.set(fingerprint, position);
693
+ }
694
+
695
+ if (locked) {
696
+ element.classList.add('position-locked');
697
+ this.makeNonDraggable(element);
698
+ } else {
699
+ element.classList.remove('position-locked');
700
+ const index = parseInt(element.getAttribute('data-drag-index'));
701
+ this.makeDraggable(element, index);
702
+ }
703
+ }
704
+
705
+ /**
706
+ * Reset position to original
707
+ *
708
+ * @param {HTMLElement} element
709
+ */
710
+ resetPosition(element) {
711
+ const fingerprint = element.getAttribute('data-fingerprint');
712
+ if (!fingerprint) return;
713
+
714
+ // ลบ position
715
+ this.positions.delete(fingerprint);
716
+
717
+ // Reset styles
718
+ element.style.position = '';
719
+ element.style.left = '';
720
+ element.style.top = '';
721
+ element.style.zIndex = '';
722
+
723
+ this.dispatchPositionChanged(fingerprint);
724
+ }
725
+
726
+ /**
727
+ * Get all positions
728
+ *
729
+ * @returns {Map}
730
+ */
731
+ getAllPositions() {
732
+ return this.positions;
733
+ }
734
+
735
+ /**
736
+ * Load positions from storage
737
+ *
738
+ * @param {Object} savedPositions
739
+ */
740
+ loadPositions(savedPositions) {
741
+ if (!savedPositions) return;
742
+
743
+ this.positions = new Map(Object.entries(savedPositions));
744
+ }
745
+
746
+ /**
747
+ * Export positions
748
+ *
749
+ * @returns {Object}
750
+ */
751
+ exportPositions() {
752
+ return Object.fromEntries(this.positions);
753
+ }
754
+
755
+ /**
756
+ * Clear all positions
757
+ */
758
+ clearAllPositions() {
759
+ this.positions.clear();
760
+ }
761
+
762
+ /**
763
+ * Dispatch position changed event
764
+ *
765
+ * @param {string} fingerprint
766
+ */
767
+ dispatchPositionChanged(fingerprint) {
768
+ const event = new CustomEvent('positionChanged', {
769
+ detail: {
770
+ fingerprint,
771
+ position: this.positions.get(fingerprint)
772
+ }
773
+ });
774
+ document.dispatchEvent(event);
775
+ }
776
+
777
+ /**
778
+ * Toggle safe zone visibility
779
+ *
780
+ * @param {boolean} show
781
+ */
782
+ toggleSafeZone(show) {
783
+ this.showSafeZone = show;
784
+ if (show) {
785
+ this.showSafeZoneOverlay();
786
+ } else {
787
+ this.hideSafeZoneOverlay();
788
+ }
789
+ }
790
+
791
+ /**
792
+ * Set safe zone margin
793
+ *
794
+ * @param {number} margin - pixels
795
+ */
796
+ setSafeZoneMargin(margin) {
797
+ this.safeZoneMargin = margin;
798
+ this.updateSafeZoneBorders();
799
+ }
800
+
801
+ /**
802
+ * Toggle snap to grid
803
+ *
804
+ * @param {boolean} enabled
805
+ */
806
+ toggleSnapToGrid(enabled) {
807
+ this.snapToGrid = enabled;
808
+ }
809
+
810
+ /**
811
+ * Set grid size
812
+ *
813
+ * @param {number} size - pixels
814
+ */
815
+ setGridSize(size) {
816
+ this.gridSize = size;
817
+ }
818
+
819
+ /**
820
+ * Cleanup
821
+ */
822
+ destroy() {
823
+ if (this.safeZoneElement) {
824
+ this.safeZoneElement.remove();
825
+ }
826
+ this.positions.clear();
827
+ }
828
+ }
829
+
830
+ export default DragDropManager;
src/renderer/js/mode-manager.js ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Mode Manager - Strict Mode Separation System
3
+ // แยกโหมดการทำงานแบบเด็ดขาด ไม่ให้ทับซ้อนกัน
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+
6
+ import { setDisplayMode } from './presentation-config.js';
7
+
8
+ /**
9
+ * Mode Manager Class
10
+ * ควบคุมโหมดการทำงานทั้งหมด แยกอย่างเด็ดขาด
11
+ */
12
+ export class ModeManager {
13
+ constructor() {
14
+ this.currentMode = 'intro';
15
+ this.modes = {
16
+ intro: null,
17
+ presentation: null,
18
+ editor: null
19
+ };
20
+
21
+ // Track all active systems
22
+ this.activeSystems = {
23
+ smartLayout: false,
24
+ dragDrop: false,
25
+ contentEditable: false,
26
+ resizeObserver: false,
27
+ keyboardNav: false,
28
+ safeZoneBorder: false
29
+ };
30
+
31
+ // System references
32
+ this.systems = {
33
+ smartLayoutControl: null,
34
+ dragDropManager: null,
35
+ resizeObserver: null,
36
+ eventListeners: []
37
+ };
38
+
39
+ console.log('[ModeManager] Initialized');
40
+ }
41
+
42
+ /**
43
+ * Switch to a specific mode (EXCLUSIVE - ปิดโหมดอื่นทั้งหมด)
44
+ */
45
+ switchMode(newMode) {
46
+ if (!['intro', 'presentation', 'editor'].includes(newMode)) {
47
+ console.error(`[ModeManager] Invalid mode: ${newMode}`);
48
+ return false;
49
+ }
50
+
51
+ if (this.currentMode === newMode) {
52
+ console.log(`[ModeManager] Already in ${newMode} mode`);
53
+ return true;
54
+ }
55
+
56
+ console.log(`[ModeManager] SWITCHING: ${this.currentMode} → ${newMode}`);
57
+
58
+ // 1. SHUTDOWN current mode completely
59
+ this.shutdownMode(this.currentMode);
60
+
61
+ // 2. UPDATE mode
62
+ this.currentMode = newMode;
63
+ setDisplayMode(newMode);
64
+
65
+ // 3. ACTIVATE new mode exclusively
66
+ this.activateMode(newMode);
67
+
68
+ // 4. Dispatch event
69
+ window.dispatchEvent(new CustomEvent('modeChanged', {
70
+ detail: {
71
+ mode: newMode,
72
+ timestamp: Date.now()
73
+ }
74
+ }));
75
+
76
+ console.log(`[ModeManager] Now in ${newMode} mode (ALL OTHER MODES DISABLED)`);
77
+ return true;
78
+ }
79
+
80
+ /**
81
+ * Shutdown a mode completely (ปิดทุกระบบในโหมดนั้น)
82
+ */
83
+ shutdownMode(mode) {
84
+ console.log(`[ModeManager] Shutting down ${mode} mode...`);
85
+
86
+ switch (mode) {
87
+ case 'intro':
88
+ this.shutdownIntroMode();
89
+ break;
90
+ case 'presentation':
91
+ this.shutdownPresentationMode();
92
+ break;
93
+ case 'editor':
94
+ this.shutdownEditorMode();
95
+ break;
96
+ }
97
+
98
+ console.log(`[ModeManager] ${mode} mode shut down completely`);
99
+ }
100
+
101
+ /**
102
+ * Activate a mode exclusively (เปิดเฉพาะระบบในโหมดนั้น)
103
+ */
104
+ activateMode(mode) {
105
+ console.log(`[ModeManager] Activating ${mode} mode...`);
106
+
107
+ switch (mode) {
108
+ case 'intro':
109
+ this.activateIntroMode();
110
+ break;
111
+ case 'presentation':
112
+ this.activatePresentationMode();
113
+ break;
114
+ case 'editor':
115
+ this.activateEditorMode();
116
+ break;
117
+ }
118
+
119
+ console.log(`[ModeManager] ${mode} mode activated exclusively`);
120
+ }
121
+
122
+ // ═══════════════════════════════════════════════════════════════════════
123
+ // INTRO MODE - เฉพาะหน้า Intro
124
+ // ═══════════════════════════════════════════════════════════════════════
125
+
126
+ activateIntroMode() {
127
+ // Intro mode: ไม่มีระบบอะไรทำงานเลย เป็นหน้าคงที่
128
+ this.disableAllSystems();
129
+
130
+ // ปิด Smart Layout อย่างเด็ดขาด
131
+ if (window.smartLayoutControl) {
132
+ window.smartLayoutControl.detach();
133
+ }
134
+
135
+ // ซ่อน UI ของโหมดอื่นทั้งหมด
136
+ this.hideAllModeUI();
137
+
138
+ // แสดงเฉพาะ intro scene
139
+ const scenes = document.querySelectorAll('[data-scene]');
140
+ scenes.forEach(scene => {
141
+ if (scene.dataset.scene === 'intro') {
142
+ scene.classList.add('active');
143
+ } else {
144
+ scene.classList.remove('active');
145
+ }
146
+ });
147
+
148
+ console.log('[ModeManager] Intro mode: Static display only (no systems)');
149
+ }
150
+
151
+ shutdownIntroMode() {
152
+ // Intro ไม่มีอะไรต้องปิด
153
+ console.log('[ModeManager] Intro mode: No systems to shutdown');
154
+ }
155
+
156
+ // ═══════════════════════════════════════════════════════════════════════
157
+ // PRESENTATION MODE - สำหรับนำเสนอเท่านั้น
158
+ // ═══════════════════════════════════════════════════════════════════════
159
+
160
+ activatePresentationMode() {
161
+ // ปิดทุกระบบก่อน
162
+ this.disableAllSystems();
163
+
164
+ // เปิดเฉพาะ Keyboard Navigation
165
+ this.activeSystems.keyboardNav = true;
166
+
167
+ // เปิด Smart Layout เฉพาะ Presentation Mode
168
+ this.activeSystems.smartLayout = true;
169
+
170
+ // Reattach Smart Layout observers สำหรับ Presentation
171
+ if (window.smartLayoutControl) {
172
+ this.systems.smartLayoutControl = window.smartLayoutControl;
173
+ window.smartLayoutControl.reattach();
174
+ }
175
+
176
+ // ปิด Safe Zone Border
177
+ this.activeSystems.safeZoneBorder = false;
178
+
179
+ // แสดงเฉพาะ UI ของ Presentation Mode
180
+ this.showPresentationUI();
181
+
182
+ console.log('[ModeManager] Presentation mode: Keyboard nav + Smart Layout ENABLED');
183
+ }
184
+
185
+ shutdownPresentationMode() {
186
+ // ปิด Keyboard Navigation
187
+ this.activeSystems.keyboardNav = false;
188
+
189
+ // ปิด Smart Layout และ detach observers
190
+ this.activeSystems.smartLayout = false;
191
+ if (window.smartLayoutControl) {
192
+ window.smartLayoutControl.detach();
193
+ }
194
+
195
+ // ✅ ซ่อน UI ของ Presentation Mode
196
+ this.hideAllModeUI();
197
+
198
+ console.log('[ModeManager] Presentation mode: Shut down');
199
+ }
200
+
201
+ // ═══════════════════════════════════════════════════════════════════════
202
+ // EDITOR MODE - สำหรับแก้ไข/ลากย้ายเท่านั้น
203
+ // ═══════════════════════════════════════════════════════════════════════
204
+
205
+ activateEditorMode() {
206
+ // ปิดทุกระบบก่อน
207
+ this.disableAllSystems();
208
+
209
+ // เปิด Content Editable
210
+ this.activeSystems.contentEditable = true;
211
+
212
+ // เปิด Drag & Drop
213
+ this.activeSystems.dragDrop = true;
214
+
215
+ // เปิด Safe Zone Border (กรอบสีแดง)
216
+ this.activeSystems.safeZoneBorder = true;
217
+ this.showSafeZoneBorder();
218
+
219
+ // ปิด Smart Layout อย่างเด็ดขาด (ห้ามทำงานใน Editor Mode)
220
+ this.activeSystems.smartLayout = false;
221
+ if (window.smartLayoutControl) {
222
+ window.smartLayoutControl.detach();
223
+ }
224
+
225
+ // ปิด Resize Observer
226
+ this.activeSystems.resizeObserver = false;
227
+
228
+ // แสดงเฉพาะ UI ของ Editor Mode
229
+ this.showEditorUI();
230
+
231
+ console.log('[ModeManager] Editor mode: Edit/Drag only (Smart Layout DISABLED)');
232
+ }
233
+
234
+ shutdownEditorMode() {
235
+ // ปิด Content Editable
236
+ this.activeSystems.contentEditable = false;
237
+ this.disableContentEditable();
238
+
239
+ // ปิด Drag & Drop
240
+ this.activeSystems.dragDrop = false;
241
+
242
+ // ปิด Safe Zone Border
243
+ this.activeSystems.safeZoneBorder = false;
244
+ this.hideSafeZoneBorder();
245
+
246
+ // ✅ ซ่อน UI ของ Editor Mode
247
+ this.hideAllModeUI();
248
+
249
+ console.log('[ModeManager] Editor mode: Shut down');
250
+ }
251
+
252
+ // ═══════════════════════════════════════════════════════════════════════
253
+ // SYSTEM CONTROL - ควบคุมระบบย่อยๆ
254
+ // ═══════════════════════════════════════════════════════════════════════
255
+
256
+ /**
257
+ * ปิดทุกระบบ (ไม่ต้อง detach Smart Layout เพราะแต่ละโหมดจัดการเอง)
258
+ */
259
+ disableAllSystems() {
260
+ // ไม่ detach Smart Layout ที่นี่ ให้แต่ละโหมดจัดการเอง
261
+
262
+ // ปิด Content Editable
263
+ this.disableContentEditable();
264
+
265
+ // ซ่อน Safe Zone Border
266
+ this.hideSafeZoneBorder();
267
+
268
+ // รีเซ็ต active systems
269
+ Object.keys(this.activeSystems).forEach(key => {
270
+ this.activeSystems[key] = false;
271
+ });
272
+
273
+ console.log('[ModeManager] All systems disabled (except Smart Layout - handled per mode)');
274
+ }
275
+
276
+ /**
277
+ * ปิด Content Editable ทุกอัน
278
+ */
279
+ disableContentEditable() {
280
+ const editables = document.querySelectorAll('[contenteditable="true"]');
281
+ editables.forEach(el => {
282
+ el.contentEditable = false;
283
+ el.blur();
284
+ });
285
+
286
+ // ลบ class editable
287
+ const stage = document.getElementById('stage');
288
+ if (stage) {
289
+ stage.classList.remove('slide-editable');
290
+ }
291
+ }
292
+
293
+ /**
294
+ * ซ่อน Safe Zone Border
295
+ */
296
+ hideSafeZoneBorder() {
297
+ const safeZone = document.querySelector('.safe-zone-overlay');
298
+ if (safeZone) {
299
+ safeZone.classList.add('hidden');
300
+ }
301
+ }
302
+
303
+ /**
304
+ * แสดง Safe Zone Border
305
+ */
306
+ showSafeZoneBorder() {
307
+ const safeZone = document.querySelector('.safe-zone-overlay');
308
+ if (safeZone) {
309
+ safeZone.classList.remove('hidden');
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Get current mode
315
+ */
316
+ getCurrentMode() {
317
+ return this.currentMode;
318
+ }
319
+
320
+ /**
321
+ * Check if specific system is active
322
+ */
323
+ isSystemActive(systemName) {
324
+ return this.activeSystems[systemName] || false;
325
+ }
326
+
327
+ /**
328
+ * Get all active systems
329
+ */
330
+ getActiveSystems() {
331
+ return Object.entries(this.activeSystems)
332
+ .filter(([key, value]) => value)
333
+ .map(([key]) => key);
334
+ }
335
+
336
+ /**
337
+ * Register system reference
338
+ */
339
+ registerSystem(name, reference) {
340
+ this.systems[name] = reference;
341
+ console.log(`[ModeManager] Registered system: ${name}`);
342
+ }
343
+
344
+ // ═══════════════════════════════════════════════════════════════════════
345
+ // UI CONTROL - ควบคุม UI elements ของแต่ละโหมด
346
+ // ═══════════════════════════════════════════════════════════════════════
347
+
348
+ /**
349
+ * ซ่อน UI ของทุกโหมด
350
+ */
351
+ hideAllModeUI() {
352
+ // Presentation Mode UI
353
+ const navControls = document.getElementById('navControls');
354
+ const exitPresentationBtn = document.getElementById('exitPresentationBtn');
355
+ const fullscreenBtn = document.getElementById('fullscreenBtn');
356
+ const editSlideBtn = document.getElementById('editSlideBtn');
357
+
358
+ if (navControls) navControls.classList.add('hidden');
359
+ if (exitPresentationBtn) exitPresentationBtn.classList.add('hidden');
360
+ if (fullscreenBtn) fullscreenBtn.classList.add('hidden');
361
+ if (editSlideBtn) editSlideBtn.classList.add('hidden');
362
+
363
+ // Editor Mode UI
364
+ const saveSlideBtn = document.getElementById('saveSlideBtn');
365
+ const cancelEditBtn = document.getElementById('cancelEditBtn');
366
+
367
+ if (saveSlideBtn) saveSlideBtn.classList.add('hidden');
368
+ if (cancelEditBtn) cancelEditBtn.classList.add('hidden');
369
+
370
+ console.log('[ModeManager] All mode UI hidden');
371
+ }
372
+
373
+ /**
374
+ * แสดง UI ของ Presentation Mode เท่านั้น
375
+ */
376
+ showPresentationUI() {
377
+ this.hideAllModeUI();
378
+
379
+ const navControls = document.getElementById('navControls');
380
+ const exitPresentationBtn = document.getElementById('exitPresentationBtn');
381
+ const fullscreenBtn = document.getElementById('fullscreenBtn');
382
+ const editSlideBtn = document.getElementById('editSlideBtn');
383
+
384
+ if (navControls) navControls.classList.remove('hidden');
385
+ if (exitPresentationBtn) exitPresentationBtn.classList.remove('hidden');
386
+ if (fullscreenBtn) fullscreenBtn.classList.remove('hidden');
387
+ if (editSlideBtn) editSlideBtn.classList.remove('hidden');
388
+
389
+ console.log('[ModeManager] Presentation UI shown exclusively');
390
+ }
391
+
392
+ /**
393
+ * แสดง UI ของ Editor Mode เท่านั้น
394
+ */
395
+ showEditorUI() {
396
+ this.hideAllModeUI();
397
+
398
+ const saveSlideBtn = document.getElementById('saveSlideBtn');
399
+ const cancelEditBtn = document.getElementById('cancelEditBtn');
400
+ const exitPresentationBtn = document.getElementById('exitPresentationBtn');
401
+
402
+ if (saveSlideBtn) saveSlideBtn.classList.remove('hidden');
403
+ if (cancelEditBtn) cancelEditBtn.classList.remove('hidden');
404
+ if (exitPresentationBtn) exitPresentationBtn.classList.remove('hidden');
405
+
406
+ console.log('[ModeManager] Editor UI shown exclusively');
407
+ }
408
+
409
+ /**
410
+ * Force shutdown all (emergency)
411
+ */
412
+ emergencyShutdown() {
413
+ console.warn('[ModeManager] EMERGENCY SHUTDOWN');
414
+ this.disableAllSystems();
415
+
416
+ // Stop all observers
417
+ if (this.systems.resizeObserver) {
418
+ this.systems.resizeObserver.disconnect();
419
+ }
420
+
421
+ // Remove all event listeners
422
+ this.systems.eventListeners.forEach(({ element, event, handler }) => {
423
+ element.removeEventListener(event, handler);
424
+ });
425
+ this.systems.eventListeners = [];
426
+
427
+ console.log('[ModeManager] Emergency shutdown complete');
428
+ }
429
+ }
430
+
431
+ // Singleton instance
432
+ let modeManagerInstance = null;
433
+
434
+ /**
435
+ * Get Mode Manager instance (Singleton)
436
+ */
437
+ export function getModeManager() {
438
+ if (!modeManagerInstance) {
439
+ modeManagerInstance = new ModeManager();
440
+ }
441
+ return modeManagerInstance;
442
+ }
443
+
444
+ /**
445
+ * Quick access functions
446
+ */
447
+ export function switchToIntroMode() {
448
+ return getModeManager().switchMode('intro');
449
+ }
450
+
451
+ export function switchToPresentationMode() {
452
+ return getModeManager().switchMode('presentation');
453
+ }
454
+
455
+ export function switchToEditorMode() {
456
+ return getModeManager().switchMode('editor');
457
+ }
458
+
459
+ export default ModeManager;
src/renderer/js/presentation-config.js ADDED
@@ -0,0 +1,2066 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Presentation Configuration System
3
+ // Flexible Configuration Instead of Fixed Templates
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 2.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ import { ConfigStorage } from './config-storage.js';
11
+
12
+ // ════════════════════════════════════════════════════════════════════════════
13
+ // DISPLAY MODE DETECTION (ตรวจสอบโหมดการแสดงผลปัจจุบัน)
14
+ // ════════════════════════════════════════════════════════════════════════════
15
+
16
+ let currentDisplayMode = 'intro'; // 'intro', 'editor', 'presentation'
17
+
18
+ /**
19
+ * Set current display mode
20
+ * @param {string} mode - 'intro' | 'editor' | 'presentation'
21
+ */
22
+ export function setDisplayMode(mode) {
23
+ const validModes = ['intro', 'editor', 'presentation'];
24
+ if (!validModes.includes(mode)) {
25
+ console.warn(`[PresentationConfig] Invalid mode: ${mode}, using 'intro'`);
26
+ mode = 'intro';
27
+ }
28
+
29
+ currentDisplayMode = mode;
30
+ console.log(`[PresentationConfig] Display mode set to: ${mode}`);
31
+
32
+ // Trigger event for other systems to respond
33
+ window.dispatchEvent(new CustomEvent('displayModeChanged', {
34
+ detail: { mode }
35
+ }));
36
+ }
37
+
38
+ /**
39
+ * Get current display mode
40
+ * @returns {string}
41
+ */
42
+ export function getDisplayMode() {
43
+ return currentDisplayMode;
44
+ }
45
+
46
+ // ════════════════════════════════════════════════════════════════════════════
47
+ // Safe Zone Configuration (แยกตามโหมดการแสดงผล 3 ชุด)
48
+ // ════════════════════════════════════════════════════════════════════════════
49
+
50
+ /**
51
+ * INTRO MODE - Safe Zone for intro scene (hard-coded values)
52
+ * ใช้สำหรับหน้า Intro เท่านั้น ค่าคงที่
53
+ */
54
+ export const INTRO_SAFE_ZONE_CONFIG = {
55
+ margins: {
56
+ horizontalRatio: 0.08, // 8% ของความกว้าง (กว้างกว่าโหมดอื่น)
57
+ verticalRatio: 0.10, // 10% ของความสูง (สูงกว่าโหมดอื่น)
58
+ maxHorizontalRatio: 0.15,
59
+ maxVerticalRatio: 0.18,
60
+ minHorizontal: 60, // ขั้นต่ำสูงกว่า
61
+ minVertical: 60
62
+ },
63
+ border: {
64
+ enabled: false, // ไม่แสดงกรอบใน Intro
65
+ color: 'rgba(100, 116, 139, 0.3)',
66
+ width: 1,
67
+ glowColor: 'rgba(100, 116, 139, 0.2)',
68
+ glowSize: '2px',
69
+ zIndex: 1000
70
+ },
71
+ enforcement: {
72
+ enabled: false, // ไม่บังคับใน Intro
73
+ snapToEdge: false,
74
+ showWarning: false
75
+ }
76
+ };
77
+
78
+ /**
79
+ * EDITOR MODE - Safe Zone for edit/drag mode (strict enforcement)
80
+ * ใช้สำหรับโหมดแก้ไข/ลาก มีกรอบสีแดงบังคับ
81
+ */
82
+ export const EDITOR_SAFE_ZONE_CONFIG = {
83
+ margins: {
84
+ horizontalRatio: 0.06, // 6% ของความกว้าง
85
+ verticalRatio: 0.08, // 8% ของความสูง
86
+ maxHorizontalRatio: 0.12,
87
+ maxVerticalRatio: 0.15,
88
+ minHorizontal: 40,
89
+ minVertical: 40
90
+ },
91
+ border: {
92
+ enabled: true, // แสดงกรอบสีแดง
93
+ color: 'rgba(239, 68, 68, 0.8)',
94
+ width: 2, // หนากว่าโหมดอื่น
95
+ glowColor: 'rgba(239, 68, 68, 0.5)',
96
+ glowSize: '6px',
97
+ zIndex: 9999 // อยู่บนสุด
98
+ },
99
+ enforcement: {
100
+ enabled: true, // บังคับไม่ให้ลากออก
101
+ snapToEdge: true,
102
+ showWarning: true
103
+ }
104
+ };
105
+
106
+ /**
107
+ * PRESENTATION MODE - Safe Zone for presentation (visual guide only)
108
+ * ใช้สำหรับโหมดนำเสนอ แสดงกรอบบางๆ เป็นแนวทาง
109
+ */
110
+ export const PRESENTATION_SAFE_ZONE_CONFIG = {
111
+ margins: {
112
+ horizontalRatio: 0.05, // 5% ของความกว้าง (น้อยที่สุด)
113
+ verticalRatio: 0.07, // 7% ของความสูง
114
+ maxHorizontalRatio: 0.10,
115
+ maxVerticalRatio: 0.12,
116
+ minHorizontal: 30,
117
+ minVertical: 30
118
+ },
119
+ border: {
120
+ enabled: false, // ไม่แสดงกรอบในการนำเสนอปกติ
121
+ color: 'rgba(100, 116, 139, 0.2)',
122
+ width: 1,
123
+ glowColor: 'rgba(100, 116, 139, 0.1)',
124
+ glowSize: '2px',
125
+ zIndex: 100
126
+ },
127
+ enforcement: {
128
+ enabled: false, // ไม่บังคับ
129
+ snapToEdge: false,
130
+ showWarning: false
131
+ }
132
+ };
133
+
134
+ /**
135
+ * Get Safe Zone Config based on current display mode
136
+ * @returns {Object} Safe Zone configuration for current mode
137
+ */
138
+ export function getSafeZoneConfig() {
139
+ switch (currentDisplayMode) {
140
+ case 'intro':
141
+ return { ...INTRO_SAFE_ZONE_CONFIG };
142
+ case 'editor':
143
+ return { ...EDITOR_SAFE_ZONE_CONFIG };
144
+ case 'presentation':
145
+ return { ...PRESENTATION_SAFE_ZONE_CONFIG };
146
+ default:
147
+ console.warn(`[PresentationConfig] Unknown mode: ${currentDisplayMode}, using editor config`);
148
+ return { ...EDITOR_SAFE_ZONE_CONFIG };
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Legacy export for backward compatibility
154
+ * WARNING: This will return config based on current mode
155
+ */
156
+ export const SAFE_ZONE_CONFIG = new Proxy({}, {
157
+ get(target, prop) {
158
+ return getSafeZoneConfig()[prop];
159
+ }
160
+ });
161
+
162
+ // ════════════════════════════════════════════════════════════════════════════
163
+ // Smart Layout Configuration (การจัดเรียงเนื้อหาอัตโนมัติ)
164
+ // ════════════════════════════════════════════════════════════════════════════
165
+
166
+ export const SMART_LAYOUT_CONFIG = {
167
+ fillRatio: 0.92, // ใช้ 92% ของพื้นที่ใช้งาน
168
+ stageFallback: { // ขนาดหน้าจอสำรอง
169
+ width: 1280,
170
+ height: 720
171
+ },
172
+ autoScale: true, // ปรับขนาดเนื้อหาอัตโนมัติ
173
+ maintainAspectRatio: true, // รักษาสัดส่วน
174
+ centerContent: true // จัดกึ่งกลาง
175
+ };
176
+
177
+ /**
178
+ * Get Smart Layout fill ratio
179
+ */
180
+ export function getSmartLayoutFillRatio() {
181
+ return SMART_LAYOUT_CONFIG.fillRatio;
182
+ }
183
+
184
+ /**
185
+ * Get Smart Layout stage fallback dimensions
186
+ */
187
+ export function getSmartLayoutStageFallback() {
188
+ return { ...SMART_LAYOUT_CONFIG.stageFallback };
189
+ }
190
+
191
+ /**
192
+ * Update Smart Layout configuration
193
+ */
194
+ export function updateSmartLayoutConfig(newConfig) {
195
+ Object.assign(SMART_LAYOUT_CONFIG, newConfig);
196
+
197
+ window.dispatchEvent(new CustomEvent('smartLayoutConfigUpdated', {
198
+ detail: SMART_LAYOUT_CONFIG
199
+ }));
200
+
201
+ return SMART_LAYOUT_CONFIG;
202
+ }
203
+
204
+ /**
205
+ * Get current Smart Layout configuration
206
+ */
207
+ export function getSmartLayoutConfig() {
208
+ return { ...SMART_LAYOUT_CONFIG };
209
+ }
210
+
211
+ /**
212
+ * Get Safe Zone margins (คำนวณ margins ตามขนาดหน้าจอและโหมดปัจจุบัน)
213
+ * @param {Object} stageRect - ขนาดและตำแหน่งของ stage
214
+ * @returns {Object} - { left, right, top, bottom }
215
+ */
216
+ export function computeSafeZoneMargins(stageRect = {}) {
217
+ const width = stageRect.width || window.innerWidth;
218
+ const height = stageRect.height || window.innerHeight;
219
+
220
+ // ใช้ config ตามโหมดปัจจุบัน
221
+ const safeZoneConfig = getSafeZoneConfig();
222
+ const config = safeZoneConfig.margins;
223
+
224
+ // คำนวณตามสัดส่วน
225
+ const horizontalBase = width * config.horizontalRatio;
226
+ const verticalBase = height * config.verticalRatio;
227
+
228
+ // จำกัดค่าให้อยู่ในช่วงที่กำหนด
229
+ const left = Math.max(
230
+ config.minHorizontal,
231
+ Math.min(horizontalBase, width * config.maxHorizontalRatio)
232
+ );
233
+ const right = left;
234
+ const top = Math.max(
235
+ config.minVertical,
236
+ Math.min(verticalBase, height * config.maxVerticalRatio)
237
+ );
238
+ const bottom = top;
239
+
240
+ console.log(`[PresentationConfig] Safe Zone margins for ${currentDisplayMode} mode:`, {
241
+ width, height, left, right, top, bottom
242
+ });
243
+
244
+ return { left, right, top, bottom };
245
+ }
246
+
247
+ /**
248
+ * Update Safe Zone configuration
249
+ * @param {Object} newConfig - ค่าการตั้งค่าใหม่
250
+ */
251
+ export function updateSafeZoneConfig(newConfig) {
252
+ if (newConfig.margins) {
253
+ Object.assign(SAFE_ZONE_CONFIG.margins, newConfig.margins);
254
+ }
255
+ if (newConfig.border) {
256
+ Object.assign(SAFE_ZONE_CONFIG.border, newConfig.border);
257
+ }
258
+ if (newConfig.enforcement) {
259
+ Object.assign(SAFE_ZONE_CONFIG.enforcement, newConfig.enforcement);
260
+ }
261
+
262
+ // Dispatch event เพื่อแจ้ง components อื่นๆ
263
+ window.dispatchEvent(new CustomEvent('safeZoneConfigUpdated', {
264
+ detail: SAFE_ZONE_CONFIG
265
+ }));
266
+
267
+ return SAFE_ZONE_CONFIG;
268
+ }
269
+
270
+ /**
271
+ * Reset Safe Zone configuration to defaults for all modes
272
+ */
273
+ export function resetSafeZoneConfig() {
274
+ // Reset Intro Mode
275
+ INTRO_SAFE_ZONE_CONFIG.margins = {
276
+ horizontalRatio: 0.08,
277
+ verticalRatio: 0.10,
278
+ maxHorizontalRatio: 0.15,
279
+ maxVerticalRatio: 0.18,
280
+ minHorizontal: 60,
281
+ minVertical: 60
282
+ };
283
+ INTRO_SAFE_ZONE_CONFIG.border = {
284
+ enabled: false,
285
+ color: 'rgba(100, 116, 139, 0.3)',
286
+ width: 1,
287
+ glowColor: 'rgba(100, 116, 139, 0.2)',
288
+ glowSize: '2px',
289
+ zIndex: 1000
290
+ };
291
+ INTRO_SAFE_ZONE_CONFIG.enforcement = {
292
+ enabled: false,
293
+ snapToEdge: false,
294
+ showWarning: false
295
+ };
296
+
297
+ // Reset Editor Mode
298
+ EDITOR_SAFE_ZONE_CONFIG.margins = {
299
+ horizontalRatio: 0.06,
300
+ verticalRatio: 0.08,
301
+ maxHorizontalRatio: 0.12,
302
+ maxVerticalRatio: 0.15,
303
+ minHorizontal: 40,
304
+ minVertical: 40
305
+ };
306
+ EDITOR_SAFE_ZONE_CONFIG.border = {
307
+ enabled: true,
308
+ color: 'rgba(239, 68, 68, 0.8)',
309
+ width: 2,
310
+ glowColor: 'rgba(239, 68, 68, 0.5)',
311
+ glowSize: '6px',
312
+ zIndex: 9999
313
+ };
314
+ EDITOR_SAFE_ZONE_CONFIG.enforcement = {
315
+ enabled: true,
316
+ snapToEdge: true,
317
+ showWarning: true
318
+ };
319
+
320
+ // Reset Presentation Mode
321
+ PRESENTATION_SAFE_ZONE_CONFIG.margins = {
322
+ horizontalRatio: 0.05,
323
+ verticalRatio: 0.07,
324
+ maxHorizontalRatio: 0.10,
325
+ maxVerticalRatio: 0.12,
326
+ minHorizontal: 30,
327
+ minVertical: 30
328
+ };
329
+ PRESENTATION_SAFE_ZONE_CONFIG.border = {
330
+ enabled: false,
331
+ color: 'rgba(100, 116, 139, 0.2)',
332
+ width: 1,
333
+ glowColor: 'rgba(100, 116, 139, 0.1)',
334
+ glowSize: '2px',
335
+ zIndex: 100
336
+ };
337
+ PRESENTATION_SAFE_ZONE_CONFIG.enforcement = {
338
+ enabled: false,
339
+ snapToEdge: false,
340
+ showWarning: false
341
+ };
342
+
343
+ window.dispatchEvent(new CustomEvent('safeZoneConfigUpdated', {
344
+ detail: getSafeZoneConfig()
345
+ }));
346
+
347
+ return getSafeZoneConfig();
348
+ }
349
+
350
+ // ════════════════════════════════════════════════════════════════════════════
351
+ // Configuration Presets (Default Configuration Examples)
352
+ // ════════════════════════════════════════════════════════════════════════════
353
+
354
+ export const CONFIG_PRESETS = {
355
+ default: {
356
+ name: 'Default',
357
+ description: 'Standard default settings',
358
+ config: {
359
+ fonts: {
360
+ heading: "'Inter', 'Segoe UI', sans-serif",
361
+ body: "'Inter', 'Segoe UI', sans-serif",
362
+ code: "'Source Code Pro', 'Consolas', monospace"
363
+ },
364
+ fontSizes: {
365
+ h1: { min: 1.75, base: 4.5, max: 3 }, // clamp(1.75rem, 4.5vw, 3rem)
366
+ h2: { min: 1.5, base: 3.5, max: 2.5 },
367
+ h3: { min: 1.25, base: 2.8, max: 1.9 },
368
+ text: { min: 1.1, base: 1.8, max: 1.6 },
369
+ code: { min: 0.95, base: 1.5, max: 1.3 }
370
+ },
371
+ colors: {
372
+ primary: '#60a5fa',
373
+ secondary: '#a855f7',
374
+ background: '#0a1628',
375
+ surface: '#132337',
376
+ text: '#e2e8f0',
377
+ textSecondary: '#94a3b8',
378
+ accent: '#06b6d4',
379
+ codeBackground: '#1e293b',
380
+ codeBorder: '#334155'
381
+ },
382
+ background: {
383
+ type: 'solid', // 'solid', 'gradient', 'image'
384
+ value: '#0a1628',
385
+ gradient: null,
386
+ image: null,
387
+ opacity: 1
388
+ },
389
+ animations: {
390
+ enabled: true,
391
+ duration: 0.6,
392
+ easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
393
+ slideTransition: 'fade', // 'fade', 'slide', 'none'
394
+ },
395
+ styles: {
396
+ borderRadius: '1.25rem',
397
+ shadow: '0 20px 40px rgba(0, 0, 0, 0.3)',
398
+ lineHeight: {
399
+ heading: 1.3,
400
+ body: 1.7
401
+ },
402
+ // UI Elements
403
+ previewOpacity: 0.68,
404
+ overlayBackground: 'rgba(10, 22, 40, 0.85)',
405
+ overlayBlur: '8px',
406
+ navBorderWidth: '2px',
407
+ navBorderOpacity: 0.5,
408
+ // Borders & Accents
409
+ headingAccentBorderWidth: '4px',
410
+ blockquoteBorderWidth: '4px',
411
+ imageBorderWidth: '2px',
412
+ linkUnderlineWidth: '2px',
413
+ tableBorderWidth: '1px',
414
+ hrBorderWidth: '2px',
415
+ // Effects
416
+ backdropGradientColor: 'rgba(59, 130, 246, 0.15)',
417
+ backdropGradientSpread: '70%',
418
+ backdropBlur: '60px',
419
+ // Page Indicator
420
+ pageIndicatorTop: '16px',
421
+ pageIndicatorRight: '16px',
422
+ pageIndicatorFontSize: '0.875rem', // text-sm
423
+ pageIndicatorOpacity: 0.7,
424
+ pageIndicatorPaddingX: '12px', // px-3
425
+ pageIndicatorPaddingY: '4px', // py-1
426
+ pageIndicatorBgColor: 'rgba(22, 78, 99, 0.5)', // bg-cyan-900/50
427
+ pageIndicatorTextColor: '#a5f3fc' // text-cyan-200
428
+ },
429
+ typography: {
430
+ paragraphSpacing: {
431
+ before: 0.5, // rem
432
+ after: 1 // rem
433
+ },
434
+ headingSpacing: {
435
+ before: 1.5, // rem
436
+ after: 0.75 // rem
437
+ },
438
+ indentation: {
439
+ firstLine: 0, // rem
440
+ hanging: 0, // rem
441
+ blockQuote: 1.5 // rem
442
+ },
443
+ listIndent: 1.5, // rem
444
+ textAlign: 'left' // 'left', 'center', 'right', 'justify'
445
+ },
446
+ layout: {
447
+ contentPadding: {
448
+ small: 40, // px - for small screens
449
+ large: 48, // px - for large screens
450
+ ultra: 64 // px - for ultra-wide screens
451
+ },
452
+ contentAlignment: {
453
+ horizontal: 'center', // 'flex-start', 'center', 'flex-end'
454
+ vertical: 'center' // 'flex-start', 'center', 'flex-end'
455
+ }
456
+ },
457
+ smartList: {
458
+ twoColumnThreshold: 6, // items threshold for 2-column layout
459
+ threeColumnThreshold: 12 // items threshold for 3-column layout
460
+ }
461
+ }
462
+ },
463
+
464
+ professional: {
465
+ name: 'Professional',
466
+ description: 'For business presentations',
467
+ config: {
468
+ fonts: {
469
+ heading: "'Montserrat', 'Arial', sans-serif",
470
+ body: "'Lato', 'Helvetica', sans-serif",
471
+ code: "'Fira Code', monospace"
472
+ },
473
+ fontSizes: {
474
+ h1: { min: 2, base: 5, max: 3.5 },
475
+ h2: { min: 1.6, base: 4, max: 2.8 },
476
+ h3: { min: 1.3, base: 3, max: 2.1 },
477
+ text: { min: 1.2, base: 2, max: 1.8 },
478
+ code: { min: 1, base: 1.6, max: 1.4 }
479
+ },
480
+ colors: {
481
+ primary: '#3b82f6',
482
+ secondary: '#8b5cf6',
483
+ background: '#0f172a',
484
+ surface: '#1e293b',
485
+ text: '#f1f5f9',
486
+ textSecondary: '#cbd5e1',
487
+ accent: '#0ea5e9',
488
+ codeBackground: '#1e293b',
489
+ codeBorder: '#475569'
490
+ },
491
+ background: {
492
+ type: 'gradient',
493
+ value: null,
494
+ gradient: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
495
+ image: null,
496
+ opacity: 1
497
+ },
498
+ animations: {
499
+ enabled: true,
500
+ duration: 0.7,
501
+ easing: 'cubic-bezier(0.25, 0.1, 0.25, 1)',
502
+ slideTransition: 'slide'
503
+ },
504
+ styles: {
505
+ borderRadius: '0.75rem',
506
+ shadow: '0 25px 50px rgba(0, 0, 0, 0.5)',
507
+ lineHeight: {
508
+ heading: 1.4,
509
+ body: 1.8
510
+ },
511
+ // UI Elements
512
+ previewOpacity: 0.68,
513
+ overlayBackground: 'rgba(15, 23, 42, 0.9)',
514
+ overlayBlur: '10px',
515
+ navBorderWidth: '2px',
516
+ navBorderOpacity: 0.6,
517
+ // Borders & Accents
518
+ headingAccentBorderWidth: '4px',
519
+ blockquoteBorderWidth: '4px',
520
+ imageBorderWidth: '2px',
521
+ linkUnderlineWidth: '2px',
522
+ tableBorderWidth: '1px',
523
+ hrBorderWidth: '2px',
524
+ // Effects
525
+ backdropGradientColor: 'rgba(59, 130, 246, 0.2)',
526
+ backdropGradientSpread: '65%',
527
+ backdropBlur: '80px',
528
+ // Page Indicator
529
+ pageIndicatorTop: '16px',
530
+ pageIndicatorRight: '16px',
531
+ pageIndicatorFontSize: '0.875rem',
532
+ pageIndicatorOpacity: 0.7,
533
+ pageIndicatorPaddingX: '12px',
534
+ pageIndicatorPaddingY: '4px',
535
+ pageIndicatorBgColor: 'rgba(30, 41, 59, 0.6)',
536
+ pageIndicatorTextColor: '#cbd5e1'
537
+ },
538
+ typography: {
539
+ paragraphSpacing: {
540
+ before: 0.75,
541
+ after: 1.25
542
+ },
543
+ headingSpacing: {
544
+ before: 2,
545
+ after: 1
546
+ },
547
+ indentation: {
548
+ firstLine: 0,
549
+ hanging: 0,
550
+ blockQuote: 2
551
+ },
552
+ listIndent: 2,
553
+ textAlign: 'left'
554
+ },
555
+ layout: {
556
+ contentPadding: {
557
+ small: 48,
558
+ large: 56,
559
+ ultra: 72
560
+ },
561
+ contentAlignment: {
562
+ horizontal: 'flex-start',
563
+ vertical: 'flex-start'
564
+ }
565
+ },
566
+ smartList: {
567
+ twoColumnThreshold: 6,
568
+ threeColumnThreshold: 12
569
+ }
570
+ }
571
+ },
572
+
573
+ minimal: {
574
+ name: 'Minimal',
575
+ description: 'Simple and clear design',
576
+ config: {
577
+ fonts: {
578
+ heading: "'Helvetica Neue', 'Arial', sans-serif",
579
+ body: "'Helvetica Neue', 'Arial', sans-serif",
580
+ code: "'SF Mono', 'Monaco', monospace"
581
+ },
582
+ fontSizes: {
583
+ h1: { min: 1.5, base: 4, max: 2.5 },
584
+ h2: { min: 1.3, base: 3, max: 2 },
585
+ h3: { min: 1.15, base: 2.5, max: 1.7 },
586
+ text: { min: 1, base: 1.6, max: 1.4 },
587
+ code: { min: 0.9, base: 1.4, max: 1.2 }
588
+ },
589
+ colors: {
590
+ primary: '#000000',
591
+ secondary: '#333333',
592
+ background: '#ffffff',
593
+ surface: '#f8f9fa',
594
+ text: '#000000',
595
+ textSecondary: '#666666',
596
+ accent: '#0066cc',
597
+ codeBackground: '#f5f5f5',
598
+ codeBorder: '#e0e0e0'
599
+ },
600
+ background: {
601
+ type: 'solid',
602
+ value: '#ffffff',
603
+ gradient: null,
604
+ image: null,
605
+ opacity: 1
606
+ },
607
+ animations: {
608
+ enabled: true,
609
+ duration: 0.3,
610
+ easing: 'ease-out',
611
+ slideTransition: 'fade'
612
+ },
613
+ styles: {
614
+ borderRadius: '0',
615
+ shadow: 'none',
616
+ lineHeight: {
617
+ heading: 1.2,
618
+ body: 1.6
619
+ },
620
+ // UI Elements
621
+ previewOpacity: 0.68,
622
+ overlayBackground: 'rgba(255, 255, 255, 0.85)',
623
+ overlayBlur: '6px',
624
+ navBorderWidth: '1px',
625
+ navBorderOpacity: 0.3,
626
+ // Borders & Accents
627
+ headingAccentBorderWidth: '2px',
628
+ blockquoteBorderWidth: '3px',
629
+ imageBorderWidth: '1px',
630
+ linkUnderlineWidth: '1px',
631
+ tableBorderWidth: '1px',
632
+ hrBorderWidth: '1px',
633
+ // Effects
634
+ backdropGradientColor: 'rgba(0, 102, 204, 0.05)',
635
+ backdropGradientSpread: '50%',
636
+ backdropBlur: '20px',
637
+ // Page Indicator
638
+ pageIndicatorTop: '12px',
639
+ pageIndicatorRight: '12px',
640
+ pageIndicatorFontSize: '0.75rem',
641
+ pageIndicatorOpacity: 0.6,
642
+ pageIndicatorPaddingX: '8px',
643
+ pageIndicatorPaddingY: '4px',
644
+ pageIndicatorBgColor: 'rgba(0, 0, 0, 0.1)',
645
+ pageIndicatorTextColor: '#666666'
646
+ },
647
+ typography: {
648
+ paragraphSpacing: {
649
+ before: 0.25,
650
+ after: 0.75
651
+ },
652
+ headingSpacing: {
653
+ before: 1.25,
654
+ after: 0.5
655
+ },
656
+ indentation: {
657
+ firstLine: 0,
658
+ hanging: 0,
659
+ blockQuote: 1
660
+ },
661
+ listIndent: 1.25,
662
+ textAlign: 'left'
663
+ },
664
+ layout: {
665
+ contentPadding: {
666
+ small: 32,
667
+ large: 40,
668
+ ultra: 52
669
+ },
670
+ contentAlignment: {
671
+ horizontal: 'center',
672
+ vertical: 'center'
673
+ }
674
+ },
675
+ smartList: {
676
+ twoColumnThreshold: 6,
677
+ threeColumnThreshold: 12
678
+ }
679
+ }
680
+ },
681
+
682
+ creative: {
683
+ name: 'Creative',
684
+ description: 'Creative and distinctive style',
685
+ config: {
686
+ fonts: {
687
+ heading: "'Poppins', 'Verdana', sans-serif",
688
+ body: "'Inter', sans-serif",
689
+ code: "'JetBrains Mono', monospace"
690
+ },
691
+ fontSizes: {
692
+ h1: { min: 2.2, base: 5.5, max: 4 },
693
+ h2: { min: 1.8, base: 4.5, max: 3 },
694
+ h3: { min: 1.4, base: 3.5, max: 2.3 },
695
+ text: { min: 1.15, base: 2, max: 1.7 },
696
+ code: { min: 1, base: 1.7, max: 1.5 }
697
+ },
698
+ colors: {
699
+ primary: '#ec4899',
700
+ secondary: '#8b5cf6',
701
+ background: '#1a0b2e',
702
+ surface: '#2d1b4e',
703
+ text: '#f0e7ff',
704
+ textSecondary: '#c4b5fd',
705
+ accent: '#f59e0b',
706
+ codeBackground: '#2d1b4e',
707
+ codeBorder: '#4c3575'
708
+ },
709
+ background: {
710
+ type: 'gradient',
711
+ value: null,
712
+ gradient: 'linear-gradient(135deg, #1a0b2e 0%, #2d1b4e 50%, #4c1d95 100%)',
713
+ image: null,
714
+ opacity: 1
715
+ },
716
+ animations: {
717
+ enabled: true,
718
+ duration: 0.8,
719
+ easing: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)',
720
+ slideTransition: 'slide'
721
+ },
722
+ styles: {
723
+ borderRadius: '2rem',
724
+ shadow: '0 30px 60px rgba(139, 92, 246, 0.4)',
725
+ lineHeight: {
726
+ heading: 1.35,
727
+ body: 1.75
728
+ },
729
+ // UI Elements
730
+ previewOpacity: 0.68,
731
+ overlayBackground: 'rgba(26, 11, 46, 0.9)',
732
+ overlayBlur: '12px',
733
+ navBorderWidth: '3px',
734
+ navBorderOpacity: 0.7,
735
+ // Borders & Accents
736
+ headingAccentBorderWidth: '6px',
737
+ blockquoteBorderWidth: '5px',
738
+ imageBorderWidth: '3px',
739
+ linkUnderlineWidth: '3px',
740
+ tableBorderWidth: '2px',
741
+ hrBorderWidth: '4px',
742
+ // Effects
743
+ backdropGradientColor: 'rgba(236, 72, 153, 0.25)',
744
+ backdropGradientSpread: '75%',
745
+ backdropBlur: '100px',
746
+ // Page Indicator
747
+ pageIndicatorTop: '20px',
748
+ pageIndicatorRight: '20px',
749
+ pageIndicatorFontSize: '1rem',
750
+ pageIndicatorOpacity: 0.8,
751
+ pageIndicatorPaddingX: '16px',
752
+ pageIndicatorPaddingY: '6px',
753
+ pageIndicatorBgColor: 'rgba(139, 92, 246, 0.4)',
754
+ pageIndicatorTextColor: '#f0e7ff'
755
+ },
756
+ typography: {
757
+ paragraphSpacing: {
758
+ before: 0.5,
759
+ after: 1.5
760
+ },
761
+ headingSpacing: {
762
+ before: 2,
763
+ after: 1.25
764
+ },
765
+ indentation: {
766
+ firstLine: 0,
767
+ hanging: 0,
768
+ blockQuote: 2
769
+ },
770
+ listIndent: 2,
771
+ textAlign: 'left'
772
+ },
773
+ layout: {
774
+ contentPadding: {
775
+ small: 40,
776
+ large: 52,
777
+ ultra: 68
778
+ },
779
+ contentAlignment: {
780
+ horizontal: 'center',
781
+ vertical: 'center'
782
+ }
783
+ },
784
+ smartList: {
785
+ twoColumnThreshold: 6,
786
+ threeColumnThreshold: 12
787
+ }
788
+ }
789
+ }
790
+ };
791
+
792
+ // ════════════════════════════════════════════════════════════════════════════
793
+ // Configuration Options (ตัวเลือกที่ใช้ได้)
794
+ // ════════════════════════════════════════════════════════════════════════════
795
+
796
+ export const FONT_OPTIONS = {
797
+ heading: [
798
+ { value: "'Inter', 'Segoe UI', sans-serif", label: 'Inter (Modern)' },
799
+ { value: "'Montserrat', 'Arial', sans-serif", label: 'Montserrat (Professional)' },
800
+ { value: "'Poppins', 'Verdana', sans-serif", label: 'Poppins (Friendly)' },
801
+ { value: "'Playfair Display', 'Georgia', serif", label: 'Playfair Display (Elegant)' },
802
+ { value: "'Space Grotesk', sans-serif", label: 'Space Grotesk (Tech)' },
803
+ { value: "'Helvetica Neue', 'Arial', sans-serif", label: 'Helvetica (Clean)' },
804
+ { value: "'Ubuntu', sans-serif", label: 'Ubuntu (Casual)' },
805
+ { value: "'Orbitron', sans-serif", label: 'Orbitron (Futuristic)' }
806
+ ],
807
+ body: [
808
+ { value: "'Inter', 'Segoe UI', sans-serif", label: 'Inter' },
809
+ { value: "'Lato', 'Helvetica', sans-serif", label: 'Lato' },
810
+ { value: "'Roboto', sans-serif", label: 'Roboto' },
811
+ { value: "'Open Sans', sans-serif", label: 'Open Sans' },
812
+ { value: "'Helvetica Neue', 'Arial', sans-serif", label: 'Helvetica' },
813
+ { value: "'Ubuntu', sans-serif", label: 'Ubuntu' }
814
+ ],
815
+ code: [
816
+ { value: "'Source Code Pro', 'Consolas', monospace", label: 'Source Code Pro' },
817
+ { value: "'Fira Code', monospace", label: 'Fira Code' },
818
+ { value: "'JetBrains Mono', monospace", label: 'JetBrains Mono' },
819
+ { value: "'Roboto Mono', monospace", label: 'Roboto Mono' },
820
+ { value: "'SF Mono', 'Monaco', monospace", label: 'SF Mono' },
821
+ { value: "'Courier Prime', 'Courier New', monospace", label: 'Courier' }
822
+ ]
823
+ };
824
+
825
+ export const BACKGROUND_TYPES = [
826
+ { value: 'solid', label: 'สีพื้น' },
827
+ { value: 'gradient', label: 'ไล่สี' },
828
+ { value: 'image', label: 'รูปภาพ' }
829
+ ];
830
+
831
+ export const TRANSITION_TYPES = [
832
+ { value: 'fade', label: 'Fade (จางเข้า-จางออก)' },
833
+ { value: 'slide', label: 'Slide (เลื่อน)' },
834
+ { value: 'none', label: 'ไม่มีเอฟเฟค' }
835
+ ];
836
+
837
+ export const TEXT_ALIGN_OPTIONS = [
838
+ { value: 'left', label: 'ชิดซ้าย' },
839
+ { value: 'center', label: 'กึ่งกลาง' },
840
+ { value: 'right', label: 'ชิดขวา' },
841
+ { value: 'justify', label: 'เต็มแนว' }
842
+ ];
843
+
844
+ // ════════════════════════════════════════════════════════════════════════════
845
+ // Configuration Management
846
+ // ════════════════════════════════════════════════════════════════════════════
847
+
848
+ let currentConfig = { ...CONFIG_PRESETS.default.config };
849
+
850
+ /**
851
+ * ดึงค่า configuration ปัจจุบัน
852
+ */
853
+ export function getCurrentConfig() {
854
+ return { ...currentConfig };
855
+ }
856
+
857
+ /**
858
+ * ตั้งค่า configuration ใหม่
859
+ */
860
+ export function setConfig(newConfig, autoSave = true) {
861
+ currentConfig = { ...currentConfig, ...newConfig };
862
+ applyConfigToDOM();
863
+
864
+ // Auto-save to localStorage
865
+ if (autoSave) {
866
+ ConfigStorage.autoSave(currentConfig);
867
+ }
868
+
869
+ return currentConfig;
870
+ }
871
+
872
+ /**
873
+ * อัปเดตค่าเฉพาะส่วน (รองรับ nested objects)
874
+ */
875
+ export function updateConfigPart(part, values, autoSave = true) {
876
+ if (!currentConfig[part]) {
877
+ currentConfig[part] = values;
878
+ } else if (typeof values === 'object' && !Array.isArray(values)) {
879
+ // Deep merge for nested objects
880
+ currentConfig[part] = deepMerge(currentConfig[part], values);
881
+ } else {
882
+ currentConfig[part] = values;
883
+ }
884
+ applyConfigToDOM();
885
+
886
+ // Auto-save to localStorage
887
+ if (autoSave) {
888
+ ConfigStorage.autoSave(currentConfig);
889
+ }
890
+
891
+ return currentConfig;
892
+ }
893
+
894
+ /**
895
+ * Deep merge helper function
896
+ */
897
+ function deepMerge(target, source) {
898
+ const result = { ...target };
899
+
900
+ for (const key in source) {
901
+ if (source.hasOwnProperty(key)) {
902
+ if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
903
+ result[key] = deepMerge(result[key] || {}, source[key]);
904
+ } else {
905
+ result[key] = source[key];
906
+ }
907
+ }
908
+ }
909
+
910
+ return result;
911
+ }
912
+
913
+ /**
914
+ * โหลด preset
915
+ */
916
+ export function loadPreset(presetName, autoSave = true) {
917
+ const preset = CONFIG_PRESETS[presetName];
918
+ if (!preset) {
919
+ console.error(`Preset "${presetName}" not found`);
920
+ return null;
921
+ }
922
+ currentConfig = { ...preset.config };
923
+ applyConfigToDOM();
924
+
925
+ // Auto-save to localStorage
926
+ if (autoSave) {
927
+ ConfigStorage.autoSave(currentConfig);
928
+ }
929
+
930
+ return currentConfig;
931
+ }
932
+
933
+ /**
934
+ * รีเซ็ตเป็นค่าเริ่มต้น
935
+ */
936
+ export function resetConfig(autoSave = true) {
937
+ currentConfig = { ...CONFIG_PRESETS.default.config };
938
+ applyConfigToDOM();
939
+
940
+ // Clear saved config และ save default
941
+ if (autoSave) {
942
+ ConfigStorage.clearLocalStorage();
943
+ ConfigStorage.saveToLocalStorage(currentConfig);
944
+ }
945
+
946
+ return currentConfig;
947
+ }
948
+
949
+ /**
950
+ * โหลดการตั้งค่าที่บันทึกไว้จาก localStorage
951
+ */
952
+ export function loadSavedConfig() {
953
+ const savedConfig = ConfigStorage.loadFromLocalStorage();
954
+ if (savedConfig) {
955
+ currentConfig = { ...CONFIG_PRESETS.default.config, ...savedConfig };
956
+ applyConfigToDOM();
957
+ console.log('[PresentationConfig] ✅ Loaded saved config from localStorage');
958
+ return currentConfig;
959
+ }
960
+ console.log('[PresentationConfig] No saved config found, using default');
961
+ return null;
962
+ }
963
+
964
+ /**
965
+ * Export การตั้งค่าปัจจุบันเป็นไฟล์
966
+ */
967
+ export async function exportConfigToFile() {
968
+ return ConfigStorage.exportToFile(currentConfig);
969
+ }
970
+
971
+ /**
972
+ * Import การตั้งค่าจากไฟล์
973
+ */
974
+ export async function importConfigFromFile() {
975
+ try {
976
+ const importedConfig = await ConfigStorage.importFromFile();
977
+ if (importedConfig) {
978
+ currentConfig = { ...CONFIG_PRESETS.default.config, ...importedConfig };
979
+ applyConfigToDOM();
980
+ ConfigStorage.saveToLocalStorage(currentConfig);
981
+ console.log('[PresentationConfig] ✅ Imported config from file');
982
+ return currentConfig;
983
+ }
984
+ } catch (error) {
985
+ console.error('[PresentationConfig] Failed to import config:', error);
986
+ }
987
+ return null;
988
+ }
989
+
990
+ /**
991
+ * ดึงรายชื่อ presets ทั้งหมด
992
+ */
993
+ export function getAllPresets() {
994
+ return Object.entries(CONFIG_PRESETS).map(([key, preset]) => ({
995
+ id: key,
996
+ name: preset.name,
997
+ description: preset.description
998
+ }));
999
+ }
1000
+
1001
+ /**
1002
+ * แปลง font size config เป็น clamp CSS
1003
+ */
1004
+ function generateClampCSS(sizeConfig) {
1005
+ return `clamp(${sizeConfig.min}rem, ${sizeConfig.base}vw, ${sizeConfig.max}rem)`;
1006
+ }
1007
+
1008
+ /**
1009
+ * ใส่ค่า configuration ลงใน DOM
1010
+ */
1011
+ export function applyConfigToDOM() {
1012
+ const root = document.documentElement;
1013
+
1014
+ console.log('[PresentationConfig] Applying configuration to DOM...', currentConfig);
1015
+
1016
+ // Fonts
1017
+ root.style.setProperty('--font-heading', currentConfig.fonts.heading);
1018
+ root.style.setProperty('--font-body', currentConfig.fonts.body);
1019
+ root.style.setProperty('--font-code', currentConfig.fonts.code);
1020
+ root.style.setProperty('--font-primary', currentConfig.fonts.body); // Backward compatibility
1021
+
1022
+ // Font Sizes
1023
+ const h1Size = generateClampCSS(currentConfig.fontSizes.h1);
1024
+ const h2Size = generateClampCSS(currentConfig.fontSizes.h2);
1025
+ const h3Size = generateClampCSS(currentConfig.fontSizes.h3);
1026
+ const textSize = generateClampCSS(currentConfig.fontSizes.text);
1027
+ const codeSize = generateClampCSS(currentConfig.fontSizes.code);
1028
+
1029
+ root.style.setProperty('--font-size-h1', h1Size);
1030
+ root.style.setProperty('--font-size-h2', h2Size);
1031
+ root.style.setProperty('--font-size-h3', h3Size);
1032
+ root.style.setProperty('--font-size-text', textSize);
1033
+ root.style.setProperty('--font-size-code', codeSize);
1034
+
1035
+ console.log('[PresentationConfig] Font sizes applied:', {
1036
+ h1: h1Size,
1037
+ h2: h2Size,
1038
+ h3: h3Size,
1039
+ text: textSize,
1040
+ code: codeSize
1041
+ });
1042
+
1043
+ // Colors
1044
+ root.style.setProperty('--color-primary', currentConfig.colors.primary);
1045
+ root.style.setProperty('--color-secondary', currentConfig.colors.secondary);
1046
+ root.style.setProperty('--color-background', currentConfig.colors.background);
1047
+ root.style.setProperty('--color-surface', currentConfig.colors.surface);
1048
+ root.style.setProperty('--color-text', currentConfig.colors.text);
1049
+ root.style.setProperty('--color-text-secondary', currentConfig.colors.textSecondary);
1050
+ root.style.setProperty('--color-accent', currentConfig.colors.accent);
1051
+ root.style.setProperty('--color-code-bg', currentConfig.colors.codeBackground);
1052
+ root.style.setProperty('--color-code-border', currentConfig.colors.codeBorder);
1053
+
1054
+ console.log('[PresentationConfig] Colors applied:', currentConfig.colors);
1055
+
1056
+ // Background
1057
+ if (currentConfig.background.type === 'solid') {
1058
+ document.body.style.background = currentConfig.background.value;
1059
+ } else if (currentConfig.background.type === 'gradient') {
1060
+ document.body.style.background = currentConfig.background.gradient;
1061
+ } else if (currentConfig.background.type === 'image' && currentConfig.background.image) {
1062
+ document.body.style.background = `url(${currentConfig.background.image})`;
1063
+ document.body.style.backgroundSize = 'cover';
1064
+ document.body.style.backgroundPosition = 'center';
1065
+ }
1066
+
1067
+ // Animations
1068
+ root.style.setProperty('--anim-duration', `${currentConfig.animations.duration}s`);
1069
+ root.style.setProperty('--anim-easing', currentConfig.animations.easing);
1070
+
1071
+ // Styles
1072
+ root.style.setProperty('--border-radius', currentConfig.styles.borderRadius);
1073
+ root.style.setProperty('--shadow', currentConfig.styles.shadow);
1074
+ root.style.setProperty('--line-height-heading', currentConfig.styles.lineHeight.heading);
1075
+ root.style.setProperty('--line-height-body', currentConfig.styles.lineHeight.body);
1076
+
1077
+ console.log('[PresentationConfig] Line heights applied:', currentConfig.styles.lineHeight);
1078
+
1079
+ // UI Elements Styles
1080
+ root.style.setProperty('--preview-opacity', currentConfig.styles.previewOpacity);
1081
+ root.style.setProperty('--overlay-background', currentConfig.styles.overlayBackground);
1082
+ root.style.setProperty('--overlay-blur', currentConfig.styles.overlayBlur);
1083
+ root.style.setProperty('--nav-border-width', currentConfig.styles.navBorderWidth);
1084
+ root.style.setProperty('--nav-border-opacity', currentConfig.styles.navBorderOpacity);
1085
+
1086
+ // Borders & Accents
1087
+ root.style.setProperty('--heading-accent-border-width', currentConfig.styles.headingAccentBorderWidth);
1088
+ root.style.setProperty('--blockquote-border-width', currentConfig.styles.blockquoteBorderWidth);
1089
+ root.style.setProperty('--image-border-width', currentConfig.styles.imageBorderWidth);
1090
+ root.style.setProperty('--link-underline-width', currentConfig.styles.linkUnderlineWidth);
1091
+ root.style.setProperty('--table-border-width', currentConfig.styles.tableBorderWidth);
1092
+ root.style.setProperty('--hr-border-width', currentConfig.styles.hrBorderWidth);
1093
+
1094
+ // Effects
1095
+ root.style.setProperty('--backdrop-gradient-color', currentConfig.styles.backdropGradientColor);
1096
+ root.style.setProperty('--backdrop-gradient-spread', currentConfig.styles.backdropGradientSpread);
1097
+ root.style.setProperty('--backdrop-blur', currentConfig.styles.backdropBlur);
1098
+
1099
+ // Page Indicator
1100
+ root.style.setProperty('--page-indicator-top', currentConfig.styles.pageIndicatorTop);
1101
+ root.style.setProperty('--page-indicator-right', currentConfig.styles.pageIndicatorRight);
1102
+ root.style.setProperty('--page-indicator-font-size', currentConfig.styles.pageIndicatorFontSize);
1103
+ root.style.setProperty('--page-indicator-opacity', currentConfig.styles.pageIndicatorOpacity);
1104
+ root.style.setProperty('--page-indicator-padding-x', currentConfig.styles.pageIndicatorPaddingX);
1105
+ root.style.setProperty('--page-indicator-padding-y', currentConfig.styles.pageIndicatorPaddingY);
1106
+ root.style.setProperty('--page-indicator-bg-color', currentConfig.styles.pageIndicatorBgColor);
1107
+ root.style.setProperty('--page-indicator-text-color', currentConfig.styles.pageIndicatorTextColor);
1108
+
1109
+ // Typography (NEW)
1110
+ if (currentConfig.typography) {
1111
+ console.log('[PresentationConfig] Applying typography:', currentConfig.typography);
1112
+
1113
+ root.style.setProperty('--paragraph-spacing-before', `${currentConfig.typography.paragraphSpacing.before}rem`);
1114
+ root.style.setProperty('--paragraph-spacing-after', `${currentConfig.typography.paragraphSpacing.after}rem`);
1115
+ root.style.setProperty('--heading-spacing-before', `${currentConfig.typography.headingSpacing.before}rem`);
1116
+ root.style.setProperty('--heading-spacing-after', `${currentConfig.typography.headingSpacing.after}rem`);
1117
+ root.style.setProperty('--indent-first-line', `${currentConfig.typography.indentation.firstLine}rem`);
1118
+ root.style.setProperty('--indent-hanging', `${currentConfig.typography.indentation.hanging || 0}rem`);
1119
+ root.style.setProperty('--indent-blockquote', `${currentConfig.typography.indentation.blockQuote}rem`);
1120
+ root.style.setProperty('--list-indent', `${currentConfig.typography.listIndent}rem`);
1121
+ root.style.setProperty('--text-align', currentConfig.typography.textAlign);
1122
+ }
1123
+
1124
+ // Layout & Content Positioning (NEW)
1125
+ if (currentConfig.layout) {
1126
+ console.log('[PresentationConfig] Applying layout:', currentConfig.layout);
1127
+
1128
+ root.style.setProperty('--content-padding-small', `${currentConfig.layout.contentPadding.small}px`);
1129
+ root.style.setProperty('--content-padding-large', `${currentConfig.layout.contentPadding.large}px`);
1130
+ root.style.setProperty('--content-padding-ultra', `${currentConfig.layout.contentPadding.ultra}px`);
1131
+ root.style.setProperty('--content-align-horizontal', currentConfig.layout.contentAlignment.horizontal);
1132
+ root.style.setProperty('--content-align-vertical', currentConfig.layout.contentAlignment.vertical);
1133
+ }
1134
+
1135
+ // Smart List Columns
1136
+ if (currentConfig.smartList) {
1137
+ root.style.setProperty('--smart-list-two-column-threshold', currentConfig.smartList.twoColumnThreshold);
1138
+ root.style.setProperty('--smart-list-three-column-threshold', currentConfig.smartList.threeColumnThreshold);
1139
+ }
1140
+
1141
+ console.log('[PresentationConfig] ✅ Configuration applied successfully');
1142
+
1143
+ return currentConfig;
1144
+ }
1145
+
1146
+ /**
1147
+ * Export configuration เป็น JSON
1148
+ */
1149
+ export function exportConfig() {
1150
+ return JSON.stringify(currentConfig, null, 2);
1151
+ }
1152
+
1153
+ /**
1154
+ * Import configuration จาก JSON
1155
+ */
1156
+ export function importConfig(jsonString) {
1157
+ try {
1158
+ const imported = JSON.parse(jsonString);
1159
+ currentConfig = { ...CONFIG_PRESETS.default.config, ...imported };
1160
+ applyConfigToDOM();
1161
+ return currentConfig;
1162
+ } catch (error) {
1163
+ console.error('Failed to import configuration:', error);
1164
+ return null;
1165
+ }
1166
+ }
1167
+
1168
+ /**
1169
+ * Update typography settings from UI values
1170
+ * @param {Object} values - Typography values from UI
1171
+ */
1172
+ export function updateTypography(values) {
1173
+ if (!currentConfig.typography) {
1174
+ // Use default preset values instead of hardcoding
1175
+ currentConfig.typography = { ...CONFIG_PRESETS.default.config.typography };
1176
+ }
1177
+
1178
+ // Deep merge typography values
1179
+ currentConfig.typography = deepMerge(currentConfig.typography, values);
1180
+ applyConfigToDOM();
1181
+ return currentConfig;
1182
+ }
1183
+
1184
+ /**
1185
+ * Get current typography settings
1186
+ */
1187
+ export function getTypography() {
1188
+ return currentConfig.typography || null;
1189
+ }
1190
+
1191
+ // ════════════════════════════════════════════════════════════════════════════
1192
+ // UI Integration
1193
+ // ════════════════════════════════════════════════════════════════════════════
1194
+
1195
+ let uiCallbacks = {
1196
+ onUpdate: null,
1197
+ onSave: null,
1198
+ setStatus: null
1199
+ };
1200
+
1201
+ /**
1202
+ * Initialize Presentation UI with DOM elements and callbacks
1203
+ * @param {Object} domElements - Object containing all DOM element references
1204
+ * @param {Object} callbacks - Callback functions { onUpdate, onSave, setStatus }
1205
+ */
1206
+ export function initPresentationUI(domElements, callbacks = {}) {
1207
+ uiCallbacks = { ...uiCallbacks, ...callbacks };
1208
+
1209
+ // Populate font options
1210
+ if (domElements.fontHeading && FONT_OPTIONS.heading) {
1211
+ domElements.fontHeading.innerHTML = '';
1212
+ FONT_OPTIONS.heading.forEach(opt => {
1213
+ const option = document.createElement('option');
1214
+ option.value = opt.value;
1215
+ option.textContent = opt.label;
1216
+ domElements.fontHeading.appendChild(option);
1217
+ });
1218
+ }
1219
+
1220
+ if (domElements.fontBody && FONT_OPTIONS.body) {
1221
+ domElements.fontBody.innerHTML = '';
1222
+ FONT_OPTIONS.body.forEach(opt => {
1223
+ const option = document.createElement('option');
1224
+ option.value = opt.value;
1225
+ option.textContent = opt.label;
1226
+ domElements.fontBody.appendChild(option);
1227
+ });
1228
+ }
1229
+
1230
+ if (domElements.fontCode && FONT_OPTIONS.code) {
1231
+ domElements.fontCode.innerHTML = '';
1232
+ FONT_OPTIONS.code.forEach(opt => {
1233
+ const option = document.createElement('option');
1234
+ option.value = opt.value;
1235
+ option.textContent = opt.label;
1236
+ domElements.fontCode.appendChild(option);
1237
+ });
1238
+ }
1239
+
1240
+ // Load current config into UI
1241
+ loadConfigToUI(domElements);
1242
+
1243
+ // Setup event listeners
1244
+ setupPresetListener(domElements);
1245
+ setupFontListeners(domElements);
1246
+ setupColorListeners(domElements);
1247
+ setupAnimationListeners(domElements);
1248
+ setupFontSizeListeners(domElements);
1249
+ setupUIStylesListeners(domElements);
1250
+ setupTypographyListeners(domElements);
1251
+ setupLayoutListeners(domElements);
1252
+ setupActionButtons(domElements);
1253
+ }
1254
+
1255
+ /**
1256
+ * Load current configuration to UI inputs
1257
+ */
1258
+ function loadConfigToUI(domElements) {
1259
+ // Load fonts
1260
+ if (domElements.fontHeading) domElements.fontHeading.value = currentConfig.fonts.heading;
1261
+ if (domElements.fontBody) domElements.fontBody.value = currentConfig.fonts.body;
1262
+ if (domElements.fontCode) domElements.fontCode.value = currentConfig.fonts.code;
1263
+
1264
+ // Load colors
1265
+ if (domElements.colorPrimary) domElements.colorPrimary.value = currentConfig.colors.primary;
1266
+ if (domElements.colorAccent) domElements.colorAccent.value = currentConfig.colors.accent;
1267
+ if (domElements.colorBackground) domElements.colorBackground.value = currentConfig.colors.background;
1268
+ if (domElements.colorText) domElements.colorText.value = currentConfig.colors.text;
1269
+
1270
+ // Load animations
1271
+ if (domElements.animationTransition) domElements.animationTransition.value = currentConfig.animations.slideTransition;
1272
+ if (domElements.animationDuration) domElements.animationDuration.value = currentConfig.animations.duration;
1273
+
1274
+ // Load font sizes
1275
+ if (currentConfig.fontSizes) {
1276
+ if (domElements.fontSizeH1Min) domElements.fontSizeH1Min.value = currentConfig.fontSizes.h1.min;
1277
+ if (domElements.fontSizeH1Base) domElements.fontSizeH1Base.value = currentConfig.fontSizes.h1.base;
1278
+ if (domElements.fontSizeH1Max) domElements.fontSizeH1Max.value = currentConfig.fontSizes.h1.max;
1279
+ if (domElements.fontSizeH2Min) domElements.fontSizeH2Min.value = currentConfig.fontSizes.h2.min;
1280
+ if (domElements.fontSizeH2Base) domElements.fontSizeH2Base.value = currentConfig.fontSizes.h2.base;
1281
+ if (domElements.fontSizeH2Max) domElements.fontSizeH2Max.value = currentConfig.fontSizes.h2.max;
1282
+ if (domElements.fontSizeTextMin) domElements.fontSizeTextMin.value = currentConfig.fontSizes.text.min;
1283
+ if (domElements.fontSizeTextBase) domElements.fontSizeTextBase.value = currentConfig.fontSizes.text.base;
1284
+ if (domElements.fontSizeTextMax) domElements.fontSizeTextMax.value = currentConfig.fontSizes.text.max;
1285
+ }
1286
+
1287
+ // Load line height
1288
+ if (currentConfig.styles && currentConfig.styles.lineHeight) {
1289
+ if (domElements.lineHeightHeading) domElements.lineHeightHeading.value = currentConfig.styles.lineHeight.heading;
1290
+ if (domElements.lineHeightBody) domElements.lineHeightBody.value = currentConfig.styles.lineHeight.body;
1291
+ }
1292
+
1293
+ // Load UI & Visual Effects
1294
+ if (currentConfig.styles) {
1295
+ if (domElements.previewOpacity) domElements.previewOpacity.value = currentConfig.styles.previewOpacity;
1296
+ if (domElements.overlayBlur) domElements.overlayBlur.value = parseInt(currentConfig.styles.overlayBlur);
1297
+ if (domElements.navBorderWidth) domElements.navBorderWidth.value = parseInt(currentConfig.styles.navBorderWidth);
1298
+ if (domElements.backdropSpread) domElements.backdropSpread.value = parseInt(currentConfig.styles.backdropGradientSpread);
1299
+ if (domElements.backdropBlur) domElements.backdropBlur.value = parseInt(currentConfig.styles.backdropBlur);
1300
+ }
1301
+
1302
+ // Load Border Widths
1303
+ if (currentConfig.styles) {
1304
+ if (domElements.headingBorderWidth) domElements.headingBorderWidth.value = parseInt(currentConfig.styles.headingAccentBorderWidth);
1305
+ if (domElements.blockquoteBorderWidth) domElements.blockquoteBorderWidth.value = parseInt(currentConfig.styles.blockquoteBorderWidth);
1306
+ if (domElements.imageBorderWidth) domElements.imageBorderWidth.value = parseInt(currentConfig.styles.imageBorderWidth);
1307
+ if (domElements.linkUnderlineWidth) domElements.linkUnderlineWidth.value = parseInt(currentConfig.styles.linkUnderlineWidth);
1308
+ if (domElements.tableBorderWidth) domElements.tableBorderWidth.value = parseInt(currentConfig.styles.tableBorderWidth);
1309
+ if (domElements.hrBorderWidth) domElements.hrBorderWidth.value = parseInt(currentConfig.styles.hrBorderWidth);
1310
+ }
1311
+
1312
+ // Load typography
1313
+ if (currentConfig.typography) {
1314
+ if (domElements.paragraphBefore) domElements.paragraphBefore.value = currentConfig.typography.paragraphSpacing.before;
1315
+ if (domElements.paragraphAfter) domElements.paragraphAfter.value = currentConfig.typography.paragraphSpacing.after;
1316
+ if (domElements.headingBefore) domElements.headingBefore.value = currentConfig.typography.headingSpacing.before;
1317
+ if (domElements.headingAfter) domElements.headingAfter.value = currentConfig.typography.headingSpacing.after;
1318
+ if (domElements.indentFirst) domElements.indentFirst.value = currentConfig.typography.indentation.firstLine;
1319
+ if (domElements.indentBlockquote) domElements.indentBlockquote.value = currentConfig.typography.indentation.blockQuote;
1320
+ if (domElements.listIndent) domElements.listIndent.value = currentConfig.typography.listIndent;
1321
+ if (domElements.textAlign) domElements.textAlign.value = currentConfig.typography.textAlign;
1322
+ }
1323
+
1324
+ // Load Page Indicator
1325
+ if (currentConfig.styles) {
1326
+ if (domElements.pageIndicatorTop) domElements.pageIndicatorTop.value = parseInt(currentConfig.styles.pageIndicatorTop);
1327
+ if (domElements.pageIndicatorRight) domElements.pageIndicatorRight.value = parseInt(currentConfig.styles.pageIndicatorRight);
1328
+ if (domElements.pageIndicatorFontSize) domElements.pageIndicatorFontSize.value = parseFloat(currentConfig.styles.pageIndicatorFontSize);
1329
+ if (domElements.pageIndicatorOpacity) domElements.pageIndicatorOpacity.value = currentConfig.styles.pageIndicatorOpacity;
1330
+ if (domElements.pageIndicatorPaddingX) domElements.pageIndicatorPaddingX.value = parseInt(currentConfig.styles.pageIndicatorPaddingX);
1331
+ if (domElements.pageIndicatorPaddingY) domElements.pageIndicatorPaddingY.value = parseInt(currentConfig.styles.pageIndicatorPaddingY);
1332
+ if (domElements.pageIndicatorBgColor) domElements.pageIndicatorBgColor.value = currentConfig.styles.pageIndicatorBgColor;
1333
+ if (domElements.pageIndicatorTextColor) domElements.pageIndicatorTextColor.value = currentConfig.styles.pageIndicatorTextColor;
1334
+ }
1335
+
1336
+ // Load Smart List Column Settings
1337
+ if (currentConfig.smartList) {
1338
+ if (domElements.smartListTwoColumn) domElements.smartListTwoColumn.value = currentConfig.smartList.twoColumnThreshold;
1339
+ if (domElements.smartListThreeColumn) domElements.smartListThreeColumn.value = currentConfig.smartList.threeColumnThreshold;
1340
+ }
1341
+
1342
+ // Load Content Layout & Positioning Settings
1343
+ if (currentConfig.layout) {
1344
+ if (domElements.contentPaddingSmall) domElements.contentPaddingSmall.value = currentConfig.layout.contentPadding.small;
1345
+ if (domElements.contentPaddingLarge) domElements.contentPaddingLarge.value = currentConfig.layout.contentPadding.large;
1346
+ if (domElements.contentPaddingUltra) domElements.contentPaddingUltra.value = currentConfig.layout.contentPadding.ultra;
1347
+ if (domElements.contentAlignHorizontal) domElements.contentAlignHorizontal.value = currentConfig.layout.contentAlignment.horizontal;
1348
+ if (domElements.contentAlignVertical) domElements.contentAlignVertical.value = currentConfig.layout.contentAlignment.vertical;
1349
+ }
1350
+ }
1351
+
1352
+ /**
1353
+ * Reload UI from current configuration (exported for external use)
1354
+ */
1355
+ export function reloadUI(domElements) {
1356
+ loadConfigToUI(domElements);
1357
+ }
1358
+
1359
+ /**
1360
+ * Load configuration from frontmatter object
1361
+ * @param {Object} frontmatter - Frontmatter key-value pairs
1362
+ * @param {Object} domElements - DOM element references for updating UI
1363
+ */
1364
+ export function loadConfigFromFrontmatter(frontmatter, domElements) {
1365
+ // Load preset first if specified
1366
+ if (frontmatter['presentation.preset']) {
1367
+ const presetName = frontmatter['presentation.preset'];
1368
+ loadPreset(presetName);
1369
+ if (domElements && domElements.presetSelector) {
1370
+ domElements.presetSelector.value = presetName;
1371
+ }
1372
+ }
1373
+
1374
+ // Load fonts (overrides preset if specified)
1375
+ const fontUpdates = {};
1376
+ if (frontmatter['presentation.fonts.heading']) {
1377
+ fontUpdates.heading = frontmatter['presentation.fonts.heading'];
1378
+ }
1379
+ if (frontmatter['presentation.fonts.body']) {
1380
+ fontUpdates.body = frontmatter['presentation.fonts.body'];
1381
+ }
1382
+ if (frontmatter['presentation.fonts.code']) {
1383
+ fontUpdates.code = frontmatter['presentation.fonts.code'];
1384
+ }
1385
+ if (Object.keys(fontUpdates).length > 0) {
1386
+ updateConfigPart('fonts', fontUpdates);
1387
+ }
1388
+
1389
+ // Load colors
1390
+ const colorUpdates = {};
1391
+ if (frontmatter['presentation.colors.primary']) {
1392
+ colorUpdates.primary = frontmatter['presentation.colors.primary'];
1393
+ }
1394
+ if (frontmatter['presentation.colors.accent']) {
1395
+ colorUpdates.accent = frontmatter['presentation.colors.accent'];
1396
+ }
1397
+ if (frontmatter['presentation.colors.background']) {
1398
+ colorUpdates.background = frontmatter['presentation.colors.background'];
1399
+ }
1400
+ if (frontmatter['presentation.colors.text']) {
1401
+ colorUpdates.text = frontmatter['presentation.colors.text'];
1402
+ }
1403
+ if (Object.keys(colorUpdates).length > 0) {
1404
+ updateConfigPart('colors', colorUpdates);
1405
+ }
1406
+
1407
+ // Load animations
1408
+ const animationUpdates = {};
1409
+ if (frontmatter['presentation.animations.slideTransition']) {
1410
+ animationUpdates.slideTransition = frontmatter['presentation.animations.slideTransition'];
1411
+ }
1412
+ if (frontmatter['presentation.animations.duration'] !== undefined) {
1413
+ animationUpdates.duration = parseFloat(frontmatter['presentation.animations.duration']);
1414
+ }
1415
+ if (Object.keys(animationUpdates).length > 0) {
1416
+ updateConfigPart('animations', animationUpdates);
1417
+ }
1418
+
1419
+ // Load font sizes
1420
+ const fontSizeUpdates = {};
1421
+
1422
+ if (frontmatter['presentation.fontSizes.h1.min'] !== undefined) {
1423
+ if (!fontSizeUpdates.h1) fontSizeUpdates.h1 = {};
1424
+ fontSizeUpdates.h1.min = parseFloat(frontmatter['presentation.fontSizes.h1.min']);
1425
+ }
1426
+ if (frontmatter['presentation.fontSizes.h1.base'] !== undefined) {
1427
+ if (!fontSizeUpdates.h1) fontSizeUpdates.h1 = {};
1428
+ fontSizeUpdates.h1.base = parseFloat(frontmatter['presentation.fontSizes.h1.base']);
1429
+ }
1430
+ if (frontmatter['presentation.fontSizes.h1.max'] !== undefined) {
1431
+ if (!fontSizeUpdates.h1) fontSizeUpdates.h1 = {};
1432
+ fontSizeUpdates.h1.max = parseFloat(frontmatter['presentation.fontSizes.h1.max']);
1433
+ }
1434
+ if (frontmatter['presentation.fontSizes.h2.min'] !== undefined) {
1435
+ if (!fontSizeUpdates.h2) fontSizeUpdates.h2 = {};
1436
+ fontSizeUpdates.h2.min = parseFloat(frontmatter['presentation.fontSizes.h2.min']);
1437
+ }
1438
+ if (frontmatter['presentation.fontSizes.h2.base'] !== undefined) {
1439
+ if (!fontSizeUpdates.h2) fontSizeUpdates.h2 = {};
1440
+ fontSizeUpdates.h2.base = parseFloat(frontmatter['presentation.fontSizes.h2.base']);
1441
+ }
1442
+ if (frontmatter['presentation.fontSizes.h2.max'] !== undefined) {
1443
+ if (!fontSizeUpdates.h2) fontSizeUpdates.h2 = {};
1444
+ fontSizeUpdates.h2.max = parseFloat(frontmatter['presentation.fontSizes.h2.max']);
1445
+ }
1446
+ if (frontmatter['presentation.fontSizes.text.min'] !== undefined) {
1447
+ if (!fontSizeUpdates.text) fontSizeUpdates.text = {};
1448
+ fontSizeUpdates.text.min = parseFloat(frontmatter['presentation.fontSizes.text.min']);
1449
+ }
1450
+ if (frontmatter['presentation.fontSizes.text.base'] !== undefined) {
1451
+ if (!fontSizeUpdates.text) fontSizeUpdates.text = {};
1452
+ fontSizeUpdates.text.base = parseFloat(frontmatter['presentation.fontSizes.text.base']);
1453
+ }
1454
+ if (frontmatter['presentation.fontSizes.text.max'] !== undefined) {
1455
+ if (!fontSizeUpdates.text) fontSizeUpdates.text = {};
1456
+ fontSizeUpdates.text.max = parseFloat(frontmatter['presentation.fontSizes.text.max']);
1457
+ }
1458
+
1459
+ if (Object.keys(fontSizeUpdates).length > 0) {
1460
+ updateConfigPart('fontSizes', fontSizeUpdates);
1461
+ }
1462
+
1463
+ // Load line height and UI styles
1464
+ const styleUpdates = {};
1465
+ if (frontmatter['presentation.styles.lineHeight.heading'] !== undefined || frontmatter['presentation.styles.lineHeight.body'] !== undefined) {
1466
+ styleUpdates.lineHeight = {};
1467
+ if (frontmatter['presentation.styles.lineHeight.heading'] !== undefined) {
1468
+ styleUpdates.lineHeight.heading = parseFloat(frontmatter['presentation.styles.lineHeight.heading']);
1469
+ }
1470
+ if (frontmatter['presentation.styles.lineHeight.body'] !== undefined) {
1471
+ styleUpdates.lineHeight.body = parseFloat(frontmatter['presentation.styles.lineHeight.body']);
1472
+ }
1473
+ }
1474
+
1475
+ // Load UI & Visual Effects
1476
+ if (frontmatter['presentation.styles.previewOpacity'] !== undefined) {
1477
+ styleUpdates.previewOpacity = parseFloat(frontmatter['presentation.styles.previewOpacity']);
1478
+ }
1479
+ if (frontmatter['presentation.styles.overlayBlur']) {
1480
+ styleUpdates.overlayBlur = frontmatter['presentation.styles.overlayBlur'];
1481
+ }
1482
+ if (frontmatter['presentation.styles.navBorderWidth']) {
1483
+ styleUpdates.navBorderWidth = frontmatter['presentation.styles.navBorderWidth'];
1484
+ }
1485
+ if (frontmatter['presentation.styles.backdropGradientSpread']) {
1486
+ styleUpdates.backdropGradientSpread = frontmatter['presentation.styles.backdropGradientSpread'];
1487
+ }
1488
+ if (frontmatter['presentation.styles.backdropBlur']) {
1489
+ styleUpdates.backdropBlur = frontmatter['presentation.styles.backdropBlur'];
1490
+ }
1491
+
1492
+ // Load Border Widths
1493
+ if (frontmatter['presentation.styles.headingAccentBorderWidth']) {
1494
+ styleUpdates.headingAccentBorderWidth = frontmatter['presentation.styles.headingAccentBorderWidth'];
1495
+ }
1496
+ if (frontmatter['presentation.styles.blockquoteBorderWidth']) {
1497
+ styleUpdates.blockquoteBorderWidth = frontmatter['presentation.styles.blockquoteBorderWidth'];
1498
+ }
1499
+ if (frontmatter['presentation.styles.imageBorderWidth']) {
1500
+ styleUpdates.imageBorderWidth = frontmatter['presentation.styles.imageBorderWidth'];
1501
+ }
1502
+ if (frontmatter['presentation.styles.linkUnderlineWidth']) {
1503
+ styleUpdates.linkUnderlineWidth = frontmatter['presentation.styles.linkUnderlineWidth'];
1504
+ }
1505
+ if (frontmatter['presentation.styles.tableBorderWidth']) {
1506
+ styleUpdates.tableBorderWidth = frontmatter['presentation.styles.tableBorderWidth'];
1507
+ }
1508
+ if (frontmatter['presentation.styles.hrBorderWidth']) {
1509
+ styleUpdates.hrBorderWidth = frontmatter['presentation.styles.hrBorderWidth'];
1510
+ }
1511
+
1512
+ // Load Page Indicator
1513
+ if (frontmatter['presentation.styles.pageIndicatorTop']) {
1514
+ styleUpdates.pageIndicatorTop = frontmatter['presentation.styles.pageIndicatorTop'];
1515
+ }
1516
+ if (frontmatter['presentation.styles.pageIndicatorRight']) {
1517
+ styleUpdates.pageIndicatorRight = frontmatter['presentation.styles.pageIndicatorRight'];
1518
+ }
1519
+ if (frontmatter['presentation.styles.pageIndicatorFontSize']) {
1520
+ styleUpdates.pageIndicatorFontSize = frontmatter['presentation.styles.pageIndicatorFontSize'];
1521
+ }
1522
+ if (frontmatter['presentation.styles.pageIndicatorOpacity'] !== undefined) {
1523
+ styleUpdates.pageIndicatorOpacity = parseFloat(frontmatter['presentation.styles.pageIndicatorOpacity']);
1524
+ }
1525
+ if (frontmatter['presentation.styles.pageIndicatorPaddingX']) {
1526
+ styleUpdates.pageIndicatorPaddingX = frontmatter['presentation.styles.pageIndicatorPaddingX'];
1527
+ }
1528
+ if (frontmatter['presentation.styles.pageIndicatorPaddingY']) {
1529
+ styleUpdates.pageIndicatorPaddingY = frontmatter['presentation.styles.pageIndicatorPaddingY'];
1530
+ }
1531
+ if (frontmatter['presentation.styles.pageIndicatorBgColor']) {
1532
+ styleUpdates.pageIndicatorBgColor = frontmatter['presentation.styles.pageIndicatorBgColor'];
1533
+ }
1534
+ if (frontmatter['presentation.styles.pageIndicatorTextColor']) {
1535
+ styleUpdates.pageIndicatorTextColor = frontmatter['presentation.styles.pageIndicatorTextColor'];
1536
+ }
1537
+
1538
+ if (Object.keys(styleUpdates).length > 0) {
1539
+ updateConfigPart('styles', styleUpdates);
1540
+ }
1541
+
1542
+ // Load typography settings
1543
+ const typographyUpdates = {};
1544
+
1545
+ if (frontmatter['presentation.typography.paragraphSpacing.before'] !== undefined) {
1546
+ if (!typographyUpdates.paragraphSpacing) typographyUpdates.paragraphSpacing = {};
1547
+ typographyUpdates.paragraphSpacing.before = parseFloat(frontmatter['presentation.typography.paragraphSpacing.before']);
1548
+ }
1549
+ if (frontmatter['presentation.typography.paragraphSpacing.after'] !== undefined) {
1550
+ if (!typographyUpdates.paragraphSpacing) typographyUpdates.paragraphSpacing = {};
1551
+ typographyUpdates.paragraphSpacing.after = parseFloat(frontmatter['presentation.typography.paragraphSpacing.after']);
1552
+ }
1553
+ if (frontmatter['presentation.typography.headingSpacing.before'] !== undefined) {
1554
+ if (!typographyUpdates.headingSpacing) typographyUpdates.headingSpacing = {};
1555
+ typographyUpdates.headingSpacing.before = parseFloat(frontmatter['presentation.typography.headingSpacing.before']);
1556
+ }
1557
+ if (frontmatter['presentation.typography.headingSpacing.after'] !== undefined) {
1558
+ if (!typographyUpdates.headingSpacing) typographyUpdates.headingSpacing = {};
1559
+ typographyUpdates.headingSpacing.after = parseFloat(frontmatter['presentation.typography.headingSpacing.after']);
1560
+ }
1561
+ if (frontmatter['presentation.typography.indentation.firstLine'] !== undefined) {
1562
+ if (!typographyUpdates.indentation) typographyUpdates.indentation = {};
1563
+ typographyUpdates.indentation.firstLine = parseFloat(frontmatter['presentation.typography.indentation.firstLine']);
1564
+ }
1565
+ if (frontmatter['presentation.typography.indentation.blockQuote'] !== undefined) {
1566
+ if (!typographyUpdates.indentation) typographyUpdates.indentation = {};
1567
+ typographyUpdates.indentation.blockQuote = parseFloat(frontmatter['presentation.typography.indentation.blockQuote']);
1568
+ }
1569
+ if (frontmatter['presentation.typography.listIndent'] !== undefined) {
1570
+ typographyUpdates.listIndent = parseFloat(frontmatter['presentation.typography.listIndent']);
1571
+ }
1572
+ if (frontmatter['presentation.typography.textAlign']) {
1573
+ typographyUpdates.textAlign = frontmatter['presentation.typography.textAlign'];
1574
+ }
1575
+
1576
+ if (Object.keys(typographyUpdates).length > 0) {
1577
+ updateConfigPart('typography', typographyUpdates);
1578
+ }
1579
+
1580
+ // Load Smart List Column Settings
1581
+ const smartListUpdates = {};
1582
+ if (frontmatter['presentation.smartList.twoColumnThreshold'] !== undefined) {
1583
+ smartListUpdates.twoColumnThreshold = parseInt(frontmatter['presentation.smartList.twoColumnThreshold']);
1584
+ }
1585
+ if (frontmatter['presentation.smartList.threeColumnThreshold'] !== undefined) {
1586
+ smartListUpdates.threeColumnThreshold = parseInt(frontmatter['presentation.smartList.threeColumnThreshold']);
1587
+ }
1588
+ if (Object.keys(smartListUpdates).length > 0) {
1589
+ updateConfigPart('smartList', smartListUpdates);
1590
+ }
1591
+
1592
+ // Reload UI to reflect changes
1593
+ if (domElements) {
1594
+ reloadUI(domElements);
1595
+ }
1596
+
1597
+ return currentConfig;
1598
+ }
1599
+
1600
+ /**
1601
+ * Sync UI values back to configuration
1602
+ */
1603
+ function syncUIToConfig(domElements) {
1604
+ console.log('[PresentationConfig] Syncing UI to config...', domElements);
1605
+
1606
+ // Update fonts
1607
+ updateConfigPart('fonts', {
1608
+ heading: domElements.fontHeading?.value,
1609
+ body: domElements.fontBody?.value,
1610
+ code: domElements.fontCode?.value
1611
+ });
1612
+
1613
+ // Update colors
1614
+ updateConfigPart('colors', {
1615
+ primary: domElements.colorPrimary?.value,
1616
+ accent: domElements.colorAccent?.value,
1617
+ background: domElements.colorBackground?.value,
1618
+ text: domElements.colorText?.value
1619
+ });
1620
+
1621
+ // Update animations
1622
+ updateConfigPart('animations', {
1623
+ slideTransition: domElements.animationTransition?.value,
1624
+ duration: parseFloat(domElements.animationDuration?.value || currentConfig.animations.duration)
1625
+ });
1626
+
1627
+ // Update font sizes
1628
+ updateConfigPart('fontSizes', {
1629
+ h1: {
1630
+ min: parseFloat(domElements.fontSizeH1Min?.value || currentConfig.fontSizes.h1.min),
1631
+ base: parseFloat(domElements.fontSizeH1Base?.value || currentConfig.fontSizes.h1.base),
1632
+ max: parseFloat(domElements.fontSizeH1Max?.value || currentConfig.fontSizes.h1.max)
1633
+ },
1634
+ h2: {
1635
+ min: parseFloat(domElements.fontSizeH2Min?.value || currentConfig.fontSizes.h2.min),
1636
+ base: parseFloat(domElements.fontSizeH2Base?.value || currentConfig.fontSizes.h2.base),
1637
+ max: parseFloat(domElements.fontSizeH2Max?.value || currentConfig.fontSizes.h2.max)
1638
+ },
1639
+ text: {
1640
+ min: parseFloat(domElements.fontSizeTextMin?.value || currentConfig.fontSizes.text.min),
1641
+ base: parseFloat(domElements.fontSizeTextBase?.value || currentConfig.fontSizes.text.base),
1642
+ max: parseFloat(domElements.fontSizeTextMax?.value || currentConfig.fontSizes.text.max)
1643
+ }
1644
+ });
1645
+
1646
+ // Update line height and UI styles
1647
+ const currentStyles = currentConfig.styles || CONFIG_PRESETS.default.config.styles;
1648
+ updateConfigPart('styles', {
1649
+ ...currentStyles,
1650
+ lineHeight: {
1651
+ heading: parseFloat(domElements.lineHeightHeading?.value || currentStyles.lineHeight.heading),
1652
+ body: parseFloat(domElements.lineHeightBody?.value || currentStyles.lineHeight.body)
1653
+ },
1654
+ // UI & Visual Effects
1655
+ previewOpacity: parseFloat(domElements.previewOpacity?.value || currentStyles.previewOpacity),
1656
+ overlayBlur: `${domElements.overlayBlur?.value || parseInt(currentStyles.overlayBlur)}px`,
1657
+ navBorderWidth: `${domElements.navBorderWidth?.value || parseInt(currentStyles.navBorderWidth)}px`,
1658
+ backdropGradientSpread: `${domElements.backdropSpread?.value || parseInt(currentStyles.backdropGradientSpread)}%`,
1659
+ backdropBlur: `${domElements.backdropBlur?.value || parseInt(currentStyles.backdropBlur)}px`,
1660
+ // Border Widths
1661
+ headingAccentBorderWidth: `${domElements.headingBorderWidth?.value || parseInt(currentStyles.headingAccentBorderWidth)}px`,
1662
+ blockquoteBorderWidth: `${domElements.blockquoteBorderWidth?.value || parseInt(currentStyles.blockquoteBorderWidth)}px`,
1663
+ imageBorderWidth: `${domElements.imageBorderWidth?.value || parseInt(currentStyles.imageBorderWidth)}px`,
1664
+ linkUnderlineWidth: `${domElements.linkUnderlineWidth?.value || parseInt(currentStyles.linkUnderlineWidth)}px`,
1665
+ tableBorderWidth: `${domElements.tableBorderWidth?.value || parseInt(currentStyles.tableBorderWidth)}px`,
1666
+ hrBorderWidth: `${domElements.hrBorderWidth?.value || parseInt(currentStyles.hrBorderWidth)}px`,
1667
+ // Page Indicator
1668
+ pageIndicatorTop: `${domElements.pageIndicatorTop?.value || parseInt(currentStyles.pageIndicatorTop)}px`,
1669
+ pageIndicatorRight: `${domElements.pageIndicatorRight?.value || parseInt(currentStyles.pageIndicatorRight)}px`,
1670
+ pageIndicatorFontSize: `${domElements.pageIndicatorFontSize?.value || parseFloat(currentStyles.pageIndicatorFontSize)}rem`,
1671
+ pageIndicatorOpacity: parseFloat(domElements.pageIndicatorOpacity?.value || currentStyles.pageIndicatorOpacity),
1672
+ pageIndicatorPaddingX: `${domElements.pageIndicatorPaddingX?.value || parseInt(currentStyles.pageIndicatorPaddingX)}px`,
1673
+ pageIndicatorPaddingY: `${domElements.pageIndicatorPaddingY?.value || parseInt(currentStyles.pageIndicatorPaddingY)}px`,
1674
+ pageIndicatorBgColor: domElements.pageIndicatorBgColor?.value || currentStyles.pageIndicatorBgColor,
1675
+ pageIndicatorTextColor: domElements.pageIndicatorTextColor?.value || currentStyles.pageIndicatorTextColor
1676
+ });
1677
+
1678
+ // Update typography (use current config as fallback)
1679
+ const currentTypography = currentConfig.typography || CONFIG_PRESETS.default.config.typography;
1680
+
1681
+ updateTypography({
1682
+ paragraphSpacing: {
1683
+ before: parseFloat(domElements.paragraphBefore?.value || currentTypography.paragraphSpacing.before),
1684
+ after: parseFloat(domElements.paragraphAfter?.value || currentTypography.paragraphSpacing.after)
1685
+ },
1686
+ headingSpacing: {
1687
+ before: parseFloat(domElements.headingBefore?.value || currentTypography.headingSpacing.before),
1688
+ after: parseFloat(domElements.headingAfter?.value || currentTypography.headingSpacing.after)
1689
+ },
1690
+ indentation: {
1691
+ firstLine: parseFloat(domElements.indentFirst?.value || currentTypography.indentation.firstLine),
1692
+ hanging: currentTypography.indentation.hanging || 0,
1693
+ blockQuote: parseFloat(domElements.indentBlockquote?.value || currentTypography.indentation.blockQuote)
1694
+ },
1695
+ listIndent: parseFloat(domElements.listIndent?.value || currentTypography.listIndent),
1696
+ textAlign: domElements.textAlign?.value || currentTypography.textAlign
1697
+ });
1698
+
1699
+ // Update Smart List Column Settings
1700
+ const currentSmartList = currentConfig.smartList || CONFIG_PRESETS.default.config.smartList;
1701
+ updateConfigPart('smartList', {
1702
+ twoColumnThreshold: parseInt(domElements.smartListTwoColumn?.value || currentSmartList.twoColumnThreshold),
1703
+ threeColumnThreshold: parseInt(domElements.smartListThreeColumn?.value || currentSmartList.threeColumnThreshold)
1704
+ });
1705
+
1706
+ // Update Content Layout & Positioning Settings
1707
+ const currentLayout = currentConfig.layout || CONFIG_PRESETS.default.config.layout;
1708
+ updateConfigPart('layout', {
1709
+ contentPadding: {
1710
+ small: parseInt(domElements.contentPaddingSmall?.value || currentLayout.contentPadding.small),
1711
+ large: parseInt(domElements.contentPaddingLarge?.value || currentLayout.contentPadding.large),
1712
+ ultra: parseInt(domElements.contentPaddingUltra?.value || currentLayout.contentPadding.ultra)
1713
+ },
1714
+ contentAlignment: {
1715
+ horizontal: domElements.contentAlignHorizontal?.value || currentLayout.contentAlignment.horizontal,
1716
+ vertical: domElements.contentAlignVertical?.value || currentLayout.contentAlignment.vertical
1717
+ }
1718
+ });
1719
+
1720
+ console.log('[PresentationConfig] ✅ UI synced to config successfully');
1721
+
1722
+ // Trigger update callback
1723
+ if (uiCallbacks.onUpdate) {
1724
+ console.log('[PresentationConfig] Triggering onUpdate callback...');
1725
+ uiCallbacks.onUpdate();
1726
+ }
1727
+ }
1728
+
1729
+ /**
1730
+ * Setup preset selector listener
1731
+ */
1732
+ function setupPresetListener(domElements) {
1733
+ if (domElements.presetSelector) {
1734
+ domElements.presetSelector.addEventListener('change', (e) => {
1735
+ loadPreset(e.target.value);
1736
+ loadConfigToUI(domElements);
1737
+
1738
+ if (uiCallbacks.onUpdate) {
1739
+ uiCallbacks.onUpdate();
1740
+ }
1741
+
1742
+ if (uiCallbacks.setStatus) {
1743
+ uiCallbacks.setStatus(`Loaded preset: ${e.target.value}`, 'online');
1744
+ }
1745
+ });
1746
+ }
1747
+ }
1748
+
1749
+ /**
1750
+ * Setup font change listeners
1751
+ */
1752
+ function setupFontListeners(domElements) {
1753
+ [domElements.fontHeading, domElements.fontBody, domElements.fontCode].forEach(select => {
1754
+ if (select) {
1755
+ // Real-time update on change
1756
+ select.addEventListener('change', () => {
1757
+ syncUIToConfig(domElements);
1758
+ });
1759
+
1760
+ // Visual feedback on hover
1761
+ setupVisualFeedback(select);
1762
+ }
1763
+ });
1764
+ }
1765
+
1766
+ /**
1767
+ * Setup color change listeners
1768
+ */
1769
+ function setupColorListeners(domElements) {
1770
+ [domElements.colorPrimary, domElements.colorAccent, domElements.colorBackground, domElements.colorText].forEach(input => {
1771
+ if (input) {
1772
+ // Real-time update on input
1773
+ input.addEventListener('input', () => {
1774
+ syncUIToConfig(domElements);
1775
+ });
1776
+
1777
+ // Visual feedback on hover
1778
+ setupVisualFeedback(input);
1779
+ }
1780
+ });
1781
+ }
1782
+
1783
+ /**
1784
+ * Setup animation change listeners
1785
+ */
1786
+ function setupAnimationListeners(domElements) {
1787
+ [domElements.animationTransition, domElements.animationDuration].forEach(input => {
1788
+ if (input) {
1789
+ // Real-time update on change/input
1790
+ input.addEventListener('input', () => {
1791
+ syncUIToConfig(domElements);
1792
+ });
1793
+ input.addEventListener('change', () => {
1794
+ syncUIToConfig(domElements);
1795
+ });
1796
+
1797
+ // Visual feedback on hover
1798
+ setupVisualFeedback(input);
1799
+ }
1800
+ });
1801
+ }
1802
+
1803
+ /**
1804
+ * Setup font size and line height change listeners
1805
+ */
1806
+ function setupFontSizeListeners(domElements) {
1807
+ [
1808
+ domElements.fontSizeH1Min, domElements.fontSizeH1Base, domElements.fontSizeH1Max,
1809
+ domElements.fontSizeH2Min, domElements.fontSizeH2Base, domElements.fontSizeH2Max,
1810
+ domElements.fontSizeTextMin, domElements.fontSizeTextBase, domElements.fontSizeTextMax,
1811
+ domElements.lineHeightHeading, domElements.lineHeightBody
1812
+ ].forEach(input => {
1813
+ if (input) {
1814
+ // Real-time update on input
1815
+ input.addEventListener('input', () => {
1816
+ syncUIToConfig(domElements);
1817
+ });
1818
+
1819
+ // Visual feedback on hover
1820
+ setupVisualFeedback(input);
1821
+ }
1822
+ });
1823
+ }
1824
+
1825
+ /**
1826
+ * Setup UI styles listeners
1827
+ */
1828
+ function setupUIStylesListeners(domElements) {
1829
+ [
1830
+ domElements.previewOpacity, domElements.overlayBlur, domElements.navBorderWidth,
1831
+ domElements.backdropSpread, domElements.backdropBlur,
1832
+ domElements.headingBorderWidth, domElements.blockquoteBorderWidth,
1833
+ domElements.imageBorderWidth, domElements.linkUnderlineWidth,
1834
+ domElements.tableBorderWidth, domElements.hrBorderWidth,
1835
+ domElements.pageIndicatorTop, domElements.pageIndicatorRight,
1836
+ domElements.pageIndicatorFontSize, domElements.pageIndicatorOpacity,
1837
+ domElements.pageIndicatorPaddingX, domElements.pageIndicatorPaddingY,
1838
+ domElements.pageIndicatorBgColor, domElements.pageIndicatorTextColor,
1839
+ domElements.smartListTwoColumn, domElements.smartListThreeColumn
1840
+ ].forEach(input => {
1841
+ if (input) {
1842
+ // Real-time update on input
1843
+ input.addEventListener('input', () => {
1844
+ syncUIToConfig(domElements);
1845
+ });
1846
+
1847
+ // Visual feedback on hover
1848
+ setupVisualFeedback(input);
1849
+ }
1850
+ });
1851
+ }
1852
+
1853
+ /**
1854
+ * Setup visual feedback system
1855
+ * Highlights stage elements when hovering over related settings
1856
+ */
1857
+ function setupVisualFeedback(inputElement) {
1858
+ if (!inputElement || !inputElement.id) return;
1859
+
1860
+ const feedbackMap = {
1861
+ // Font settings -> all text elements
1862
+ 'fontHeading': { selector: 'h1, h2, h3, h4, h5, h6', type: 'content' },
1863
+ 'fontBody': { selector: 'p, li, blockquote', type: 'content' },
1864
+ 'fontCode': { selector: 'code, pre', type: 'content' },
1865
+
1866
+ // Font sizes -> specific headings
1867
+ 'fontSizeH1Min': { selector: 'h1', type: 'content' },
1868
+ 'fontSizeH1Base': { selector: 'h1', type: 'content' },
1869
+ 'fontSizeH1Max': { selector: 'h1', type: 'content' },
1870
+ 'fontSizeH2Min': { selector: 'h2', type: 'content' },
1871
+ 'fontSizeH2Base': { selector: 'h2', type: 'content' },
1872
+ 'fontSizeH2Max': { selector: 'h2', type: 'content' },
1873
+ 'fontSizeTextMin': { selector: 'p, li', type: 'content' },
1874
+ 'fontSizeTextBase': { selector: 'p, li', type: 'content' },
1875
+ 'fontSizeTextMax': { selector: 'p, li', type: 'content' },
1876
+
1877
+ // Colors -> elements with those colors
1878
+ 'colorPrimary': { selector: 'h1, a', type: 'content' },
1879
+ 'colorAccent': { selector: '.accent, .badge', type: 'content' },
1880
+ 'colorBackground': { selector: '#stage', type: 'content' },
1881
+ 'colorText': { selector: 'p, li, span', type: 'content' },
1882
+
1883
+ // Line height
1884
+ 'lineHeightHeading': { selector: 'h1, h2, h3', type: 'content' },
1885
+ 'lineHeightBody': { selector: 'p, li', type: 'content' },
1886
+
1887
+ // Border widths
1888
+ 'headingBorderWidth': { selector: 'h1, h2, h3', type: 'content' },
1889
+ 'blockquoteBorderWidth': { selector: 'blockquote', type: 'content' },
1890
+ 'imageBorderWidth': { selector: 'img', type: 'content' },
1891
+ 'linkUnderlineWidth': { selector: 'a', type: 'content' },
1892
+ 'tableBorderWidth': { selector: 'table, td, th', type: 'content' },
1893
+ 'hrBorderWidth': { selector: 'hr', type: 'content' },
1894
+
1895
+ // Typography
1896
+ 'paragraphBefore': { selector: 'p', type: 'content' },
1897
+ 'paragraphAfter': { selector: 'p', type: 'content' },
1898
+ 'headingBefore': { selector: 'h1, h2, h3', type: 'content' },
1899
+ 'headingAfter': { selector: 'h1, h2, h3', type: 'content' },
1900
+ 'indentBlockquote': { selector: 'blockquote', type: 'content' },
1901
+ 'listIndent': { selector: 'ul, ol, li', type: 'content' },
1902
+ 'textAlign': { selector: 'p, h1, h2, h3', type: 'content' },
1903
+
1904
+ // Smart lists
1905
+ 'smartListTwoColumn': { selector: 'ul, ol', type: 'content' },
1906
+ 'smartListThreeColumn': { selector: 'ul, ol', type: 'content' },
1907
+
1908
+ // Content Layout
1909
+ 'contentPaddingSmall': { selector: '.scene', type: 'content' },
1910
+ 'contentPaddingLarge': { selector: '.scene', type: 'content' },
1911
+ 'contentPaddingUltra': { selector: '.scene', type: 'content' },
1912
+ 'contentAlignHorizontal': { selector: '#slideContainer, .scene', type: 'content' },
1913
+ 'contentAlignVertical': { selector: '#slideContainer, .scene', type: 'content' },
1914
+
1915
+ // UI Elements
1916
+ 'previewOpacity': { selector: '.scene:not(.active)', type: 'ui' },
1917
+ 'overlayBlur': { selector: '#pauseOverlay', type: 'ui' },
1918
+ 'navBorderWidth': { selector: '.nav-btn', type: 'ui' },
1919
+ 'backdropSpread': { selector: '.gradient-backdrop', type: 'ui' },
1920
+ 'backdropBlur': { selector: '.gradient-backdrop', type: 'ui' },
1921
+ 'pageIndicatorTop': { selector: '#slideCounter', type: 'ui' },
1922
+ 'pageIndicatorRight': { selector: '#slideCounter', type: 'ui' },
1923
+ 'pageIndicatorFontSize': { selector: '#slideCounter', type: 'ui' },
1924
+ 'pageIndicatorOpacity': { selector: '#slideCounter', type: 'ui' },
1925
+ 'pageIndicatorPaddingX': { selector: '#slideCounter', type: 'ui' },
1926
+ 'pageIndicatorPaddingY': { selector: '#slideCounter', type: 'ui' },
1927
+ 'pageIndicatorBgColor': { selector: '#slideCounter', type: 'ui' },
1928
+ 'pageIndicatorTextColor': { selector: '#slideCounter', type: 'ui' }
1929
+ };
1930
+
1931
+ const mapping = feedbackMap[inputElement.id];
1932
+ if (!mapping) return;
1933
+
1934
+ // Mouse enter - highlight elements
1935
+ inputElement.addEventListener('mouseenter', () => {
1936
+ const stage = document.getElementById('stage');
1937
+ if (!stage) return;
1938
+
1939
+ const elements = stage.querySelectorAll(mapping.selector);
1940
+ elements.forEach(el => {
1941
+ // Add highlight class based on type
1942
+ if (mapping.type === 'content') {
1943
+ el.style.outline = '2px solid rgba(96, 165, 250, 0.5)'; // Blue for content
1944
+ el.style.outlineOffset = '4px';
1945
+ el.style.transition = 'outline 0.2s ease';
1946
+ } else {
1947
+ el.style.outline = '2px solid rgba(168, 85, 247, 0.5)'; // Purple for UI
1948
+ el.style.outlineOffset = '4px';
1949
+ el.style.transition = 'outline 0.2s ease';
1950
+ }
1951
+ });
1952
+
1953
+ // Add visual feedback to the input itself
1954
+ const color = mapping.type === 'content' ? 'rgba(96, 165, 250, 0.3)' : 'rgba(168, 85, 247, 0.3)';
1955
+ inputElement.style.backgroundColor = color;
1956
+ inputElement.style.transition = 'background-color 0.2s ease';
1957
+ });
1958
+
1959
+ // Mouse leave - remove highlight
1960
+ inputElement.addEventListener('mouseleave', () => {
1961
+ const stage = document.getElementById('stage');
1962
+ if (!stage) return;
1963
+
1964
+ const elements = stage.querySelectorAll(mapping.selector);
1965
+ elements.forEach(el => {
1966
+ el.style.outline = '';
1967
+ el.style.outlineOffset = '';
1968
+ });
1969
+
1970
+ // Remove input highlight
1971
+ inputElement.style.backgroundColor = '';
1972
+ });
1973
+ }
1974
+
1975
+ /**
1976
+ * Setup typography change listeners
1977
+ */
1978
+ function setupTypographyListeners(domElements) {
1979
+ [
1980
+ domElements.paragraphBefore, domElements.paragraphAfter,
1981
+ domElements.headingBefore, domElements.headingAfter,
1982
+ domElements.indentFirst, domElements.indentBlockquote,
1983
+ domElements.listIndent, domElements.textAlign
1984
+ ].forEach(input => {
1985
+ if (input) {
1986
+ // Real-time update on input
1987
+ input.addEventListener('input', () => {
1988
+ syncUIToConfig(domElements);
1989
+ });
1990
+
1991
+ // Visual feedback on hover
1992
+ setupVisualFeedback(input);
1993
+ }
1994
+ });
1995
+ }
1996
+
1997
+ /**
1998
+ * Setup layout change listeners
1999
+ */
2000
+ function setupLayoutListeners(domElements) {
2001
+ [
2002
+ domElements.contentPaddingSmall, domElements.contentPaddingLarge, domElements.contentPaddingUltra,
2003
+ domElements.contentAlignHorizontal, domElements.contentAlignVertical
2004
+ ].forEach(input => {
2005
+ if (input) {
2006
+ // Real-time update on input
2007
+ input.addEventListener('input', () => {
2008
+ syncUIToConfig(domElements);
2009
+ });
2010
+
2011
+ // Real-time update on change (for select elements)
2012
+ input.addEventListener('change', () => {
2013
+ syncUIToConfig(domElements);
2014
+ });
2015
+
2016
+ // Visual feedback on hover
2017
+ setupVisualFeedback(input);
2018
+ }
2019
+ });
2020
+ }
2021
+
2022
+ /**
2023
+ * Setup Save and Reset buttons
2024
+ */
2025
+ function setupActionButtons(domElements) {
2026
+ // Save button
2027
+ if (domElements.saveSettingsBtn) {
2028
+ domElements.saveSettingsBtn.addEventListener('click', () => {
2029
+ if (uiCallbacks.onSave) {
2030
+ uiCallbacks.onSave(currentConfig, domElements.presetSelector?.value);
2031
+ }
2032
+
2033
+ if (uiCallbacks.setStatus) {
2034
+ uiCallbacks.setStatus('Settings saved to frontmatter', 'online');
2035
+ }
2036
+ });
2037
+ }
2038
+
2039
+ // Reset button
2040
+ if (domElements.resetSettingsBtn) {
2041
+ domElements.resetSettingsBtn.addEventListener('click', () => {
2042
+ resetConfig();
2043
+ loadConfigToUI(domElements);
2044
+
2045
+ if (domElements.presetSelector) {
2046
+ domElements.presetSelector.value = 'default';
2047
+ }
2048
+
2049
+ if (uiCallbacks.onUpdate) {
2050
+ uiCallbacks.onUpdate();
2051
+ }
2052
+
2053
+ if (uiCallbacks.setStatus) {
2054
+ uiCallbacks.setStatus('Settings reset to default', 'online');
2055
+ }
2056
+ });
2057
+ }
2058
+ }
2059
+
2060
+ // Auto-apply on load
2061
+ if (typeof window !== 'undefined') {
2062
+ window.addEventListener('DOMContentLoaded', () => {
2063
+ applyConfigToDOM();
2064
+ });
2065
+ }
2066
+
src/renderer/js/slide-editor.js ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Markdown Presenter - Slide Editor
3
+ // In-Presentation Slide Editing System with Drag & Drop
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 2.1.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ import { DragDropManager } from './drag-drop-manager.js';
11
+ import { PersistentStorage } from '../../shared/persistent-storage.js';
12
+ import { ContentFingerprint } from '../../shared/content-fingerprint.js';
13
+ import { setDisplayMode, getDisplayMode } from './presentation-config.js';
14
+ import {
15
+ switchToEditorMode,
16
+ switchToPresentationMode,
17
+ getModeManager
18
+ } from './mode-manager.js';
19
+
20
+ /**
21
+ * Slide Editor - แก้ไขสไลด์แบบ inline ใน Presentation Mode
22
+ * พร้อมระบบลากย้ายตำแหน่งและบันทึกถาวร
23
+ */
24
+ export class SlideEditor {
25
+ constructor() {
26
+ this.isEditMode = false;
27
+ this.isDragMode = false;
28
+ this.currentSlideIndex = -1;
29
+ this.currentFilePath = null;
30
+ this.slideOverrides = new Map(); // เก็บการแก้ไขแยกตามสไลด์
31
+ this.originalContent = null;
32
+ this.hasUnsavedChanges = false;
33
+
34
+ // DOM Elements
35
+ this.editBtn = document.getElementById('editSlideBtn');
36
+ this.saveBtn = document.getElementById('saveSlideBtn');
37
+ this.cancelBtn = document.getElementById('cancelEditBtn');
38
+ this.stage = document.getElementById('stage');
39
+
40
+ // Position Controls
41
+ this.positionControls = document.getElementById('positionControls');
42
+ this.toggleSafeZoneBtn = document.getElementById('toggleSafeZoneBtn');
43
+ this.toggleSnapGridBtn = document.getElementById('toggleSnapGridBtn');
44
+ this.resetPositionsBtn = document.getElementById('resetPositionsBtn');
45
+ this.exportSettingsBtn = document.getElementById('exportSettingsBtn');
46
+ this.positionIndicator = document.getElementById('positionIndicator');
47
+
48
+ // Managers
49
+ this.dragDropManager = new DragDropManager();
50
+ this.persistentStorage = new PersistentStorage();
51
+
52
+ this.init();
53
+ }
54
+
55
+ /**
56
+ * Initialize editor
57
+ */
58
+ init() {
59
+ if (!this.editBtn || !this.saveBtn || !this.cancelBtn) {
60
+ console.warn('[SlideEditor] Required buttons not found');
61
+ return;
62
+ }
63
+
64
+ // Event listeners
65
+ this.editBtn.addEventListener('click', () => this.toggleEditMode());
66
+ this.saveBtn.addEventListener('click', () => this.saveChanges());
67
+ this.cancelBtn.addEventListener('click', () => this.cancelEdit());
68
+
69
+ // Position control listeners
70
+ if (this.toggleSafeZoneBtn) {
71
+ this.toggleSafeZoneBtn.addEventListener('click', () => this.toggleSafeZone());
72
+ }
73
+ if (this.toggleSnapGridBtn) {
74
+ this.toggleSnapGridBtn.addEventListener('click', () => this.toggleSnapGrid());
75
+ }
76
+ if (this.resetPositionsBtn) {
77
+ this.resetPositionsBtn.addEventListener('click', () => this.resetAllPositions());
78
+ }
79
+ if (this.exportSettingsBtn) {
80
+ this.exportSettingsBtn.addEventListener('click', () => this.exportAllSettings());
81
+ }
82
+
83
+ // Keyboard shortcuts
84
+ document.addEventListener('keydown', (e) => {
85
+ if (!this.isEditMode) return;
86
+
87
+ // Ctrl/Cmd + S = Save
88
+ if ((e.ctrlKey || e.metaKey) && e.key === 's') {
89
+ e.preventDefault();
90
+ this.saveChanges();
91
+ }
92
+
93
+ // ESC = Cancel
94
+ if (e.key === 'Escape') {
95
+ e.preventDefault();
96
+ this.cancelEdit();
97
+ }
98
+ });
99
+
100
+ console.log('[SlideEditor] Initialized');
101
+ }
102
+
103
+ /**
104
+ * Show edit button when in presentation mode
105
+ */
106
+ showEditButton() {
107
+ if (this.editBtn) {
108
+ this.editBtn.classList.remove('hidden');
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Hide edit button
114
+ */
115
+ hideEditButton() {
116
+ if (this.editBtn) {
117
+ this.editBtn.classList.add('hidden');
118
+ }
119
+ this.exitEditMode();
120
+ }
121
+
122
+ /**
123
+ * Set current slide index
124
+ */
125
+ setCurrentSlide(index) {
126
+ this.currentSlideIndex = index;
127
+ }
128
+
129
+ /**
130
+ * Toggle edit mode
131
+ */
132
+ toggleEditMode() {
133
+ if (this.isEditMode) {
134
+ this.exitEditMode();
135
+ } else {
136
+ this.enterEditMode();
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Enter edit mode
142
+ */
143
+ /**
144
+ * Enter edit mode
145
+ */
146
+ enterEditMode() {
147
+ if (this.currentSlideIndex < 0) {
148
+ console.warn('[SlideEditor] No slide selected');
149
+ return;
150
+ }
151
+
152
+ // สลับไปโหมด editor และปิดโหมดอื่นทั้งหมด
153
+ switchToEditorMode();
154
+
155
+ this.isEditMode = true;
156
+ this.hasUnsavedChanges = false;
157
+
158
+ // Save original content
159
+ const activeScene = this.stage.querySelector('.scene.active');
160
+ if (!activeScene) {
161
+ console.warn('[SlideEditor] No active scene found');
162
+ return;
163
+ }
164
+
165
+ this.originalContent = activeScene.cloneNode(true);
166
+
167
+ // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง detach ที่นี่
168
+
169
+ // Make content editable
170
+ this.makeContentEditable(activeScene);
171
+
172
+ // Update UI
173
+ this.stage.classList.add('slide-editable');
174
+ this.editBtn.classList.add('active');
175
+ this.showEditIndicator();
176
+
177
+ // Mode Manager จัดการ Safe Zone แล้ว ไม่ต้องแสดงที่นี่
178
+
179
+ console.log(`[SlideEditor] Edit mode entered for slide ${this.currentSlideIndex}`);
180
+ }
181
+
182
+ /**
183
+ * Exit edit mode (with unsaved changes check)
184
+ */
185
+ async exitEditMode() {
186
+ if (!this.isEditMode) return;
187
+
188
+ // ถ้ามีการแก้ไขที่ยังไม่บันทึก ให้ถามผู้ใช้
189
+ if (this.hasUnsavedChanges) {
190
+ const result = await this.showExitConfirmation('Edit Mode', 'You have unsaved changes.');
191
+
192
+ if (result === 'cancel') {
193
+ // ยกเลิก ไม่ออกจาก Edit Mode
194
+ return;
195
+ } else if (result === 'save') {
196
+ // บันทึกก่อนออก
197
+ await this.saveCurrentSlide();
198
+ }
199
+ // ถ้าเลือก 'discard' ก็ออกเลยโดยไม่บันทึก
200
+ }
201
+
202
+ this.isEditMode = false;
203
+
204
+ // กลับไปโหมด presentation และปิดโหมดอื่นทั้งหมด
205
+ switchToPresentationMode();
206
+
207
+ // Remove contenteditable
208
+ const activeScene = this.stage.querySelector('.scene.active');
209
+ if (activeScene) {
210
+ this.makeContentNonEditable(activeScene);
211
+ }
212
+
213
+ // Update UI
214
+ this.stage.classList.remove('slide-editable');
215
+ this.editBtn.classList.remove('active');
216
+ this.hideEditIndicator();
217
+ this.hideSaveButtons();
218
+
219
+ // Mode Manager จัดการ Safe Zone และ Smart Layout แล้ว
220
+
221
+ this.originalContent = null;
222
+ this.hasUnsavedChanges = false;
223
+
224
+ console.log('[SlideEditor] Edit mode exited');
225
+ }
226
+
227
+ /**
228
+ * Show exit confirmation dialog
229
+ * @param {string} modeName - ชื่อโหมด
230
+ * @param {string} message - ข้อความเพิ่มเติม
231
+ * @returns {Promise<string>} 'save', 'discard', หรือ 'cancel'
232
+ */
233
+ async showExitConfirmation(modeName, message = '') {
234
+ return new Promise((resolve) => {
235
+ const dialog = document.createElement('div');
236
+ dialog.className = 'exit-confirmation-dialog';
237
+ dialog.innerHTML = `
238
+ <div class="exit-confirmation-overlay"></div>
239
+ <div class="exit-confirmation-content">
240
+ <div class="exit-confirmation-header">
241
+ <h3>Exit ${modeName}?</h3>
242
+ </div>
243
+ <div class="exit-confirmation-body">
244
+ <p class="warning-text">${message}</p>
245
+ <p>Do you want to save your changes?</p>
246
+ </div>
247
+ <div class="exit-confirmation-footer">
248
+ <button class="btn-exit-save" data-action="save">
249
+ Save & Exit
250
+ </button>
251
+ <button class="btn-exit-discard" data-action="discard">
252
+ Discard Changes
253
+ </button>
254
+ <button class="btn-exit-cancel" data-action="cancel">
255
+ Cancel
256
+ </button>
257
+ </div>
258
+ </div>
259
+ `;
260
+
261
+ document.body.appendChild(dialog);
262
+
263
+ // Handle button clicks
264
+ dialog.querySelectorAll('button').forEach(btn => {
265
+ btn.addEventListener('click', () => {
266
+ const action = btn.dataset.action;
267
+ document.body.removeChild(dialog);
268
+ resolve(action);
269
+ });
270
+ });
271
+
272
+ // ESC to cancel
273
+ const escHandler = (e) => {
274
+ if (e.key === 'Escape') {
275
+ document.body.removeChild(dialog);
276
+ document.removeEventListener('keydown', escHandler);
277
+ resolve('cancel');
278
+ }
279
+ };
280
+ document.addEventListener('keydown', escHandler);
281
+ });
282
+ }
283
+
284
+ /**
285
+ * Make scene content editable
286
+ */
287
+ makeContentEditable(scene) {
288
+ // Find all editable elements
289
+ const editableElements = scene.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote');
290
+
291
+ editableElements.forEach((el, index) => {
292
+ el.setAttribute('contenteditable', 'true');
293
+ el.setAttribute('data-editable-id', `edit-${index}`);
294
+ el.setAttribute('data-placeholder', 'Click to edit...');
295
+
296
+ // Track changes
297
+ el.addEventListener('input', () => this.onContentChange());
298
+ el.addEventListener('blur', () => this.onContentChange());
299
+ });
300
+ }
301
+
302
+ /**
303
+ * Remove contenteditable
304
+ */
305
+ makeContentNonEditable(scene) {
306
+ const editableElements = scene.querySelectorAll('[contenteditable="true"]');
307
+
308
+ editableElements.forEach(el => {
309
+ el.removeAttribute('contenteditable');
310
+ el.removeAttribute('data-editable-id');
311
+ el.removeAttribute('data-placeholder');
312
+ });
313
+ }
314
+
315
+ /**
316
+ * Handle content change
317
+ */
318
+ onContentChange() {
319
+ if (!this.hasUnsavedChanges) {
320
+ this.hasUnsavedChanges = true;
321
+ this.showSaveButtons();
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Save changes to current slide
327
+ */
328
+ saveChanges() {
329
+ if (!this.isEditMode || this.currentSlideIndex < 0) return;
330
+
331
+ const activeScene = this.stage.querySelector('.scene.active');
332
+ if (!activeScene) return;
333
+
334
+ // Extract edited content
335
+ const editedContent = this.extractEditedContent(activeScene);
336
+
337
+ // Save to overrides map
338
+ this.slideOverrides.set(this.currentSlideIndex, {
339
+ timestamp: Date.now(),
340
+ content: editedContent,
341
+ html: activeScene.innerHTML
342
+ });
343
+
344
+ console.log(`[SlideEditor] Saved changes for slide ${this.currentSlideIndex}`, editedContent);
345
+
346
+ // Exit edit mode
347
+ this.exitEditMode();
348
+
349
+ // Show success notification
350
+ this.showNotification('✓ Slide saved', 'success');
351
+ }
352
+
353
+ /**
354
+ * Cancel edit and revert changes
355
+ */
356
+ cancelEdit() {
357
+ if (!this.isEditMode || !this.originalContent) return;
358
+
359
+ const activeScene = this.stage.querySelector('.scene.active');
360
+ if (activeScene && this.originalContent) {
361
+ // Restore original content
362
+ activeScene.parentNode.replaceChild(this.originalContent.cloneNode(true), activeScene);
363
+
364
+ // Re-add active class
365
+ const restoredScene = this.stage.querySelector('.scene[data-scene]');
366
+ if (restoredScene) {
367
+ restoredScene.classList.add('active');
368
+ }
369
+ }
370
+
371
+ this.exitEditMode();
372
+ this.showNotification('✗ Changes cancelled', 'warning');
373
+ }
374
+
375
+ /**
376
+ * Extract edited content from scene
377
+ */
378
+ extractEditedContent(scene) {
379
+ const content = {};
380
+
381
+ // Extract text from editable elements
382
+ const editables = scene.querySelectorAll('[data-editable-id]');
383
+ editables.forEach(el => {
384
+ const id = el.getAttribute('data-editable-id');
385
+ content[id] = {
386
+ tag: el.tagName.toLowerCase(),
387
+ text: el.textContent.trim(),
388
+ html: el.innerHTML
389
+ };
390
+ });
391
+
392
+ return content;
393
+ }
394
+
395
+ /**
396
+ * Apply saved overrides to a slide
397
+ */
398
+ applyOverrides(slideIndex, scene) {
399
+ if (!this.slideOverrides.has(slideIndex)) return false;
400
+
401
+ const override = this.slideOverrides.get(slideIndex);
402
+
403
+ // Apply saved HTML
404
+ if (override.html) {
405
+ scene.innerHTML = override.html;
406
+ console.log(`[SlideEditor] Applied overrides to slide ${slideIndex}`);
407
+ return true;
408
+ }
409
+
410
+ return false;
411
+ }
412
+
413
+ /**
414
+ * Check if slide has overrides
415
+ */
416
+ hasOverrides(slideIndex) {
417
+ return this.slideOverrides.has(slideIndex);
418
+ }
419
+
420
+ /**
421
+ * Get all overrides
422
+ */
423
+ getAllOverrides() {
424
+ return Array.from(this.slideOverrides.entries()).map(([index, data]) => ({
425
+ slideIndex: index,
426
+ ...data
427
+ }));
428
+ }
429
+
430
+ /**
431
+ * Clear override for specific slide
432
+ */
433
+ clearOverride(slideIndex) {
434
+ this.slideOverrides.delete(slideIndex);
435
+ }
436
+
437
+ /**
438
+ * Clear all overrides
439
+ */
440
+ clearAllOverrides() {
441
+ this.slideOverrides.clear();
442
+ }
443
+
444
+ /**
445
+ * Export overrides as JSON
446
+ */
447
+ exportOverrides() {
448
+ const data = this.getAllOverrides();
449
+ return JSON.stringify(data, null, 2);
450
+ }
451
+
452
+ /**
453
+ * Import overrides from JSON
454
+ */
455
+ importOverrides(jsonString) {
456
+ try {
457
+ const data = JSON.parse(jsonString);
458
+ data.forEach(item => {
459
+ this.slideOverrides.set(item.slideIndex, {
460
+ timestamp: item.timestamp,
461
+ content: item.content,
462
+ html: item.html
463
+ });
464
+ });
465
+ console.log(`[SlideEditor] Imported ${data.length} overrides`);
466
+ return true;
467
+ } catch (error) {
468
+ console.error('[SlideEditor] Failed to import overrides:', error);
469
+ return false;
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Show edit mode indicator
475
+ */
476
+ showEditIndicator() {
477
+ let indicator = document.getElementById('editModeIndicator');
478
+ if (!indicator) {
479
+ indicator = document.createElement('div');
480
+ indicator.id = 'editModeIndicator';
481
+ indicator.className = 'edit-mode-indicator';
482
+ indicator.textContent = '✎ Edit Mode';
483
+ this.stage.appendChild(indicator);
484
+ }
485
+ }
486
+
487
+ /**
488
+ * Hide edit mode indicator
489
+ */
490
+ hideEditIndicator() {
491
+ const indicator = document.getElementById('editModeIndicator');
492
+ if (indicator) {
493
+ indicator.remove();
494
+ }
495
+ }
496
+
497
+ /**
498
+ * Show save/cancel buttons
499
+ */
500
+ showSaveButtons() {
501
+ if (this.saveBtn) this.saveBtn.classList.remove('hidden');
502
+ if (this.cancelBtn) this.cancelBtn.classList.remove('hidden');
503
+ }
504
+
505
+ /**
506
+ * Hide save/cancel buttons
507
+ */
508
+ hideSaveButtons() {
509
+ if (this.saveBtn) this.saveBtn.classList.add('hidden');
510
+ if (this.cancelBtn) this.cancelBtn.classList.add('hidden');
511
+ }
512
+
513
+ /**
514
+ * Show notification
515
+ */
516
+ showNotification(message, type = 'info') {
517
+ // Create notification element
518
+ const notification = document.createElement('div');
519
+ notification.className = `slide-edit-notification notification-${type}`;
520
+ notification.textContent = message;
521
+ notification.style.cssText = `
522
+ position: fixed;
523
+ top: 5rem;
524
+ left: 50%;
525
+ transform: translateX(-50%);
526
+ z-index: 1000;
527
+ background: ${type === 'success' ? 'rgba(16, 185, 129, 0.95)' :
528
+ type === 'warning' ? 'rgba(245, 158, 11, 0.95)' :
529
+ 'rgba(59, 130, 246, 0.95)'};
530
+ color: white;
531
+ padding: 0.75rem 1.5rem;
532
+ border-radius: 0.5rem;
533
+ font-weight: 600;
534
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
535
+ animation: slideDown 0.3s ease-out;
536
+ `;
537
+
538
+ document.body.appendChild(notification);
539
+
540
+ // Remove after 3 seconds
541
+ setTimeout(() => {
542
+ notification.style.animation = 'slideUp 0.3s ease-out';
543
+ setTimeout(() => notification.remove(), 300);
544
+ }, 3000);
545
+ }
546
+
547
+ /**
548
+ * Reset editor state
549
+ */
550
+ reset() {
551
+ this.exitEditMode();
552
+ this.exitDragMode();
553
+ this.currentSlideIndex = -1;
554
+ this.hideEditButton();
555
+ this.hidePositionControls();
556
+ }
557
+
558
+ // ═══════════════════════════════════════════════════════════════════════════
559
+ // DRAG & DROP METHODS
560
+ // ═══════════════════════════════════════════════════════════════════════════
561
+
562
+ /**
563
+ * เข้าสู่ Drag Mode
564
+ */
565
+ /**
566
+ * เข้าสู่ Drag Mode
567
+ */
568
+ enterDragMode() {
569
+ const activeScene = this.stage?.querySelector('.scene.active');
570
+ if (!activeScene) return;
571
+
572
+ // สลับไปโหมด editor และปิดโหมดอื่นทั้งหมด
573
+ switchToEditorMode();
574
+
575
+ this.isDragMode = true;
576
+
577
+ // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง detach ที่นี่
578
+
579
+ this.dragDropManager.enableDragging(activeScene);
580
+ this.showPositionControls();
581
+
582
+ // เปลี่ยนสีปุ่ม edit
583
+ if (this.editBtn) {
584
+ this.editBtn.style.background = 'rgba(139, 92, 246, 0.9)'; // สีม่วง
585
+ }
586
+
587
+ this.showNotification('⊕ Drag Mode - ลากเพื่อย้ายตำแหน่งบรรทัด', 'info');
588
+ }
589
+
590
+ /**
591
+ * ออกจาก Drag Mode
592
+ */
593
+ exitDragMode() {
594
+ const activeScene = this.stage?.querySelector('.scene.active');
595
+ if (activeScene) {
596
+ this.dragDropManager.disableDragging(activeScene);
597
+ }
598
+
599
+ // กลับไปโหมด presentation และปิดโหมดอื่นทั้งหมด
600
+ switchToPresentationMode();
601
+
602
+ this.isDragMode = false;
603
+ this.hidePositionControls();
604
+
605
+ // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง reattach ที่นี่
606
+
607
+ // คืนสีปุ่ม edit
608
+ if (this.editBtn) {
609
+ this.editBtn.style.background = '';
610
+ }
611
+ }
612
+
613
+ /**
614
+ * Toggle Drag Mode
615
+ */
616
+ toggleDragMode() {
617
+ if (this.isDragMode) {
618
+ this.exitDragMode();
619
+ } else {
620
+ // ออกจาก Edit Mode ก่อน (ถ้ากำลัง edit อยู่)
621
+ if (this.isEditMode) {
622
+ this.exitEditMode();
623
+ }
624
+ this.enterDragMode();
625
+ }
626
+ }
627
+
628
+ /**
629
+ * แสดง Position Controls
630
+ */
631
+ showPositionControls() {
632
+ if (this.positionControls) {
633
+ this.positionControls.classList.remove('hidden');
634
+ }
635
+ }
636
+
637
+ /**
638
+ * ซ่อน Position Controls
639
+ */
640
+ hidePositionControls() {
641
+ if (this.positionControls) {
642
+ this.positionControls.classList.add('hidden');
643
+ }
644
+ }
645
+
646
+ /**
647
+ * Toggle Safe Zone
648
+ */
649
+ toggleSafeZone() {
650
+ const isActive = this.dragDropManager.showSafeZone;
651
+ this.dragDropManager.toggleSafeZone(!isActive);
652
+
653
+ if (this.toggleSafeZoneBtn) {
654
+ if (!isActive) {
655
+ this.toggleSafeZoneBtn.classList.add('active');
656
+ this.showNotification('✓ Safe Zone เปิด', 'success');
657
+ } else {
658
+ this.toggleSafeZoneBtn.classList.remove('active');
659
+ this.showNotification('✗ Safe Zone ปิด', 'info');
660
+ }
661
+ }
662
+ }
663
+
664
+ /**
665
+ * Toggle Snap to Grid
666
+ */
667
+ toggleSnapGrid() {
668
+ const isActive = this.dragDropManager.snapToGrid;
669
+ this.dragDropManager.toggleSnapToGrid(!isActive);
670
+
671
+ if (this.toggleSnapGridBtn) {
672
+ if (!isActive) {
673
+ this.toggleSnapGridBtn.classList.add('active');
674
+ this.showNotification('✓ Snap to Grid เปิด', 'success');
675
+ } else {
676
+ this.toggleSnapGridBtn.classList.remove('active');
677
+ this.showNotification('✗ Snap to Grid ปิด', 'info');
678
+ }
679
+ }
680
+ }
681
+
682
+ /**
683
+ * รีเซ็ตตำแหน่งทั้งหมดของสไลด์ปัจจุบัน
684
+ */
685
+ resetAllPositions() {
686
+ if (!confirm('รีเซ็ตตำแหน่งและการแก้ไขทั้งหมดของสไลด์นี้?\n(การตั้งค่าจะถูกลบถาวร)')) {
687
+ return;
688
+ }
689
+
690
+ const activeScene = this.stage?.querySelector('.scene.active');
691
+ if (!activeScene) return;
692
+
693
+ // รีเซ็ตตำแหน่ง
694
+ const elements = activeScene.querySelectorAll('.draggable-content');
695
+ elements.forEach(element => {
696
+ this.dragDropManager.resetPosition(element);
697
+ });
698
+
699
+ // ลบการแก้ไขเนื้อหา
700
+ if (this.currentSlideIndex >= 0) {
701
+ this.slideOverrides.delete(this.currentSlideIndex);
702
+ }
703
+
704
+ // ลบจาก localStorage
705
+ if (this.currentFilePath && this.currentSlideIndex >= 0) {
706
+ this.persistentStorage.clearSlide(this.currentFilePath, this.currentSlideIndex);
707
+ }
708
+
709
+ // ลบข้อมูล positions จาก dragDropManager
710
+ this.dragDropManager.clearAllPositions();
711
+
712
+ this.showNotification('✓ รีเซ็ตทั้งหมดเรียบร้อย', 'success');
713
+ }
714
+
715
+ /**
716
+ * Export การตั้งค่าทั้งหมด
717
+ */
718
+ exportAllSettings() {
719
+ if (!this.currentFilePath) {
720
+ this.showNotification('��� กรุณาเปิดไฟล์ก่อน', 'warning');
721
+ return;
722
+ }
723
+
724
+ const totalSlides = this.getTotalSlides();
725
+ this.persistentStorage.downloadJSON(this.currentFilePath, totalSlides);
726
+ this.showNotification('✓ ส่งออกการตั้งค่าเรียบร้อย', 'success');
727
+ }
728
+
729
+ /**
730
+ * นับจำนวน slides ทั้งหมด
731
+ */
732
+ getTotalSlides() {
733
+ // ควร implement ตามโครงสร้างจริง
734
+ return 10; // placeholder
735
+ }
736
+
737
+ /**
738
+ * ตั้งค่าไฟล์ปัจจุบัน
739
+ */
740
+ setCurrentFile(filePath) {
741
+ this.currentFilePath = filePath;
742
+ this.persistentStorage.setCurrentFile(filePath);
743
+ }
744
+
745
+ /**
746
+ * Apply positions จาก storage
747
+ */
748
+ applyPositions(slideIndex, scene) {
749
+ if (!this.currentFilePath) return false;
750
+
751
+ const positions = this.persistentStorage.loadPositions(this.currentFilePath, slideIndex);
752
+ if (!positions) return false;
753
+
754
+ this.dragDropManager.loadPositions(positions);
755
+ return true;
756
+ }
757
+
758
+ /**
759
+ * Save positions ไปยัง storage
760
+ */
761
+ savePositions() {
762
+ if (!this.currentFilePath || this.currentSlideIndex < 0) return;
763
+
764
+ const positions = this.dragDropManager.exportPositions();
765
+ this.persistentStorage.savePositions(
766
+ this.currentFilePath,
767
+ this.currentSlideIndex,
768
+ positions
769
+ );
770
+ }
771
+
772
+ // ═══════════════════════════════════════════════════════════════════════════
773
+ // CONTENT FINGERPRINTING
774
+ // ═══════════════════════════════════════════════════════════════════════════
775
+
776
+ /**
777
+ * สร้าง fingerprint map สำหรับ slide
778
+ */
779
+ createFingerprintMap(scene) {
780
+ return ContentFingerprint.mapSlideElements(scene);
781
+ }
782
+
783
+ /**
784
+ * Match settings กับ content ใหม่
785
+ */
786
+ matchSettingsToContent(scene, savedSettings) {
787
+ const elementMap = this.createFingerprintMap(scene);
788
+ const matched = [];
789
+
790
+ elementMap.forEach(({ element, fingerprint }) => {
791
+ const setting = ContentFingerprint.match(fingerprint, savedSettings);
792
+ if (setting) {
793
+ matched.push({
794
+ element,
795
+ setting,
796
+ confidence: setting.matchConfidence
797
+ });
798
+ }
799
+ });
800
+
801
+ return matched;
802
+ }
803
+ }
804
+
805
+ // CSS for notification animation
806
+ const style = document.createElement('style');
807
+ style.textContent = `
808
+ @keyframes slideDown {
809
+ from {
810
+ opacity: 0;
811
+ transform: translate(-50%, -20px);
812
+ }
813
+ to {
814
+ opacity: 1;
815
+ transform: translate(-50%, 0);
816
+ }
817
+ }
818
+
819
+ @keyframes slideUp {
820
+ from {
821
+ opacity: 1;
822
+ transform: translate(-50%, 0);
823
+ }
824
+ to {
825
+ opacity: 0;
826
+ transform: translate(-50%, -20px);
827
+ }
828
+ }
829
+ `;
830
+ document.head.appendChild(style);
831
+
src/renderer/js/templates.js ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Video Templates
3
+ // Multiple Professional Templates for Video Creation
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ // สีหลักที่ใช้ร่วมกันทุก template
11
+ const SHARED_COLORS = {
12
+ primary: '#60a5fa', // Blue
13
+ secondary: '#a855f7', // Purple
14
+ background: '#0a1628', // Dark blue-black
15
+ surface: '#132337', // Dark blue-gray
16
+ text: '#e2e8f0', // Light gray
17
+ textSecondary: '#94a3b8', // Medium gray
18
+ accent: '#06b6d4' // Cyan
19
+ };
20
+
21
+ export const VIDEO_TEMPLATES = {
22
+ // ════════════════════════════════════════════════════════════════════════════
23
+ // Modern Template - Inter Font + Rounded Corners
24
+ // ════════════════════════════════════════════════════════════════════════════
25
+ modern: {
26
+ id: 'modern',
27
+ name: 'Modern',
28
+ description: 'Clean and professional design with gradient accents',
29
+ colors: { ...SHARED_COLORS },
30
+ fonts: {
31
+ primary: "'Inter', 'Segoe UI', sans-serif",
32
+ code: "'Source Code Pro', monospace"
33
+ },
34
+ animations: {
35
+ duration: 0.6,
36
+ easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
37
+ fadeIn: 'fadeIn 0.6s ease-out',
38
+ slideUp: 'slideUp 0.6s ease-out'
39
+ },
40
+ styles: {
41
+ borderRadius: '1.25rem',
42
+ shadow: '0 20px 40px rgba(0, 0, 0, 0.3)',
43
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.2), rgba(168, 85, 247, 0.2))'
44
+ }
45
+ },
46
+
47
+ // ════════════════════════════════════════════════════════════════════════════
48
+ // Classic Template - Serif Font + Traditional Style
49
+ // ════════════════════════════════════════════════════════════════════════════
50
+ classic: {
51
+ id: 'classic',
52
+ name: 'Classic',
53
+ description: 'Traditional elegant design with serif fonts',
54
+ colors: { ...SHARED_COLORS },
55
+ fonts: {
56
+ primary: "'Playfair Display', 'Georgia', serif",
57
+ code: "'Courier Prime', 'Courier New', monospace"
58
+ },
59
+ animations: {
60
+ duration: 0.8,
61
+ easing: 'ease-in-out',
62
+ fadeIn: 'fadeIn 0.8s ease-in-out',
63
+ slideUp: 'slideUp 0.8s ease-in-out'
64
+ },
65
+ styles: {
66
+ borderRadius: '0.5rem',
67
+ shadow: '0 10px 30px rgba(0, 0, 0, 0.5)',
68
+ gradient: 'linear-gradient(180deg, rgba(59, 130, 246, 0.1), transparent)'
69
+ }
70
+ },
71
+
72
+ // ════════════════════════════════════════════════════════════════════════════
73
+ // Minimal Template - Helvetica + Sharp Edges
74
+ // ════════════════════════════════════════════════════════════════════════════
75
+ minimal: {
76
+ id: 'minimal',
77
+ name: 'Minimal',
78
+ description: 'Ultra-clean minimalist design',
79
+ colors: { ...SHARED_COLORS },
80
+ fonts: {
81
+ primary: "'Helvetica Neue', 'Arial', sans-serif",
82
+ code: "'SF Mono', 'Monaco', monospace"
83
+ },
84
+ animations: {
85
+ duration: 0.4,
86
+ easing: 'linear',
87
+ fadeIn: 'fadeIn 0.4s linear',
88
+ slideUp: 'slideUp 0.4s linear'
89
+ },
90
+ styles: {
91
+ borderRadius: '0',
92
+ shadow: 'none',
93
+ gradient: 'none'
94
+ }
95
+ },
96
+
97
+ // ════════════════════════════════════════════════════════════════════════════
98
+ // Mono Template - Monospace Font + Terminal Style
99
+ // ════════════════════════════════════════════════════════════════════════════
100
+ mono: {
101
+ id: 'mono',
102
+ name: 'Mono',
103
+ description: 'Monospace terminal-inspired style',
104
+ colors: { ...SHARED_COLORS },
105
+ fonts: {
106
+ primary: "'Roboto Mono', 'Consolas', monospace",
107
+ code: "'Fira Code', 'Courier New', monospace"
108
+ },
109
+ animations: {
110
+ duration: 0.3,
111
+ easing: 'ease-out',
112
+ fadeIn: 'fadeIn 0.3s ease-out',
113
+ slideUp: 'slideUp 0.3s ease-out'
114
+ },
115
+ styles: {
116
+ borderRadius: '0',
117
+ shadow: '0 0 20px rgba(0, 255, 0, 0.3)',
118
+ gradient: 'radial-gradient(circle, rgba(0, 255, 0, 0.1), transparent)'
119
+ }
120
+ },
121
+
122
+ // ════════════════════════════════════════════════════════════════════════════
123
+ // Rounded Template - Poppins Font + Maximum Roundness
124
+ // ════════════════════════════════════════════════════════════════════════════
125
+ rounded: {
126
+ id: 'rounded',
127
+ name: 'Rounded',
128
+ description: 'Soft and friendly with rounded corners',
129
+ colors: { ...SHARED_COLORS },
130
+ fonts: {
131
+ primary: "'Poppins', 'Nunito', sans-serif",
132
+ code: "'JetBrains Mono', monospace"
133
+ },
134
+ animations: {
135
+ duration: 0.7,
136
+ easing: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)',
137
+ fadeIn: 'fadeIn 0.7s cubic-bezier(0.68, -0.55, 0.265, 1.55)',
138
+ slideUp: 'slideUp 0.7s cubic-bezier(0.68, -0.55, 0.265, 1.55)'
139
+ },
140
+ styles: {
141
+ borderRadius: '0.25rem',
142
+ shadow: '0 4px 8px rgba(96, 165, 250, 0.15)',
143
+ gradient: 'none'
144
+ }
145
+ },
146
+
147
+ // ════════════════════════════════════════════════════════════════════════════
148
+ // Rounded Template - Poppins Font + Maximum Roundness
149
+ // ════════════════════════════════════════════════════════════════════════════
150
+ rounded: {
151
+ id: 'rounded',
152
+ name: 'Rounded',
153
+ description: 'Soft and friendly with rounded corners',
154
+ colors: { ...SHARED_COLORS },
155
+ fonts: {
156
+ primary: "'Poppins', 'Nunito', sans-serif",
157
+ code: "'JetBrains Mono', monospace"
158
+ },
159
+ animations: {
160
+ duration: 0.65,
161
+ easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
162
+ fadeIn: 'fadeIn 0.65s cubic-bezier(0.34, 1.56, 0.64, 1)',
163
+ slideUp: 'slideUp 0.65s cubic-bezier(0.34, 1.56, 0.64, 1)'
164
+ },
165
+ styles: {
166
+ borderRadius: '2.5rem',
167
+ shadow: '0 25px 50px rgba(96, 165, 250, 0.3)',
168
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.2), rgba(168, 85, 247, 0.2))'
169
+ }
170
+ },
171
+
172
+ // ════════════════════════════════════════════════════════════════════════════
173
+ // Space Template - Space Grotesk Font + Futuristic
174
+ // ════════════════════════════════════════════════════════════════════════════
175
+ space: {
176
+ id: 'space',
177
+ name: 'Space',
178
+ description: 'Futuristic space-themed design',
179
+ colors: { ...SHARED_COLORS },
180
+ fonts: {
181
+ primary: "'Space Grotesk', 'Orbitron', sans-serif",
182
+ code: "'Space Mono', monospace"
183
+ },
184
+ animations: {
185
+ duration: 0.55,
186
+ easing: 'cubic-bezier(0.19, 1, 0.22, 1)',
187
+ fadeIn: 'fadeIn 0.55s cubic-bezier(0.19, 1, 0.22, 1)',
188
+ slideUp: 'slideUp 0.55s cubic-bezier(0.19, 1, 0.22, 1)'
189
+ },
190
+ styles: {
191
+ borderRadius: '0.75rem',
192
+ shadow: '0 0 20px rgba(96, 165, 250, 0.4), 0 0 40px rgba(168, 85, 247, 0.2)',
193
+ gradient: 'radial-gradient(circle, rgba(96, 165, 250, 0.15), transparent)'
194
+ }
195
+ },
196
+
197
+ // ════════════════════════════════════════════════════════════════════════════
198
+ // Code Template - Developer-Friendly Monospace
199
+ // ════════════════════════════════════════════════════════════════════════════
200
+ code: {
201
+ id: 'code',
202
+ name: 'Code',
203
+ description: 'Developer-friendly monospace design',
204
+ colors: { ...SHARED_COLORS },
205
+ fonts: {
206
+ primary: "'Fira Code', 'Cascadia Code', monospace",
207
+ code: "'JetBrains Mono', 'Source Code Pro', monospace"
208
+ },
209
+ animations: {
210
+ duration: 0.38,
211
+ easing: 'cubic-bezier(0, 0, 0.2, 1)',
212
+ fadeIn: 'fadeIn 0.38s cubic-bezier(0, 0, 0.2, 1)',
213
+ slideUp: 'slideUp 0.38s cubic-bezier(0, 0, 0.2, 1)'
214
+ },
215
+ styles: {
216
+ borderRadius: '0.5rem',
217
+ shadow: '0 8px 24px rgba(96, 165, 250, 0.15)',
218
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.1), rgba(168, 85, 247, 0.1))'
219
+ }
220
+ },
221
+
222
+ // ════════════════════════════════════════════════════════════════════════════
223
+ // Tech Template - Ubuntu Font + Clean Tech Style
224
+ // ════════════════════════════════════════════════════════════════════════════
225
+ tech: {
226
+ id: 'tech',
227
+ name: 'Tech',
228
+ description: 'Clean technical presentation style',
229
+ colors: { ...SHARED_COLORS },
230
+ fonts: {
231
+ primary: "'Ubuntu', 'Roboto', sans-serif",
232
+ code: "'Ubuntu Mono', 'Inconsolata', monospace"
233
+ },
234
+ animations: {
235
+ duration: 0.48,
236
+ easing: 'cubic-bezier(0.25, 0.1, 0.25, 1)',
237
+ fadeIn: 'fadeIn 0.48s cubic-bezier(0.25, 0.1, 0.25, 1)',
238
+ slideUp: 'slideUp 0.48s cubic-bezier(0.25, 0.1, 0.25, 1)'
239
+ },
240
+ styles: {
241
+ borderRadius: '0.5rem',
242
+ shadow: '0 8px 24px rgba(96, 165, 250, 0.15)',
243
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.1), rgba(168, 85, 247, 0.1))'
244
+ }
245
+ },
246
+
247
+ // ════════════════════════════════════════════════════════════════════════════
248
+ // Tech Template - Ubuntu Font + Clean Tech Style
249
+ // ════════════════════════════════════════════════════════════════════════════
250
+ tech: {
251
+ id: 'tech',
252
+ name: 'Tech',
253
+ description: 'Clean technical presentation style',
254
+ colors: { ...SHARED_COLORS },
255
+ fonts: {
256
+ primary: "'Ubuntu', 'Roboto', sans-serif",
257
+ code: "'Ubuntu Mono', 'Inconsolata', monospace"
258
+ },
259
+ animations: {
260
+ duration: 0.72,
261
+ easing: 'cubic-bezier(0.16, 1, 0.3, 1)',
262
+ fadeIn: 'fadeIn 0.72s cubic-bezier(0.16, 1, 0.3, 1)',
263
+ slideUp: 'slideUp 0.72s cubic-bezier(0.16, 1, 0.3, 1)'
264
+ },
265
+ styles: {
266
+ borderRadius: '1rem',
267
+ shadow: '0 20px 40px rgba(96, 165, 250, 0.3)',
268
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.2), rgba(168, 85, 247, 0.2))'
269
+ }
270
+ },
271
+
272
+ // ════════════════════════════════════════════════════════════════════════════
273
+ // Corporate Template - Professional Business Style
274
+ // ════════════════════════════════════════════════════════════════════════════
275
+ corporate: {
276
+ id: 'corporate',
277
+ name: 'Corporate',
278
+ description: 'Professional business presentation',
279
+ colors: { ...SHARED_COLORS },
280
+ fonts: {
281
+ primary: "'Lato', 'Open Sans', sans-serif",
282
+ code: "'Consolas', monospace"
283
+ },
284
+ animations: {
285
+ duration: 0.52,
286
+ easing: 'cubic-bezier(0.45, 0, 0.55, 1)',
287
+ fadeIn: 'fadeIn 0.52s cubic-bezier(0.45, 0, 0.55, 1)',
288
+ slideUp: 'slideUp 0.52s cubic-bezier(0.45, 0, 0.55, 1)'
289
+ },
290
+ styles: {
291
+ borderRadius: '0.5rem',
292
+ shadow: '0 6px 20px rgba(96, 165, 250, 0.2)',
293
+ gradient: 'linear-gradient(180deg, rgba(96, 165, 250, 0.1), transparent)'
294
+ }
295
+ },
296
+
297
+ // ════════════════════════════════════════════════════════════════════════════
298
+ // Display Template - Display Fonts + High Impact
299
+ // ════════════════════════════════════════════════════════════════════════════
300
+ display: {
301
+ id: 'display',
302
+ name: 'Display',
303
+ description: 'Bold display fonts for maximum impact',
304
+ colors: { ...SHARED_COLORS },
305
+ fonts: {
306
+ primary: "'Montserrat', 'Oswald', sans-serif",
307
+ code: "'Inconsolata', monospace"
308
+ },
309
+ animations: {
310
+ duration: 0.72,
311
+ easing: 'cubic-bezier(0.16, 1, 0.3, 1)',
312
+ fadeIn: 'fadeIn 0.72s cubic-bezier(0.16, 1, 0.3, 1)',
313
+ slideUp: 'slideUp 0.72s cubic-bezier(0.16, 1, 0.3, 1)'
314
+ },
315
+ styles: {
316
+ borderRadius: '1rem',
317
+ shadow: '0 20px 40px rgba(96, 165, 250, 0.3)',
318
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.2), rgba(168, 85, 247, 0.2))'
319
+ }
320
+ },
321
+
322
+ // ════════════════════════════════════════════════════════════════════════════
323
+ // Corporate Template - Professional Business Style
324
+ // ════════════════════════════════════════════════════════════════════════════
325
+ corporate: {
326
+ id: 'corporate',
327
+ name: 'Corporate',
328
+ description: 'Professional business presentation',
329
+ colors: { ...SHARED_COLORS },
330
+ fonts: {
331
+ primary: "'Lato', 'Open Sans', sans-serif",
332
+ code: "'Consolas', monospace"
333
+ },
334
+ animations: {
335
+ duration: 0.5,
336
+ easing: 'ease-in-out',
337
+ fadeIn: 'fadeIn 0.5s ease-in-out',
338
+ slideUp: 'slideUp 0.5s ease-in-out'
339
+ },
340
+ styles: {
341
+ borderRadius: '0.5rem',
342
+ shadow: '0 8px 20px rgba(96, 165, 250, 0.15)',
343
+ gradient: 'linear-gradient(135deg, rgba(96, 165, 250, 0.08), rgba(168, 85, 247, 0.08))'
344
+ }
345
+ }
346
+ };
347
+
348
+ // ══════════════════════════════════════════════════════════════════════════════
349
+ // Template Helper Functions
350
+ // ══════════════════════════════════════════════════════════════════════════════
351
+
352
+ export function getTemplate(templateId) {
353
+ return VIDEO_TEMPLATES[templateId] || VIDEO_TEMPLATES.modern;
354
+ }
355
+
356
+ export function getAllTemplates() {
357
+ return Object.values(VIDEO_TEMPLATES);
358
+ }
359
+
360
+ export function applyTemplate(templateId) {
361
+ const template = getTemplate(templateId);
362
+ const root = document.documentElement;
363
+
364
+ // Apply colors as CSS variables
365
+ Object.entries(template.colors).forEach(([key, value]) => {
366
+ root.style.setProperty(`--color-${key}`, value);
367
+ });
368
+
369
+ // Apply fonts
370
+ root.style.setProperty('--font-primary', template.fonts.primary);
371
+ root.style.setProperty('--font-code', template.fonts.code);
372
+
373
+ // Apply animation settings
374
+ root.style.setProperty('--anim-duration', `${template.animations.duration}s`);
375
+ root.style.setProperty('--anim-easing', template.animations.easing);
376
+
377
+ // Apply styles
378
+ root.style.setProperty('--border-radius', template.styles.borderRadius);
379
+ root.style.setProperty('--shadow', template.styles.shadow);
380
+ root.style.setProperty('--gradient', template.styles.gradient);
381
+
382
+ // Apply syntax highlighting colors (if available)
383
+ if (template.syntax) {
384
+ Object.entries(template.syntax).forEach(([key, value]) => {
385
+ root.style.setProperty(`--syntax-${key}`, value);
386
+ });
387
+ }
388
+
389
+ return template;
390
+ }
391
+
392
+ export function generateCSS(template) {
393
+ return `
394
+ :root {
395
+ --color-primary: ${template.colors.primary};
396
+ --color-secondary: ${template.colors.secondary};
397
+ --color-background: ${template.colors.background};
398
+ --color-surface: ${template.colors.surface};
399
+ --color-text: ${template.colors.text};
400
+ --color-text-secondary: ${template.colors.textSecondary};
401
+ --color-accent: ${template.colors.accent};
402
+
403
+ --font-primary: ${template.fonts.primary};
404
+ --font-code: ${template.fonts.code};
405
+
406
+ --anim-duration: ${template.animations.duration}s;
407
+ --anim-easing: ${template.animations.easing};
408
+
409
+ --border-radius: ${template.styles.borderRadius};
410
+ --shadow: ${template.styles.shadow};
411
+ --gradient: ${template.styles.gradient};
412
+ }
413
+
414
+ body {
415
+ font-family: var(--font-primary);
416
+ background-color: var(--color-background);
417
+ color: var(--color-text);
418
+ }
419
+
420
+ .code-block {
421
+ font-family: var(--font-code);
422
+ background: var(--color-surface);
423
+ border-radius: var(--border-radius);
424
+ box-shadow: var(--shadow);
425
+ }
426
+
427
+ .gradient-backdrop {
428
+ background: var(--gradient);
429
+ }
430
+ `;
431
+ }
src/renderer/js/video-renderer.js ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Video Renderer
3
+ // 100% Native Video Rendering Engine - No External Dependencies
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ export class VideoRenderer {
11
+ constructor(options = {}) {
12
+ this.options = {
13
+ width: options.width || 1920,
14
+ height: options.height || 1080,
15
+ fps: options.fps || 60,
16
+ format: options.format || 'webm',
17
+ quality: options.quality || 0.95,
18
+ videoBitsPerSecond: options.videoBitsPerSecond || 8000000, // 8 Mbps
19
+ ...options
20
+ };
21
+
22
+ this.mediaRecorder = null;
23
+ this.recordedChunks = [];
24
+ this.isRecording = false;
25
+ }
26
+
27
+ // ════════════════════════════════════════════════════════════════════════════
28
+ // WebM/MP4 Recording using MediaRecorder API
29
+ // ════════════════════════════════════════════════════════════════════════════
30
+
31
+ async startRecording(element) {
32
+ if (this.isRecording) {
33
+ throw new Error('Recording already in progress');
34
+ }
35
+
36
+ try {
37
+ // Create a canvas to capture the element
38
+ this.canvas = document.createElement('canvas');
39
+ this.canvas.width = this.options.width;
40
+ this.canvas.height = this.options.height;
41
+ this.ctx = this.canvas.getContext('2d', {
42
+ willReadFrequently: true,
43
+ alpha: false
44
+ });
45
+
46
+ // Store element reference
47
+ this.element = element;
48
+
49
+ // Start capturing frames
50
+ this.startFrameCapture();
51
+
52
+ // Get stream from canvas
53
+ const stream = this.canvas.captureStream(this.options.fps);
54
+
55
+ // Determine MIME type
56
+ const mimeType = this.getBestMimeType();
57
+ console.log('[VideoRenderer] Recording with:', mimeType, 'at', this.options.fps, 'fps');
58
+
59
+ // Create MediaRecorder
60
+ this.mediaRecorder = new MediaRecorder(stream, {
61
+ mimeType,
62
+ videoBitsPerSecond: this.options.videoBitsPerSecond
63
+ });
64
+
65
+ this.recordedChunks = [];
66
+
67
+ // Handle data available
68
+ this.mediaRecorder.addEventListener('dataavailable', (event) => {
69
+ if (event.data && event.data.size > 0) {
70
+ this.recordedChunks.push(event.data);
71
+ console.log('[VideoRenderer] Chunk received:', event.data.size, 'bytes');
72
+ }
73
+ });
74
+
75
+ // Start recording
76
+ this.mediaRecorder.start(100); // Collect data every 100ms
77
+ this.isRecording = true;
78
+
79
+ console.log('[VideoRenderer] Recording started successfully');
80
+
81
+ return {
82
+ success: true,
83
+ message: 'Recording started'
84
+ };
85
+ } catch (error) {
86
+ console.error('[VideoRenderer] Error starting recording:', error);
87
+ throw error;
88
+ }
89
+ }
90
+
91
+ startFrameCapture() {
92
+ const captureFrame = () => {
93
+ if (!this.isRecording) {
94
+ return;
95
+ }
96
+
97
+ try {
98
+ // Clear canvas
99
+ this.ctx.fillStyle = '#000000';
100
+ this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
101
+
102
+ // Get element's computed styles
103
+ const styles = window.getComputedStyle(this.element);
104
+
105
+ // Draw background
106
+ if (styles.backgroundColor && styles.backgroundColor !== 'rgba(0, 0, 0, 0)') {
107
+ this.ctx.fillStyle = styles.backgroundColor;
108
+ this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
109
+ }
110
+
111
+ // Render element content using DOM to canvas conversion
112
+ this.renderElementToCanvas(this.element, this.ctx);
113
+
114
+ } catch (error) {
115
+ console.error('[VideoRenderer] Frame capture error:', error);
116
+ }
117
+
118
+ if (this.isRecording) {
119
+ this._frameId = requestAnimationFrame(captureFrame);
120
+ }
121
+ };
122
+
123
+ captureFrame();
124
+ }
125
+
126
+ renderElementToCanvas(element, ctx) {
127
+ // Get all text nodes and render them
128
+ const walker = document.createTreeWalker(
129
+ element,
130
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
131
+ null
132
+ );
133
+
134
+ const texts = [];
135
+ let node;
136
+
137
+ while (node = walker.nextNode()) {
138
+ if (node.nodeType === Node.TEXT_NODE && node.textContent.trim()) {
139
+ const parent = node.parentElement;
140
+ if (parent && parent.offsetParent !== null) {
141
+ const rect = parent.getBoundingClientRect();
142
+ const elementRect = element.getBoundingClientRect();
143
+ const styles = window.getComputedStyle(parent);
144
+
145
+ texts.push({
146
+ text: node.textContent,
147
+ x: rect.left - elementRect.left,
148
+ y: rect.top - elementRect.top,
149
+ width: rect.width,
150
+ height: rect.height,
151
+ font: styles.font || '16px sans-serif',
152
+ color: styles.color || '#ffffff',
153
+ fontSize: styles.fontSize,
154
+ fontFamily: styles.fontFamily,
155
+ fontWeight: styles.fontWeight,
156
+ textAlign: styles.textAlign || 'left',
157
+ lineHeight: parseFloat(styles.lineHeight) || parseFloat(styles.fontSize) * 1.2
158
+ });
159
+ }
160
+ }
161
+ }
162
+
163
+ // Scale factor
164
+ const scaleX = this.canvas.width / element.offsetWidth;
165
+ const scaleY = this.canvas.height / element.offsetHeight;
166
+
167
+ // Render texts
168
+ texts.forEach(item => {
169
+ ctx.save();
170
+ ctx.fillStyle = item.color;
171
+ ctx.font = `${item.fontWeight} ${parseFloat(item.fontSize) * scaleY}px ${item.fontFamily}`;
172
+ ctx.textAlign = item.textAlign;
173
+ ctx.textBaseline = 'top';
174
+
175
+ const x = item.x * scaleX;
176
+ const y = item.y * scaleY + (parseFloat(item.fontSize) * scaleY);
177
+
178
+ ctx.fillText(item.text, x, y);
179
+ ctx.restore();
180
+ });
181
+ }
182
+
183
+ async stopRecording() {
184
+ if (!this.isRecording || !this.mediaRecorder) {
185
+ throw new Error('No recording in progress');
186
+ }
187
+
188
+ return new Promise((resolve, reject) => {
189
+ this.mediaRecorder.addEventListener('stop', () => {
190
+ // Stop frame capture
191
+ if (this._frameId) {
192
+ cancelAnimationFrame(this._frameId);
193
+ this._frameId = null;
194
+ }
195
+
196
+ const blob = new Blob(this.recordedChunks, {
197
+ type: this.mediaRecorder.mimeType
198
+ });
199
+
200
+ this.isRecording = false;
201
+
202
+ console.log('[VideoRenderer] Recording stopped. Total size:', blob.size, 'bytes');
203
+ console.log('[VideoRenderer] Total chunks:', this.recordedChunks.length);
204
+
205
+ resolve({
206
+ success: true,
207
+ blob,
208
+ size: blob.size,
209
+ mimeType: this.mediaRecorder.mimeType,
210
+ url: URL.createObjectURL(blob)
211
+ });
212
+ });
213
+
214
+ this.mediaRecorder.addEventListener('error', (event) => {
215
+ this.isRecording = false;
216
+ if (this._frameId) {
217
+ cancelAnimationFrame(this._frameId);
218
+ this._frameId = null;
219
+ }
220
+ reject(new Error(`Recording error: ${event.error}`));
221
+ });
222
+
223
+ this.mediaRecorder.stop();
224
+ });
225
+ }
226
+
227
+ // ════════════════════════════════════════════════════════════════════════════
228
+ // GIF Rendering using Canvas
229
+ // ════════════════════════════════════════════════════════════════════════════
230
+
231
+ async renderGIF(element, duration, fps = 15) {
232
+ const frames = [];
233
+ const interval = 1000 / fps;
234
+ const totalFrames = Math.ceil((duration / 1000) * fps);
235
+
236
+ // Create canvas for capturing
237
+ const canvas = document.createElement('canvas');
238
+ canvas.width = this.options.width;
239
+ canvas.height = this.options.height;
240
+ const ctx = canvas.getContext('2d');
241
+
242
+ // Capture frames
243
+ for (let i = 0; i < totalFrames; i++) {
244
+ await this.wait(interval);
245
+
246
+ // Draw element to canvas
247
+ await this.drawElementToCanvas(element, canvas, ctx);
248
+
249
+ // Get image data
250
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
251
+ frames.push({
252
+ data: this.quantizeColors(imageData.data, 256),
253
+ width: canvas.width,
254
+ height: canvas.height,
255
+ delay: Math.round(interval / 10) // Delay in 1/100s
256
+ });
257
+ }
258
+
259
+ // Encode GIF
260
+ const gifData = this.encodeGIF(frames);
261
+
262
+ return {
263
+ success: true,
264
+ frames: frames.length,
265
+ data: gifData,
266
+ blob: new Blob([gifData], { type: 'image/gif' })
267
+ };
268
+ }
269
+
270
+ // ════════════════════════════════════════════════════════════════════════════
271
+ // Helper Functions
272
+ // ════════════════════════════════════════════════════════════════════════════
273
+
274
+ getBestMimeType() {
275
+ // Chromium/Electron supports WebM very well, MP4 encoding is not directly supported
276
+ const types = [
277
+ 'video/webm;codecs=vp9,opus',
278
+ 'video/webm;codecs=vp9',
279
+ 'video/webm;codecs=vp8,opus',
280
+ 'video/webm;codecs=vp8',
281
+ 'video/webm'
282
+ ];
283
+
284
+ for (const type of types) {
285
+ if (MediaRecorder.isTypeSupported(type)) {
286
+ console.log('[VideoRenderer] Using MIME type:', type);
287
+ return type;
288
+ }
289
+ }
290
+
291
+ console.warn('[VideoRenderer] No preferred MIME type supported, using default');
292
+ return 'video/webm';
293
+ }
294
+
295
+ async captureElementStream(element) {
296
+ const canvas = document.createElement('canvas');
297
+ canvas.width = this.options.width;
298
+ canvas.height = this.options.height;
299
+ const ctx = canvas.getContext('2d');
300
+
301
+ // Capture frames manually
302
+ const captureFrame = async () => {
303
+ await this.drawElementToCanvas(element, canvas, ctx);
304
+ };
305
+
306
+ const intervalId = setInterval(captureFrame, 1000 / this.options.fps);
307
+
308
+ // Store interval ID for cleanup
309
+ this._captureIntervalId = intervalId;
310
+
311
+ return canvas.captureStream(this.options.fps);
312
+ }
313
+
314
+ async drawElementToCanvas(element, canvas, ctx) {
315
+ // Use html2canvas-like approach
316
+ const rect = element.getBoundingClientRect();
317
+
318
+ // Clear canvas
319
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
320
+
321
+ // Draw background
322
+ ctx.fillStyle = window.getComputedStyle(element).backgroundColor || '#000';
323
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
324
+
325
+ // For simplicity, we'll use drawImage if element is video/canvas
326
+ // For other elements, we'd need to serialize to SVG
327
+ if (element.tagName === 'CANVAS' || element.tagName === 'VIDEO') {
328
+ ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
329
+ } else {
330
+ // Serialize element to data URL and draw
331
+ const data = await this.elementToDataURL(element);
332
+ const img = new Image();
333
+ await new Promise((resolve, reject) => {
334
+ img.onload = resolve;
335
+ img.onerror = reject;
336
+ img.src = data;
337
+ });
338
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
339
+ }
340
+ }
341
+
342
+ async elementToDataURL(element) {
343
+ // Create SVG foreignObject
344
+ const rect = element.getBoundingClientRect();
345
+ const svg = `
346
+ <svg xmlns="http://www.w3.org/2000/svg" width="${rect.width}" height="${rect.height}">
347
+ <foreignObject width="100%" height="100%">
348
+ <div xmlns="http://www.w3.org/1999/xhtml">
349
+ ${element.outerHTML}
350
+ </div>
351
+ </foreignObject>
352
+ </svg>
353
+ `;
354
+
355
+ const blob = new Blob([svg], { type: 'image/svg+xml' });
356
+ return URL.createObjectURL(blob);
357
+ }
358
+
359
+ // ════════════════════════════════════════════════════════════════════════════
360
+ // GIF Encoding (Simplified LZW Compression)
361
+ // ════════════════════════════════════════════════════════════════════════════
362
+
363
+ encodeGIF(frames) {
364
+ const { width, height } = frames[0];
365
+
366
+ // GIF Header
367
+ const header = this.stringToBytes('GIF89a');
368
+
369
+ // Logical Screen Descriptor
370
+ const lsd = new Uint8Array(7);
371
+ lsd[0] = width & 0xFF;
372
+ lsd[1] = (width >> 8) & 0xFF;
373
+ lsd[2] = height & 0xFF;
374
+ lsd[3] = (height >> 8) & 0xFF;
375
+ lsd[4] = 0xF7; // Global Color Table Flag
376
+ lsd[5] = 0x00; // Background Color Index
377
+ lsd[6] = 0x00; // Pixel Aspect Ratio
378
+
379
+ // Global Color Table (256 colors)
380
+ const gct = this.generateColorTable(256);
381
+
382
+ // Application Extension (for looping)
383
+ const appExt = new Uint8Array([
384
+ 0x21, 0xFF, 0x0B,
385
+ ...this.stringToBytes('NETSCAPE2.0'),
386
+ 0x03, 0x01, 0x00, 0x00, 0x00
387
+ ]);
388
+
389
+ const frameData = [];
390
+
391
+ for (const frame of frames) {
392
+ // Graphics Control Extension
393
+ const gce = new Uint8Array([
394
+ 0x21, 0xF9, 0x04,
395
+ 0x04, // Disposal method
396
+ frame.delay & 0xFF, (frame.delay >> 8) & 0xFF,
397
+ 0x00, // Transparent color index
398
+ 0x00
399
+ ]);
400
+
401
+ // Image Descriptor
402
+ const imgDesc = new Uint8Array(10);
403
+ imgDesc[0] = 0x2C; // Image separator
404
+ imgDesc[1] = 0x00; imgDesc[2] = 0x00; // Left
405
+ imgDesc[3] = 0x00; imgDesc[4] = 0x00; // Top
406
+ imgDesc[5] = width & 0xFF; imgDesc[6] = (width >> 8) & 0xFF;
407
+ imgDesc[7] = height & 0xFF; imgDesc[8] = (height >> 8) & 0xFF;
408
+ imgDesc[9] = 0x00; // Packed fields
409
+
410
+ // Image Data (simplified - use minimal compression)
411
+ const imageData = this.compressImageData(frame.data);
412
+
413
+ frameData.push(...gce, ...imgDesc, ...imageData);
414
+ }
415
+
416
+ // Trailer
417
+ const trailer = new Uint8Array([0x3B]);
418
+
419
+ // Combine all parts
420
+ return new Uint8Array([
421
+ ...header,
422
+ ...lsd,
423
+ ...gct,
424
+ ...appExt,
425
+ ...frameData,
426
+ ...trailer
427
+ ]);
428
+ }
429
+
430
+ generateColorTable(size) {
431
+ const table = new Uint8Array(size * 3);
432
+ for (let i = 0; i < size; i++) {
433
+ table[i * 3] = i;
434
+ table[i * 3 + 1] = i;
435
+ table[i * 3 + 2] = i;
436
+ }
437
+ return table;
438
+ }
439
+
440
+ quantizeColors(imageData, colorCount) {
441
+ // Simple color quantization
442
+ const quantized = new Uint8Array(imageData.length / 4);
443
+ for (let i = 0; i < imageData.length; i += 4) {
444
+ const r = imageData[i];
445
+ const g = imageData[i + 1];
446
+ const b = imageData[i + 2];
447
+ const gray = Math.floor(0.299 * r + 0.587 * g + 0.114 * b);
448
+ quantized[i / 4] = Math.floor(gray * (colorCount - 1) / 255);
449
+ }
450
+ return quantized;
451
+ }
452
+
453
+ compressImageData(data) {
454
+ // Minimal LZW compression (simplified)
455
+ const lzwMinCodeSize = 8;
456
+ const compressed = [lzwMinCodeSize];
457
+
458
+ // Simple run-length encoding as fallback
459
+ const blocks = [];
460
+ let currentBlock = [];
461
+
462
+ for (let i = 0; i < data.length; i++) {
463
+ currentBlock.push(data[i]);
464
+ if (currentBlock.length === 255) {
465
+ blocks.push(currentBlock.length, ...currentBlock);
466
+ currentBlock = [];
467
+ }
468
+ }
469
+
470
+ if (currentBlock.length > 0) {
471
+ blocks.push(currentBlock.length, ...currentBlock);
472
+ }
473
+
474
+ blocks.push(0); // Block terminator
475
+
476
+ return new Uint8Array([...compressed, ...blocks]);
477
+ }
478
+
479
+ stringToBytes(str) {
480
+ return new Uint8Array([...str].map(c => c.charCodeAt(0)));
481
+ }
482
+
483
+ wait(ms) {
484
+ return new Promise(resolve => setTimeout(resolve, ms));
485
+ }
486
+
487
+ // ════════════════════════════════════════════════════════════════════════════
488
+ // Cleanup
489
+ // ════════════════════════════════════════════════════════════════════════════
490
+
491
+ cleanup() {
492
+ if (this._captureIntervalId) {
493
+ clearInterval(this._captureIntervalId);
494
+ this._captureIntervalId = null;
495
+ }
496
+
497
+ if (this.mediaRecorder && this.isRecording) {
498
+ this.mediaRecorder.stop();
499
+ }
500
+
501
+ this.recordedChunks = [];
502
+ this.mediaRecorder = null;
503
+ this.isRecording = false;
504
+ }
505
+ }
506
+
507
+ // ══════════════════════════════════════════════════════════════════════════════
508
+ // Export Format Helpers
509
+ // ══════════════════════════════════════════════════════════════════════════════
510
+
511
+ export function blobToBase64(blob) {
512
+ return new Promise((resolve, reject) => {
513
+ const reader = new FileReader();
514
+ reader.onloadend = () => resolve(reader.result);
515
+ reader.onerror = reject;
516
+ reader.readAsDataURL(blob);
517
+ });
518
+ }
519
+
520
+ export function downloadBlob(blob, filename) {
521
+ const url = URL.createObjectURL(blob);
522
+ const a = document.createElement('a');
523
+ a.href = url;
524
+ a.download = filename;
525
+ document.body.appendChild(a);
526
+ a.click();
527
+ document.body.removeChild(a);
528
+ URL.revokeObjectURL(url);
529
+ }
src/renderer/vendor/tailwind.js ADDED
The diff for this file is too large to render. See raw diff
 
src/shared/README.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared Modules
2
+
3
+ This folder contains modules used by both main and renderer processes.
4
+
5
+ ## Files
6
+
7
+ ### security-core.js
8
+ Enterprise-grade security system with comprehensive protection.
9
+
10
+ ## Features
11
+
12
+ ### 1. Input Validation
13
+ - Path traversal detection
14
+ - Malicious pattern checking
15
+ - Length validation
16
+
17
+ ### 2. Path Safety
18
+ - Forbidden directory protection (Windows, System, etc.)
19
+ - Whitelist validation
20
+ - Workspace folder support
21
+
22
+ ### 3. Symlink Protection
23
+ - Symlink detection
24
+ - Circular reference prevention
25
+ - Depth limiting
26
+
27
+ ### 4. File Validation
28
+ - Extension whitelist
29
+ - Size limits (min/max)
30
+ - Content verification
31
+
32
+ ### 5. Integrity Verification
33
+ - SHA-256 hash calculation
34
+ - File tampering detection
35
+ - Cache management
36
+
37
+ ### 6. Rate Limiting
38
+ - Operation throttling
39
+ - Time-window based limits
40
+ - Abuse prevention
41
+
42
+ ### 7. ReDoS Protection
43
+ - Regex timeout enforcement
44
+ - Pattern execution monitoring
45
+ - Safe regex execution
46
+
47
+ ## Usage
48
+
49
+ ```javascript
50
+ import { SecurityManager } from './security-core.js';
51
+
52
+ const security = new SecurityManager({
53
+ MAX_FILE_SIZE: 10 * 1024 * 1024,
54
+ ALLOWED_EXTENSIONS: ['.js', '.ts', '.py'],
55
+ EXTRA_ALLOWED_DIRS: ['/path/to/allowed/dir']
56
+ });
57
+
58
+ // Validate and read file
59
+ const result = await security.secureReadFile(filePath);
60
+
61
+ // Get statistics
62
+ const stats = security.getSecurityStats();
63
+
64
+ // Export audit log
65
+ const log = security.exportSecurityLog();
66
+ ```
67
+
68
+ ## Custom Error Classes
69
+
70
+ - `SecurityError` - Base security error
71
+ - `PathTraversalError` - Path attack detected
72
+ - `SymlinkError` - Symlink violation
73
+ - `FileValidationError` - File validation failed
74
+ - `ReDoSError` - Regex timeout
75
+ - `RateLimitError` - Rate limit exceeded
76
+
77
+ ## Configuration
78
+
79
+ All security settings are configurable:
80
+
81
+ ```javascript
82
+ const SECURITY_CONFIG = {
83
+ MAX_PATH_LENGTH: 260,
84
+ MAX_FILE_SIZE: 10 * 1024 * 1024,
85
+ ALLOWED_EXTENSIONS: [...],
86
+ FORBIDDEN_PATHS: [...],
87
+ MAX_OPERATIONS_PER_MINUTE: 500,
88
+ // ... more settings
89
+ };
90
+ ```
91
+
92
+ ## Adding New Validations
93
+
94
+ 1. Create validation method in SecurityManager class
95
+ 2. Add to validateFile() pipeline
96
+ 3. Add custom error class if needed
97
+ 4. Update configuration
src/shared/content-fingerprint.js ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Content Fingerprinting System
3
+ *
4
+ * สร้าง unique identifier สำหรับแต่ละบรรทัดเนื้อหา
5
+ * ใช้ในการจับคู่การตั้งค่า (position, edits) กับเนื้อหา
6
+ * แม้ว่าจะมีการเพิ่ม/ลบเนื้อหาอื่นในไฟล์
7
+ *
8
+ * @author Chahua Development Co., Ltd.
9
+ * @version 2.1.0
10
+ */
11
+
12
+ export class ContentFingerprint {
13
+ /**
14
+ * สร้าง fingerprint จากเนื้อหาและ metadata
15
+ *
16
+ * @param {HTMLElement} element - Element ที่ต้องการสร้าง fingerprint
17
+ * @returns {string} - Unique fingerprint string
18
+ */
19
+ static generate(element) {
20
+ if (!element) return null;
21
+
22
+ const tag = element.tagName.toLowerCase();
23
+ const text = element.textContent.trim();
24
+
25
+ // ใช้ 80 ตัวอักษรแรกเพื่อความแม่นยำสูง
26
+ const contentPreview = text.substring(0, 80);
27
+
28
+ // สร้าง fingerprint จาก tag + content + length
29
+ const fingerprint = `${tag}:${contentPreview}:${text.length}`;
30
+
31
+ // สร้าง hash แบบง่าย
32
+ return this.simpleHash(fingerprint);
33
+ }
34
+
35
+ /**
36
+ * สร้าง stable fingerprint ที่ไม่เปลี่ยนแปลงง่าย
37
+ * เหมาะสำหรับการเก็บ settings ระยะยาว
38
+ *
39
+ * @param {HTMLElement} element
40
+ * @returns {Object} - Fingerprint object with multiple identifiers
41
+ */
42
+ static generateStable(element) {
43
+ if (!element) return null;
44
+
45
+ const tag = element.tagName.toLowerCase();
46
+ const text = element.textContent.trim();
47
+
48
+ // Primary: hash ของ 80 ตัวแรก
49
+ const primary = this.generate(element);
50
+
51
+ // Secondary: hash ของ 30 ตัวแรก (partial match)
52
+ const partialText = text.substring(0, 30);
53
+ const secondary = this.simpleHash(`${tag}:${partialText}`);
54
+
55
+ // Tertiary: hash จาก pattern (ใช้ได้กับข้อความที่มี structure คล้ายกัน)
56
+ const pattern = this.extractPattern(text);
57
+ const tertiary = this.simpleHash(`${tag}:${pattern}`);
58
+
59
+ return {
60
+ primary, // ความแม่นยำสูงสุด
61
+ secondary, // ทนต่อการแก้ไขเล็กน้อย
62
+ tertiary, // ทนต่อการเปลี่ยนแปลงมาก
63
+ tag,
64
+ length: text.length,
65
+ preview: text.substring(0, 50)
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Extract pattern จากข้อความ
71
+ * เช่น "Item 1" -> "Item #"
72
+ *
73
+ * @param {string} text
74
+ * @returns {string}
75
+ */
76
+ static extractPattern(text) {
77
+ return text
78
+ .replace(/\d+/g, '#') // เลข -> #
79
+ .replace(/[a-zA-Z]{4,}/g, 'W') // คำยาว -> W
80
+ .substring(0, 40); // เอาแค่ 40 ตัวแรก
81
+ }
82
+
83
+ /**
84
+ * Simple hash function (DJB2 algorithm)
85
+ *
86
+ * @param {string} str
87
+ * @returns {string} - Hex hash string
88
+ */
89
+ static simpleHash(str) {
90
+ let hash = 5381;
91
+ for (let i = 0; i < str.length; i++) {
92
+ hash = ((hash << 5) + hash) + str.charCodeAt(i);
93
+ hash = hash & hash; // Convert to 32bit integer
94
+ }
95
+ return Math.abs(hash).toString(36); // Base36 สั้นกว่า hex
96
+ }
97
+
98
+ /**
99
+ * จับคู่ fingerprint กับ settings ที่บันทึกไว้
100
+ * รองรับการ match แบบ fuzzy
101
+ *
102
+ * @param {Object} stableFingerprint - จาก generateStable()
103
+ * @param {Array} savedSettings - Array of saved setting objects
104
+ * @returns {Object|null} - Matched setting หรือ null
105
+ */
106
+ static match(stableFingerprint, savedSettings) {
107
+ if (!stableFingerprint || !savedSettings || !savedSettings.length) {
108
+ return null;
109
+ }
110
+
111
+ // 1. ลอง match primary (exact match)
112
+ let matched = savedSettings.find(s =>
113
+ s.fingerprint?.primary === stableFingerprint.primary
114
+ );
115
+ if (matched) {
116
+ matched.matchConfidence = 'exact';
117
+ return matched;
118
+ }
119
+
120
+ // 2. ลอง match secondary (partial match)
121
+ matched = savedSettings.find(s =>
122
+ s.fingerprint?.secondary === stableFingerprint.secondary &&
123
+ s.fingerprint?.tag === stableFingerprint.tag
124
+ );
125
+ if (matched) {
126
+ matched.matchConfidence = 'high';
127
+ return matched;
128
+ }
129
+
130
+ // 3. ลอง match tertiary (pattern match)
131
+ matched = savedSettings.find(s =>
132
+ s.fingerprint?.tertiary === stableFingerprint.tertiary &&
133
+ s.fingerprint?.tag === stableFingerprint.tag
134
+ );
135
+ if (matched) {
136
+ matched.matchConfidence = 'medium';
137
+ return matched;
138
+ }
139
+
140
+ // 4. ลอง match โดยดูจาก tag + length (คล้ายกัน)
141
+ matched = savedSettings.find(s =>
142
+ s.fingerprint?.tag === stableFingerprint.tag &&
143
+ Math.abs(s.fingerprint?.length - stableFingerprint.length) < 10
144
+ );
145
+ if (matched) {
146
+ matched.matchConfidence = 'low';
147
+ return matched;
148
+ }
149
+
150
+ return null;
151
+ }
152
+
153
+ /**
154
+ * สร้าง fingerprint สำหรับทั้ง slide
155
+ * ใช้ detect ว่ามีการเปลี่ยนแปลงเนื้อหาหรือไม่
156
+ *
157
+ * @param {HTMLElement} sceneElement
158
+ * @returns {string}
159
+ */
160
+ static generateSlideFingerprint(sceneElement) {
161
+ if (!sceneElement) return null;
162
+
163
+ const elements = sceneElement.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote');
164
+ const fingerprints = Array.from(elements).map(el => this.generate(el));
165
+
166
+ return this.simpleHash(fingerprints.join('|'));
167
+ }
168
+
169
+ /**
170
+ * เปรียบเทียบว่า slide เปลี่ยนแปลงหรือไม่
171
+ *
172
+ * @param {string} oldFingerprint
173
+ * @param {string} newFingerprint
174
+ * @returns {boolean}
175
+ */
176
+ static hasSlideChanged(oldFingerprint, newFingerprint) {
177
+ return oldFingerprint !== newFingerprint;
178
+ }
179
+
180
+ /**
181
+ * สร้าง element mapping สำหรับทั้ง slide
182
+ * เพื่อใช้ในการ apply settings
183
+ *
184
+ * @param {HTMLElement} sceneElement
185
+ * @returns {Array} - Array of {element, fingerprint, index}
186
+ */
187
+ static mapSlideElements(sceneElement) {
188
+ if (!sceneElement) return [];
189
+
190
+ const elements = sceneElement.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote');
191
+
192
+ return Array.from(elements).map((element, index) => ({
193
+ element,
194
+ fingerprint: this.generateStable(element),
195
+ index,
196
+ tag: element.tagName.toLowerCase()
197
+ }));
198
+ }
199
+
200
+ /**
201
+ * Validate fingerprint object
202
+ *
203
+ * @param {Object} fingerprint
204
+ * @returns {boolean}
205
+ */
206
+ static isValid(fingerprint) {
207
+ return fingerprint &&
208
+ fingerprint.primary &&
209
+ fingerprint.secondary &&
210
+ fingerprint.tertiary &&
211
+ fingerprint.tag;
212
+ }
213
+
214
+ /**
215
+ * สร้าง debug info สำหรับ fingerprint
216
+ *
217
+ * @param {Object} fingerprint
218
+ * @returns {string}
219
+ */
220
+ static debug(fingerprint) {
221
+ if (!fingerprint) return 'null';
222
+
223
+ return `
224
+ Fingerprint Debug:
225
+ - Primary: ${fingerprint.primary}
226
+ - Secondary: ${fingerprint.secondary}
227
+ - Tertiary: ${fingerprint.tertiary}
228
+ - Tag: ${fingerprint.tag}
229
+ - Length: ${fingerprint.length}
230
+ - Preview: "${fingerprint.preview}"
231
+ `.trim();
232
+ }
233
+ }
234
+
235
+ // Export เป็น named export
236
+ export default ContentFingerprint;
src/shared/layout-schema.js ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Markdown Presenter - Layout Schema & Tree Builder
3
+ // Converts parsed markdown slides into structured presentation layout blocks
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ const LayoutNodeKind = {
11
+ SLIDE: 'slide',
12
+ SECTION: 'section',
13
+ HEADING: 'heading',
14
+ TEXT: 'text',
15
+ LIST: 'list',
16
+ CODE: 'code',
17
+ TABLE: 'table',
18
+ CALLOUT: 'callout',
19
+ IMAGE: 'image',
20
+ DIVIDER: 'divider',
21
+ HTML: 'html',
22
+ LINK: 'link'
23
+ };
24
+
25
+ const ListKind = {
26
+ UNORDERED: 'unordered',
27
+ ORDERED: 'ordered',
28
+ TASK: 'task'
29
+ };
30
+
31
+ let layoutIdCounter = 0;
32
+ function nextLayoutId(prefix) {
33
+ layoutIdCounter += 1;
34
+ return `${prefix}-${layoutIdCounter}`;
35
+ }
36
+
37
+ const HEADING_LINE_WEIGHTS = {
38
+ 1: 3.2,
39
+ 2: 2.6,
40
+ 3: 2,
41
+ 4: 1.6,
42
+ 5: 1.4,
43
+ 6: 1.2
44
+ };
45
+
46
+ function estimateTextLines(text) {
47
+ if (!text) return 1;
48
+ const words = text.trim().split(/\s+/).length;
49
+ return Math.max(1, Math.ceil(words / 12));
50
+ }
51
+
52
+ function estimateListLines(items) {
53
+ if (!items || items.length === 0) return 0;
54
+ return items.reduce((sum, item) => sum + Math.max(1.1, estimateTextLines(item.text) * 0.85), 0);
55
+ }
56
+
57
+ function estimateBlockLines(block) {
58
+ switch (block.kind) {
59
+ case LayoutNodeKind.HEADING:
60
+ return HEADING_LINE_WEIGHTS[block.level] || 2.4;
61
+ case LayoutNodeKind.TEXT:
62
+ return estimateTextLines(block.text);
63
+ case LayoutNodeKind.LIST:
64
+ return estimateListLines(block.items) + 0.5;
65
+ case LayoutNodeKind.CODE: {
66
+ const lines = block.content.split('\n').length;
67
+ return Math.min(12, lines + 1.5);
68
+ }
69
+ case LayoutNodeKind.TABLE: {
70
+ const rows = block.rows ? block.rows.length : 0;
71
+ return 2.5 + rows * 0.8;
72
+ }
73
+ case LayoutNodeKind.CALLOUT:
74
+ return Math.max(2, estimateTextLines(block.text) * 1.2);
75
+ case LayoutNodeKind.IMAGE:
76
+ return 4.5;
77
+ case LayoutNodeKind.DIVIDER:
78
+ return 0.5;
79
+ case LayoutNodeKind.HTML:
80
+ return 3;
81
+ case LayoutNodeKind.LINK:
82
+ return Math.max(1, estimateTextLines(block.text));
83
+ default:
84
+ return 1;
85
+ }
86
+ }
87
+
88
+ function createHeadingBlock(level, text, html = null) {
89
+ const normalizedLevel = Math.min(Math.max(level || 1, 1), 6);
90
+ const block = {
91
+ id: nextLayoutId('block'),
92
+ kind: LayoutNodeKind.HEADING,
93
+ level: normalizedLevel,
94
+ text: text || '',
95
+ html: html || null
96
+ };
97
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
98
+ return block;
99
+ }
100
+
101
+ function createSectionFromHeading(headingItem, fallbackTitle, fallbackLevel = 2) {
102
+ const level = headingItem ? parseInt(headingItem.type.replace('h', ''), 10) || fallbackLevel : fallbackLevel;
103
+ const title = headingItem ? headingItem.content : fallbackTitle;
104
+
105
+ const section = {
106
+ id: nextLayoutId('section'),
107
+ kind: LayoutNodeKind.SECTION,
108
+ level,
109
+ title: title || fallbackTitle || '',
110
+ heading: headingItem || null,
111
+ blocks: [],
112
+ metrics: {
113
+ estimatedLines: 0
114
+ }
115
+ };
116
+
117
+ const headingText = title || fallbackTitle || '';
118
+ if (headingText) {
119
+ const headingBlock = createHeadingBlock(level, headingText, headingItem?.html || null);
120
+ section.blocks.push(headingBlock);
121
+ section.metrics.estimatedLines += headingBlock.metrics.estimatedLines;
122
+ }
123
+
124
+ return section;
125
+ }
126
+
127
+ function createTextBlock(text, html = null) {
128
+ const block = {
129
+ id: nextLayoutId('block'),
130
+ kind: LayoutNodeKind.TEXT,
131
+ text,
132
+ html: html || null
133
+ };
134
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
135
+ return block;
136
+ }
137
+
138
+ function createListBlock(listType) {
139
+ const block = {
140
+ id: nextLayoutId('block'),
141
+ kind: LayoutNodeKind.LIST,
142
+ listType,
143
+ items: []
144
+ };
145
+ block.metrics = { estimatedLines: 0 };
146
+ return block;
147
+ }
148
+
149
+ function createCodeBlock(item) {
150
+ const block = {
151
+ id: nextLayoutId('block'),
152
+ kind: LayoutNodeKind.CODE,
153
+ language: item.language || 'text',
154
+ content: item.content
155
+ };
156
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
157
+ return block;
158
+ }
159
+
160
+ function createTableBlock(item) {
161
+ const block = {
162
+ id: nextLayoutId('block'),
163
+ kind: LayoutNodeKind.TABLE,
164
+ rows: item.rows || []
165
+ };
166
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
167
+ return block;
168
+ }
169
+
170
+ function createCalloutBlock(item) {
171
+ const block = {
172
+ id: nextLayoutId('block'),
173
+ kind: LayoutNodeKind.CALLOUT,
174
+ text: item.content,
175
+ level: item.level || 1,
176
+ html: item.html || null
177
+ };
178
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
179
+ return block;
180
+ }
181
+
182
+ function createImageBlock(item) {
183
+ const block = {
184
+ id: nextLayoutId('block'),
185
+ kind: LayoutNodeKind.IMAGE,
186
+ src: item.src,
187
+ alt: item.alt || '',
188
+ title: item.title || ''
189
+ };
190
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
191
+ return block;
192
+ }
193
+
194
+ function createDividerBlock() {
195
+ const block = {
196
+ id: nextLayoutId('block'),
197
+ kind: LayoutNodeKind.DIVIDER
198
+ };
199
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
200
+ return block;
201
+ }
202
+
203
+ function createHtmlBlock(item) {
204
+ const block = {
205
+ id: nextLayoutId('block'),
206
+ kind: LayoutNodeKind.HTML,
207
+ html: item.html || item.content
208
+ };
209
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
210
+ return block;
211
+ }
212
+
213
+ function createLinkBlock(item) {
214
+ const block = {
215
+ id: nextLayoutId('block'),
216
+ kind: LayoutNodeKind.LINK,
217
+ text: item.text || item.content || '',
218
+ href: item.url || item.href || '',
219
+ title: item.title || '',
220
+ html: item.html || null
221
+ };
222
+ block.metrics = { estimatedLines: estimateBlockLines(block) };
223
+ return block;
224
+ }
225
+
226
+ function appendBlockToSection(section, block) {
227
+ section.blocks.push(block);
228
+ section.metrics.estimatedLines += block.metrics.estimatedLines;
229
+ }
230
+
231
+ function appendListItem(block, item) {
232
+ block.items.push({
233
+ id: nextLayoutId('listitem'),
234
+ text: item.content,
235
+ marker: item.marker || null,
236
+ number: item.number || null,
237
+ checked: !!item.checked,
238
+ html: item.html || null
239
+ });
240
+ block.metrics.estimatedLines = estimateBlockLines(block);
241
+ }
242
+
243
+ function resolveListType(itemType) {
244
+ if (itemType === 'numbered-item') return ListKind.ORDERED;
245
+ if (itemType === 'task-list') return ListKind.TASK;
246
+ return ListKind.UNORDERED;
247
+ }
248
+
249
+ function addItemToSection(section, item) {
250
+ switch (item.type) {
251
+ case 'text': {
252
+ const lastBlock = section.blocks[section.blocks.length - 1];
253
+ if (lastBlock && lastBlock.kind === LayoutNodeKind.TEXT) {
254
+ const previousLines = lastBlock.metrics.estimatedLines;
255
+ lastBlock.text = `${lastBlock.text}\n\n${item.content}`;
256
+ if (item.html) {
257
+ const joiner = lastBlock.html ? '<br><br>' : '';
258
+ lastBlock.html = lastBlock.html ? `${lastBlock.html}${joiner}${item.html}` : item.html;
259
+ }
260
+ lastBlock.metrics.estimatedLines = estimateBlockLines(lastBlock);
261
+ section.metrics.estimatedLines += (lastBlock.metrics.estimatedLines - previousLines);
262
+ } else {
263
+ appendBlockToSection(section, createTextBlock(item.content, item.html || null));
264
+ }
265
+ break;
266
+ }
267
+ case 'list-item':
268
+ case 'numbered-item':
269
+ case 'task-list': {
270
+ const listType = resolveListType(item.type);
271
+ let listBlock = section.blocks[section.blocks.length - 1];
272
+ if (!listBlock || listBlock.kind !== LayoutNodeKind.LIST || listBlock.listType !== listType) {
273
+ listBlock = createListBlock(listType);
274
+ appendBlockToSection(section, listBlock);
275
+ }
276
+ const previousLines = listBlock.metrics.estimatedLines;
277
+ appendListItem(listBlock, item);
278
+ section.metrics.estimatedLines += (listBlock.metrics.estimatedLines - previousLines);
279
+ break;
280
+ }
281
+ case 'code':
282
+ appendBlockToSection(section, createCodeBlock(item));
283
+ break;
284
+ case 'table':
285
+ appendBlockToSection(section, createTableBlock(item));
286
+ break;
287
+ case 'blockquote':
288
+ appendBlockToSection(section, createCalloutBlock(item));
289
+ break;
290
+ case 'image':
291
+ appendBlockToSection(section, createImageBlock(item));
292
+ break;
293
+ case 'hr':
294
+ appendBlockToSection(section, createDividerBlock());
295
+ break;
296
+ case 'html':
297
+ appendBlockToSection(section, createHtmlBlock(item));
298
+ break;
299
+ case 'link':
300
+ appendBlockToSection(section, createLinkBlock(item));
301
+ break;
302
+ default:
303
+ appendBlockToSection(section, createTextBlock(item.content || '', item.html || null));
304
+ break;
305
+ }
306
+ }
307
+
308
+ export function buildLayoutTreeForSlide(slide) {
309
+ const root = {
310
+ id: nextLayoutId('slide'),
311
+ kind: LayoutNodeKind.SLIDE,
312
+ title: slide.title || '',
313
+ subtitle: slide.subtitle || '',
314
+ sections: [],
315
+ metrics: {
316
+ estimatedLines: 0
317
+ }
318
+ };
319
+
320
+ let currentSection = null;
321
+
322
+ const ensureSection = (headingItem = null) => {
323
+ if (headingItem) {
324
+ currentSection = createSectionFromHeading(headingItem, slide.title);
325
+ root.sections.push(currentSection);
326
+ } else if (!currentSection) {
327
+ currentSection = createSectionFromHeading(null, slide.title || '');
328
+ root.sections.push(currentSection);
329
+ }
330
+ return currentSection;
331
+ };
332
+
333
+ const contentItems = Array.isArray(slide.content) ? slide.content : [];
334
+ for (const item of contentItems) {
335
+ if (item.type && /^h[1-6]$/.test(item.type)) {
336
+ ensureSection(item);
337
+ continue;
338
+ }
339
+
340
+ ensureSection();
341
+ addItemToSection(currentSection, item);
342
+ }
343
+
344
+ if (root.sections.length === 0) {
345
+ currentSection = createSectionFromHeading(null, slide.title || 'Overview');
346
+ root.sections.push(currentSection);
347
+ if (contentItems.length === 0 && slide.subtitle) {
348
+ appendBlockToSection(currentSection, createTextBlock(slide.subtitle));
349
+ }
350
+ }
351
+
352
+ root.metrics.estimatedLines = root.sections.reduce((sum, section) => {
353
+ return sum + (section.metrics?.estimatedLines || 0);
354
+ }, 0);
355
+
356
+ return root;
357
+ }
358
+
359
+ export {
360
+ LayoutNodeKind,
361
+ ListKind,
362
+ estimateBlockLines
363
+ };
src/shared/markdown-parser.js ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Markdown Presenter - Markdown Parser
3
+ // Parse Markdown into Presentation Slides
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+ // Company: Chahua Development Co., Ltd.
6
+ // Version: 2.0.0
7
+ // License: MIT
8
+ // ══════════════════════════════════════════════════════════════════════════════
9
+
10
+ import { MarkdownSyntax, detectBlockType, parseInline } from './markdown-syntax.js';
11
+ import { applyPagination, getPaginationInfo } from './slide-paginator.js';
12
+
13
+ export class MarkdownParser {
14
+ constructor(options = {}) {
15
+ this.options = {
16
+ slideBreak: options.slideBreak || '---', // Horizontal rule for slide breaks
17
+ h1AsSlide: options.h1AsSlide !== false, // # creates new slide
18
+ h2AsSlide: options.h2AsSlide || false, // ## creates new slide
19
+ enablePagination: options.enablePagination !== false, // Auto-split long slides
20
+ maxLinesPerSlide: options.maxLinesPerSlide || 8, // Max visual lines per slide
21
+ ...options
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Parse markdown text into slides
27
+ * @param {string} markdown - Raw markdown text
28
+ * @returns {Array} Array of slide objects
29
+ */
30
+ parse(markdown) {
31
+ if (!markdown || typeof markdown !== 'string') {
32
+ throw new Error('Invalid markdown input');
33
+ }
34
+
35
+ // Split by slide breaks (---)
36
+ const rawSlides = this.splitIntoSlides(markdown);
37
+
38
+ // Parse each slide
39
+ const slides = rawSlides.map((slideText, index) => {
40
+ return this.parseSlide(slideText, index);
41
+ });
42
+
43
+ // Filter empty slides
44
+ const nonEmptySlides = slides.filter(slide => slide.content.length > 0);
45
+
46
+ // Apply pagination if enabled
47
+ if (this.options.enablePagination) {
48
+ const paginatedSlides = [];
49
+ let globalIndex = 0;
50
+
51
+ for (const slide of nonEmptySlides) {
52
+ const pages = applyPagination(slide);
53
+
54
+ // Update indices
55
+ pages.forEach((page, pageIndex) => {
56
+ page.index = globalIndex++;
57
+ page.originalIndex = slide.index;
58
+ paginatedSlides.push(page);
59
+ });
60
+ }
61
+
62
+ return paginatedSlides;
63
+ }
64
+
65
+ return nonEmptySlides;
66
+ }
67
+
68
+ /**
69
+ * Split markdown into slides based on rules
70
+ */
71
+ splitIntoSlides(markdown) {
72
+ const slides = [];
73
+ let currentSlide = [];
74
+ const lines = markdown.split('\n');
75
+
76
+ // Skip frontmatter block if present
77
+ let startIndex = 0;
78
+ if (lines[0] && lines[0].trim() === '---') {
79
+ // Find closing ---
80
+ for (let i = 1; i < Math.min(lines.length, 50); i++) {
81
+ if (lines[i].trim() === '---') {
82
+ startIndex = i + 1;
83
+ break;
84
+ }
85
+ }
86
+ }
87
+
88
+ for (let i = startIndex; i < lines.length; i++) {
89
+ const line = lines[i];
90
+ const trimmed = line.trim();
91
+
92
+ // Check for slide break (---)
93
+ if (trimmed === '---' || trimmed === '___' || trimmed === '***') {
94
+ if (currentSlide.length > 0) {
95
+ slides.push(currentSlide.join('\n'));
96
+ currentSlide = [];
97
+ }
98
+ continue;
99
+ }
100
+
101
+ // Check for H1 as slide break
102
+ if (this.options.h1AsSlide && trimmed.startsWith('# ') && currentSlide.length > 0) {
103
+ slides.push(currentSlide.join('\n'));
104
+ currentSlide = [line];
105
+ continue;
106
+ }
107
+
108
+ // Check for H2 as slide break
109
+ if (this.options.h2AsSlide && trimmed.startsWith('## ') && currentSlide.length > 0) {
110
+ slides.push(currentSlide.join('\n'));
111
+ currentSlide = [line];
112
+ continue;
113
+ }
114
+
115
+ currentSlide.push(line);
116
+ }
117
+
118
+ // Add last slide
119
+ if (currentSlide.length > 0) {
120
+ slides.push(currentSlide.join('\n'));
121
+ }
122
+
123
+ return slides;
124
+ }
125
+
126
+ /**
127
+ * Parse individual slide content using Markdown Dictionary
128
+ */
129
+ parseSlide(slideText, index) {
130
+ const content = [];
131
+ const lines = slideText.split('\n');
132
+
133
+ let title = '';
134
+ let subtitle = '';
135
+ let customDuration = null;
136
+ let inCodeBlock = false;
137
+ let codeLines = [];
138
+ let codeLang = '';
139
+ let codeFence = '```';
140
+ let inBlockquote = false;
141
+ let blockquoteLines = [];
142
+ let inTable = false;
143
+ let tableRows = [];
144
+ let inHtml = false;
145
+ let htmlLines = [];
146
+
147
+ for (let i = 0; i < lines.length; i++) {
148
+ const line = lines[i];
149
+ const trimmed = line.trim();
150
+ const nextLine = i < lines.length - 1 ? lines[i + 1] : null;
151
+
152
+ // Skip empty lines (unless in special block)
153
+ if (!trimmed && !inCodeBlock && !inHtml) {
154
+ // End blockquote on empty line
155
+ if (inBlockquote && blockquoteLines.length > 0) {
156
+ const quoteText = blockquoteLines.join('\n');
157
+ content.push({
158
+ type: 'blockquote',
159
+ content: quoteText,
160
+ html: this.parseInline(quoteText)
161
+ });
162
+ blockquoteLines = [];
163
+ inBlockquote = false;
164
+ }
165
+ // End table on empty line
166
+ if (inTable && tableRows.length > 0) {
167
+ content.push({
168
+ type: 'table',
169
+ rows: tableRows
170
+ });
171
+ tableRows = [];
172
+ inTable = false;
173
+ }
174
+ continue;
175
+ }
176
+
177
+ // Check for metadata (subtitle: or duration:)
178
+ if (trimmed.match(/^(subtitle|duration):\s*(.+)$/i)) {
179
+ const match = trimmed.match(/^(subtitle|duration):\s*(.+)$/i);
180
+ const key = match[1].toLowerCase();
181
+ const value = match[2].trim();
182
+
183
+ if (key === 'subtitle') {
184
+ subtitle = value;
185
+ } else if (key === 'duration') {
186
+ customDuration = parseFloat(value);
187
+ }
188
+ continue;
189
+ }
190
+
191
+ // Code block detection (using dictionary)
192
+ const codeBlockCheck = MarkdownSyntax.blocks.codeBlock.detect(trimmed);
193
+ if (codeBlockCheck) {
194
+ if (codeBlockCheck.type === 'code-fence-start') {
195
+ if (!inCodeBlock) {
196
+ // Start code block
197
+ inCodeBlock = true;
198
+ codeLang = codeBlockCheck.language || 'text';
199
+ codeFence = codeBlockCheck.fence || '```';
200
+ codeLines = [];
201
+ } else {
202
+ // End code block
203
+ inCodeBlock = false;
204
+ content.push({
205
+ type: 'code',
206
+ language: codeLang,
207
+ content: codeLines.join('\n')
208
+ });
209
+ codeLines = [];
210
+ codeLang = '';
211
+ codeFence = '```';
212
+ }
213
+ continue;
214
+ } else if (codeBlockCheck.type === 'code-indented' && !inCodeBlock) {
215
+ // Indented code (4 spaces or tab)
216
+ content.push({
217
+ type: 'code',
218
+ language: 'text',
219
+ content: codeBlockCheck.content
220
+ });
221
+ continue;
222
+ }
223
+ }
224
+
225
+ if (inCodeBlock) {
226
+ codeLines.push(line);
227
+ continue;
228
+ }
229
+
230
+ // HTML block detection
231
+ const htmlCheck = MarkdownSyntax.blocks.html.detect(trimmed);
232
+ if (htmlCheck) {
233
+ if (!inHtml) {
234
+ inHtml = true;
235
+ htmlLines = [line];
236
+ } else {
237
+ htmlLines.push(line);
238
+ }
239
+
240
+ // Check if HTML block ends (closing tag)
241
+ if (trimmed.match(/<\/[a-z][a-z0-9-]*\s*>/i) || trimmed === '-->') {
242
+ inHtml = false;
243
+ content.push({
244
+ type: 'html',
245
+ content: htmlLines.join('\n')
246
+ });
247
+ htmlLines = [];
248
+ }
249
+ continue;
250
+ }
251
+
252
+ if (inHtml) {
253
+ htmlLines.push(line);
254
+ continue;
255
+ }
256
+
257
+ // Heading detection (using dictionary - supports both ATX and Setext)
258
+ const headingCheck = MarkdownSyntax.blocks.heading.detect(trimmed, nextLine?.trim());
259
+ if (headingCheck) {
260
+ const text = headingCheck.content;
261
+ const level = headingCheck.level;
262
+
263
+ const headingHtml = this.parseInline(text);
264
+
265
+ if (level === 1) {
266
+ if (!title) title = text;
267
+ content.push({ type: 'h1', content: text, html: headingHtml });
268
+ } else if (level === 2) {
269
+ if (!subtitle && title) subtitle = text;
270
+ content.push({ type: 'h2', content: text, html: headingHtml });
271
+ } else if (level === 3) {
272
+ content.push({ type: 'h3', content: text, html: headingHtml });
273
+ } else if (level === 4) {
274
+ content.push({ type: 'h4', content: text, html: headingHtml });
275
+ } else if (level === 5) {
276
+ content.push({ type: 'h5', content: text, html: headingHtml });
277
+ } else if (level === 6) {
278
+ content.push({ type: 'h6', content: text, html: headingHtml });
279
+ }
280
+
281
+ // Skip next line if Setext style
282
+ if (headingCheck.style === 'setext') {
283
+ i++;
284
+ }
285
+ continue;
286
+ }
287
+
288
+ // Horizontal rule detection
289
+ const hrCheck = MarkdownSyntax.blocks.hr.detect(trimmed);
290
+ if (hrCheck) {
291
+ content.push({ type: 'hr' });
292
+ continue;
293
+ }
294
+
295
+ // Task list detection (GFM)
296
+ const taskCheck = MarkdownSyntax.blocks.taskList.detect(trimmed);
297
+ if (taskCheck) {
298
+ content.push({
299
+ type: 'task-list',
300
+ checked: taskCheck.checked,
301
+ content: taskCheck.content,
302
+ html: this.parseInline(taskCheck.content)
303
+ });
304
+ continue;
305
+ }
306
+
307
+ // Table detection (GFM)
308
+ const tableCheck = MarkdownSyntax.blocks.table.detect(trimmed);
309
+ if (tableCheck) {
310
+ inTable = true;
311
+ if (tableCheck.type === 'table-row') {
312
+ tableRows.push(tableCheck.cells);
313
+ }
314
+ continue;
315
+ }
316
+
317
+ // List detection (using dictionary - supports -, *, +, and numbered)
318
+ const listCheck = MarkdownSyntax.blocks.list.detect(trimmed);
319
+ if (listCheck) {
320
+ if (listCheck.ordered) {
321
+ content.push({
322
+ type: 'numbered-item',
323
+ number: listCheck.number,
324
+ content: listCheck.content,
325
+ html: this.parseInline(listCheck.content)
326
+ });
327
+ } else {
328
+ content.push({
329
+ type: 'list-item',
330
+ marker: listCheck.marker,
331
+ content: listCheck.content,
332
+ html: this.parseInline(listCheck.content)
333
+ });
334
+ }
335
+ continue;
336
+ }
337
+
338
+ // Blockquote detection (using dictionary - supports nested >)
339
+ const blockquoteCheck = MarkdownSyntax.blocks.blockquote.detect(trimmed);
340
+ if (blockquoteCheck) {
341
+ inBlockquote = true;
342
+ blockquoteLines.push(blockquoteCheck.content);
343
+ continue;
344
+ }
345
+
346
+ // Image detection (inline pattern)
347
+ if (trimmed.match(MarkdownSyntax.inline.image.patterns[0].regex)) {
348
+ const match = trimmed.match(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/);
349
+ content.push({
350
+ type: 'image',
351
+ alt: match[1] || '',
352
+ src: match[2],
353
+ title: match[3] || ''
354
+ });
355
+ continue;
356
+ }
357
+
358
+ // Link detection (inline pattern)
359
+ if (trimmed.match(MarkdownSyntax.inline.link.patterns[0].regex)) {
360
+ const match = trimmed.match(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/);
361
+ content.push({
362
+ type: 'link',
363
+ text: match[1],
364
+ url: match[2],
365
+ title: match[3] || '',
366
+ html: this.parseInline(match[0])
367
+ });
368
+ continue;
369
+ }
370
+
371
+ // Regular text/paragraph (with inline formatting)
372
+ if (trimmed) {
373
+ content.push({
374
+ type: 'text',
375
+ content: trimmed,
376
+ html: this.parseInline(trimmed)
377
+ });
378
+ }
379
+ }
380
+
381
+ // Flush remaining blocks
382
+ if (blockquoteLines.length > 0) {
383
+ const quoteText = blockquoteLines.join('\n');
384
+ content.push({
385
+ type: 'blockquote',
386
+ content: quoteText,
387
+ html: this.parseInline(quoteText)
388
+ });
389
+ }
390
+ if (tableRows.length > 0) {
391
+ content.push({
392
+ type: 'table',
393
+ rows: tableRows
394
+ });
395
+ }
396
+ if (htmlLines.length > 0) {
397
+ content.push({
398
+ type: 'html',
399
+ content: htmlLines.join('\n')
400
+ });
401
+ }
402
+
403
+ const normalizedTitle = title ? title.trim() : '';
404
+
405
+ return {
406
+ index,
407
+ title: normalizedTitle,
408
+ subtitle: subtitle || '',
409
+ content,
410
+ duration: customDuration !== null ? customDuration : this.calculateDuration(content)
411
+ };
412
+ }
413
+
414
+ /**
415
+ * Calculate recommended duration for slide based on content
416
+ */
417
+ calculateDuration(content) {
418
+ let duration = 3; // Base duration in seconds
419
+
420
+ content.forEach(item => {
421
+ switch (item.type) {
422
+ case 'h1':
423
+ duration += 2;
424
+ break;
425
+ case 'h2':
426
+ case 'h3':
427
+ duration += 1.5;
428
+ break;
429
+ case 'h4':
430
+ case 'h5':
431
+ case 'h6':
432
+ duration += 1;
433
+ break;
434
+ case 'list-item':
435
+ case 'numbered-item':
436
+ case 'task-list':
437
+ duration += 1;
438
+ break;
439
+ case 'code':
440
+ const lines = item.content.split('\n').length;
441
+ duration += Math.min(lines * 0.5, 10); // Max 10 seconds for code
442
+ break;
443
+ case 'blockquote':
444
+ const words = item.content.split(' ').length;
445
+ duration += words * 0.4; // Quotes need more reading time
446
+ break;
447
+ case 'text':
448
+ const textWords = item.content.split(' ').length;
449
+ duration += textWords * 0.3; // ~200 words per minute
450
+ break;
451
+ case 'image':
452
+ duration += 3;
453
+ break;
454
+ case 'table':
455
+ const rows = item.rows ? item.rows.length : 1;
456
+ duration += rows * 1.5; // Tables need time to understand
457
+ break;
458
+ case 'html':
459
+ duration += 2; // HTML content
460
+ break;
461
+ case 'hr':
462
+ duration += 0.5; // Separator
463
+ break;
464
+ default:
465
+ duration += 1;
466
+ }
467
+ });
468
+
469
+ return Math.round(duration);
470
+ }
471
+
472
+ /**
473
+ * Parse inline markdown (bold, italic, code, strikethrough, etc.)
474
+ * Uses Markdown Dictionary for comprehensive syntax support
475
+ */
476
+ parseInline(text) {
477
+ if (!text) return '';
478
+
479
+ // Use the dictionary's parseInline function
480
+ return parseInline(text);
481
+ }
482
+
483
+ /**
484
+ * Get summary of parsed markdown
485
+ */
486
+ getSummary(slides) {
487
+ const totalPages = slides.reduce((sum, slide) => {
488
+ return sum + (slide.totalPages || 1);
489
+ }, 0);
490
+
491
+ return {
492
+ totalSlides: slides.length,
493
+ totalPages: totalPages,
494
+ estimatedDuration: slides.reduce((sum, slide) => sum + slide.duration, 0),
495
+ titles: slides.map(slide => slide.title),
496
+ paginatedSlides: slides.filter(s => s.totalPages > 1).length
497
+ };
498
+ }
499
+
500
+ /**
501
+ * Get pagination info for a slide without parsing
502
+ */
503
+ getPaginationPreview(slideContent) {
504
+ return getPaginationInfo(slideContent);
505
+ }
506
+ }
507
+
508
+ // Export helper function
509
+ export function parseMarkdown(markdown, options = {}) {
510
+ const parser = new MarkdownParser(options);
511
+ return parser.parse(markdown);
512
+ }
src/shared/markdown-syntax.js ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Markdown Syntax Dictionary
3
+ // Complete Markdown syntax patterns and recognition rules
4
+ // ══════════════════════════════════════════════════════════════════════════════
5
+
6
+ /**
7
+ * Markdown Syntax Dictionary
8
+ * Based on CommonMark + GitHub Flavored Markdown (GFM)
9
+ */
10
+ export const MarkdownSyntax = {
11
+ // ════════════════════════════════════════════════════════════════════════════
12
+ // Block-level Elements
13
+ // ════════════════════════════════════════════════════════════════════════════
14
+
15
+ blocks: {
16
+ // Headings: # H1, ## H2, ### H3, #### H4, ##### H5, ###### H6
17
+ heading: {
18
+ patterns: [
19
+ /^(#{1,6})\s+(.+)$/, // ATX style: # Heading
20
+ /^(.+)\n={3,}\s*$/, // Setext H1: underline with ===
21
+ /^(.+)\n-{3,}\s*$/ // Setext H2: underline with ---
22
+ ],
23
+ detect: (line, nextLine) => {
24
+ // ATX headings
25
+ const atx = line.match(/^(#{1,6})\s+(.+)$/);
26
+ if (atx) {
27
+ return {
28
+ type: 'heading',
29
+ level: atx[1].length,
30
+ content: atx[2].trim(),
31
+ style: 'atx'
32
+ };
33
+ }
34
+
35
+ // Setext headings (require next line)
36
+ if (nextLine) {
37
+ if (nextLine.match(/^={3,}\s*$/)) {
38
+ return { type: 'heading', level: 1, content: line.trim(), style: 'setext' };
39
+ }
40
+ if (nextLine.match(/^-{3,}\s*$/) && !line.match(/^\s*$/)) {
41
+ return { type: 'heading', level: 2, content: line.trim(), style: 'setext' };
42
+ }
43
+ }
44
+
45
+ return null;
46
+ }
47
+ },
48
+
49
+ // Horizontal Rules: ---, ***, ___
50
+ hr: {
51
+ patterns: [
52
+ /^-{3,}\s*$/,
53
+ /^\*{3,}\s*$/,
54
+ /^_{3,}\s*$/,
55
+ /^- {0,2}- {0,2}-/,
56
+ /^\* {0,2}\* {0,2}\*/,
57
+ /^_ {0,2}_ {0,2}_/
58
+ ],
59
+ detect: (line) => {
60
+ for (const pattern of MarkdownSyntax.blocks.hr.patterns) {
61
+ if (pattern.test(line.trim())) {
62
+ return { type: 'hr' };
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+ },
68
+
69
+ // Code Blocks: ```lang or indented 4 spaces
70
+ codeBlock: {
71
+ patterns: [
72
+ /^```(\w*)\s*$/, // Fenced code block start
73
+ /^~~~(\w*)\s*$/, // Alternative fence
74
+ /^ (.+)$/, // Indented code (4 spaces)
75
+ /^\t(.+)$/ // Indented code (tab)
76
+ ],
77
+ detect: (line) => {
78
+ // Fenced code block
79
+ const fenced = line.match(/^```(\w*)\s*$/);
80
+ if (fenced) {
81
+ return { type: 'code-fence-start', language: fenced[1] || 'text' };
82
+ }
83
+
84
+ const tilde = line.match(/^~~~(\w*)\s*$/);
85
+ if (tilde) {
86
+ return { type: 'code-fence-start', language: tilde[1] || 'text', fence: '~~~' };
87
+ }
88
+
89
+ // Indented code
90
+ if (line.match(/^ (.+)$/) || line.match(/^\t(.+)$/)) {
91
+ return { type: 'code-indented', content: line.replace(/^ |\t/, '') };
92
+ }
93
+
94
+ return null;
95
+ }
96
+ },
97
+
98
+ // Blockquotes: > Quote
99
+ blockquote: {
100
+ patterns: [
101
+ /^>\s?(.*)$/, // > Quote
102
+ /^> ?> ?(.*)$/ // Nested: >> Quote
103
+ ],
104
+ detect: (line) => {
105
+ const match = line.match(/^(>+)\s?(.*)$/);
106
+ if (match) {
107
+ return {
108
+ type: 'blockquote',
109
+ level: match[1].length,
110
+ content: match[2]
111
+ };
112
+ }
113
+ return null;
114
+ }
115
+ },
116
+
117
+ // Lists: Unordered (-, *, +) and Ordered (1., 2.)
118
+ list: {
119
+ patterns: [
120
+ /^(\s*)([-*+])\s+(.+)$/, // Unordered: -, *, +
121
+ /^(\s*)(\d{1,9})[.)]\s+(.+)$/ // Ordered: 1., 2), etc.
122
+ ],
123
+ detect: (line) => {
124
+ // Unordered list
125
+ const unordered = line.match(/^(\s*)([-*+])\s+(.+)$/);
126
+ if (unordered) {
127
+ return {
128
+ type: 'list',
129
+ ordered: false,
130
+ indent: unordered[1].length,
131
+ marker: unordered[2],
132
+ content: unordered[3]
133
+ };
134
+ }
135
+
136
+ // Ordered list
137
+ const ordered = line.match(/^(\s*)(\d{1,9})[.)]\s+(.+)$/);
138
+ if (ordered) {
139
+ return {
140
+ type: 'list',
141
+ ordered: true,
142
+ indent: ordered[1].length,
143
+ number: parseInt(ordered[2]),
144
+ content: ordered[3]
145
+ };
146
+ }
147
+
148
+ return null;
149
+ }
150
+ },
151
+
152
+ // Task Lists (GFM): - [ ] Task or - [x] Done
153
+ taskList: {
154
+ patterns: [
155
+ /^(\s*)([-*+])\s+\[([ xX])\]\s+(.+)$/
156
+ ],
157
+ detect: (line) => {
158
+ const match = line.match(/^(\s*)([-*+])\s+\[([ xX])\]\s+(.+)$/);
159
+ if (match) {
160
+ return {
161
+ type: 'task-list',
162
+ indent: match[1].length,
163
+ checked: match[3].toLowerCase() === 'x',
164
+ content: match[4]
165
+ };
166
+ }
167
+ return null;
168
+ }
169
+ },
170
+
171
+ // Tables (GFM): | Header | Header |
172
+ table: {
173
+ patterns: [
174
+ /^\|(.+)\|$/, // Table row
175
+ /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$/ // Separator
176
+ ],
177
+ detect: (line) => {
178
+ if (line.match(/^\|(.+)\|$/)) {
179
+ return { type: 'table-row', cells: line.split('|').filter(c => c.trim()) };
180
+ }
181
+ if (line.match(/^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$/)) {
182
+ return { type: 'table-separator' };
183
+ }
184
+ return null;
185
+ }
186
+ },
187
+
188
+ // HTML Blocks: <div>, <!-- comment -->
189
+ html: {
190
+ patterns: [
191
+ /^<([a-z][a-z0-9-]*)\b[^>]*>/i, // Opening tag
192
+ /^<\/([a-z][a-z0-9-]*)\s*>/i, // Closing tag
193
+ /^<!--/, // Comment start
194
+ /^<\?/, // Processing instruction
195
+ /^<![A-Z]/, // Declaration
196
+ /^<!\[CDATA\[/ // CDATA section
197
+ ],
198
+ detect: (line) => {
199
+ for (const pattern of MarkdownSyntax.blocks.html.patterns) {
200
+ if (pattern.test(line.trim())) {
201
+ return { type: 'html', content: line };
202
+ }
203
+ }
204
+ return null;
205
+ }
206
+ },
207
+
208
+ // Metadata blocks (YAML frontmatter, TOML, JSON)
209
+ metadata: {
210
+ patterns: [
211
+ /^---\s*$/, // YAML
212
+ /^\+\+\+\s*$/, // TOML
213
+ /^;;;\s*$/ // JSON (some parsers)
214
+ ],
215
+ detect: (line) => {
216
+ if (line.trim() === '---') return { type: 'metadata', format: 'yaml' };
217
+ if (line.trim() === '+++') return { type: 'metadata', format: 'toml' };
218
+ if (line.trim() === ';;;') return { type: 'metadata', format: 'json' };
219
+ return null;
220
+ }
221
+ }
222
+ },
223
+
224
+ // ════════════════════════════════════════════════════════════════════════════
225
+ // Inline Elements
226
+ // ════════════════════════════════════════════════════════════════════════════
227
+
228
+ inline: {
229
+ // Emphasis: *italic*, _italic_, **bold**, __bold__, ***bold italic***
230
+ emphasis: {
231
+ patterns: [
232
+ { regex: /\*\*\*(.+?)\*\*\*/g, type: 'bold-italic', tag: 'strong-em' },
233
+ { regex: /___(.+?)___/g, type: 'bold-italic', tag: 'strong-em' },
234
+ { regex: /\*\*(.+?)\*\*/g, type: 'bold', tag: 'strong' },
235
+ { regex: /__(.+?)__/g, type: 'bold', tag: 'strong' },
236
+ { regex: /\*(.+?)\*/g, type: 'italic', tag: 'em' },
237
+ { regex: /_(.+?)_/g, type: 'italic', tag: 'em' }
238
+ ]
239
+ },
240
+
241
+ // Strikethrough (GFM): ~~deleted~~
242
+ strikethrough: {
243
+ patterns: [
244
+ { regex: /~~(.+?)~~/g, type: 'strikethrough', tag: 'del' }
245
+ ]
246
+ },
247
+
248
+ // Code: `inline code`
249
+ code: {
250
+ patterns: [
251
+ { regex: /``(.+?)``/g, type: 'code', tag: 'code' }, // Double backtick
252
+ { regex: /`(.+?)`/g, type: 'code', tag: 'code' } // Single backtick
253
+ ]
254
+ },
255
+
256
+ // Links: [text](url "title"), [text][ref], <url>
257
+ link: {
258
+ patterns: [
259
+ { regex: /\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, type: 'link' }, // Inline
260
+ { regex: /\[([^\]]+)\]\[([^\]]+)\]/g, type: 'link-ref' }, // Reference
261
+ { regex: /\[([^\]]+)\]/g, type: 'link-shortcut' }, // Shortcut
262
+ { regex: /<(https?:\/\/[^>]+)>/g, type: 'autolink' }, // Autolink
263
+ { regex: /<([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>/g, type: 'email' } // Email
264
+ ]
265
+ },
266
+
267
+ // Images: ![alt](url "title"), ![alt][ref]
268
+ image: {
269
+ patterns: [
270
+ { regex: /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, type: 'image' }, // Inline
271
+ { regex: /!\[([^\]]*)\]\[([^\]]+)\]/g, type: 'image-ref' } // Reference
272
+ ]
273
+ },
274
+
275
+ // Line breaks: two spaces + newline, backslash + newline, <br>
276
+ lineBreak: {
277
+ patterns: [
278
+ { regex: / \n/g, type: 'soft-break' },
279
+ { regex: /\\\n/g, type: 'hard-break' },
280
+ { regex: /<br\s*\/?>/gi, type: 'html-break' }
281
+ ]
282
+ },
283
+
284
+ // Escape sequences: \*, \[, etc.
285
+ escape: {
286
+ characters: ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '.', '!', '|']
287
+ },
288
+
289
+ // Emoji (GFM): :smile:, :heart:
290
+ emoji: {
291
+ pattern: /:([a-z0-9_+-]+):/g
292
+ },
293
+
294
+ // Mentions (GFM): @username
295
+ mention: {
296
+ pattern: /@([a-zA-Z0-9_-]+)/g
297
+ },
298
+
299
+ // Hashtags: #tag
300
+ hashtag: {
301
+ pattern: /#([a-zA-Z0-9_-]+)/g
302
+ }
303
+ },
304
+
305
+ // ════════════════════════════════════════════════════════════════════════════
306
+ // Special Constructs
307
+ // ════════════════════════════════════════════════════════════════════════════
308
+
309
+ special: {
310
+ // Footnotes: [^1], [^note]
311
+ footnote: {
312
+ definition: /^\[\^([^\]]+)\]:\s+(.+)$/,
313
+ reference: /\[\^([^\]]+)\]/g
314
+ },
315
+
316
+ // Abbreviations: *[HTML]: Hyper Text Markup Language
317
+ abbreviation: {
318
+ pattern: /^\*\[([^\]]+)\]:\s+(.+)$/
319
+ },
320
+
321
+ // Definition lists:
322
+ // Term
323
+ // : Definition
324
+ definitionList: {
325
+ term: /^([^\n:]+)\s*$/,
326
+ definition: /^:\s+(.+)$/
327
+ },
328
+
329
+ // Math (KaTeX/MathJax): $inline$, $$block$$
330
+ math: {
331
+ inline: /\$([^$]+)\$/g,
332
+ block: /\$\$([^$]+)\$\$/g
333
+ }
334
+ }
335
+ };
336
+
337
+ /**
338
+ * Check if a line matches any block-level syntax
339
+ */
340
+ export function detectBlockType(line, nextLine = null) {
341
+ // Check each block type
342
+ for (const [blockName, block] of Object.entries(MarkdownSyntax.blocks)) {
343
+ const result = block.detect(line, nextLine);
344
+ if (result) {
345
+ return result;
346
+ }
347
+ }
348
+ return { type: 'paragraph' };
349
+ }
350
+
351
+ /**
352
+ * Parse inline markdown syntax
353
+ */
354
+ function escapeHtml(str) {
355
+ if (str == null) return '';
356
+ return String(str)
357
+ .replace(/&/g, '&amp;')
358
+ .replace(/</g, '&lt;')
359
+ .replace(/>/g, '&gt;')
360
+ .replace(/"/g, '&quot;')
361
+ .replace(/'/g, '&#39;');
362
+ }
363
+
364
+ export function parseInline(text) {
365
+ if (!text) return '';
366
+
367
+ let result = escapeHtml(text);
368
+
369
+ // Images (handle before links so the leading ! is preserved)
370
+ result = result.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, (match, alt, url, title) => {
371
+ const altAttr = escapeHtml(alt || '');
372
+ const srcAttr = escapeHtml(url || '');
373
+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
374
+ return `<img src="${srcAttr}" alt="${altAttr}"${titleAttr}>`;
375
+ });
376
+
377
+ // Inline links [text](url "title")
378
+ result = result.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, (match, label, url, title) => {
379
+ const textContent = escapeHtml(label || '');
380
+ const hrefAttr = escapeHtml(url || '#');
381
+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
382
+ return `<a href="${hrefAttr}"${titleAttr}>${textContent}</a>`;
383
+ });
384
+
385
+ // Autolinks <https://example.com>
386
+ result = result.replace(/&lt;(https?:\/\/[^&]+)&gt;/g, (match, url) => {
387
+ const hrefAttr = escapeHtml(url);
388
+ return `<a href="${hrefAttr}">${hrefAttr}</a>`;
389
+ });
390
+
391
+ // Email autolinks <user@example.com>
392
+ result = result.replace(/&lt;([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})&gt;/g, (match, email) => {
393
+ const mailto = `mailto:${email}`;
394
+ return `<a href="${escapeHtml(mailto)}">${escapeHtml(email)}</a>`;
395
+ });
396
+
397
+ // Emphasis and code (process complex patterns first)
398
+ const replacements = [
399
+ { regex: /\*\*\*(.+?)\*\*\*/g, wrap: content => `<strong><em>${content}</em></strong>` },
400
+ { regex: /___(.+?)___/g, wrap: content => `<strong><em>${content}</em></strong>` },
401
+ { regex: /\*\*(.+?)\*\*/g, wrap: content => `<strong>${content}</strong>` },
402
+ { regex: /__(.+?)__/g, wrap: content => `<strong>${content}</strong>` },
403
+ { regex: /\*(.+?)\*/g, wrap: content => `<em>${content}</em>` },
404
+ { regex: /_(.+?)_/g, wrap: content => `<em>${content}</em>` },
405
+ { regex: /~~(.+?)~~/g, wrap: content => `<del>${content}</del>` },
406
+ { regex: /``(.+?)``/g, wrap: content => `<code>${content}</code>` },
407
+ { regex: /`(.+?)`/g, wrap: content => `<code>${content}</code>` }
408
+ ];
409
+
410
+ replacements.forEach(({ regex, wrap }) => {
411
+ result = result.replace(regex, (match, content) => wrap(content));
412
+ });
413
+
414
+ // Line breaks
415
+ result = result.replace(/ \n/g, '<br>');
416
+ result = result.replace(/\\\n/g, '<br>');
417
+ result = result.replace(/&lt;br\s*\/?&gt;/gi, '<br>');
418
+
419
+ return result;
420
+ }
421
+
422
+ /**
423
+ * Get syntax info for documentation
424
+ */
425
+ export function getSyntaxInfo(category) {
426
+ const info = {
427
+ blocks: 'Block-level elements (headings, lists, code blocks, etc.)',
428
+ inline: 'Inline elements (emphasis, links, images, etc.)',
429
+ special: 'Special constructs (footnotes, math, definitions, etc.)'
430
+ };
431
+
432
+ return info[category] || 'Unknown category';
433
+ }
src/shared/persistent-storage.js ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Persistent Storage Manager
3
+ *
4
+ * จัดการการบันทึกและโหลดการตั้งค่าทั้งหมด (positions, edits, layouts)
5
+ * รองรับ localStorage และ Export/Import JSON
6
+ * Auto-save ทุก 2-3 วินาที
7
+ *
8
+ * @author Chahua Development Co., Ltd.
9
+ * @version 2.1.0
10
+ */
11
+
12
+ export class PersistentStorage {
13
+ constructor() {
14
+ this.currentFilePath = null;
15
+ this.autoSaveInterval = null;
16
+ this.autoSaveDelay = 2000; // 2 วินาที
17
+ this.hasUnsavedChanges = false;
18
+
19
+ // Storage keys
20
+ this.STORAGE_PREFIX = 'chahua-md-presenter';
21
+ this.POSITIONS_KEY = 'positions';
22
+ this.EDITS_KEY = 'edits';
23
+ this.LAYOUTS_KEY = 'layouts';
24
+ this.SETTINGS_KEY = 'settings';
25
+
26
+ this.init();
27
+ }
28
+
29
+ init() {
30
+ // Listen for changes
31
+ this.setupEventListeners();
32
+
33
+ // Auto-save on window close
34
+ window.addEventListener('beforeunload', () => {
35
+ if (this.hasUnsavedChanges) {
36
+ this.save();
37
+ }
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Setup event listeners สำหรับ auto-save
43
+ */
44
+ setupEventListeners() {
45
+ // Listen for position changes
46
+ document.addEventListener('positionChanged', () => {
47
+ this.hasUnsavedChanges = true;
48
+ this.scheduleAutoSave();
49
+ });
50
+
51
+ // Listen for content changes
52
+ document.addEventListener('contentChanged', () => {
53
+ this.hasUnsavedChanges = true;
54
+ this.scheduleAutoSave();
55
+ });
56
+
57
+ // Listen for layout changes
58
+ document.addEventListener('layoutChanged', () => {
59
+ this.hasUnsavedChanges = true;
60
+ this.scheduleAutoSave();
61
+ });
62
+ }
63
+
64
+ /**
65
+ * กำหนดไฟล์ปัจจุบัน
66
+ *
67
+ * @param {string} filePath
68
+ */
69
+ setCurrentFile(filePath) {
70
+ this.currentFilePath = filePath;
71
+ }
72
+
73
+ /**
74
+ * สร้าง storage key จาก file path และ slide index
75
+ *
76
+ * @param {string} filePath
77
+ * @param {number} slideIndex
78
+ * @param {string} dataType - 'positions', 'edits', 'layouts', 'settings'
79
+ * @returns {string}
80
+ */
81
+ getStorageKey(filePath, slideIndex = null, dataType = 'positions') {
82
+ const cleanPath = this.sanitizeFilePath(filePath);
83
+ const slideKey = slideIndex !== null ? `:slide-${slideIndex}` : '';
84
+ return `${this.STORAGE_PREFIX}:${cleanPath}${slideKey}:${dataType}`;
85
+ }
86
+
87
+ /**
88
+ * Sanitize file path สำหรับใช้เป็น key
89
+ *
90
+ * @param {string} filePath
91
+ * @returns {string}
92
+ */
93
+ sanitizeFilePath(filePath) {
94
+ if (!filePath) return 'untitled';
95
+
96
+ // แปลง path เป็น hash เพื่อให้สั้นลง
97
+ return this.simpleHash(filePath);
98
+ }
99
+
100
+ /**
101
+ * Simple hash function
102
+ *
103
+ * @param {string} str
104
+ * @returns {string}
105
+ */
106
+ simpleHash(str) {
107
+ let hash = 0;
108
+ for (let i = 0; i < str.length; i++) {
109
+ const char = str.charCodeAt(i);
110
+ hash = ((hash << 5) - hash) + char;
111
+ hash = hash & hash;
112
+ }
113
+ return Math.abs(hash).toString(36);
114
+ }
115
+
116
+ /**
117
+ * บันทึก positions สำหรับ slide หนึ่ง
118
+ *
119
+ * @param {string} filePath
120
+ * @param {number} slideIndex
121
+ * @param {Object} positions
122
+ */
123
+ savePositions(filePath, slideIndex, positions) {
124
+ const key = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY);
125
+ const data = {
126
+ timestamp: Date.now(),
127
+ filePath,
128
+ slideIndex,
129
+ positions
130
+ };
131
+
132
+ try {
133
+ localStorage.setItem(key, JSON.stringify(data));
134
+ return true;
135
+ } catch (error) {
136
+ console.error('Failed to save positions:', error);
137
+ return false;
138
+ }
139
+ }
140
+
141
+ /**
142
+ * โหลด positions สำหรับ slide หนึ่ง
143
+ *
144
+ * @param {string} filePath
145
+ * @param {number} slideIndex
146
+ * @returns {Object|null}
147
+ */
148
+ loadPositions(filePath, slideIndex) {
149
+ const key = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY);
150
+
151
+ try {
152
+ const data = localStorage.getItem(key);
153
+ if (!data) return null;
154
+
155
+ const parsed = JSON.parse(data);
156
+ return parsed.positions;
157
+ } catch (error) {
158
+ console.error('Failed to load positions:', error);
159
+ return null;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * บันทึก content edits สำ��รับ slide หนึ่ง
165
+ *
166
+ * @param {string} filePath
167
+ * @param {number} slideIndex
168
+ * @param {Object} edits
169
+ */
170
+ saveEdits(filePath, slideIndex, edits) {
171
+ const key = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY);
172
+ const data = {
173
+ timestamp: Date.now(),
174
+ filePath,
175
+ slideIndex,
176
+ edits
177
+ };
178
+
179
+ try {
180
+ localStorage.setItem(key, JSON.stringify(data));
181
+ return true;
182
+ } catch (error) {
183
+ console.error('Failed to save edits:', error);
184
+ return false;
185
+ }
186
+ }
187
+
188
+ /**
189
+ * โหลด content edits สำหรับ slide หนึ่ง
190
+ *
191
+ * @param {string} filePath
192
+ * @param {number} slideIndex
193
+ * @returns {Object|null}
194
+ */
195
+ loadEdits(filePath, slideIndex) {
196
+ const key = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY);
197
+
198
+ try {
199
+ const data = localStorage.getItem(key);
200
+ if (!data) return null;
201
+
202
+ const parsed = JSON.parse(data);
203
+ return parsed.edits;
204
+ } catch (error) {
205
+ console.error('Failed to load edits:', error);
206
+ return null;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * บันทึก layout settings สำหรับ slide หนึ่ง
212
+ *
213
+ * @param {string} filePath
214
+ * @param {number} slideIndex
215
+ * @param {Object} layout
216
+ */
217
+ saveLayout(filePath, slideIndex, layout) {
218
+ const key = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY);
219
+ const data = {
220
+ timestamp: Date.now(),
221
+ filePath,
222
+ slideIndex,
223
+ layout
224
+ };
225
+
226
+ try {
227
+ localStorage.setItem(key, JSON.stringify(data));
228
+ return true;
229
+ } catch (error) {
230
+ console.error('Failed to save layout:', error);
231
+ return false;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * โหลด layout settings สำหรับ slide หนึ่ง
237
+ *
238
+ * @param {string} filePath
239
+ * @param {number} slideIndex
240
+ * @returns {Object|null}
241
+ */
242
+ loadLayout(filePath, slideIndex) {
243
+ const key = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY);
244
+
245
+ try {
246
+ const data = localStorage.getItem(key);
247
+ if (!data) return null;
248
+
249
+ const parsed = JSON.parse(data);
250
+ return parsed.layout;
251
+ } catch (error) {
252
+ console.error('Failed to load layout:', error);
253
+ return null;
254
+ }
255
+ }
256
+
257
+ /**
258
+ * บันทึกทุกอย่างสำหรับไฟล์ปัจจุบัน
259
+ *
260
+ * @param {Array} allData - Array of {slideIndex, positions, edits, layout}
261
+ */
262
+ saveAll(filePath, allData) {
263
+ let savedCount = 0;
264
+
265
+ allData.forEach(slideData => {
266
+ const { slideIndex, positions, edits, layout } = slideData;
267
+
268
+ if (positions) {
269
+ this.savePositions(filePath, slideIndex, positions);
270
+ savedCount++;
271
+ }
272
+
273
+ if (edits) {
274
+ this.saveEdits(filePath, slideIndex, edits);
275
+ savedCount++;
276
+ }
277
+
278
+ if (layout) {
279
+ this.saveLayout(filePath, slideIndex, layout);
280
+ savedCount++;
281
+ }
282
+ });
283
+
284
+ this.hasUnsavedChanges = false;
285
+ return savedCount;
286
+ }
287
+
288
+ /**
289
+ * โหลดทุกอย่างสำหรับไฟล์ปัจจุบัน
290
+ *
291
+ * @param {string} filePath
292
+ * @param {number} totalSlides
293
+ * @returns {Array}
294
+ */
295
+ loadAll(filePath, totalSlides) {
296
+ const allData = [];
297
+
298
+ for (let i = 0; i < totalSlides; i++) {
299
+ const positions = this.loadPositions(filePath, i);
300
+ const edits = this.loadEdits(filePath, i);
301
+ const layout = this.loadLayout(filePath, i);
302
+
303
+ if (positions || edits || layout) {
304
+ allData.push({
305
+ slideIndex: i,
306
+ positions,
307
+ edits,
308
+ layout
309
+ });
310
+ }
311
+ }
312
+
313
+ return allData;
314
+ }
315
+
316
+ /**
317
+ * Export ทุกอย่างเป็น JSON file
318
+ *
319
+ * @param {string} filePath
320
+ * @param {number} totalSlides
321
+ * @returns {string} - JSON string
322
+ */
323
+ exportToJSON(filePath, totalSlides) {
324
+ const allData = this.loadAll(filePath, totalSlides);
325
+
326
+ const exportData = {
327
+ version: '2.1.0',
328
+ exportedAt: new Date().toISOString(),
329
+ filePath,
330
+ totalSlides,
331
+ slides: allData
332
+ };
333
+
334
+ return JSON.stringify(exportData, null, 2);
335
+ }
336
+
337
+ /**
338
+ * Import จาก JSON file
339
+ *
340
+ * @param {string} jsonString
341
+ * @returns {boolean}
342
+ */
343
+ importFromJSON(jsonString) {
344
+ try {
345
+ const data = JSON.parse(jsonString);
346
+
347
+ if (!data.version || !data.slides) {
348
+ throw new Error('Invalid JSON format');
349
+ }
350
+
351
+ const { filePath, slides } = data;
352
+
353
+ slides.forEach(slideData => {
354
+ const { slideIndex, positions, edits, layout } = slideData;
355
+
356
+ if (positions) {
357
+ this.savePositions(filePath, slideIndex, positions);
358
+ }
359
+
360
+ if (edits) {
361
+ this.saveEdits(filePath, slideIndex, edits);
362
+ }
363
+
364
+ if (layout) {
365
+ this.saveLayout(filePath, slideIndex, layout);
366
+ }
367
+ });
368
+
369
+ return true;
370
+ } catch (error) {
371
+ console.error('Failed to import JSON:', error);
372
+ return false;
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Download JSON file
378
+ *
379
+ * @param {string} filePath
380
+ * @param {number} totalSlides
381
+ */
382
+ downloadJSON(filePath, totalSlides) {
383
+ const json = this.exportToJSON(filePath, totalSlides);
384
+ const blob = new Blob([json], { type: 'application/json' });
385
+ const url = URL.createObjectURL(blob);
386
+
387
+ const a = document.createElement('a');
388
+ a.href = url;
389
+ a.download = `presentation-settings-${Date.now()}.json`;
390
+ document.body.appendChild(a);
391
+ a.click();
392
+ document.body.removeChild(a);
393
+ URL.revokeObjectURL(url);
394
+ }
395
+
396
+ /**
397
+ * Schedule auto-save
398
+ */
399
+ scheduleAutoSave() {
400
+ if (this.autoSaveInterval) {
401
+ clearTimeout(this.autoSaveInterval);
402
+ }
403
+
404
+ this.autoSaveInterval = setTimeout(() => {
405
+ this.save();
406
+ }, this.autoSaveDelay);
407
+ }
408
+
409
+ /**
410
+ * บันทึกทันที (manual save)
411
+ */
412
+ save() {
413
+ if (!this.hasUnsavedChanges) return;
414
+
415
+ // Trigger save event
416
+ const event = new CustomEvent('persistentStorageSave', {
417
+ detail: {
418
+ filePath: this.currentFilePath,
419
+ timestamp: Date.now()
420
+ }
421
+ });
422
+ document.dispatchEvent(event);
423
+
424
+ this.hasUnsavedChanges = false;
425
+ }
426
+
427
+ /**
428
+ * ลบข้อมูลสำหรับ slide หนึ่ง
429
+ *
430
+ * @param {string} filePath
431
+ * @param {number} slideIndex
432
+ */
433
+ clearSlide(filePath, slideIndex) {
434
+ const posKey = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY);
435
+ const editKey = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY);
436
+ const layoutKey = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY);
437
+
438
+ localStorage.removeItem(posKey);
439
+ localStorage.removeItem(editKey);
440
+ localStorage.removeItem(layoutKey);
441
+ }
442
+
443
+ /**
444
+ * ลบข้อมูลทั้งหมดสำหรับไฟล์หนึ่ง
445
+ *
446
+ * @param {string} filePath
447
+ */
448
+ clearFile(filePath) {
449
+ const prefix = `${this.STORAGE_PREFIX}:${this.sanitizeFilePath(filePath)}`;
450
+
451
+ // หา keys ทั้งหมดที่ตรงกับ prefix
452
+ const keysToRemove = [];
453
+ for (let i = 0; i < localStorage.length; i++) {
454
+ const key = localStorage.key(i);
455
+ if (key.startsWith(prefix)) {
456
+ keysToRemove.push(key);
457
+ }
458
+ }
459
+
460
+ // ลบทั้งหมด
461
+ keysToRemove.forEach(key => localStorage.removeItem(key));
462
+ }
463
+
464
+ /**
465
+ * ลบข้อมูลทั้งหมด
466
+ */
467
+ clearAll() {
468
+ const keysToRemove = [];
469
+ for (let i = 0; i < localStorage.length; i++) {
470
+ const key = localStorage.key(i);
471
+ if (key.startsWith(this.STORAGE_PREFIX)) {
472
+ keysToRemove.push(key);
473
+ }
474
+ }
475
+
476
+ keysToRemove.forEach(key => localStorage.removeItem(key));
477
+ }
478
+
479
+ /**
480
+ * Get storage usage info
481
+ *
482
+ * @returns {Object}
483
+ */
484
+ getStorageInfo() {
485
+ let totalSize = 0;
486
+ let itemCount = 0;
487
+
488
+ for (let i = 0; i < localStorage.length; i++) {
489
+ const key = localStorage.key(i);
490
+ if (key.startsWith(this.STORAGE_PREFIX)) {
491
+ const value = localStorage.getItem(key);
492
+ totalSize += key.length + value.length;
493
+ itemCount++;
494
+ }
495
+ }
496
+
497
+ return {
498
+ itemCount,
499
+ totalSize,
500
+ totalSizeKB: (totalSize / 1024).toFixed(2),
501
+ maxSize: 5120, // 5MB typical localStorage limit
502
+ usagePercent: ((totalSize / (5 * 1024 * 1024)) * 100).toFixed(2)
503
+ };
504
+ }
505
+
506
+ /**
507
+ * Cleanup old data (optional)
508
+ * ลบข้อมูลที่เก่ากว่า X วัน
509
+ *
510
+ * @param {number} daysOld
511
+ */
512
+ cleanupOldData(daysOld = 30) {
513
+ const cutoffTime = Date.now() - (daysOld * 24 * 60 * 60 * 1000);
514
+ const keysToRemove = [];
515
+
516
+ for (let i = 0; i < localStorage.length; i++) {
517
+ const key = localStorage.key(i);
518
+ if (!key.startsWith(this.STORAGE_PREFIX)) continue;
519
+
520
+ try {
521
+ const data = JSON.parse(localStorage.getItem(key));
522
+ if (data.timestamp && data.timestamp < cutoffTime) {
523
+ keysToRemove.push(key);
524
+ }
525
+ } catch (error) {
526
+ // Invalid JSON, skip
527
+ }
528
+ }
529
+
530
+ keysToRemove.forEach(key => localStorage.removeItem(key));
531
+ return keysToRemove.length;
532
+ }
533
+ }
534
+
535
+ export default PersistentStorage;
src/shared/security-core.js ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Chahua Video Builder - Security Core Module
3
+ // ══════════════════════════════════════════════════════════════════════════════
4
+ // Company: Chahua Development Co., Ltd.
5
+ // Repository: https://github.com/chahuadev/chahuadev-Video-Builder.git
6
+ // Version: 1.0.0
7
+ // License: MIT
8
+ // Contact: chahuadev@gmail.com
9
+ // ══════════════════════════════════════════════════════════════════════════════
10
+ // @description Enterprise-grade security module for video builder application
11
+ // @security_level FORTRESS - Maximum Protection
12
+ // ══════════════════════════════════════════════════════════════════════════════
13
+
14
+ import fs from 'fs';
15
+ import path from 'path';
16
+ import crypto from 'crypto';
17
+
18
+ // ╔══════════════════════════════════════════════════════════════════════════════════╗
19
+ // ║ Custom Error Classes - Zone 0 ║
20
+ // ║ Enhanced Error Handling System ║
21
+ // ╚══════════════════════════════════════════════════════════════════════════════════╝
22
+
23
+ class SecurityError extends Error {
24
+ constructor(message, filePath = null, errorCode = 'SEC_001') {
25
+ super(message);
26
+ this.name = 'SecurityError';
27
+ this.filePath = filePath;
28
+ this.errorCode = errorCode;
29
+ this.timestamp = new Date().toISOString();
30
+ }
31
+ }
32
+
33
+ class PathTraversalError extends SecurityError {
34
+ constructor(message, filePath = null, attemptedPath = null) {
35
+ super(message, filePath, 'PATH_TRAVERSAL_001');
36
+ this.name = 'PathTraversalError';
37
+ this.attemptedPath = attemptedPath;
38
+ }
39
+ }
40
+
41
+ class SymlinkError extends SecurityError {
42
+ constructor(message, filePath = null, linkTarget = null) {
43
+ super(message, filePath, 'SYMLINK_001');
44
+ this.name = 'SymlinkError';
45
+ this.linkTarget = linkTarget;
46
+ }
47
+ }
48
+
49
+ class FileValidationError extends SecurityError {
50
+ constructor(message, filePath = null, reason = null) {
51
+ super(message, filePath, 'FILE_VAL_001');
52
+ this.name = 'FileValidationError';
53
+ this.reason = reason;
54
+ }
55
+ }
56
+
57
+ class ReDoSError extends SecurityError {
58
+ constructor(message, pattern = null, filePath = null) {
59
+ super(message, filePath, 'REDOS_001');
60
+ this.name = 'ReDoSError';
61
+ this.pattern = pattern;
62
+ }
63
+ }
64
+
65
+ class RateLimitError extends SecurityError {
66
+ constructor(message, operation = null) {
67
+ super(message, null, 'RATE_LIMIT_001');
68
+ this.name = 'RateLimitError';
69
+ this.operation = operation;
70
+ }
71
+ }
72
+
73
+ // ╔══════════════════════════════════════════════════════════════════════════════════╗
74
+ // ║ Security Configuration - Zone 1 ║
75
+ // ║ System-wide Security Settings ║
76
+ // ╚══════════════════════════════════════════════════════════════════════════════════╝
77
+
78
+ const SECURITY_CONFIG = {
79
+ // Path Security
80
+ MAX_PATH_LENGTH: 260,
81
+ ALLOWED_EXTENSIONS: [
82
+ '.js', '.ts', '.jsx', '.tsx', '.vue', '.svelte',
83
+ '.html', '.css', '.scss', '.sass', '.less',
84
+ '.py', '.java', '.cpp', '.c', '.cs', '.go', '.rs', '.rb',
85
+ '.php', '.pl', '.sh', '.bash', '.zsh',
86
+ '.yml', '.yaml', '.json', '.xml', '.toml',
87
+ '.md', '.txt', '.sql', '.lua', '.swift', '.kt', '.dart', '.scala'
88
+ ],
89
+ FORBIDDEN_PATHS: [
90
+ /^[A-Z]:\\Windows\\/i,
91
+ /^[A-Z]:\\Program Files\\/i,
92
+ /^\/etc\//,
93
+ /^\/usr\/bin\//,
94
+ /^\/System\//,
95
+ /^\/bin\//,
96
+ /^\/sbin\//,
97
+ /node_modules/,
98
+ /\.git/
99
+ ],
100
+ // Additional allowed directories (absolute paths). Empty by default.
101
+ EXTRA_ALLOWED_DIRS: [],
102
+
103
+ // File Security
104
+ MAX_FILE_SIZE: 10 * 1024 * 1024, // 10MB
105
+ MIN_FILE_SIZE: 1, // 1 byte
106
+
107
+ // Symlink Security
108
+ ALLOW_SYMLINKS: false,
109
+ MAX_SYMLINK_DEPTH: 3,
110
+
111
+ // ReDoS Protection
112
+ ENABLE_REDOS_PROTECTION: true,
113
+ MAX_PATTERN_EXECUTION_TIME: 1000, // 1 second
114
+ REGEX_TIMEOUT: 5000, // 5 seconds
115
+
116
+ // Rate Limiting
117
+ MAX_FILES_PER_SECOND: 50,
118
+ MAX_OPERATIONS_PER_MINUTE: 500,
119
+ RATE_LIMIT_WINDOW: 60000, // 1 minute
120
+
121
+ // Content Security
122
+ MAX_ANIMATION_DURATION: 300000, // 5 minutes
123
+ MAX_BLOCKS_PER_FILE: 1000,
124
+ MAX_LINES_PER_BLOCK: 50,
125
+
126
+ // Hash & Integrity
127
+ HASH_ALGORITHM: 'sha256',
128
+ VERIFY_FILE_INTEGRITY: true
129
+ };
130
+
131
+ // ╔══════════════════════════════════════════════════════════════════════════════════╗
132
+ // ║ Security Manager - Zone 2 ║
133
+ // ║ Core Security Implementation ║
134
+ // ╚══════════════════════════════════════════════════════════════════════════════════╝
135
+
136
+ class SecurityManager {
137
+ constructor(config = {}) {
138
+ this.config = { ...SECURITY_CONFIG, ...config };
139
+ this.rateLimitStore = new Map();
140
+ this.fileHashCache = new Map();
141
+ this.operationLog = [];
142
+ this.startTime = Date.now();
143
+ }
144
+
145
+ // ══════════════════════════════════════════════════════════════════════════════
146
+ // Input Validation Functions
147
+ // ══════════════════════════════════════════════════════════════════════════════
148
+
149
+ /**
150
+ * Validate user input for path traversal and malicious patterns
151
+ */
152
+ validateInput(target) {
153
+ if (!target || typeof target !== 'string') {
154
+ throw new SecurityError('Invalid input: target must be a non-empty string');
155
+ }
156
+
157
+ // Check for path traversal patterns (but allow absolute paths)
158
+ const dangerousPatterns = [
159
+ /\.\.[\/\\]/, // ../ or ..\
160
+ /[<>"|?*]/, // Invalid filename characters (allow : for Windows drives)
161
+ /\0/, // Null bytes
162
+ /[\x00-\x1f\x7f]/ // Control characters
163
+ ];
164
+
165
+ for (const pattern of dangerousPatterns) {
166
+ if (pattern.test(target)) {
167
+ throw new PathTraversalError(
168
+ `Dangerous pattern detected in input: ${target}`,
169
+ null,
170
+ target
171
+ );
172
+ }
173
+ }
174
+
175
+ // Length validation
176
+ if (target.length > this.config.MAX_PATH_LENGTH) {
177
+ throw new PathTraversalError(
178
+ `Path too long: ${target.length} > ${this.config.MAX_PATH_LENGTH}`,
179
+ null,
180
+ target
181
+ );
182
+ }
183
+
184
+ return true;
185
+ }
186
+
187
+ /**
188
+ * Check if path is safe and not in forbidden directories
189
+ */
190
+ isPathSafe(targetPath) {
191
+ const normalizedPath = path.normalize(targetPath).replace(/\\/g, '/');
192
+
193
+ // Check against forbidden paths
194
+ for (const forbiddenPattern of this.config.FORBIDDEN_PATHS) {
195
+ if (forbiddenPattern.test(normalizedPath)) {
196
+ throw new PathTraversalError(
197
+ `Access to forbidden path: ${targetPath}`,
198
+ targetPath,
199
+ normalizedPath
200
+ );
201
+ }
202
+ }
203
+
204
+ // Allow files within working directory OR workspace folder OR any EXTRA_ALLOWED_DIRS
205
+ const absolutePath = path.resolve(targetPath);
206
+ const workingDir = process.cwd();
207
+ const workspaceDir = path.join(workingDir, 'workspace');
208
+
209
+ const isInWorkingDir = absolutePath.startsWith(workingDir);
210
+ const isInWorkspace = absolutePath.startsWith(workspaceDir);
211
+
212
+ let isInExtra = false;
213
+ if (Array.isArray(this.config.EXTRA_ALLOWED_DIRS)) {
214
+ for (const extra of this.config.EXTRA_ALLOWED_DIRS) {
215
+ if (!extra) continue;
216
+ try {
217
+ const absExtra = path.resolve(extra);
218
+ if (absolutePath.startsWith(absExtra)) {
219
+ isInExtra = true;
220
+ break;
221
+ }
222
+ } catch (e) {
223
+ // ignore invalid entries
224
+ }
225
+ }
226
+ }
227
+
228
+ if (!isInWorkingDir && !isInWorkspace && !isInExtra) {
229
+ throw new PathTraversalError(
230
+ `Path outside allowed directories. Please copy files to workspace folder: ${workspaceDir}`,
231
+ targetPath,
232
+ absolutePath
233
+ );
234
+ }
235
+
236
+ return true;
237
+ }
238
+
239
+ /**
240
+ * Check symlink safety and prevent circular references
241
+ */
242
+ checkSymlinkSafety(filePath, depth = 0) {
243
+ if (!this.config.ALLOW_SYMLINKS) {
244
+ try {
245
+ const stats = fs.lstatSync(filePath);
246
+ if (stats.isSymbolicLink()) {
247
+ throw new SymlinkError(
248
+ 'Symlinks are disabled by security policy',
249
+ filePath,
250
+ fs.readlinkSync(filePath)
251
+ );
252
+ }
253
+ } catch (error) {
254
+ if (error instanceof SymlinkError) throw error;
255
+ // File doesn't exist or other error - will be caught by file validation
256
+ }
257
+ }
258
+
259
+ // Check symlink depth
260
+ if (depth > this.config.MAX_SYMLINK_DEPTH) {
261
+ throw new SymlinkError(
262
+ `Symlink depth exceeded: ${depth} > ${this.config.MAX_SYMLINK_DEPTH}`,
263
+ filePath,
264
+ null
265
+ );
266
+ }
267
+
268
+ return { safe: true, depth };
269
+ }
270
+
271
+ /**
272
+ * Validate file extension
273
+ */
274
+ validateFileExtension(filePath) {
275
+ const ext = path.extname(filePath).toLowerCase();
276
+
277
+ if (!this.config.ALLOWED_EXTENSIONS.includes(ext)) {
278
+ throw new FileValidationError(
279
+ `File extension not allowed: ${ext}`,
280
+ filePath,
281
+ 'INVALID_EXTENSION'
282
+ );
283
+ }
284
+
285
+ return true;
286
+ }
287
+
288
+ /**
289
+ * Validate file size
290
+ */
291
+ validateFileSize(filePath) {
292
+ try {
293
+ const stats = fs.statSync(filePath);
294
+ const size = stats.size;
295
+
296
+ if (size < this.config.MIN_FILE_SIZE) {
297
+ throw new FileValidationError(
298
+ `File too small: ${size} bytes`,
299
+ filePath,
300
+ 'FILE_TOO_SMALL'
301
+ );
302
+ }
303
+
304
+ if (size > this.config.MAX_FILE_SIZE) {
305
+ throw new FileValidationError(
306
+ `File too large: ${size} > ${this.config.MAX_FILE_SIZE}`,
307
+ filePath,
308
+ 'FILE_TOO_LARGE'
309
+ );
310
+ }
311
+
312
+ return { valid: true, size };
313
+ } catch (error) {
314
+ if (error instanceof FileValidationError) throw error;
315
+ throw new FileValidationError(
316
+ `Cannot validate file size: ${error.message}`,
317
+ filePath,
318
+ 'STAT_ERROR'
319
+ );
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Calculate file hash for integrity verification
325
+ */
326
+ calculateFileHash(filePath) {
327
+ try {
328
+ const content = fs.readFileSync(filePath);
329
+ const hash = crypto
330
+ .createHash(this.config.HASH_ALGORITHM)
331
+ .update(content)
332
+ .digest('hex');
333
+
334
+ this.fileHashCache.set(filePath, {
335
+ hash,
336
+ timestamp: Date.now()
337
+ });
338
+
339
+ return hash;
340
+ } catch (error) {
341
+ throw new SecurityError(
342
+ `Failed to calculate file hash: ${error.message}`,
343
+ filePath,
344
+ 'HASH_ERROR'
345
+ );
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Verify file integrity
351
+ */
352
+ verifyFileIntegrity(filePath, expectedHash) {
353
+ const currentHash = this.calculateFileHash(filePath);
354
+
355
+ if (currentHash !== expectedHash) {
356
+ throw new SecurityError(
357
+ 'File integrity verification failed - file may have been tampered with',
358
+ filePath,
359
+ 'INTEGRITY_ERROR'
360
+ );
361
+ }
362
+
363
+ return true;
364
+ }
365
+
366
+ // ══════════════════════════════════════════════════════════════════════════════
367
+ // Rate Limiting Functions
368
+ // ══════════════════════════════════════════════════════════════════════════════
369
+
370
+ /**
371
+ * Check rate limit for operations
372
+ */
373
+ checkRateLimit(operation) {
374
+ const now = Date.now();
375
+ const key = `${operation}_${now}`;
376
+
377
+ // Clean old entries
378
+ for (const [k, v] of this.rateLimitStore.entries()) {
379
+ if (now - v.timestamp > this.config.RATE_LIMIT_WINDOW) {
380
+ this.rateLimitStore.delete(k);
381
+ }
382
+ }
383
+
384
+ // Count operations in current window
385
+ const recentOps = Array.from(this.rateLimitStore.values())
386
+ .filter(entry =>
387
+ entry.operation === operation &&
388
+ now - entry.timestamp < this.config.RATE_LIMIT_WINDOW
389
+ );
390
+
391
+ if (recentOps.length >= this.config.MAX_OPERATIONS_PER_MINUTE) {
392
+ throw new RateLimitError(
393
+ `Rate limit exceeded for operation: ${operation}`,
394
+ operation
395
+ );
396
+ }
397
+
398
+ // Record operation
399
+ this.rateLimitStore.set(key, {
400
+ operation,
401
+ timestamp: now
402
+ });
403
+
404
+ return true;
405
+ }
406
+
407
+ // ══════════════════════════════════════════════════════════════════════════════
408
+ // ReDoS Protection Functions
409
+ // ══════════════════════════════════════════════════════════════════════════════
410
+
411
+ /**
412
+ * Safe regex execution with timeout protection
413
+ */
414
+ safeRegexExecution(pattern, content, filePath = null) {
415
+ if (!this.config.ENABLE_REDOS_PROTECTION) {
416
+ return pattern.test(content);
417
+ }
418
+
419
+ const startTime = Date.now();
420
+ let timeoutId;
421
+ let result = false;
422
+
423
+ const timeoutPromise = new Promise((_, reject) => {
424
+ timeoutId = setTimeout(() => {
425
+ reject(new ReDoSError(
426
+ 'Regex execution timeout - possible ReDoS attack',
427
+ pattern.toString(),
428
+ filePath
429
+ ));
430
+ }, this.config.MAX_PATTERN_EXECUTION_TIME);
431
+ });
432
+
433
+ const executionPromise = new Promise((resolve) => {
434
+ result = pattern.test(content);
435
+ resolve(result);
436
+ });
437
+
438
+ return Promise.race([executionPromise, timeoutPromise])
439
+ .finally(() => {
440
+ clearTimeout(timeoutId);
441
+ const executionTime = Date.now() - startTime;
442
+
443
+ if (executionTime > this.config.MAX_PATTERN_EXECUTION_TIME * 0.8) {
444
+ console.warn(`[SECURITY] Slow regex execution: ${executionTime}ms`);
445
+ }
446
+ });
447
+ }
448
+
449
+ // ══════════════════════════════════════════════════════════════════════════════
450
+ // Complete File Validation
451
+ // ══════════════════════════════════════════════════════════════════════════════
452
+
453
+ /**
454
+ * Comprehensive file validation pipeline
455
+ */
456
+ async validateFile(filePath) {
457
+ try {
458
+ // 1. Resolve absolute path
459
+ const absolutePath = path.resolve(filePath);
460
+
461
+ // 2. Input validation
462
+ this.validateInput(absolutePath);
463
+
464
+ // 3. Path safety check
465
+ this.isPathSafe(absolutePath);
466
+
467
+ // 4. Symlink safety
468
+ this.checkSymlinkSafety(absolutePath);
469
+
470
+ // 5. File extension validation
471
+ this.validateFileExtension(absolutePath);
472
+
473
+ // 6. File size validation
474
+ const sizeInfo = this.validateFileSize(absolutePath);
475
+
476
+ // 7. Rate limit check
477
+ this.checkRateLimit(`file_access_${absolutePath}`);
478
+
479
+ // 8. Calculate hash for integrity
480
+ const hash = this.config.VERIFY_FILE_INTEGRITY
481
+ ? this.calculateFileHash(absolutePath)
482
+ : null;
483
+
484
+ // Log successful validation
485
+ this.logOperation('FILE_VALIDATION_SUCCESS', {
486
+ filePath: absolutePath,
487
+ size: sizeInfo.size,
488
+ hash
489
+ });
490
+
491
+ return {
492
+ valid: true,
493
+ filePath: absolutePath,
494
+ size: sizeInfo.size,
495
+ hash,
496
+ timestamp: Date.now()
497
+ };
498
+
499
+ } catch (error) {
500
+ this.logOperation('FILE_VALIDATION_FAILED', {
501
+ filePath,
502
+ error: error.message,
503
+ errorType: error.name
504
+ });
505
+ throw error;
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Read file with full security validation
511
+ */
512
+ async secureReadFile(filePath) {
513
+ const validation = await this.validateFile(filePath);
514
+
515
+ try {
516
+ const content = fs.readFileSync(validation.filePath, 'utf8');
517
+
518
+ return {
519
+ success: true,
520
+ content,
521
+ filePath: validation.filePath,
522
+ size: validation.size,
523
+ hash: validation.hash
524
+ };
525
+ } catch (error) {
526
+ throw new SecurityError(
527
+ `Failed to read file: ${error.message}`,
528
+ validation.filePath,
529
+ 'READ_ERROR'
530
+ );
531
+ }
532
+ }
533
+
534
+ // ══════════════════════════════════════════════════════════════════════════════
535
+ // Logging & Monitoring
536
+ // ══════════════════════════════════════════════════════════════════════════════
537
+
538
+ /**
539
+ * Log security operations
540
+ */
541
+ logOperation(type, data) {
542
+ const entry = {
543
+ type,
544
+ timestamp: new Date().toISOString(),
545
+ data,
546
+ uptime: Date.now() - this.startTime
547
+ };
548
+
549
+ this.operationLog.push(entry);
550
+
551
+ // Keep only recent logs (last 1000)
552
+ if (this.operationLog.length > 1000) {
553
+ this.operationLog.shift();
554
+ }
555
+
556
+ // Console output in dev mode
557
+ if (process.env.NODE_ENV === 'development') {
558
+ console.log(`[SECURITY] ${type}:`, data);
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Get security statistics
564
+ */
565
+ getSecurityStats() {
566
+ return {
567
+ totalOperations: this.operationLog.length,
568
+ uptime: Date.now() - this.startTime,
569
+ rateLimitEntries: this.rateLimitStore.size,
570
+ cachedHashes: this.fileHashCache.size,
571
+ config: this.config
572
+ };
573
+ }
574
+
575
+ /**
576
+ * Export security log
577
+ */
578
+ exportSecurityLog() {
579
+ return {
580
+ generatedAt: new Date().toISOString(),
581
+ stats: this.getSecurityStats(),
582
+ operations: this.operationLog
583
+ };
584
+ }
585
+ }
586
+
587
+ // ══════════════════════════════════════════════════════════════════════════════
588
+ // Module Exports
589
+ // ══════════════════════════════════════════════════════════════════════════════
590
+
591
+ export {
592
+ SecurityManager,
593
+ SecurityError,
594
+ PathTraversalError,
595
+ SymlinkError,
596
+ FileValidationError,
597
+ ReDoSError,
598
+ RateLimitError,
599
+ SECURITY_CONFIG
600
+ };
src/shared/slide-paginator.js ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ══════════════════════════════════════════════════════════════════════════════
2
+ // Slide Paginator - Auto-split slides based on visual line count
3
+ // ══════════════════════════════════════════════════════════════════════════════
4
+
5
+ /**
6
+ * Configuration for slide pagination
7
+ */
8
+ export const PaginationConfig = {
9
+ maxLinesPerSlide: 6, // Maximum visual lines per slide (reduced to prevent overflow)
10
+ minLinesForSplit: 4, // Minimum lines to justify creating new slide
11
+ balanceThreshold: 0.3, // Balance ratio for splitting (30%)
12
+
13
+ // Visual line weights (how many lines each content type occupies)
14
+ visualLines: {
15
+ h1: 2.5, // H1 takes 2.5 lines (large font with spacing)
16
+ h2: 2, // H2 takes 2 lines
17
+ h3: 1.5,
18
+ h4: 1.2,
19
+ h5: 1,
20
+ h6: 1,
21
+ text: 1, // Normal text = 1 line
22
+ 'list-item': 1.2, // Lists need more space
23
+ 'numbered-item': 1.2,
24
+ 'task-list': 1.2,
25
+ 'code-line': 1, // Code lines are more readable at 1:1 ratio
26
+ blockquote: 1.2,
27
+ image: 4, // Images take significant space
28
+ table: 2.5, // Base table size
29
+ 'table-row': 0.8, // Each table row
30
+ hr: 1,
31
+ html: 3,
32
+ link: 1
33
+ },
34
+
35
+ // Block types that should NOT be split
36
+ atomicBlocks: ['image', 'html', 'hr'],
37
+
38
+ // Block types that CAN be split into multiple parts
39
+ splittableBlocks: ['code', 'blockquote', 'table']
40
+ };
41
+
42
+ /**
43
+ * Calculate visual lines for a content item
44
+ */
45
+ export function calculateVisualLines(item) {
46
+ const config = PaginationConfig;
47
+
48
+ switch (item.type) {
49
+ case 'code':
50
+ const codeLines = item.content.split('\n').length;
51
+ return Math.ceil(codeLines * config.visualLines['code-line']) + 1; // +1 for wrapper
52
+
53
+ case 'blockquote':
54
+ // Count lines in blockquote
55
+ const quoteLines = item.content.split('\n').length;
56
+ return quoteLines * config.visualLines.blockquote;
57
+
58
+ case 'table':
59
+ const rows = item.rows ? item.rows.length : 0;
60
+ return config.visualLines.table + (rows * config.visualLines['table-row']);
61
+
62
+ default:
63
+ return config.visualLines[item.type] || 1;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Calculate total visual lines for an array of content items
69
+ */
70
+ export function calculateTotalLines(contentArray) {
71
+ return contentArray.reduce((total, item) => {
72
+ return total + calculateVisualLines(item);
73
+ }, 0);
74
+ }
75
+
76
+ /**
77
+ * Check if content exceeds max lines per slide
78
+ */
79
+ export function needsPagination(contentArray) {
80
+ return calculateTotalLines(contentArray) > PaginationConfig.maxLinesPerSlide;
81
+ }
82
+
83
+ /**
84
+ * Split a code block into multiple parts
85
+ */
86
+ function splitCodeBlock(codeItem, targetLines) {
87
+ const lines = codeItem.content.split('\n');
88
+ const linesPerPart = Math.ceil(targetLines / PaginationConfig.visualLines['code-line']);
89
+ const parts = [];
90
+
91
+ for (let i = 0; i < lines.length; i += linesPerPart) {
92
+ parts.push({
93
+ type: 'code',
94
+ language: codeItem.language,
95
+ content: lines.slice(i, i + linesPerPart).join('\n'),
96
+ isContinuation: i > 0,
97
+ hasMore: i + linesPerPart < lines.length
98
+ });
99
+ }
100
+
101
+ return parts;
102
+ }
103
+
104
+ /**
105
+ * Split a blockquote into multiple parts
106
+ */
107
+ function splitBlockquote(quoteItem, targetLines) {
108
+ const lines = quoteItem.content.split('\n');
109
+ const parts = [];
110
+
111
+ for (let i = 0; i < lines.length; i += targetLines) {
112
+ parts.push({
113
+ type: 'blockquote',
114
+ content: lines.slice(i, i + targetLines).join('\n'),
115
+ level: quoteItem.level,
116
+ isContinuation: i > 0,
117
+ hasMore: i + targetLines < lines.length
118
+ });
119
+ }
120
+
121
+ return parts;
122
+ }
123
+
124
+ /**
125
+ * Split a table into multiple parts
126
+ */
127
+ function splitTable(tableItem, targetLines) {
128
+ if (!tableItem.rows || tableItem.rows.length <= 2) {
129
+ return [tableItem]; // Too small to split
130
+ }
131
+
132
+ const header = tableItem.rows[0];
133
+ const separator = tableItem.rows[1];
134
+ const dataRows = tableItem.rows.slice(2);
135
+
136
+ const rowsPerPart = Math.max(2, Math.floor(targetLines / PaginationConfig.visualLines['table-row']));
137
+ const parts = [];
138
+
139
+ for (let i = 0; i < dataRows.length; i += rowsPerPart) {
140
+ parts.push({
141
+ type: 'table',
142
+ rows: [
143
+ header,
144
+ separator,
145
+ ...dataRows.slice(i, i + rowsPerPart)
146
+ ],
147
+ isContinuation: i > 0,
148
+ hasMore: i + rowsPerPart < dataRows.length
149
+ });
150
+ }
151
+
152
+ return parts;
153
+ }
154
+
155
+ /**
156
+ * Split a large content block into multiple parts
157
+ */
158
+ function splitLargeBlock(item, availableLines) {
159
+ const targetLines = Math.max(3, availableLines);
160
+
161
+ switch (item.type) {
162
+ case 'code':
163
+ return splitCodeBlock(item, targetLines);
164
+ case 'blockquote':
165
+ return splitBlockquote(item, targetLines);
166
+ case 'table':
167
+ return splitTable(item, targetLines);
168
+ default:
169
+ return [item]; // Can't split this type
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Main pagination function - split content into multiple slides
175
+ */
176
+ export function paginateContent(contentArray, slideInfo = {}) {
177
+ const config = PaginationConfig;
178
+ const slides = [];
179
+ let currentSlide = [];
180
+ let currentLines = 0;
181
+
182
+ // Extract title and subtitle (they go on first slide only)
183
+ const title = slideInfo.title || '';
184
+ const subtitle = slideInfo.subtitle || '';
185
+ const titleLines = title ? config.visualLines.h1 : 0;
186
+ const subtitleLines = subtitle ? config.visualLines.h2 : 0;
187
+ const headerLines = titleLines + subtitleLines;
188
+
189
+ for (let i = 0; i < contentArray.length; i++) {
190
+ const item = contentArray[i];
191
+ const itemLines = calculateVisualLines(item);
192
+
193
+ // Check if this item is atomic (cannot be split)
194
+ const isAtomic = config.atomicBlocks.includes(item.type);
195
+ const isSplittable = config.splittableBlocks.includes(item.type);
196
+
197
+ // Calculate available space in current slide
198
+ const usedLines = currentSlide.length === 0 ? headerLines : 0;
199
+ const availableLines = config.maxLinesPerSlide - currentLines - usedLines;
200
+
201
+ // Case 1: Item fits in current slide
202
+ if (currentLines + itemLines <= config.maxLinesPerSlide - usedLines) {
203
+ currentSlide.push(item);
204
+ currentLines += itemLines;
205
+ }
206
+ // Case 2: Item is too large and can be split
207
+ else if (isSplittable && itemLines > config.maxLinesPerSlide / 2) {
208
+ // Try to use remaining space in current slide
209
+ if (availableLines >= config.minLinesForSplit) {
210
+ const parts = splitLargeBlock(item, availableLines);
211
+
212
+ // Add first part to current slide
213
+ if (parts.length > 0) {
214
+ currentSlide.push(parts[0]);
215
+ currentLines += calculateVisualLines(parts[0]);
216
+ }
217
+
218
+ // Start new slide if current is full
219
+ if (currentSlide.length > 0) {
220
+ slides.push({
221
+ content: currentSlide,
222
+ lines: currentLines,
223
+ pageNumber: slides.length + 1
224
+ });
225
+ currentSlide = [];
226
+ currentLines = 0;
227
+ }
228
+
229
+ // Add remaining parts
230
+ for (let j = 1; j < parts.length; j++) {
231
+ const part = parts[j];
232
+ const partLines = calculateVisualLines(part);
233
+
234
+ if (currentLines + partLines <= config.maxLinesPerSlide) {
235
+ currentSlide.push(part);
236
+ currentLines += partLines;
237
+ } else {
238
+ // Flush current slide
239
+ if (currentSlide.length > 0) {
240
+ slides.push({
241
+ content: currentSlide,
242
+ lines: currentLines,
243
+ pageNumber: slides.length + 1
244
+ });
245
+ }
246
+ // Start new slide with this part
247
+ currentSlide = [part];
248
+ currentLines = partLines;
249
+ }
250
+ }
251
+ } else {
252
+ // Not enough space, start new slide
253
+ if (currentSlide.length > 0) {
254
+ slides.push({
255
+ content: currentSlide,
256
+ lines: currentLines,
257
+ pageNumber: slides.length + 1
258
+ });
259
+ }
260
+
261
+ // Split item across multiple slides
262
+ const parts = splitLargeBlock(item, config.maxLinesPerSlide);
263
+ for (const part of parts) {
264
+ slides.push({
265
+ content: [part],
266
+ lines: calculateVisualLines(part),
267
+ pageNumber: slides.length + 1
268
+ });
269
+ }
270
+
271
+ currentSlide = [];
272
+ currentLines = 0;
273
+ }
274
+ }
275
+ // Case 3: Item doesn't fit and is atomic (must start new slide)
276
+ else {
277
+ // Flush current slide if not empty
278
+ if (currentSlide.length > 0) {
279
+ slides.push({
280
+ content: currentSlide,
281
+ lines: currentLines,
282
+ pageNumber: slides.length + 1
283
+ });
284
+ }
285
+
286
+ // Start new slide with this item
287
+ currentSlide = [item];
288
+ currentLines = itemLines;
289
+ }
290
+ }
291
+
292
+ // Add last slide
293
+ if (currentSlide.length > 0) {
294
+ slides.push({
295
+ content: currentSlide,
296
+ lines: currentLines,
297
+ pageNumber: slides.length + 1
298
+ });
299
+ }
300
+
301
+ return slides;
302
+ }
303
+
304
+ /**
305
+ * Apply pagination to parsed slide and create multiple slides if needed
306
+ */
307
+ export function applyPagination(slide) {
308
+ const totalLines = calculateTotalLines(slide.content);
309
+
310
+ // No pagination needed
311
+ if (totalLines <= PaginationConfig.maxLinesPerSlide) {
312
+ return [{
313
+ ...slide,
314
+ visualLines: totalLines,
315
+ totalPages: 1,
316
+ pageNumber: 1
317
+ }];
318
+ }
319
+
320
+ // Split into multiple pages
321
+ const pages = paginateContent(slide.content, {
322
+ title: slide.title,
323
+ subtitle: slide.subtitle
324
+ });
325
+
326
+ // Create slide objects for each page
327
+ return pages.map((page, index) => ({
328
+ ...slide,
329
+ content: page.content,
330
+ visualLines: page.lines,
331
+ totalPages: pages.length,
332
+ pageNumber: index + 1,
333
+ title: !slide.title
334
+ ? ''
335
+ : index === 0
336
+ ? slide.title
337
+ : `${slide.title} (${index + 1}/${pages.length})`,
338
+ subtitle: index === 0 ? slide.subtitle : '',
339
+ // Adjust duration proportionally
340
+ duration: Math.ceil((slide.duration / pages.length) * 10) / 10
341
+ }));
342
+ }
343
+
344
+ /**
345
+ * Get pagination info for a content array
346
+ */
347
+ export function getPaginationInfo(contentArray) {
348
+ const totalLines = calculateTotalLines(contentArray);
349
+ const needsSplit = totalLines > PaginationConfig.maxLinesPerSlide;
350
+ const estimatedPages = Math.ceil(totalLines / PaginationConfig.maxLinesPerSlide);
351
+
352
+ return {
353
+ totalLines,
354
+ maxLinesPerSlide: PaginationConfig.maxLinesPerSlide,
355
+ needsPagination: needsSplit,
356
+ estimatedPages,
357
+ breakdown: contentArray.map(item => ({
358
+ type: item.type,
359
+ lines: calculateVisualLines(item)
360
+ }))
361
+ };
362
+ }