Download src/renderer/js/app.js from chahuadev/chahuadev-markdown-presenter: direct link, hf CLI and curl.
- Browser
- Download file 105 kB
-
https://huggingface.co/datasets/chahuadev/chahuadev-markdown-presenter/resolve/main/src/renderer/js/app.js
- Command line
-
hf download hf://datasets/chahuadev/chahuadev-markdown-presenter/src/renderer/js/app.js
-
curl -L -o app.js https://huggingface.co/datasets/chahuadev/chahuadev-markdown-presenter/resolve/main/src/renderer/js/app.js
105 kB
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Chahua Markdown Video Studio - Main Application Controller | |
| // Markdown-First Workflow - v2.0 Timeline Engine | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Company: Chahua Development Co., Ltd. | |
| // Version: 2.0.0 | |
| import { MarkdownParser } from '../../shared/markdown-parser.js'; | |
| import { buildLayoutTreeForSlide, LayoutNodeKind } from '../../shared/layout-schema.js'; | |
| import { VideoRenderer, blobToBase64 } from './video-renderer.js'; | |
| import { applyTemplate, getAllTemplates } from './templates.js'; | |
| import { | |
| getAllPresets, | |
| loadPreset, | |
| getCurrentConfig, | |
| updateConfigPart, | |
| initPresentationUI, | |
| reloadUI, | |
| loadConfigFromFrontmatter, | |
| resetConfig, | |
| computeSafeZoneMargins, | |
| SAFE_ZONE_CONFIG, | |
| getSmartLayoutFillRatio, | |
| getSmartLayoutStageFallback, | |
| SMART_LAYOUT_CONFIG, | |
| loadSavedConfig, | |
| exportConfigToFile, | |
| importConfigFromFile, | |
| setDisplayMode, | |
| getDisplayMode, | |
| getSafeZoneConfig | |
| } from './presentation-config.js'; | |
| import { SlideEditor } from './slide-editor.js'; | |
| import { ConfigStorage } from './config-storage.js'; | |
| import { | |
| switchToIntroMode, | |
| switchToPresentationMode, | |
| switchToEditorMode, | |
| getModeManager | |
| } from './mode-manager.js'; | |
| // ============================================================================== | |
| // INTRO SCENE CONSTANTS - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: These constants are used exclusively by the intro scene system | |
| // The intro scene is working perfectly - modifications are not needed | |
| // Do not link these constants to presentation mode or any other logic | |
| // ============================================================================== | |
| // SMART LAYOUT CONSTANTS - Smart content layout optimization | |
| // ============================================================================== | |
| // DEPRECATED: Use SMART_LAYOUT_CONFIG from presentation-config.js instead | |
| // Kept for backward compatibility only | |
| const SMART_LAYOUT_FILL_RATIO = 0.92; | |
| const SMART_LAYOUT_STAGE_FALLBACK = { width: 1280, height: 720 }; | |
| // DEPRECATED: Use SAFE_ZONE_CONFIG from presentation-config.js instead | |
| // Kept for backward compatibility only | |
| const SMART_SAFE_ZONE = { | |
| horizontalRatio: 0.06, | |
| verticalRatio: 0.08, | |
| maxHorizontalRatio: 0.12, | |
| maxVerticalRatio: 0.15, | |
| minHorizontal: 40, | |
| minVertical: 40 | |
| }; | |
| // ============================================================================== | |
| // INTRO SCENE HELPER FUNCTIONS - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: These functions are used exclusively by the intro scene system | |
| // Do not link these to presentation mode - create separate functions if needed | |
| // ============================================================================== | |
| /** | |
| * LOCKED - Intro scene utility function | |
| * Do not modify or reuse for other purposes | |
| */ | |
| function clamp(value, min, max) { | |
| return Math.min(Math.max(value, min), max); | |
| } | |
| /** | |
| * LOCKED - Intro scene safe zone calculation | |
| * Do not use for presentation mode - create separate function if needed | |
| * | |
| * DEPRECATED: Use computeSafeZoneMargins from presentation-config.js instead | |
| */ | |
| function computeSafeZoneInsets(stageRect = {}) { | |
| // Redirect to new centralized function | |
| return computeSafeZoneMargins(stageRect); | |
| } | |
| /** | |
| * LOCKED - Intro scene padding formatter | |
| * Do not modify or reuse for other purposes | |
| */ | |
| function formatSafeZonePadding(insets) { | |
| return `${Math.round(insets.top)}px ${Math.round(insets.right)}px ${Math.round(insets.bottom)}px ${Math.round(insets.left)}px`; | |
| } | |
| /** | |
| * LOCKED - Intro scene padding applicator | |
| * Do not use for presentation mode - create separate function if needed | |
| */ | |
| function applySafeZonePadding(target, insets) { | |
| if (!target || !insets) return; | |
| const paddingValue = formatSafeZonePadding(insets); | |
| target.style.boxSizing = 'border-box'; | |
| target.style.padding = paddingValue; | |
| target.style.setProperty('--smart-safe-padding', paddingValue); | |
| target.dataset.safeTop = String(Math.round(insets.top)); | |
| target.dataset.safeBottom = String(Math.round(insets.bottom)); | |
| target.dataset.safeLeft = String(Math.round(insets.left)); | |
| target.dataset.safeRight = String(Math.round(insets.right)); | |
| } | |
| const state = { | |
| markdown: '', | |
| frontmatter: {}, | |
| slides: [], | |
| totalDuration: 0, | |
| template: 'modern', | |
| videoConfig: { | |
| resolution: '1920x1080', | |
| fps: 60, | |
| quality: 0.95 | |
| }, | |
| themeConfig: { | |
| accent: '#60a5fa' | |
| }, | |
| isPlaying: false, | |
| isPaused: false, | |
| isPresentationMode: false, | |
| currentSlideIndex: 0, | |
| pauseResolve: null, | |
| errors: [], | |
| warnings: [], | |
| screenSensor: { | |
| width: window.innerWidth, | |
| height: window.innerHeight, | |
| pixelRatio: window.devicePixelRatio || 1, | |
| isLargeScreen: false, | |
| screenType: 'normal', | |
| isFullscreen: false, | |
| availableSpace: window.innerWidth * window.innerHeight, | |
| lastUpdate: Date.now() | |
| } | |
| }; | |
| const dom = { | |
| stage: document.getElementById('stage'), | |
| stageFrame: document.getElementById('stageFrame'), | |
| pauseOverlay: document.getElementById('pauseOverlay'), | |
| navControls: document.getElementById('navControls'), | |
| prevSlideBtn: document.getElementById('prevSlideBtn'), | |
| nextSlideBtn: document.getElementById('nextSlideBtn'), | |
| slideCounter: document.getElementById('slideCounter'), | |
| fullscreenBtn: document.getElementById('fullscreenBtn'), | |
| sceneElements: null, | |
| statusPill: document.getElementById('statusPill'), | |
| statusLog: document.getElementById('statusLog'), | |
| progressContainer: document.getElementById('progressContainer'), | |
| progressBar: document.getElementById('progressBar'), | |
| progressText: document.getElementById('progressText'), | |
| markdownEditor: document.getElementById('markdownEditor'), | |
| markdownDiagnostics: document.getElementById('markdownDiagnostics'), | |
| markdownSummary: document.getElementById('markdownSummary'), | |
| timelineTotal: document.getElementById('timelineTotal'), | |
| timelineSceneList: document.getElementById('timelineSceneList'), | |
| assetChecklist: document.getElementById('assetChecklist'), | |
| templatesContainer: document.getElementById('templatesContainer'), | |
| templateActiveLabel: document.getElementById('templateActiveLabel'), | |
| // Presentation Settings Controls | |
| presetSelector: document.getElementById('presetSelector'), | |
| fontHeading: document.getElementById('fontHeading'), | |
| fontBody: document.getElementById('fontBody'), | |
| fontCode: document.getElementById('fontCode'), | |
| colorPrimary: document.getElementById('colorPrimary'), | |
| colorAccent: document.getElementById('colorAccent'), | |
| colorBackground: document.getElementById('colorBackground'), | |
| colorText: document.getElementById('colorText'), | |
| animationTransition: document.getElementById('animationTransition'), | |
| animationDuration: document.getElementById('animationDuration'), | |
| // Font Sizes | |
| fontSizeH1Min: document.getElementById('fontSizeH1Min'), | |
| fontSizeH1Base: document.getElementById('fontSizeH1Base'), | |
| fontSizeH1Max: document.getElementById('fontSizeH1Max'), | |
| fontSizeH2Min: document.getElementById('fontSizeH2Min'), | |
| fontSizeH2Base: document.getElementById('fontSizeH2Base'), | |
| fontSizeH2Max: document.getElementById('fontSizeH2Max'), | |
| fontSizeTextMin: document.getElementById('fontSizeTextMin'), | |
| fontSizeTextBase: document.getElementById('fontSizeTextBase'), | |
| fontSizeTextMax: document.getElementById('fontSizeTextMax'), | |
| lineHeightHeading: document.getElementById('lineHeightHeading'), | |
| lineHeightBody: document.getElementById('lineHeightBody'), | |
| // UI & Visual Effects | |
| previewOpacity: document.getElementById('previewOpacity'), | |
| overlayBlur: document.getElementById('overlayBlur'), | |
| navBorderWidth: document.getElementById('navBorderWidth'), | |
| backdropSpread: document.getElementById('backdropSpread'), | |
| backdropBlur: document.getElementById('backdropBlur'), | |
| // Border Widths | |
| headingBorderWidth: document.getElementById('headingBorderWidth'), | |
| blockquoteBorderWidth: document.getElementById('blockquoteBorderWidth'), | |
| imageBorderWidth: document.getElementById('imageBorderWidth'), | |
| linkUnderlineWidth: document.getElementById('linkUnderlineWidth'), | |
| tableBorderWidth: document.getElementById('tableBorderWidth'), | |
| hrBorderWidth: document.getElementById('hrBorderWidth'), | |
| // Typography Controls | |
| paragraphBefore: document.getElementById('paragraphBefore'), | |
| paragraphAfter: document.getElementById('paragraphAfter'), | |
| headingBefore: document.getElementById('headingBefore'), | |
| headingAfter: document.getElementById('headingAfter'), | |
| indentFirst: document.getElementById('indentFirst'), | |
| indentBlockquote: document.getElementById('indentBlockquote'), | |
| listIndent: document.getElementById('listIndent'), | |
| textAlign: document.getElementById('textAlign'), | |
| // Page Indicator | |
| pageIndicatorTop: document.getElementById('pageIndicatorTop'), | |
| pageIndicatorRight: document.getElementById('pageIndicatorRight'), | |
| pageIndicatorFontSize: document.getElementById('pageIndicatorFontSize'), | |
| pageIndicatorOpacity: document.getElementById('pageIndicatorOpacity'), | |
| pageIndicatorPaddingX: document.getElementById('pageIndicatorPaddingX'), | |
| pageIndicatorPaddingY: document.getElementById('pageIndicatorPaddingY'), | |
| pageIndicatorBgColor: document.getElementById('pageIndicatorBgColor'), | |
| pageIndicatorTextColor: document.getElementById('pageIndicatorTextColor'), | |
| // Smart List Column Settings | |
| smartListTwoColumn: document.getElementById('smartListTwoColumn'), | |
| smartListThreeColumn: document.getElementById('smartListThreeColumn'), | |
| // Content Layout & Positioning | |
| contentPaddingSmall: document.getElementById('contentPaddingSmall'), | |
| contentPaddingLarge: document.getElementById('contentPaddingLarge'), | |
| contentPaddingUltra: document.getElementById('contentPaddingUltra'), | |
| contentAlignHorizontal: document.getElementById('contentAlignHorizontal'), | |
| contentAlignVertical: document.getElementById('contentAlignVertical'), | |
| // Action Buttons | |
| saveSettingsBtn: document.getElementById('saveSettingsBtn'), | |
| resetSettingsBtn: document.getElementById('resetSettingsBtn'), | |
| // Other Controls | |
| syncMarkdownBtn: document.getElementById('syncMarkdownBtn'), | |
| loadMarkdownSample: document.getElementById('loadMarkdownSample'), | |
| importMarkdownBtn: document.getElementById('importMarkdownBtn'), | |
| openWorkspaceBtn: document.getElementById('openWorkspaceBtn'), | |
| presentationModeBtn: document.getElementById('presentationModeBtn'), | |
| exitPresentationBtn: document.getElementById('exitPresentationBtn'), | |
| stopPreviewBtn: document.getElementById('stopPreviewBtn'), | |
| stopExportBtn: document.getElementById('stopExportBtn'), | |
| previewBtn: document.getElementById('previewBtn'), | |
| recordWebMBtn: document.getElementById('recordWebMBtn'), | |
| resetBtn: document.getElementById('resetBtn'), | |
| securityBtn: document.getElementById('securityBtn'), | |
| measurementStage: null, | |
| measurementScene: null, | |
| measurementRoot: null | |
| }; | |
| function flattenLayoutTree(layout) { | |
| if (!layout || !Array.isArray(layout.sections)) { | |
| return []; | |
| } | |
| const items = []; | |
| layout.sections.forEach(section => { | |
| const sectionId = section.id; | |
| section.blocks.forEach(block => { | |
| const baseMeta = { | |
| layoutBlockId: block.id, | |
| layoutBlockKind: block.kind, | |
| sectionId | |
| }; | |
| switch (block.kind) { | |
| case LayoutNodeKind.HEADING: { | |
| const level = Math.min(Math.max(block.level || 1, 1), 6); | |
| items.push({ | |
| ...baseMeta, | |
| type: `h${level}`, | |
| content: block.text || '', | |
| html: block.html || null | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.TEXT: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'text', | |
| content: block.text || '', | |
| html: block.html || null | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.LIST: { | |
| const listType = block.listType; | |
| block.items.forEach((listItem, index) => { | |
| let type = 'list-item'; | |
| if (listType === 'ordered') type = 'numbered-item'; | |
| if (listType === 'task') type = 'task-list'; | |
| items.push({ | |
| ...baseMeta, | |
| type, | |
| content: listItem.text || '', | |
| marker: listItem.marker || '•', | |
| number: listItem.number || index + 1, | |
| checked: !!listItem.checked, | |
| listId: block.id, | |
| listItemId: listItem.id, | |
| html: listItem.html || null | |
| }); | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.CODE: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'code', | |
| content: block.content || '', | |
| language: block.language || 'text' | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.TABLE: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'table', | |
| rows: block.rows || [] | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.CALLOUT: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'blockquote', | |
| content: block.text || '', | |
| html: block.html || null | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.IMAGE: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'image', | |
| src: block.src, | |
| alt: block.alt || '', | |
| title: block.title || '' | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.DIVIDER: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'hr' | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.HTML: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'html', | |
| content: block.html || '', | |
| html: block.html || null | |
| }); | |
| break; | |
| } | |
| case LayoutNodeKind.LINK: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'link', | |
| text: block.text || block.href || '', | |
| url: block.href || '', | |
| title: block.title || '', | |
| html: block.html || null | |
| }); | |
| break; | |
| } | |
| default: { | |
| items.push({ | |
| ...baseMeta, | |
| type: 'text', | |
| content: block.text || block.content || '', | |
| html: block.html || null | |
| }); | |
| } | |
| } | |
| }); | |
| }); | |
| return items; | |
| } | |
| function enrichSlidesWithLayout(slides) { | |
| return slides.map(slide => { | |
| const layout = buildLayoutTreeForSlide(slide); | |
| const renderItems = flattenLayoutTree(layout); | |
| const visualLines = slide.visualLines != null ? slide.visualLines : layout?.metrics?.estimatedLines; | |
| return { | |
| ...slide, | |
| layout, | |
| renderItems, | |
| visualLines | |
| }; | |
| }); | |
| } | |
| // ============================================================================== | |
| // INTRO SCENE MEASUREMENT STAGE - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: This function creates measurement stage for intro scene only | |
| // Do not link to presentation mode logic | |
| // ============================================================================== | |
| /** | |
| * LOCKED - Intro scene measurement stage setup | |
| * Do not modify - intro scene depends on this exact implementation | |
| */ | |
| function ensureMeasurementStage() { | |
| if (!dom.measurementStage) { | |
| const measurementStage = document.createElement('div'); | |
| measurementStage.id = 'smartMeasurementStage'; | |
| measurementStage.style.position = 'fixed'; | |
| measurementStage.style.top = '-10000px'; | |
| measurementStage.style.left = '-10000px'; | |
| measurementStage.style.visibility = 'hidden'; | |
| measurementStage.style.pointerEvents = 'none'; | |
| measurementStage.style.zIndex = '-1'; | |
| const measurementScene = document.createElement('div'); | |
| measurementScene.className = 'scene active'; | |
| measurementScene.dataset.scene = 'body'; | |
| const measurementRoot = document.createElement('div'); | |
| measurementRoot.className = 'smart-layout-root relative z-10 space-y-4'; | |
| measurementScene.appendChild(measurementRoot); | |
| measurementStage.appendChild(measurementScene); | |
| document.body.appendChild(measurementStage); | |
| dom.measurementStage = measurementStage; | |
| dom.measurementScene = measurementScene; | |
| dom.measurementRoot = measurementRoot; | |
| } | |
| updateMeasurementStageSize(); | |
| if (dom.measurementRoot) { | |
| dom.measurementRoot.innerHTML = ''; | |
| } | |
| return dom.measurementRoot; | |
| } | |
| // ============================================================================== | |
| // INTRO SCENE SIZE UPDATE - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: This function syncs measurement stage size for intro scene only | |
| // Do not use for presentation mode - create separate function if needed | |
| // ============================================================================== | |
| /** | |
| * LOCKED - Intro scene measurement stage size synchronization | |
| * Do not modify - intro scene depends on this exact implementation | |
| */ | |
| function updateMeasurementStageSize() { | |
| if (!dom.measurementStage) return; | |
| dom.measurementRoot.innerHTML = ''; | |
| const stageRect = dom.stage | |
| ? dom.stage.getBoundingClientRect() | |
| : dom.stageFrame | |
| ? dom.stageFrame.getBoundingClientRect() | |
| : getSmartLayoutStageFallback(); | |
| dom.measurementStage.style.width = `${stageRect.width}px`; | |
| dom.measurementStage.style.height = `${stageRect.height}px`; | |
| const screenType = state.screenSensor?.screenType || 'normal'; | |
| dom.measurementStage.classList.remove('screen-normal', 'screen-large', 'screen-ultra'); | |
| dom.measurementStage.classList.add(`screen-${screenType}`); | |
| if (dom.measurementScene) { | |
| // Get padding values from CSS variables (set by presentation config) | |
| const root = document.documentElement; | |
| const paddingSmall = parseInt(root.style.getPropertyValue('--content-padding-small')) || 40; | |
| const paddingLarge = parseInt(root.style.getPropertyValue('--content-padding-large')) || 48; | |
| const paddingUltra = parseInt(root.style.getPropertyValue('--content-padding-ultra')) || 64; | |
| const alignHorizontal = root.style.getPropertyValue('--content-align-horizontal') || 'center'; | |
| const alignVertical = root.style.getPropertyValue('--content-align-vertical') || 'center'; | |
| let paddingTop = paddingSmall; | |
| let paddingSides = paddingSmall; | |
| if (screenType === 'large') { | |
| paddingTop = paddingLarge; | |
| paddingSides = paddingLarge; | |
| } else if (screenType === 'ultra') { | |
| paddingTop = paddingUltra; | |
| paddingSides = paddingUltra; | |
| } | |
| // Apply alignment from config | |
| dom.measurementScene.style.justifyContent = alignHorizontal; | |
| dom.measurementScene.style.alignItems = alignVertical; | |
| dom.measurementScene.style.paddingTop = `${paddingTop}px`; | |
| dom.measurementScene.style.paddingBottom = `${paddingTop}px`; | |
| dom.measurementScene.style.paddingLeft = `${paddingSides}px`; | |
| dom.measurementScene.style.paddingRight = `${paddingSides}px`; | |
| } | |
| if (dom.measurementRoot) { | |
| dom.measurementRoot.style.width = '100%'; | |
| dom.measurementRoot.style.maxWidth = '100%'; | |
| } | |
| } | |
| function setupTabs() { | |
| const tabButtons = document.querySelectorAll('.tab-button'); | |
| const tabContents = document.querySelectorAll('.tab-content'); | |
| tabButtons.forEach(button => { | |
| button.addEventListener('click', () => { | |
| const tabName = button.dataset.tab; | |
| tabButtons.forEach(btn => btn.classList.remove('active')); | |
| tabContents.forEach(content => content.classList.remove('active')); | |
| button.classList.add('active'); | |
| const target = document.querySelector(`[data-tab-content="${tabName}"]`); | |
| if (target) { | |
| target.classList.add('active'); | |
| } | |
| }); | |
| }); | |
| } | |
| function getTemplateEmoji(templateId) { | |
| const icons = { | |
| modern: '◆', | |
| classic: '■', | |
| minimal: '○', | |
| mono: '●', | |
| rounded: '◉', | |
| space: '▲', | |
| code: '◈', | |
| tech: '◐', | |
| display: '▼', | |
| corporate: '□' | |
| }; | |
| return icons[templateId] || '◇'; | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Presentation Settings (replaces fixed templates) | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupPresentationSettings() { | |
| // Initialize UI with callbacks | |
| initPresentationUI(dom, { | |
| onUpdate: updateStagePreview, | |
| onSave: savePresentationSettings, | |
| setStatus: setStatus | |
| }); | |
| } | |
| function savePresentationSettings(config, presetName) { | |
| // ⚠️ DEPRECATED: Frontmatter config saving has been removed | |
| // All settings are now automatically saved to localStorage | |
| // Use Export Config button to create JSON backup files | |
| console.log('[App] ℹ️ Config auto-saved to localStorage'); | |
| console.log('[App] Current preset:', presetName || 'custom'); | |
| // Note: Auto-save is handled by setConfig() and updateConfigPart() in presentation-config.js | |
| // No manual frontmatter saving needed anymore | |
| } | |
| function setupTemplates() { | |
| if (!dom.templatesContainer) return; | |
| dom.templatesContainer.innerHTML = ''; | |
| const templates = getAllTemplates(); | |
| templates.forEach(template => { | |
| const card = document.createElement('div'); | |
| card.className = `template-card ${template.id === state.template ? 'active' : ''}`; | |
| card.innerHTML = ` | |
| <div class="text-2xl mb-2">${getTemplateEmoji(template.id)}</div> | |
| <div class="font-semibold text-sm mb-1">${template.name}</div> | |
| <div class="text-xs text-slate-400">${template.description}</div> | |
| `; | |
| card.addEventListener('click', () => selectTemplate(template.id)); | |
| dom.templatesContainer.appendChild(card); | |
| }); | |
| } | |
| function selectTemplate(templateId) { | |
| state.template = templateId; | |
| const cards = dom.templatesContainer ? dom.templatesContainer.querySelectorAll('.template-card') : []; | |
| cards.forEach(card => card.classList.remove('active')); | |
| const templates = getAllTemplates(); | |
| const index = templates.findIndex(t => t.id === templateId); | |
| if (cards[index]) { | |
| cards[index].classList.add('active'); | |
| } | |
| applyTemplate(templateId); | |
| updateTemplateUI(); | |
| upsertFrontmatterValue('template', templateId); | |
| if (state.slides.length > 0) { | |
| syncMarkdown(); | |
| } | |
| setStatus(`Template: ${templateId}`, 'online'); | |
| } | |
| function updateTemplateUI() { | |
| if (!dom.templateActiveLabel) return; | |
| dom.templateActiveLabel.textContent = state.template; | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Markdown Controls & Parsing | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupMarkdownControls() { | |
| dom.syncMarkdownBtn.addEventListener('click', syncMarkdown); | |
| dom.loadMarkdownSample.addEventListener('click', loadSampleDeck); | |
| dom.importMarkdownBtn.addEventListener('click', importMarkdownFile); | |
| dom.openWorkspaceBtn.addEventListener('click', openWorkspaceFolder); | |
| let markdownTimeout; | |
| dom.markdownEditor.addEventListener('input', () => { | |
| clearTimeout(markdownTimeout); | |
| markdownTimeout = setTimeout(() => { | |
| dom.syncMarkdownBtn.classList.add('pulse'); | |
| }, 1000); | |
| }); | |
| // Setup Drag & Drop for markdown editor | |
| setupMarkdownDropZone(); | |
| } | |
| /** | |
| * Setup Drag & Drop zone for markdown files | |
| */ | |
| function setupMarkdownDropZone() { | |
| const dropZone = document.getElementById('markdownDropZone'); | |
| const textarea = dom.markdownEditor; | |
| const overlay = dropZone?.querySelector('.drop-overlay'); | |
| if (!dropZone || !textarea || !overlay) return; | |
| // Prevent default drag behaviors on the document | |
| ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { | |
| dropZone.addEventListener(eventName, preventDefaults, false); | |
| document.body.addEventListener(eventName, preventDefaults, false); | |
| }); | |
| function preventDefaults(e) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| } | |
| // Highlight drop zone when dragging over | |
| ['dragenter', 'dragover'].forEach(eventName => { | |
| dropZone.addEventListener(eventName, () => { | |
| dropZone.classList.add('drag-over'); | |
| overlay.classList.remove('hidden'); | |
| }, false); | |
| }); | |
| ['dragleave', 'drop'].forEach(eventName => { | |
| dropZone.addEventListener(eventName, () => { | |
| dropZone.classList.remove('drag-over'); | |
| overlay.classList.add('hidden'); | |
| }, false); | |
| }); | |
| // Handle dropped files | |
| dropZone.addEventListener('drop', handleDrop, false); | |
| async function handleDrop(e) { | |
| const dt = e.dataTransfer; | |
| const files = dt.files; | |
| if (files.length === 0) return; | |
| const file = files[0]; | |
| const fileName = file.name.toLowerCase(); | |
| // Check if it's a text-based file | |
| if (!fileName.endsWith('.md') && | |
| !fileName.endsWith('.markdown') && | |
| !fileName.endsWith('.txt')) { | |
| setStatus('Please drop a markdown file (.md, .markdown, .txt)', 'online'); | |
| return; | |
| } | |
| try { | |
| const text = await file.text(); | |
| textarea.value = text; | |
| setStatus(`Loaded: ${file.name} (${formatFileSize(file.size)})`, 'online'); | |
| dom.syncMarkdownBtn.classList.add('pulse'); | |
| // Auto-sync if markdown is valid | |
| if (text.trim().length > 0) { | |
| setTimeout(() => { | |
| syncMarkdown(); | |
| }, 500); | |
| } | |
| } catch (error) { | |
| console.error('[App] Drop error:', error); | |
| setStatus('Failed to read file', 'online'); | |
| } | |
| } | |
| } | |
| /** | |
| * Format file size for display | |
| */ | |
| function formatFileSize(bytes) { | |
| if (bytes < 1024) return bytes + ' B'; | |
| if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; | |
| return (bytes / 1024 / 1024).toFixed(1) + ' MB'; | |
| } | |
| async function syncMarkdown() { | |
| try { | |
| dom.syncMarkdownBtn.classList.remove('pulse'); | |
| dom.syncMarkdownBtn.textContent = 'Sync Markdown'; | |
| setStatus('Parsing markdown...', 'online'); | |
| state.markdown = dom.markdownEditor.value; | |
| parseFrontmatter(); | |
| // Determine slide break mode from frontmatter or use default | |
| const slideBreakMode = state.frontmatter.slideBreak || 'auto'; | |
| let parserOptions = { | |
| h1AsSlide: true, | |
| h2AsSlide: true, | |
| slideBreak: '---' | |
| }; | |
| switch (slideBreakMode) { | |
| case 'h1': | |
| parserOptions.h1AsSlide = true; | |
| parserOptions.h2AsSlide = false; | |
| break; | |
| case 'h2': | |
| parserOptions.h1AsSlide = false; | |
| parserOptions.h2AsSlide = true; | |
| break; | |
| case 'delimiter': | |
| case 'manual': | |
| parserOptions.h1AsSlide = false; | |
| parserOptions.h2AsSlide = false; | |
| break; | |
| case 'auto': | |
| default: | |
| parserOptions.h1AsSlide = true; | |
| parserOptions.h2AsSlide = true; | |
| } | |
| const parser = new MarkdownParser(parserOptions); | |
| const parsedSlides = parser.parse(state.markdown); | |
| state.slides = enrichSlidesWithLayout(parsedSlides); | |
| state.totalDuration = state.slides.reduce((sum, slide) => sum + slide.duration, 0); | |
| validateMarkdown(); | |
| updateMarkdownSummary(); | |
| updateTimelineUI(); | |
| updateStagePreview(); | |
| applyConfigFromFrontmatter(); | |
| if (state.errors.length === 0) { | |
| dom.markdownDiagnostics.classList.add('hidden'); | |
| setStatus(`Synced: ${state.slides.length} slides, ${formatDuration(state.totalDuration)}`, 'online'); | |
| } else { | |
| showDiagnostics(); | |
| } | |
| } catch (error) { | |
| console.error('[App] Sync error:', error); | |
| state.errors.push(`Parse error: ${error.message}`); | |
| showDiagnostics(); | |
| setStatus('Sync failed - see diagnostics', 'online'); | |
| } | |
| } | |
| function parseFrontmatter() { | |
| state.frontmatter = {}; | |
| const lines = state.markdown.split('\n'); | |
| let inFrontmatter = false; | |
| let frontmatterLines = []; | |
| let foundClosing = false; | |
| // Frontmatter must start at line 0 or 1 (after empty line) | |
| const startLine = lines[0].trim() === '' ? 1 : 0; | |
| for (let i = startLine; i < lines.length; i++) { | |
| const line = lines[i].trim(); | |
| // First delimiter | |
| if (line === '---' && !inFrontmatter && i === startLine) { | |
| inFrontmatter = true; | |
| continue; | |
| } | |
| // Closing delimiter | |
| if (line === '---' && inFrontmatter) { | |
| foundClosing = true; | |
| break; | |
| } | |
| // Collect frontmatter lines | |
| if (inFrontmatter) { | |
| // Stop if we hit 50 lines without closing (prevent runaway) | |
| if (i - startLine > 50) { | |
| console.warn('[App] Frontmatter not closed within 50 lines, ignoring'); | |
| state.frontmatter = {}; | |
| return; | |
| } | |
| frontmatterLines.push(line); | |
| } | |
| } | |
| // If no valid frontmatter block found, return empty | |
| if (!foundClosing) { | |
| state.frontmatter = {}; | |
| return; | |
| } | |
| // Parse YAML-like frontmatter | |
| frontmatterLines.forEach(line => { | |
| const match = line.match(/^([^:]+):\s*(.+)$/); | |
| if (match) { | |
| const key = match[1].trim(); | |
| let value = match[2].trim().replace(/^["']|["']$/g, ''); | |
| state.frontmatter[key] = value; | |
| } | |
| }); | |
| } | |
| function upsertFrontmatterValue(key, value) { | |
| state.frontmatter[key] = value; | |
| const lines = dom.markdownEditor.value.split('\n'); | |
| let inFrontmatter = false; | |
| let frontmatterStartIndex = -1; | |
| let frontmatterEndIndex = -1; | |
| let keyFound = false; | |
| // Find frontmatter block | |
| for (let i = 0; i < lines.length; i++) { | |
| const line = lines[i].trim(); | |
| if (line === '---') { | |
| if (!inFrontmatter) { | |
| inFrontmatter = true; | |
| frontmatterStartIndex = i; | |
| continue; | |
| } else { | |
| frontmatterEndIndex = i; | |
| break; | |
| } | |
| } | |
| } | |
| // If no frontmatter block exists, create one | |
| if (frontmatterStartIndex === -1) { | |
| lines.unshift('---', `${key}: ${value}`, '---', ''); | |
| dom.markdownEditor.value = lines.join('\n'); | |
| return; | |
| } | |
| // Check if key already exists and update it | |
| for (let i = frontmatterStartIndex + 1; i < frontmatterEndIndex; i++) { | |
| const line = lines[i].trim(); | |
| if (line.startsWith(`${key}:`)) { | |
| lines[i] = `${key}: ${value}`; | |
| keyFound = true; | |
| break; | |
| } | |
| } | |
| // If key not found, insert before closing delimiter | |
| if (!keyFound && frontmatterEndIndex > 0) { | |
| lines.splice(frontmatterEndIndex, 0, `${key}: ${value}`); | |
| } | |
| dom.markdownEditor.value = lines.join('\n'); | |
| } | |
| function applyConfigFromFrontmatter() { | |
| // ⚠️ CHANGED: Only load config from frontmatter if user has NO saved config | |
| // This prevents overwriting user's saved settings when loading different markdown files | |
| const hasSavedConfig = ConfigStorage.hasSavedConfig(); | |
| if (!hasSavedConfig) { | |
| // No saved config - load from frontmatter as fallback | |
| console.log('[App] No saved config found, loading from markdown frontmatter'); | |
| loadConfigFromFrontmatter(state.frontmatter, dom); | |
| } else { | |
| console.log('[App] Using saved config, ignoring markdown frontmatter'); | |
| } | |
| // Legacy template support (fallback for old markdown files) | |
| if (state.frontmatter.template) { | |
| state.template = state.frontmatter.template; | |
| applyTemplate(state.template); | |
| updateTemplateUI(); | |
| } | |
| // Video config | |
| if (state.frontmatter['video.resolution']) { | |
| state.videoConfig.resolution = state.frontmatter['video.resolution']; | |
| const resSelect = document.querySelector('[data-config="video.resolution"]'); | |
| if (resSelect) resSelect.value = state.videoConfig.resolution; | |
| } | |
| if (state.frontmatter['video.fps']) { | |
| state.videoConfig.fps = parseInt(state.frontmatter['video.fps']); | |
| const fpsSelect = document.querySelector('[data-config="video.fps"]'); | |
| if (fpsSelect) fpsSelect.value = state.videoConfig.fps; | |
| } | |
| if (state.frontmatter['video.quality']) { | |
| state.videoConfig.quality = parseFloat(state.frontmatter['video.quality']); | |
| const qualitySlider = document.querySelector('[data-config="video.quality"]'); | |
| if (qualitySlider) { | |
| qualitySlider.value = state.videoConfig.quality; | |
| document.getElementById('qualityValue').textContent = Math.round(state.videoConfig.quality * 100) + '%'; | |
| } | |
| } | |
| // Theme config | |
| if (state.frontmatter['theme.accent']) { | |
| state.themeConfig.accent = state.frontmatter['theme.accent']; | |
| const accentInput = document.querySelector('[data-config="theme.accent"]'); | |
| if (accentInput) accentInput.value = state.themeConfig.accent; | |
| document.documentElement.style.setProperty('--accent-color', state.themeConfig.accent); | |
| } | |
| } | |
| function validateMarkdown() { | |
| state.errors = []; | |
| state.warnings = []; | |
| if (!state.markdown.trim()) { | |
| state.errors.push('Markdown is empty'); | |
| return; | |
| } | |
| // Check frontmatter validity | |
| const lines = state.markdown.split('\n'); | |
| if (lines[0].trim() === '---') { | |
| let foundClosing = false; | |
| for (let i = 1; i < Math.min(lines.length, 50); i++) { | |
| if (lines[i].trim() === '---') { | |
| foundClosing = true; | |
| break; | |
| } | |
| } | |
| if (!foundClosing) { | |
| state.errors.push('Missing closing frontmatter delimiter (---). Add --- after your frontmatter block.'); | |
| } | |
| } | |
| if (state.slides.length === 0) { | |
| const slideBreak = state.frontmatter.slideBreak || 'auto'; | |
| if (slideBreak === 'h1') { | |
| state.errors.push('No slides found - add # headings to create slides (slideBreak: h1 mode)'); | |
| } else if (slideBreak === 'h2') { | |
| state.errors.push('No slides found - add ## headings to create slides (slideBreak: h2 mode)'); | |
| } else { | |
| state.errors.push('No slides found - add --- separators or # headings'); | |
| } | |
| return; | |
| } | |
| // Warn about short slides | |
| state.slides.forEach((slide, i) => { | |
| const slideName = (slide.title || '').trim() || `Slide ${i + 1}`; | |
| if (slide.duration < 2) { | |
| state.warnings.push(`${slideName} is very short (${slide.duration}s) - consider adding more content`); | |
| } | |
| if (slide.duration > 60) { | |
| state.warnings.push(`${slideName} is very long (${slide.duration}s) - consider splitting`); | |
| } | |
| if (slide.content.length === 0) { | |
| state.warnings.push(`${slideName} has no content`); | |
| } | |
| }); | |
| // Warn about total duration | |
| if (state.totalDuration > 600) { | |
| state.warnings.push(`Total duration is ${formatDuration(state.totalDuration)} (over 10 minutes) - consider shorter presentation`); | |
| } | |
| } | |
| function showDiagnostics() { | |
| if (state.errors.length === 0 && state.warnings.length === 0) { | |
| dom.markdownDiagnostics.classList.add('hidden'); | |
| return; | |
| } | |
| const messages = [ | |
| ...state.errors.map(e => `[ERROR] ${e}`), | |
| ...state.warnings.map(w => `[WARN] ${w}`) | |
| ]; | |
| dom.markdownDiagnostics.innerHTML = messages.join('<br>'); | |
| dom.markdownDiagnostics.classList.remove('hidden'); | |
| } | |
| function updateMarkdownSummary() { | |
| dom.markdownSummary.innerHTML = ` | |
| <strong>Slides:</strong> ${state.slides.length} | | |
| <strong>Duration:</strong> ${formatDuration(state.totalDuration)} | | |
| <strong>Template:</strong> ${state.template} | |
| `; | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Timeline UI Updates | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function updateTimelineUI() { | |
| dom.timelineTotal.textContent = formatDuration(state.totalDuration); | |
| let currentTime = 0; | |
| const sceneHTML = state.slides.map((slide, i) => { | |
| const startTime = currentTime; | |
| const endTime = currentTime + slide.duration; | |
| currentTime = endTime; | |
| // Pagination indicator | |
| const pageInfo = slide.totalPages > 1 | |
| ? `<span class="timeline-page-indicator">Page ${slide.pageNumber}/${slide.totalPages}</span>` | |
| : ''; | |
| // Visual lines indicator | |
| const linesInfo = slide.visualLines | |
| ? `<span class="text-xs opacity-60">${Math.round(slide.visualLines)} lines</span>` | |
| : ''; | |
| const titleText = (slide.title || '').trim(); | |
| const slideLabel = titleText | |
| ? `Slide ${i + 1} - ${escapeHtml(titleText)}` | |
| : `Slide ${i + 1}`; | |
| return ` | |
| <div class="py-3 flex flex-col gap-1"> | |
| <div class="flex items-center justify-between text-sm text-slate-200"> | |
| <div class="flex items-center gap-2"> | |
| <span>${slideLabel}</span> | |
| ${pageInfo} | |
| </div> | |
| <span>${slide.duration}s</span> | |
| </div> | |
| <div class="flex items-center justify-between"> | |
| <p class="text-xs text-slate-500"> | |
| ${formatTimecode(startTime)} to ${formatTimecode(endTime)} | |
| </p> | |
| ${linesInfo} | |
| </div> | |
| </div> | |
| `; | |
| }).join('<div class="border-t border-slate-800"></div>'); | |
| dom.timelineSceneList.innerHTML = sceneHTML || '<p class="text-slate-500 text-sm">No slides yet</p>'; | |
| updateAssetChecklist(); | |
| } | |
| function updateAssetChecklist() { | |
| const assets = []; | |
| state.slides.forEach(slide => { | |
| const items = slide.renderItems || slide.content || []; | |
| items.forEach(item => { | |
| if (item.type === 'image') { | |
| assets.push({ path: item.src, status: 'pending' }); | |
| } | |
| }); | |
| }); | |
| if (assets.length === 0) { | |
| dom.assetChecklist.innerHTML = '<li class="text-slate-500">No assets referenced</li>'; | |
| return; | |
| } | |
| const assetHTML = assets.map(asset => ` | |
| <li class="flex items-center justify-between"> | |
| <span>${escapeHtml(asset.path)}</span> | |
| <span class="status-pill ${asset.status}">${asset.status}</span> | |
| </li> | |
| `).join(''); | |
| dom.assetChecklist.innerHTML = assetHTML; | |
| } | |
| // ============================================================================== | |
| // INTRO SCENE - STAGE PREVIEW SYSTEM - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: These functions are used exclusively by the intro scene | |
| // The intro scene is working perfectly with UI sidebar and small preview | |
| // Any modifications may break the intro scene display | |
| // Do not link these to presentation mode - use separate functions | |
| // ============================================================================== | |
| /** | |
| * LOCKED - Intro scene preview data extraction | |
| * Do not modify - intro scene working perfectly | |
| */ | |
| function getStagePreviewData(slides, totalDuration) { | |
| if (!slides || slides.length === 0) { | |
| return null; | |
| } | |
| const firstSlide = slides[0]; | |
| const lastSlide = slides[slides.length - 1]; | |
| let currentTime = 0; | |
| const timelineItems = slides.slice(0, 3).map((slide, index) => { | |
| const slideTitle = slide.title || 'Untitled Slide'; | |
| const startTime = currentTime; | |
| const endTime = currentTime + slide.duration; | |
| currentTime = endTime; | |
| return { | |
| label: `Slide ${index + 1} - ${slideTitle}`, | |
| startTime, | |
| endTime | |
| }; | |
| }); | |
| return { | |
| intro: { | |
| title: firstSlide.title || 'Untitled Slide', | |
| subtitle: firstSlide.subtitle || 'Markdown Video Studio' | |
| }, | |
| outro: { | |
| title: lastSlide.title || 'Thank You', | |
| tagline: `${slides.length} slides - ${formatDuration(totalDuration)}` | |
| }, | |
| timelineItems | |
| }; | |
| } | |
| /** | |
| * LOCKED - Intro scene preview renderer | |
| * Do not modify - intro scene working perfectly | |
| */ | |
| function renderStagePreview(previewData) { | |
| if (!previewData) return; | |
| const introTitle = document.querySelector('[data-bind="intro.title"]'); | |
| const introSubtitle = document.querySelector('[data-bind="intro.subtitle"]'); | |
| if (introTitle) introTitle.textContent = previewData.intro.title; | |
| if (introSubtitle) introSubtitle.textContent = previewData.intro.subtitle; | |
| const outroTitle = document.querySelector('[data-bind="outro.title"]'); | |
| const outroTagline = document.querySelector('[data-bind="outro.tagline"]'); | |
| if (outroTitle) outroTitle.textContent = previewData.outro.title; | |
| if (outroTagline) outroTagline.textContent = previewData.outro.tagline; | |
| const timelinePreview = document.getElementById('timelinePreview'); | |
| if (!timelinePreview) return; | |
| const previewHTML = previewData.timelineItems.map(item => ( | |
| ` | |
| <li class="flex items-start justify-between gap-3"> | |
| <span class="font-semibold">${escapeHtml(item.label)}</span> | |
| <span class="opacity-70">${formatTimecode(item.startTime)} to ${formatTimecode(item.endTime)}</span> | |
| </li> | |
| ` | |
| )).join(''); | |
| timelinePreview.innerHTML = previewHTML; | |
| } | |
| function updateStagePreview() { | |
| if (state.slides.length === 0) return; | |
| const previewData = getStagePreviewData(state.slides, state.totalDuration); | |
| renderStagePreview(previewData); | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Config Inputs | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupConfigInputs() { | |
| const resSelect = document.querySelector('[data-config="video.resolution"]'); | |
| if (resSelect) { | |
| resSelect.addEventListener('change', (e) => { | |
| state.videoConfig.resolution = e.target.value; | |
| upsertFrontmatterValue('video.resolution', e.target.value); | |
| }); | |
| } | |
| const fpsSelect = document.querySelector('[data-config="video.fps"]'); | |
| if (fpsSelect) { | |
| fpsSelect.addEventListener('change', (e) => { | |
| state.videoConfig.fps = parseInt(e.target.value); | |
| upsertFrontmatterValue('video.fps', e.target.value); | |
| }); | |
| } | |
| const qualitySlider = document.querySelector('[data-config="video.quality"]'); | |
| const qualityValue = document.getElementById('qualityValue'); | |
| if (qualitySlider) { | |
| qualitySlider.addEventListener('input', (e) => { | |
| const value = parseFloat(e.target.value); | |
| state.videoConfig.quality = value; | |
| if (qualityValue) qualityValue.textContent = Math.round(value * 100) + '%'; | |
| upsertFrontmatterValue('video.quality', value.toFixed(2)); | |
| }); | |
| } | |
| const accentInput = document.querySelector('[data-config="theme.accent"]'); | |
| if (accentInput) { | |
| accentInput.addEventListener('input', (e) => { | |
| state.themeConfig.accent = e.target.value; | |
| document.documentElement.style.setProperty('--accent-color', e.target.value); | |
| upsertFrontmatterValue('theme.accent', e.target.value); | |
| }); | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Export Controls | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupExportControls() { | |
| dom.previewBtn.addEventListener('click', previewTimeline); | |
| dom.recordWebMBtn.addEventListener('click', exportVideo); | |
| dom.resetBtn.addEventListener('click', resetApplication); | |
| dom.securityBtn.addEventListener('click', showSecurityStats); | |
| // Stop buttons | |
| if (dom.stopPreviewBtn) { | |
| dom.stopPreviewBtn.addEventListener('click', () => { | |
| stopPreview(); | |
| }); | |
| } | |
| if (dom.stopExportBtn) { | |
| dom.stopExportBtn.addEventListener('click', () => { | |
| // Stop export will be handled by the export function | |
| state.isExporting = false; | |
| if (dom.stopExportBtn) dom.stopExportBtn.classList.add('hidden'); | |
| }); | |
| } | |
| const rendererBackend = document.getElementById('rendererBackend'); | |
| if (rendererBackend) { | |
| rendererBackend.textContent = 'MediaRecorder (WebM)'; | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Configuration Management (Import/Export/Reset) | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupConfigManagement() { | |
| // Export Config Button | |
| const exportConfigBtn = document.getElementById('exportConfigBtn'); | |
| if (exportConfigBtn) { | |
| exportConfigBtn.addEventListener('click', async () => { | |
| try { | |
| await exportConfigToFile(); | |
| setStatus('Config exported successfully', 'online'); | |
| } catch (error) { | |
| console.error('[App] Failed to export config:', error); | |
| setStatus('Failed to export config', 'error'); | |
| } | |
| }); | |
| } | |
| // Import Config Button | |
| const importConfigBtn = document.getElementById('importConfigBtn'); | |
| if (importConfigBtn) { | |
| importConfigBtn.addEventListener('click', async () => { | |
| try { | |
| const result = await importConfigFromFile(); | |
| if (result) { | |
| setStatus('Config imported and applied successfully', 'online'); | |
| // Reload UI to reflect new config | |
| reloadUI(); | |
| } | |
| } catch (error) { | |
| console.error('[App] Failed to import config:', error); | |
| setStatus('Failed to import config', 'error'); | |
| } | |
| }); | |
| } | |
| // Reset Config Button (with confirmation) | |
| const resetConfigBtn = document.getElementById('resetConfigBtn'); | |
| if (resetConfigBtn) { | |
| resetConfigBtn.addEventListener('click', () => { | |
| if (confirm('Reset all settings to default? This will clear your saved configuration.')) { | |
| resetConfig(true); | |
| reloadUI(); | |
| setStatus('Configuration reset to defaults', 'online'); | |
| } | |
| }); | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Presentation Mode (Manual Navigation) | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupPresentationMode() { | |
| // Presentation Mode Button | |
| if (dom.presentationModeBtn) { | |
| dom.presentationModeBtn.addEventListener('click', startPresentationMode); | |
| } | |
| // Exit Presentation Mode Button | |
| if (dom.exitPresentationBtn) { | |
| dom.exitPresentationBtn.addEventListener('click', () => { | |
| exitPresentationMode(); | |
| }); | |
| } | |
| // Navigation Buttons | |
| if (dom.prevSlideBtn) { | |
| dom.prevSlideBtn.addEventListener('click', gotoPreviousSlide); | |
| } | |
| if (dom.nextSlideBtn) { | |
| dom.nextSlideBtn.addEventListener('click', gotoNextSlide); | |
| } | |
| // Keyboard navigation (Arrow keys) | |
| document.addEventListener('keydown', (e) => { | |
| if (!state.isPresentationMode) return; | |
| // Don't trigger navigation if in edit or drag mode (except ESC) | |
| if ((slideEditor.isEditMode || slideEditor.isDragMode) && e.code !== 'Escape') { | |
| return; | |
| } | |
| if (e.code === 'ArrowLeft') { | |
| e.preventDefault(); | |
| gotoPreviousSlide(); | |
| } else if (e.code === 'ArrowRight' || e.code === 'Space') { | |
| e.preventDefault(); | |
| gotoNextSlide(); | |
| } else if (e.code === 'Escape') { | |
| e.preventDefault(); | |
| exitPresentationMode(); | |
| } else if (e.code === 'Home') { | |
| e.preventDefault(); | |
| gotoSlide(0); | |
| } else if (e.code === 'End') { | |
| e.preventDefault(); | |
| gotoSlide(state.slides.length - 1); | |
| } else if (e.code === 'KeyE') { | |
| // Toggle edit mode with E key | |
| e.preventDefault(); | |
| slideEditor.toggleEditMode(); | |
| } else if (e.code === 'KeyD') { | |
| // Toggle drag mode with D key | |
| e.preventDefault(); | |
| slideEditor.toggleDragMode(); | |
| } | |
| }); | |
| } | |
| async function startPresentationMode() { | |
| if (state.slides.length === 0) { | |
| setStatus('No slides - sync markdown first', 'online'); | |
| return; | |
| } | |
| // ตั้งค่าโหมดเป็น presentation และปิดโหมดอื่นทั้งหมด | |
| // Mode Manager จะจัดการ UI ให้ทั้งหมด (navControls, exitBtn, fullscreenBtn, editBtn) | |
| switchToPresentationMode(); | |
| state.isPresentationMode = true; | |
| state.currentSlideIndex = 0; | |
| // ไม่ต้อง show/hide UI elements ด้วยตัวเอง - Mode Manager จัดการแล้ว | |
| // Set current slide for editor (but don't show button - Mode Manager handles it) | |
| slideEditor.setCurrentSlide(0); | |
| // Disable other controls | |
| setControlsDisabled(true); | |
| // Detect screen and render first slide with smart layout | |
| detectScreenSize(); | |
| gotoSlideWithSmartLayout(0); | |
| setStatus('Presentation Mode - Use arrow keys to navigate, ESC to exit', 'online'); | |
| } | |
| function exitPresentationMode() { | |
| state.isPresentationMode = false; | |
| state.currentSlideIndex = 0; | |
| // กลับไปโหมด intro และปิดโหมดอื่นทั้งหมด | |
| // Mode Manager จะจัดการ UI ให้ทั้งหมด | |
| switchToIntroMode(); | |
| // ไม่ต้อง hide UI elements ด้วยตัวเอง - Mode Manager จัดการแล้ว | |
| // Reset slide editor (Mode Manager handles UI hiding) | |
| slideEditor.reset(); | |
| // Exit fullscreen if active | |
| if (document.fullscreenElement || document.webkitFullscreenElement) { | |
| exitFullscreen(); | |
| } | |
| // Re-enable controls | |
| setControlsDisabled(false); | |
| // Reset to intro scene | |
| showScene('intro'); | |
| setStatus('Exited presentation mode', 'online'); | |
| } | |
| function gotoSlide(index) { | |
| if (index < 0 || index >= state.slides.length) return; | |
| state.currentSlideIndex = index; | |
| // Update slide editor | |
| slideEditor.setCurrentSlide(index); | |
| if (state.isPresentationMode) { | |
| gotoSlideWithSmartLayout(index); | |
| return; | |
| } | |
| const slide = state.slides[index]; | |
| renderSlideToStage(slide); | |
| showScene('body'); | |
| updateSlideCounter(); | |
| updateNavigationButtons(); | |
| } | |
| function gotoPreviousSlide() { | |
| if (state.currentSlideIndex > 0) { | |
| gotoSlide(state.currentSlideIndex - 1); | |
| } | |
| } | |
| function gotoNextSlide() { | |
| if (state.currentSlideIndex < state.slides.length - 1) { | |
| gotoSlide(state.currentSlideIndex + 1); | |
| } | |
| } | |
| function updateSlideCounter() { | |
| if (dom.slideCounter) { | |
| dom.slideCounter.textContent = `${state.currentSlideIndex + 1} / ${state.slides.length}`; | |
| } | |
| } | |
| function updateNavigationButtons() { | |
| // Disable prev button on first slide | |
| if (dom.prevSlideBtn) { | |
| dom.prevSlideBtn.disabled = state.currentSlideIndex === 0; | |
| } | |
| // Disable next button on last slide | |
| if (dom.nextSlideBtn) { | |
| dom.nextSlideBtn.disabled = state.currentSlideIndex === state.slides.length - 1; | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Fullscreen Control | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupFullscreenControl() { | |
| if (dom.fullscreenBtn) { | |
| dom.fullscreenBtn.addEventListener('click', toggleFullscreen); | |
| } | |
| // Listen for fullscreen changes | |
| document.addEventListener('fullscreenchange', onFullscreenChange); | |
| document.addEventListener('webkitfullscreenchange', onFullscreenChange); | |
| document.addEventListener('mozfullscreenchange', onFullscreenChange); | |
| document.addEventListener('MSFullscreenChange', onFullscreenChange); | |
| // Keyboard shortcut: F key | |
| document.addEventListener('keydown', (e) => { | |
| if (e.code === 'KeyF' && state.isPresentationMode) { | |
| e.preventDefault(); | |
| toggleFullscreen(); | |
| } | |
| }); | |
| } | |
| function toggleFullscreen() { | |
| if (!document.fullscreenElement && !document.webkitFullscreenElement) { | |
| enterFullscreen(); | |
| } else { | |
| exitFullscreen(); | |
| } | |
| } | |
| function enterFullscreen() { | |
| const element = dom.stageFrame; | |
| if (element.requestFullscreen) { | |
| element.requestFullscreen(); | |
| } else if (element.webkitRequestFullscreen) { | |
| element.webkitRequestFullscreen(); | |
| } else if (element.mozRequestFullScreen) { | |
| element.mozRequestFullScreen(); | |
| } else if (element.msRequestFullscreen) { | |
| element.msRequestFullscreen(); | |
| } | |
| } | |
| function exitFullscreen() { | |
| if (document.exitFullscreen) { | |
| document.exitFullscreen(); | |
| } else if (document.webkitExitFullscreen) { | |
| document.webkitExitFullscreen(); | |
| } else if (document.mozCancelFullScreen) { | |
| document.mozCancelFullScreen(); | |
| } else if (document.msExitFullscreen) { | |
| document.msExitFullscreen(); | |
| } | |
| } | |
| function onFullscreenChange() { | |
| const isFullscreen = !!(document.fullscreenElement || document.webkitFullscreenElement); | |
| // Update fullscreen button icon | |
| if (dom.fullscreenBtn) { | |
| const icon = dom.fullscreenBtn.querySelector('.fullscreen-icon'); | |
| if (icon) { | |
| icon.textContent = isFullscreen ? '⛶' : '⛶'; | |
| } | |
| } | |
| if (state.isPresentationMode) { | |
| detectScreenSize(); | |
| gotoSlideWithSmartLayout(state.currentSlideIndex); | |
| // อัปเดต Safe Zone เมื่อเข้า/ออก fullscreen | |
| if (slideEditor.isDragMode) { | |
| slideEditor.dragDropManager.updateSafeZoneBorders(); | |
| } | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Smart Content Layout Engine - Intelligent Fullscreen Presentation Mode | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function setupScreenSensor() { | |
| ensureMeasurementStage(); | |
| detectScreenSize(); | |
| window.addEventListener('resize', debounce(() => { | |
| ensureMeasurementStage(); | |
| detectScreenSize(); | |
| if (state.isPresentationMode) { | |
| gotoSlideWithSmartLayout(state.currentSlideIndex); | |
| } | |
| }, 200)); | |
| if (window.screen && window.screen.orientation && typeof window.screen.orientation.addEventListener === 'function') { | |
| window.screen.orientation.addEventListener('change', () => { | |
| ensureMeasurementStage(); | |
| detectScreenSize(); | |
| if (state.isPresentationMode) { | |
| gotoSlideWithSmartLayout(state.currentSlideIndex); | |
| } | |
| }); | |
| } | |
| } | |
| function detectScreenSize() { | |
| const width = window.innerWidth; | |
| const height = window.innerHeight; | |
| const pixelRatio = window.devicePixelRatio || 1; | |
| const isFullscreen = !!(document.fullscreenElement || document.webkitFullscreenElement); | |
| const availableSpace = width * height; | |
| let screenType = 'normal'; | |
| let isLargeScreen = false; | |
| if (availableSpace >= 3840000 || width >= 2560 || isFullscreen) { | |
| screenType = 'ultra'; | |
| isLargeScreen = true; | |
| } else if (availableSpace >= 2073600 || width >= 1920) { | |
| screenType = 'large'; | |
| isLargeScreen = true; | |
| } | |
| const previousType = state.screenSensor.screenType; | |
| state.screenSensor = { | |
| width, | |
| height, | |
| pixelRatio, | |
| isLargeScreen, | |
| screenType, | |
| isFullscreen, | |
| availableSpace, | |
| lastUpdate: Date.now() | |
| }; | |
| const stage = dom.stage || document.getElementById('stage'); | |
| if (stage) { | |
| stage.classList.remove('screen-normal', 'screen-large', 'screen-ultra'); | |
| stage.classList.add(`screen-${screenType}`); | |
| updateMeasurementStageSize(); | |
| } | |
| if (previousType !== screenType) { | |
| console.log(`[SmartLayout] Screen changed: ${previousType} -> ${screenType} (${width}x${height})`); | |
| } | |
| return state.screenSensor; | |
| } | |
| function buildSlideItemHtml(item, { isPreview = false } = {}) { | |
| const previewClass = isPreview ? 'preview-block' : ''; | |
| const previewAttr = isPreview ? ' data-preview="true"' : ''; | |
| const blockAttr = item.layoutBlockId ? ` data-block-id="${item.layoutBlockId}"` : ''; | |
| const sectionAttr = item.sectionId ? ` data-section-id="${item.sectionId}"` : ''; | |
| const listAttr = item.listId ? ` data-list-id="${item.listId}"` : ''; | |
| const dataAttrs = `${previewAttr}${blockAttr}${sectionAttr}${listAttr}`; | |
| const language = item.language || ''; | |
| switch (item.type) { | |
| case 'h1': | |
| return `<h1 class="slide-heading slide-h1 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</h1>`; | |
| case 'h2': | |
| return `<h2 class="slide-heading slide-h2 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</h2>`; | |
| case 'h3': | |
| return `<h3 class="slide-heading slide-h3 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</h3>`; | |
| case 'h4': | |
| return `<h4 class="slide-heading slide-h4 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</h4>`; | |
| case 'h5': | |
| return `<h5 class="slide-heading slide-h5 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</h5>`; | |
| case 'h6': | |
| return `<h6 class="slide-heading slide-h6 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</h6>`; | |
| case 'list-item': { | |
| const marker = item.marker || '•'; | |
| return `<li class="slide-list-item ${previewClass}"${dataAttrs}>${escapeHtml(marker)} ${item.html ?? escapeHtml(item.content)}</li>`; | |
| } | |
| case 'numbered-item': { | |
| const numberLabel = item.number != null ? `${item.number}.` : ''; | |
| const prefix = numberLabel ? `${escapeHtml(numberLabel)} ` : ''; | |
| return `<li class="slide-list-item ${previewClass}"${dataAttrs}>${prefix}${item.html ?? escapeHtml(item.content)}</li>`; | |
| } | |
| case 'task-list': { | |
| const checkbox = item.checked ? '☑' : '☐'; | |
| return `<li class="slide-list-item ${previewClass}"${dataAttrs}>${escapeHtml(checkbox)} ${item.html ?? escapeHtml(item.content)}</li>`; | |
| } | |
| case 'text': { | |
| const textClass = isPreview ? 'slide-text slide-text-preview' : 'slide-text'; | |
| return `<p class="${textClass} ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content)}</p>`; | |
| } | |
| case 'code': | |
| return `<div class="relative slide-code ${previewClass}"${dataAttrs}><pre class="code-block"><code class="language-${language}">${escapeHtml(item.content)}</code></pre></div>`; | |
| case 'blockquote': | |
| return `<blockquote class="slide-blockquote ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content || '')}</blockquote>`; | |
| case 'image': { | |
| const title = item.title ? `title="${escapeHtml(item.title)}"` : ''; | |
| return `<img src="${escapeHtml(item.src)}" alt="${escapeHtml(item.alt)}" ${title} class="slide-image ${previewClass}"${dataAttrs} />`; | |
| } | |
| case 'link': { | |
| const linkTitle = item.title ? `title="${escapeHtml(item.title)}"` : ''; | |
| return `<a href="${escapeHtml(item.url)}" ${linkTitle} class="slide-link ${previewClass}"${dataAttrs}>${escapeHtml(item.text)}</a>`; | |
| } | |
| case 'table': { | |
| let html = `<div class="relative ${previewClass}"${dataAttrs}>`; | |
| html += '<table class="slide-table">'; | |
| if (item.rows && item.rows.length > 0) { | |
| html += '<thead><tr>'; | |
| item.rows[0].forEach(cell => { | |
| html += `<th>${escapeHtml(cell)}</th>`; | |
| }); | |
| html += '</tr></thead>'; | |
| if (item.rows.length > 2) { | |
| html += '<tbody>'; | |
| for (let i = 2; i < item.rows.length; i++) { | |
| html += '<tr>'; | |
| item.rows[i].forEach(cell => { | |
| html += `<td>${escapeHtml(cell)}</td>`; | |
| }); | |
| html += '</tr>'; | |
| } | |
| html += '</tbody>'; | |
| } | |
| } | |
| html += '</table>'; | |
| html += '</div>'; | |
| return html; | |
| } | |
| case 'hr': | |
| return `<hr class="slide-hr ${previewClass}"${dataAttrs} />`; | |
| case 'html': | |
| return `<div class="html-content ${previewClass}"${dataAttrs}>${item.html ?? item.content ?? ''}</div>`; | |
| default: | |
| return `<p class="text-2xl mb-2 ${previewClass}"${dataAttrs}>${item.html ?? escapeHtml(item.content || '')}</p>`; | |
| } | |
| } | |
| function htmlToNode(html) { | |
| const template = document.createElement('template'); | |
| template.innerHTML = html.trim(); | |
| return template.content.firstElementChild; | |
| } | |
| function getSmartSlideBlocks(slides, startIndex, screenType) { | |
| if (!Array.isArray(slides) || startIndex < 0 || startIndex >= slides.length) { | |
| return []; | |
| } | |
| const candidates = []; | |
| const maxSlidesToConsider = screenType === 'ultra' | |
| ? 4 | |
| : screenType === 'large' | |
| ? 3 | |
| : 2; | |
| const upperBound = Math.min(slides.length, startIndex + maxSlidesToConsider); | |
| for (let slideIndex = startIndex; slideIndex < upperBound; slideIndex += 1) { | |
| const slide = slides[slideIndex]; | |
| if (!slide) continue; | |
| const isPreviewSlide = slideIndex !== startIndex; | |
| const sourceItems = slide.renderItems || slide.content || []; | |
| sourceItems.forEach((originalItem, itemIndex) => { | |
| if (isPreviewSlide && /^h[1-6]$/.test(originalItem.type || '')) { | |
| return; | |
| } | |
| const block = { ...originalItem }; | |
| if (isPreviewSlide) { | |
| block.isPreview = true; | |
| block.fromNextSlide = true; | |
| block.previewSourceIndex = slideIndex; | |
| block.previewItemIndex = itemIndex; | |
| } | |
| candidates.push(block); | |
| }); | |
| } | |
| return candidates; | |
| } | |
| // ============================================================================== | |
| // INTRO SCENE CONTENT PREPARATION - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: This function uses intro scene measurement stage | |
| // Do not link to presentation mode - create separate function if needed | |
| // ============================================================================== | |
| /** | |
| * LOCKED - Intro scene smart content preparation | |
| * Do not modify - intro scene depends on this exact implementation | |
| */ | |
| function prepareSmartSlideContent(slides, startIndex, screenType) { | |
| const measurementRoot = ensureMeasurementStage(); | |
| if (!measurementRoot || !Array.isArray(slides) || startIndex < 0 || startIndex >= slides.length) { | |
| const fallbackSlide = slides?.[startIndex]; | |
| return fallbackSlide?.renderItems || fallbackSlide?.content || []; | |
| } | |
| const stageRect = dom.stage | |
| ? dom.stage.getBoundingClientRect() | |
| : dom.stageFrame | |
| ? dom.stageFrame.getBoundingClientRect() | |
| : getSmartLayoutStageFallback(); | |
| const safeZoneInsets = computeSafeZoneInsets(stageRect); | |
| applySafeZonePadding(dom.measurementRoot, safeZoneInsets); | |
| const usableHeight = Math.max(stageRect.height - safeZoneInsets.top - safeZoneInsets.bottom, 0); | |
| const heightBudget = usableHeight > 0 ? usableHeight : stageRect.height; | |
| const maxHeight = heightBudget * getSmartLayoutFillRatio(); | |
| const candidates = getSmartSlideBlocks(slides, startIndex, screenType); | |
| if (!candidates.length) { | |
| const fallbackSlide = slides[startIndex]; | |
| return fallbackSlide?.renderItems || fallbackSlide?.content || []; | |
| } | |
| const selectedItems = []; | |
| for (let index = 0; index < candidates.length; index += 1) { | |
| const originalBlock = candidates[index]; | |
| const block = { ...originalBlock }; | |
| const itemHtml = buildSlideItemHtml(block, { isPreview: !!block.isPreview }); | |
| const node = htmlToNode(itemHtml); | |
| if (!node) { | |
| continue; | |
| } | |
| measurementRoot.appendChild(node); | |
| const measuredHeight = dom.measurementRoot.getBoundingClientRect().height; | |
| const contentHeight = Math.max(measuredHeight - safeZoneInsets.top - safeZoneInsets.bottom, 0); | |
| const canFit = contentHeight <= maxHeight; | |
| const forceInclude = selectedItems.length === 0; | |
| if (canFit || forceInclude) { | |
| selectedItems.push(block); | |
| } else { | |
| measurementRoot.removeChild(node); | |
| break; | |
| } | |
| } | |
| measurementRoot.innerHTML = ''; | |
| if (selectedItems.length === 0) { | |
| const fallbackSlide = slides[startIndex]; | |
| return [...(fallbackSlide?.renderItems || fallbackSlide?.content || [])]; | |
| } | |
| return selectedItems; | |
| } | |
| function gotoSlideWithSmartLayout(index) { | |
| if (index < 0 || index >= state.slides.length) return; | |
| const { screenType } = state.screenSensor; | |
| const baseSlide = state.slides[index]; | |
| let itemsToRender = baseSlide.renderItems || baseSlide.content || []; | |
| if (screenType === 'large' || screenType === 'ultra') { | |
| itemsToRender = prepareSmartSlideContent(state.slides, index, screenType); | |
| } | |
| renderSlideToStage(baseSlide, itemsToRender); | |
| // Apply slide editor overrides if any | |
| const activeScene = dom.stage.querySelector('.scene.active'); | |
| if (activeScene) { | |
| const hasOverrides = slideEditor.applyOverrides(index, activeScene); | |
| if (hasOverrides) { | |
| console.log(`[App] Applied slide edits for slide ${index}`); | |
| } | |
| // Apply position overrides if any | |
| const hasPositions = slideEditor.applyPositions(index, activeScene); | |
| if (hasPositions) { | |
| console.log(`[App] Applied position overrides for slide ${index}`); | |
| } | |
| } | |
| showScene('body'); | |
| updateSlideCounter(); | |
| updateNavigationButtons(); | |
| const scheduleBoundsCheck = () => ensureContentWithinBounds(); | |
| if (typeof requestAnimationFrame === 'function') { | |
| requestAnimationFrame(scheduleBoundsCheck); | |
| } else { | |
| setTimeout(scheduleBoundsCheck, 0); | |
| } | |
| } | |
| let smartLayoutResizeObserver = null; | |
| let smartLayoutMutationObserver = null; | |
| let smartLayoutResizeFrame = null; | |
| function ensureContentWithinBounds() { | |
| // ตรวจสอบว่า Smart Layout ควรทำงานหรือไม่ตาม Mode Manager | |
| const modeManager = getModeManager(); | |
| if (modeManager && !modeManager.isSystemActive('smartLayout')) { | |
| // ปิดอยู่ ห้ามทำงาน | |
| return; | |
| } | |
| const stage = dom.stage; | |
| if (!stage) return; | |
| const root = stage.querySelector('.smart-layout-root'); | |
| if (!root) return; | |
| root.style.transform = ''; | |
| root.style.transformOrigin = ''; | |
| root.style.width = ''; | |
| const stageRect = stage.getBoundingClientRect(); | |
| const contentRect = root.getBoundingClientRect(); | |
| if (!stageRect.height || !contentRect.height) return; | |
| // อ่านค่า Safe Zone จาก presentation-config.js แทน dataset | |
| const safeZoneMargins = computeSafeZoneMargins(stageRect); | |
| const safeTop = safeZoneMargins.top || 0; | |
| const safeBottom = safeZoneMargins.bottom || 0; | |
| const safeLeft = safeZoneMargins.left || 0; | |
| const safeRight = safeZoneMargins.right || 0; | |
| const usableHeight = Math.max(stageRect.height - safeTop - safeBottom, 0); | |
| const usableWidth = Math.max(stageRect.width - safeLeft - safeRight, 0); | |
| if (usableHeight > 0 && contentRect.height <= usableHeight * 0.97) { | |
| return; | |
| } | |
| const heightTarget = usableHeight > 0 ? usableHeight : stageRect.height; | |
| if (!heightTarget) { | |
| return; | |
| } | |
| const scale = (heightTarget * 0.94) / contentRect.height; | |
| if (scale >= 1) { | |
| return; | |
| } | |
| root.style.transform = `scale(${scale})`; | |
| root.style.transformOrigin = 'top left'; | |
| const widthTarget = usableWidth > 0 ? usableWidth : stageRect.width || stage.offsetWidth; | |
| if (widthTarget) { | |
| root.style.width = `${widthTarget / scale}px`; | |
| } | |
| } | |
| function attachSmartLayoutObservers(layoutRoot) { | |
| if (smartLayoutResizeObserver) { | |
| smartLayoutResizeObserver.disconnect(); | |
| smartLayoutResizeObserver = null; | |
| } | |
| if (smartLayoutMutationObserver) { | |
| smartLayoutMutationObserver.disconnect(); | |
| smartLayoutMutationObserver = null; | |
| } | |
| if (smartLayoutResizeFrame) { | |
| cancelAnimationFrame(smartLayoutResizeFrame); | |
| smartLayoutResizeFrame = null; | |
| } | |
| if (!layoutRoot) { | |
| return; | |
| } | |
| const scheduleBoundsCheck = () => { | |
| if (smartLayoutResizeFrame) { | |
| cancelAnimationFrame(smartLayoutResizeFrame); | |
| } | |
| smartLayoutResizeFrame = requestAnimationFrame(() => { | |
| smartLayoutResizeFrame = null; | |
| ensureContentWithinBounds(); | |
| }); | |
| }; | |
| if (typeof ResizeObserver === 'function') { | |
| smartLayoutResizeObserver = new ResizeObserver(() => scheduleBoundsCheck()); | |
| smartLayoutResizeObserver.observe(layoutRoot); | |
| if (dom.stage) { | |
| smartLayoutResizeObserver.observe(dom.stage); | |
| } | |
| } | |
| if (typeof MutationObserver === 'function') { | |
| smartLayoutMutationObserver = new MutationObserver(() => scheduleBoundsCheck()); | |
| smartLayoutMutationObserver.observe(layoutRoot, { | |
| childList: true, | |
| subtree: true, | |
| characterData: true | |
| }); | |
| } | |
| scheduleBoundsCheck(); | |
| } | |
| /** | |
| * ปิด Smart Layout observers (เรียกใช้ตอนเข้าโหมดแก้ไข) | |
| */ | |
| function detachSmartLayoutObservers() { | |
| if (smartLayoutResizeObserver) { | |
| smartLayoutResizeObserver.disconnect(); | |
| smartLayoutResizeObserver = null; | |
| } | |
| if (smartLayoutMutationObserver) { | |
| smartLayoutMutationObserver.disconnect(); | |
| smartLayoutMutationObserver = null; | |
| } | |
| if (smartLayoutResizeFrame) { | |
| cancelAnimationFrame(smartLayoutResizeFrame); | |
| smartLayoutResizeFrame = null; | |
| } | |
| console.log('[SmartLayout] Observers detached'); | |
| } | |
| /** | |
| * เปิด Smart Layout observers อีกครั้ง | |
| */ | |
| function reattachSmartLayoutObservers() { | |
| const activeScene = dom.stage?.querySelector('.scene.active'); | |
| const layoutRoot = activeScene?.querySelector('.smart-layout-root'); | |
| if (layoutRoot) { | |
| attachSmartLayoutObservers(layoutRoot); | |
| console.log('[SmartLayout] Observers reattached'); | |
| } | |
| } | |
| // Export functions สำหรับเข้าถึงจากภายนอก | |
| window.smartLayoutControl = { | |
| detach: detachSmartLayoutObservers, | |
| reattach: reattachSmartLayoutObservers | |
| }; | |
| function debounce(func, wait) { | |
| let timeoutId; | |
| return function debounced(...args) { | |
| clearTimeout(timeoutId); | |
| timeoutId = setTimeout(() => func.apply(this, args), wait); | |
| }; | |
| } | |
| /** | |
| * Setup stage click handler for pause/resume during preview | |
| */ | |
| function setupStageClickHandler() { | |
| if (!dom.stage) return; | |
| // Click to pause/resume (only in preview mode, not presentation mode) | |
| dom.stage.addEventListener('click', (e) => { | |
| // Only handle clicks during preview playback (not presentation mode) | |
| if (!state.isPlaying || state.isPresentationMode) return; | |
| togglePause(); | |
| }); | |
| // Keyboard shortcut: Space or P to pause/resume (only in preview mode) | |
| document.addEventListener('keydown', (e) => { | |
| // Don't handle if in presentation mode | |
| if (state.isPresentationMode) return; | |
| if (!state.isPlaying) return; | |
| if (e.code === 'Space' || e.code === 'KeyP') { | |
| e.preventDefault(); | |
| togglePause(); | |
| } | |
| // ESC to stop preview | |
| if (e.code === 'Escape') { | |
| e.preventDefault(); | |
| stopPreview(); | |
| } | |
| }); | |
| // Also add visual feedback | |
| dom.stage.style.cursor = 'pointer'; | |
| dom.stage.title = 'Click to pause/resume preview (or press Space/P)'; | |
| } | |
| /** | |
| * Toggle pause/resume state | |
| */ | |
| function togglePause() { | |
| if (state.isPaused) { | |
| // Resume playback | |
| console.log('[App] Resuming preview...'); | |
| state.isPaused = false; | |
| setStatus('Playing preview... (Click or Space to pause)', 'online'); | |
| // Hide pause overlay | |
| if (dom.pauseOverlay) { | |
| dom.pauseOverlay.classList.add('hidden'); | |
| } | |
| // Resolve the pause promise to continue | |
| if (state.pauseResolve) { | |
| state.pauseResolve(); | |
| } | |
| } else { | |
| // Pause playback | |
| console.log('[App] Paused preview'); | |
| state.isPaused = true; | |
| setStatus('Preview PAUSED - Click or Space to resume', 'warning'); | |
| // Show pause overlay | |
| if (dom.pauseOverlay) { | |
| dom.pauseOverlay.classList.remove('hidden'); | |
| } | |
| } | |
| } | |
| /** | |
| * Stop preview playback | |
| */ | |
| function stopPreview() { | |
| console.log('[App] Stopping preview...'); | |
| state.isPlaying = false; | |
| state.isPaused = false; | |
| // Resume if paused (to unblock waitWithPause) | |
| if (state.pauseResolve) { | |
| state.pauseResolve(); | |
| state.pauseResolve = null; | |
| } | |
| setStatus('Preview stopped', 'online'); | |
| } | |
| async function previewTimeline() { | |
| if (state.isPlaying) return; | |
| if (state.slides.length === 0) { | |
| setStatus('No slides - sync markdown first', 'online'); | |
| return; | |
| } | |
| state.isPlaying = true; | |
| state.isPaused = false; | |
| setControlsDisabled(true); | |
| // Show stop preview button | |
| if (dom.stopPreviewBtn) dom.stopPreviewBtn.classList.remove('hidden'); | |
| setStatus('Playing preview... (Click stage to pause)', 'online'); | |
| // Hide pause overlay at start | |
| if (dom.pauseOverlay) { | |
| dom.pauseOverlay.classList.add('hidden'); | |
| } | |
| try { | |
| for (let i = 0; i < state.slides.length; i++) { | |
| state.currentSlideIndex = i; | |
| await playSlide(state.slides[i]); | |
| // Check if stopped during playback | |
| if (!state.isPlaying) break; | |
| } | |
| setStatus('Preview completed', 'online'); | |
| } catch (error) { | |
| console.error('[App] Preview error:', error); | |
| setStatus('Preview error: ' + error.message, 'online'); | |
| } finally { | |
| state.isPlaying = false; | |
| state.isPaused = false; | |
| state.pauseResolve = null; | |
| state.currentSlideIndex = 0; | |
| setControlsDisabled(false); | |
| showScene('intro'); | |
| // Hide stop preview button | |
| if (dom.stopPreviewBtn) dom.stopPreviewBtn.classList.add('hidden'); | |
| // Hide pause overlay when done | |
| if (dom.pauseOverlay) { | |
| dom.pauseOverlay.classList.add('hidden'); | |
| } | |
| } | |
| } | |
| async function playSlide(slide) { | |
| console.log('[App] Playing:', slide.title, slide.duration + 's'); | |
| renderSlideToStage(slide); | |
| showScene('body'); | |
| await waitWithPause(slide.duration * 1000); | |
| } | |
| /** | |
| * Wait function that supports pause/resume | |
| */ | |
| async function waitWithPause(duration) { | |
| const startTime = Date.now(); | |
| let elapsed = 0; | |
| while (elapsed < duration) { | |
| // Check if paused | |
| if (state.isPaused) { | |
| // Wait for resume | |
| await new Promise(resolve => { | |
| state.pauseResolve = resolve; | |
| }); | |
| // Reset pause state after resume | |
| state.isPaused = false; | |
| state.pauseResolve = null; | |
| } | |
| // Wait in small increments (100ms) to allow pause checking | |
| const remainingTime = duration - elapsed; | |
| const waitTime = Math.min(100, remainingTime); | |
| await new Promise(resolve => setTimeout(resolve, waitTime)); | |
| elapsed = Date.now() - startTime; | |
| } | |
| } | |
| // ============================================================================== | |
| // INTRO SCENE RENDER FUNCTION - DO NOT MODIFY | |
| // ============================================================================== | |
| // WARNING: This function uses intro scene safe zone calculation | |
| // Do not link to presentation mode - create separate function if needed | |
| // ============================================================================== | |
| /** | |
| * LOCKED - Intro scene slide rendering | |
| * Do not modify - intro scene depends on this exact implementation | |
| */ | |
| function renderSlideToStage(slide, itemsOverride = null) { | |
| const bodyScene = document.querySelector('[data-scene="body"]'); | |
| if (!bodyScene) return; | |
| const stageRect = dom.stage | |
| ? dom.stage.getBoundingClientRect() | |
| : dom.stageFrame | |
| ? dom.stageFrame.getBoundingClientRect() | |
| : getSmartLayoutStageFallback(); | |
| const safeZoneInsets = computeSafeZoneInsets(stageRect); | |
| const htmlParts = ['<div class="smart-layout-root relative z-10 space-y-4">']; | |
| if (slide.totalPages > 1) { | |
| htmlParts.push(`<div class="slide-page-indicator"> | |
| <span> | |
| ${slide.pageNumber} / ${slide.totalPages} | |
| </span> | |
| </div>`); | |
| } | |
| const isListType = (type) => type === 'list-item' || type === 'numbered-item' || type === 'task-list'; | |
| let listBuffer = null; | |
| const flushListBuffer = () => { | |
| if (!listBuffer || listBuffer.items.length === 0) { | |
| listBuffer = null; | |
| return; | |
| } | |
| const classes = ['smart-list']; | |
| if (listBuffer.hasPreview) { | |
| classes.push('has-preview'); | |
| } | |
| htmlParts.push(`<${listBuffer.tag} class="${classes.join(' ')}">`); | |
| listBuffer.items.forEach(itemHtml => htmlParts.push(itemHtml)); | |
| htmlParts.push(`</${listBuffer.tag}>`); | |
| listBuffer = null; | |
| }; | |
| const items = itemsOverride || slide.renderItems || slide.content || []; | |
| items.forEach(item => { | |
| const isPreview = !!(item.isPreview || item.fromNextSlide); | |
| const itemHtml = buildSlideItemHtml(item, { isPreview }); | |
| if (isListType(item.type)) { | |
| const tag = item.type === 'numbered-item' ? 'ol' : 'ul'; | |
| if (!listBuffer || listBuffer.tag !== tag) { | |
| flushListBuffer(); | |
| listBuffer = { tag, items: [], hasPreview: false }; | |
| } | |
| listBuffer.items.push(itemHtml); | |
| listBuffer.hasPreview = listBuffer.hasPreview || isPreview; | |
| } else { | |
| flushListBuffer(); | |
| htmlParts.push(itemHtml); | |
| } | |
| }); | |
| flushListBuffer(); | |
| htmlParts.push('</div>'); | |
| htmlParts.push('<div class="gradient-backdrop"></div>'); | |
| bodyScene.innerHTML = htmlParts.join(''); | |
| applySmartLayoutTransforms(bodyScene); | |
| const layoutRoot = bodyScene.querySelector('.smart-layout-root'); | |
| applySafeZonePadding(layoutRoot, safeZoneInsets); | |
| attachSmartLayoutObservers(layoutRoot); | |
| } | |
| function applySmartLayoutTransforms(container) { | |
| const layoutRoot = container.querySelector('.smart-layout-root'); | |
| if (!layoutRoot) return; | |
| enhanceSmartLists(layoutRoot); | |
| } | |
| function enhanceSmartLists(layoutRoot) { | |
| const lists = layoutRoot.querySelectorAll('.smart-list'); | |
| if (!lists.length) return; | |
| const isLargeScreen = !!state.screenSensor?.isLargeScreen; | |
| lists.forEach(list => { | |
| list.classList.remove('smart-balanced', 'smart-balanced-three'); | |
| if (!isLargeScreen) { | |
| return; | |
| } | |
| const items = Array.from(list.querySelectorAll('li')); | |
| const previewCount = items.filter(li => li.dataset.preview === 'true').length; | |
| const visibleCount = items.length - previewCount; | |
| // Get thresholds from config (use default values as fallback) | |
| const config = getCurrentConfig(); | |
| const twoColumnThreshold = config?.smartList?.twoColumnThreshold || 6; | |
| const threeColumnThreshold = config?.smartList?.threeColumnThreshold || 12; | |
| if (visibleCount >= threeColumnThreshold) { | |
| list.classList.add('smart-balanced-three'); | |
| } else if (visibleCount >= twoColumnThreshold) { | |
| list.classList.add('smart-balanced'); | |
| } | |
| }); | |
| } | |
| async function exportVideo() { | |
| if (state.slides.length === 0) { | |
| setStatus('No slides - sync markdown first', 'online'); | |
| return; | |
| } | |
| const [width, height] = state.videoConfig.resolution.split('x').map(Number); | |
| const renderer = new VideoRenderer({ | |
| width, | |
| height, | |
| fps: state.videoConfig.fps, | |
| quality: state.videoConfig.quality, | |
| format: 'webm' | |
| }); | |
| setControlsDisabled(true); | |
| dom.progressContainer.classList.remove('hidden'); | |
| setStatus('Recording video...', 'recording'); | |
| try { | |
| await renderer.startRecording(dom.stage); | |
| for (let i = 0; i < state.slides.length; i++) { | |
| updateProgress(i, state.slides.length); | |
| await playSlide(state.slides[i]); | |
| } | |
| const result = await renderer.stopRecording(); | |
| const base64 = await blobToBase64(result.blob); | |
| const filename = 'chahua-video-' + Date.now() + '.webm'; | |
| const saveResult = await window.chahuaVideo.saveVideo({ | |
| blob: base64, | |
| format: 'webm', | |
| filename | |
| }); | |
| if (saveResult.success && !saveResult.canceled) { | |
| setStatus('Video saved: ' + saveResult.filePath + ' (' + formatBytes(saveResult.size) + ')', 'online'); | |
| } else if (!saveResult.canceled) { | |
| setStatus('Save failed: ' + saveResult.error, 'online'); | |
| } else { | |
| setStatus('Export canceled', 'online'); | |
| } | |
| } catch (error) { | |
| console.error('[App] Export error:', error); | |
| setStatus('Export error: ' + error.message, 'online'); | |
| } finally { | |
| setControlsDisabled(false); | |
| dom.progressContainer.classList.add('hidden'); | |
| } | |
| } | |
| function updateProgress(current, total) { | |
| const percent = Math.round((current / total) * 100); | |
| dom.progressBar.style.width = percent + '%'; | |
| dom.progressText.textContent = 'Recording slide ' + (current + 1) + ' of ' + total + '...'; | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // File Operations | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| async function loadSampleDeck() { | |
| const sampleMarkdown = `--- | |
| template: modern | |
| video: | |
| resolution: 1920x1080 | |
| fps: 60 | |
| quality: 0.95 | |
| theme: | |
| accent: #60a5fa | |
| --- | |
| # Introduction | |
| subtitle: Markdown Video Studio | |
| duration: 4 | |
| Welcome to the new Markdown-first workflow. | |
| --- | |
| # Feature Highlights | |
| duration: 6 | |
| - Native WebM encoding | |
| - Real-time preview | |
| - Frontmatter config sync | |
| - Offline-first architecture | |
| --- | |
| # Conclusion | |
| subtitle: Built with Electron + MediaRecorder | |
| duration: 5 | |
| Thank you for watching! | |
| `; | |
| dom.markdownEditor.value = sampleMarkdown; | |
| syncMarkdown(); | |
| setStatus('Sample deck loaded', 'online'); | |
| } | |
| async function importMarkdownFile() { | |
| try { | |
| const result = await window.chahuaVideo.openMarkdownFile(); | |
| if (result.success && !result.canceled) { | |
| dom.markdownEditor.value = result.content; | |
| syncMarkdown(); | |
| setStatus('Loaded: ' + result.filePath, 'online'); | |
| } | |
| } catch (error) { | |
| console.error('[App] Import error:', error); | |
| setStatus('Import failed: ' + error.message, 'online'); | |
| } | |
| } | |
| async function openWorkspaceFolder() { | |
| try { | |
| const result = await window.chahuaVideo.openWorkspaceFolder(); | |
| if (result.success) { | |
| setStatus('Opened workspace folder', 'online'); | |
| } | |
| } catch (error) { | |
| console.error('[App] Workspace error:', error); | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Application Reset | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| async function resetApplication() { | |
| // Confirm before reset | |
| const confirmed = confirm( | |
| 'Reset Application?\n\n' + | |
| 'This will:\n' + | |
| '• Clear all markdown content\n' + | |
| '• Reset all slides and timeline\n' + | |
| '• Reset to default template and settings\n' + | |
| '• Return to initial state\n\n' + | |
| 'This action cannot be undone.' | |
| ); | |
| if (!confirmed) return; | |
| console.log('[App] Resetting application to initial state...'); | |
| // Stop any active playback or presentation | |
| if (state.isPlaying) { | |
| state.isPlaying = false; | |
| if (state.pauseResolve) { | |
| state.pauseResolve(); | |
| } | |
| } | |
| if (state.isPresentationMode) { | |
| exitPresentationMode(); | |
| } | |
| // Reset state to initial values | |
| state.markdown = ''; | |
| state.frontmatter = {}; | |
| state.slides = []; | |
| state.totalDuration = 0; | |
| state.template = 'modern'; | |
| state.videoConfig = { | |
| resolution: '1920x1080', | |
| fps: 60, | |
| quality: 0.95 | |
| }; | |
| state.themeConfig = { | |
| accent: '#60a5fa' | |
| }; | |
| state.isPlaying = false; | |
| state.isPaused = false; | |
| state.isPresentationMode = false; | |
| state.currentSlideIndex = 0; | |
| state.pauseResolve = null; | |
| state.errors = []; | |
| state.warnings = []; | |
| // Clear markdown editor | |
| dom.markdownEditor.value = ''; | |
| // Hide diagnostics | |
| dom.markdownDiagnostics.classList.add('hidden'); | |
| // Reset markdown summary | |
| dom.markdownSummary.innerHTML = 'Awaiting markdown sync.'; | |
| // Reset timeline UI | |
| dom.timelineTotal.textContent = '00:00'; | |
| dom.timelineSceneList.innerHTML = '<p class="text-slate-500 text-sm">No slides yet</p>'; | |
| // Reset asset checklist | |
| dom.assetChecklist.innerHTML = '<li class="text-slate-500">No assets referenced</li>'; | |
| // Reset stage to intro scene | |
| showScene('intro'); | |
| // Reset intro content to default | |
| const introTitle = document.querySelector('[data-bind="intro.title"]'); | |
| const introSubtitle = document.querySelector('[data-bind="intro.subtitle"]'); | |
| if (introTitle) introTitle.textContent = 'Markdown Video Studio'; | |
| if (introSubtitle) introSubtitle.textContent = 'Define every slide, timing, and asset straight from your markdown deck.'; | |
| // Reset outro content | |
| const outroTitle = document.querySelector('[data-bind="outro.title"]'); | |
| const outroTagline = document.querySelector('[data-bind="outro.tagline"]'); | |
| if (outroTitle) outroTitle.textContent = 'Render from Markdown'; | |
| if (outroTagline) outroTagline.textContent = 'Export consistent videos without ever leaving your markdown workflow.'; | |
| // Reset timeline preview | |
| const timelinePreview = document.getElementById('timelinePreview'); | |
| if (timelinePreview) { | |
| timelinePreview.innerHTML = ` | |
| <li class="flex items-start justify-between gap-3"> | |
| <span class="font-semibold">Slide 1 · Intro</span> | |
| <span class="opacity-70">00:00 → 00:05</span> | |
| </li> | |
| <li class="flex items-start justify-between gap-3"> | |
| <span class="font-semibold">Slide 2 · Agenda</span> | |
| <span class="opacity-70">00:05 → 00:15</span> | |
| </li> | |
| <li class="flex items-start justify-between gap-3"> | |
| <span class="font-semibold">Slide 3 · Demo</span> | |
| <span class="opacity-70">00:15 → 00:35</span> | |
| </li> | |
| `; | |
| } | |
| // Reset to default template | |
| applyTemplate('modern'); | |
| updateTemplateUI(); | |
| // Reset presentation configuration to default | |
| resetConfig(); | |
| reloadUI(dom); | |
| // Reset all template cards | |
| document.querySelectorAll('.template-card').forEach((card, index) => { | |
| card.classList.toggle('active', index === 0); // First template is 'modern' | |
| }); | |
| // Reset config inputs to defaults | |
| const resSelect = document.querySelector('[data-config="video.resolution"]'); | |
| if (resSelect) resSelect.value = '1920x1080'; | |
| const fpsSelect = document.querySelector('[data-config="video.fps"]'); | |
| if (fpsSelect) fpsSelect.value = '60'; | |
| const qualitySlider = document.querySelector('[data-config="video.quality"]'); | |
| const qualityValue = document.getElementById('qualityValue'); | |
| if (qualitySlider) { | |
| qualitySlider.value = 0.95; | |
| if (qualityValue) qualityValue.textContent = '95%'; | |
| } | |
| // Hide progress container | |
| dom.progressContainer.classList.add('hidden'); | |
| // Hide pause overlay | |
| if (dom.pauseOverlay) { | |
| dom.pauseOverlay.classList.add('hidden'); | |
| } | |
| // ไม่ต้อง hide UI elements - Mode Manager จัดการแล้ว | |
| // Re-enable controls | |
| setControlsDisabled(false); | |
| // Reset status | |
| setStatus('Application reset - Ready to start', 'online'); | |
| console.log('[App] Reset complete'); | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Security | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| async function showSecurityStats() { | |
| try { | |
| const result = await window.chahuaVideo.getSecurityStats(); | |
| if (result.success) { | |
| const stats = result.stats; | |
| alert(`Security Statistics:\n\n` + | |
| `Total Operations: ${stats.totalOperations}\n` + | |
| `Uptime: ${Math.round(stats.uptime / 1000)}s\n` + | |
| `Rate Limit Entries: ${stats.rateLimitEntries}\n` + | |
| `Cached Hashes: ${stats.cachedHashes}`); | |
| } | |
| } catch (error) { | |
| console.error('Security stats error:', error); | |
| } | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Helper Functions | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| function showScene(sceneId) { | |
| dom.sceneElements.forEach(scene => { | |
| scene.classList.toggle('active', scene.dataset.scene === sceneId); | |
| }); | |
| } | |
| function setStatus(message, state = 'online') { | |
| dom.statusLog.innerHTML = `<strong>${state === 'recording' ? 'Recording:' : 'Status:'}</strong> ${message}`; | |
| dom.statusPill.textContent = state === 'recording' ? 'Recording' : 'Ready'; | |
| dom.statusPill.className = `status-pill ${state}`; | |
| } | |
| function setControlsDisabled(disabled) { | |
| dom.previewBtn.disabled = disabled; | |
| dom.recordWebMBtn.disabled = disabled; | |
| dom.securityBtn.disabled = disabled; | |
| } | |
| function wait(ms) { | |
| return new Promise(resolve => setTimeout(resolve, ms)); | |
| } | |
| function formatDuration(seconds) { | |
| const mins = Math.floor(seconds / 60); | |
| const secs = Math.floor(seconds % 60); | |
| return mins > 0 ? `${mins}:${secs.toString().padStart(2, '0')}` : `${secs}s`; | |
| } | |
| function formatTimecode(seconds) { | |
| const mins = Math.floor(seconds / 60); | |
| const secs = Math.floor(seconds % 60); | |
| return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`; | |
| } | |
| function formatBytes(bytes) { | |
| if (bytes === 0) return '0 Bytes'; | |
| const k = 1024; | |
| const sizes = ['Bytes', 'KB', 'MB', 'GB']; | |
| const i = Math.floor(Math.log(bytes) / Math.log(k)); | |
| return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]; | |
| } | |
| function escapeHtml(text) { | |
| const div = document.createElement('div'); | |
| div.textContent = text; | |
| return div.innerHTML; | |
| } | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Start Application | |
| // ══════════════════════════════════════════════════════════════════════════════ | |
| // Initialize Slide Editor | |
| const slideEditor = new SlideEditor(); | |
| function init() { | |
| console.log('[App] Initializing Markdown Presenter'); | |
| // ตั้งค่าโหมดเริ่มต้นเป็น intro และปิดโหมดอื่นทั้งหมด | |
| switchToIntroMode(); | |
| // Load saved config FIRST before any UI setup | |
| const savedConfig = loadSavedConfig(); | |
| if (savedConfig) { | |
| console.log('[App] Loaded saved configuration from localStorage'); | |
| } | |
| dom.sceneElements = Array.from(document.querySelectorAll('[data-scene]')); | |
| if (dom.markdownEditor) { | |
| state.markdown = dom.markdownEditor.value; | |
| } | |
| document.documentElement.style.setProperty('--accent-color', state.themeConfig.accent); | |
| setupTabs(); | |
| setupPresentationSettings(); // NEW: Setup presentation config controls | |
| setupTemplates(); // Keep legacy template support | |
| updateTemplateUI(); | |
| setupMarkdownControls(); | |
| setupConfigInputs(); | |
| setupExportControls(); | |
| setupPresentationMode(); | |
| setupFullscreenControl(); | |
| setupStageClickHandler(); | |
| setupScreenSensor(); | |
| setupConfigManagement(); // NEW: Setup Import/Export buttons | |
| if (dom.slideCounter) { | |
| dom.slideCounter.textContent = state.slides.length > 0 | |
| ? `${state.currentSlideIndex + 1} / ${state.slides.length}` | |
| : '0 / 0'; | |
| } | |
| if (dom.prevSlideBtn) dom.prevSlideBtn.disabled = true; | |
| if (dom.nextSlideBtn) dom.nextSlideBtn.disabled = true; | |
| // ไม่ต้อง hide UI elements - Mode Manager จัดการแล้วตอน switchToIntroMode() | |
| if (dom.progressContainer) dom.progressContainer.classList.add('hidden'); | |
| if (dom.pauseOverlay) dom.pauseOverlay.classList.add('hidden'); | |
| showScene('intro'); | |
| setStatus('Ready - Sync markdown to begin', 'online'); | |
| } | |
| init(); | |