// ══════════════════════════════════════════════════════════════════════════════ // Chahua Markdown Presenter - Slide Editor // In-Presentation Slide Editing System with Drag & Drop // ══════════════════════════════════════════════════════════════════════════════ // Company: Chahua Development Co., Ltd. // Version: 2.1.0 // License: MIT // ══════════════════════════════════════════════════════════════════════════════ import { DragDropManager } from './drag-drop-manager.js'; import { PersistentStorage } from '../../shared/persistent-storage.js'; import { ContentFingerprint } from '../../shared/content-fingerprint.js'; import { setDisplayMode, getDisplayMode } from './presentation-config.js'; import { switchToEditorMode, switchToPresentationMode, getModeManager } from './mode-manager.js'; /** * Slide Editor - แก้ไขสไลด์แบบ inline ใน Presentation Mode * พร้อมระบบลากย้ายตำแหน่งและบันทึกถาวร */ export class SlideEditor { constructor() { this.isEditMode = false; this.isDragMode = false; this.currentSlideIndex = -1; this.currentFilePath = null; this.slideOverrides = new Map(); // เก็บการแก้ไขแยกตามสไลด์ this.originalContent = null; this.hasUnsavedChanges = false; // DOM Elements this.editBtn = document.getElementById('editSlideBtn'); this.saveBtn = document.getElementById('saveSlideBtn'); this.cancelBtn = document.getElementById('cancelEditBtn'); this.stage = document.getElementById('stage'); // Position Controls this.positionControls = document.getElementById('positionControls'); this.toggleSafeZoneBtn = document.getElementById('toggleSafeZoneBtn'); this.toggleSnapGridBtn = document.getElementById('toggleSnapGridBtn'); this.resetPositionsBtn = document.getElementById('resetPositionsBtn'); this.exportSettingsBtn = document.getElementById('exportSettingsBtn'); this.positionIndicator = document.getElementById('positionIndicator'); // Managers this.dragDropManager = new DragDropManager(); this.persistentStorage = new PersistentStorage(); this.init(); } /** * Initialize editor */ init() { if (!this.editBtn || !this.saveBtn || !this.cancelBtn) { console.warn('[SlideEditor] Required buttons not found'); return; } // Event listeners this.editBtn.addEventListener('click', () => this.toggleEditMode()); this.saveBtn.addEventListener('click', () => this.saveChanges()); this.cancelBtn.addEventListener('click', () => this.cancelEdit()); // Position control listeners if (this.toggleSafeZoneBtn) { this.toggleSafeZoneBtn.addEventListener('click', () => this.toggleSafeZone()); } if (this.toggleSnapGridBtn) { this.toggleSnapGridBtn.addEventListener('click', () => this.toggleSnapGrid()); } if (this.resetPositionsBtn) { this.resetPositionsBtn.addEventListener('click', () => this.resetAllPositions()); } if (this.exportSettingsBtn) { this.exportSettingsBtn.addEventListener('click', () => this.exportAllSettings()); } // Keyboard shortcuts document.addEventListener('keydown', (e) => { if (!this.isEditMode) return; // Ctrl/Cmd + S = Save if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); this.saveChanges(); } // ESC = Cancel if (e.key === 'Escape') { e.preventDefault(); this.cancelEdit(); } }); console.log('[SlideEditor] Initialized'); } /** * Show edit button when in presentation mode */ showEditButton() { if (this.editBtn) { this.editBtn.classList.remove('hidden'); } } /** * Hide edit button */ hideEditButton() { if (this.editBtn) { this.editBtn.classList.add('hidden'); } this.exitEditMode(); } /** * Set current slide index */ setCurrentSlide(index) { this.currentSlideIndex = index; } /** * Toggle edit mode */ toggleEditMode() { if (this.isEditMode) { this.exitEditMode(); } else { this.enterEditMode(); } } /** * Enter edit mode */ /** * Enter edit mode */ enterEditMode() { if (this.currentSlideIndex < 0) { console.warn('[SlideEditor] No slide selected'); return; } // สลับไปโหมด editor และปิดโหมดอื่นทั้งหมด switchToEditorMode(); this.isEditMode = true; this.hasUnsavedChanges = false; // Save original content const activeScene = this.stage.querySelector('.scene.active'); if (!activeScene) { console.warn('[SlideEditor] No active scene found'); return; } this.originalContent = activeScene.cloneNode(true); // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง detach ที่นี่ // Make content editable this.makeContentEditable(activeScene); // Update UI this.stage.classList.add('slide-editable'); this.editBtn.classList.add('active'); this.showEditIndicator(); // Mode Manager จัดการ Safe Zone แล้ว ไม่ต้องแสดงที่นี่ console.log(`[SlideEditor] Edit mode entered for slide ${this.currentSlideIndex}`); } /** * Exit edit mode (with unsaved changes check) */ async exitEditMode() { if (!this.isEditMode) return; // ถ้ามีการแก้ไขที่ยังไม่บันทึก ให้ถามผู้ใช้ if (this.hasUnsavedChanges) { const result = await this.showExitConfirmation('Edit Mode', 'You have unsaved changes.'); if (result === 'cancel') { // ยกเลิก ไม่ออกจาก Edit Mode return; } else if (result === 'save') { // บันทึกก่อนออก await this.saveCurrentSlide(); } // ถ้าเลือก 'discard' ก็ออกเลยโดยไม่บันทึก } this.isEditMode = false; // กลับไปโหมด presentation และปิดโหมดอื่นทั้งหมด switchToPresentationMode(); // Remove contenteditable const activeScene = this.stage.querySelector('.scene.active'); if (activeScene) { this.makeContentNonEditable(activeScene); } // Update UI this.stage.classList.remove('slide-editable'); this.editBtn.classList.remove('active'); this.hideEditIndicator(); this.hideSaveButtons(); // Mode Manager จัดการ Safe Zone และ Smart Layout แล้ว this.originalContent = null; this.hasUnsavedChanges = false; console.log('[SlideEditor] Edit mode exited'); } /** * Show exit confirmation dialog * @param {string} modeName - ชื่อโหมด * @param {string} message - ข้อความเพิ่มเติม * @returns {Promise} 'save', 'discard', หรือ 'cancel' */ async showExitConfirmation(modeName, message = '') { return new Promise((resolve) => { const dialog = document.createElement('div'); dialog.className = 'exit-confirmation-dialog'; dialog.innerHTML = `

Exit ${modeName}?

${message}

Do you want to save your changes?

`; document.body.appendChild(dialog); // Handle button clicks dialog.querySelectorAll('button').forEach(btn => { btn.addEventListener('click', () => { const action = btn.dataset.action; document.body.removeChild(dialog); resolve(action); }); }); // ESC to cancel const escHandler = (e) => { if (e.key === 'Escape') { document.body.removeChild(dialog); document.removeEventListener('keydown', escHandler); resolve('cancel'); } }; document.addEventListener('keydown', escHandler); }); } /** * Make scene content editable */ makeContentEditable(scene) { // Find all editable elements const editableElements = scene.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote'); editableElements.forEach((el, index) => { el.setAttribute('contenteditable', 'true'); el.setAttribute('data-editable-id', `edit-${index}`); el.setAttribute('data-placeholder', 'Click to edit...'); // Track changes el.addEventListener('input', () => this.onContentChange()); el.addEventListener('blur', () => this.onContentChange()); }); } /** * Remove contenteditable */ makeContentNonEditable(scene) { const editableElements = scene.querySelectorAll('[contenteditable="true"]'); editableElements.forEach(el => { el.removeAttribute('contenteditable'); el.removeAttribute('data-editable-id'); el.removeAttribute('data-placeholder'); }); } /** * Handle content change */ onContentChange() { if (!this.hasUnsavedChanges) { this.hasUnsavedChanges = true; this.showSaveButtons(); } } /** * Save changes to current slide */ saveChanges() { if (!this.isEditMode || this.currentSlideIndex < 0) return; const activeScene = this.stage.querySelector('.scene.active'); if (!activeScene) return; // Extract edited content const editedContent = this.extractEditedContent(activeScene); // Save to overrides map this.slideOverrides.set(this.currentSlideIndex, { timestamp: Date.now(), content: editedContent, html: activeScene.innerHTML }); console.log(`[SlideEditor] Saved changes for slide ${this.currentSlideIndex}`, editedContent); // Exit edit mode this.exitEditMode(); // Show success notification this.showNotification('✓ Slide saved', 'success'); } /** * Cancel edit and revert changes */ cancelEdit() { if (!this.isEditMode || !this.originalContent) return; const activeScene = this.stage.querySelector('.scene.active'); if (activeScene && this.originalContent) { // Restore original content activeScene.parentNode.replaceChild(this.originalContent.cloneNode(true), activeScene); // Re-add active class const restoredScene = this.stage.querySelector('.scene[data-scene]'); if (restoredScene) { restoredScene.classList.add('active'); } } this.exitEditMode(); this.showNotification('✗ Changes cancelled', 'warning'); } /** * Extract edited content from scene */ extractEditedContent(scene) { const content = {}; // Extract text from editable elements const editables = scene.querySelectorAll('[data-editable-id]'); editables.forEach(el => { const id = el.getAttribute('data-editable-id'); content[id] = { tag: el.tagName.toLowerCase(), text: el.textContent.trim(), html: el.innerHTML }; }); return content; } /** * Apply saved overrides to a slide */ applyOverrides(slideIndex, scene) { if (!this.slideOverrides.has(slideIndex)) return false; const override = this.slideOverrides.get(slideIndex); // Apply saved HTML if (override.html) { scene.innerHTML = override.html; console.log(`[SlideEditor] Applied overrides to slide ${slideIndex}`); return true; } return false; } /** * Check if slide has overrides */ hasOverrides(slideIndex) { return this.slideOverrides.has(slideIndex); } /** * Get all overrides */ getAllOverrides() { return Array.from(this.slideOverrides.entries()).map(([index, data]) => ({ slideIndex: index, ...data })); } /** * Clear override for specific slide */ clearOverride(slideIndex) { this.slideOverrides.delete(slideIndex); } /** * Clear all overrides */ clearAllOverrides() { this.slideOverrides.clear(); } /** * Export overrides as JSON */ exportOverrides() { const data = this.getAllOverrides(); return JSON.stringify(data, null, 2); } /** * Import overrides from JSON */ importOverrides(jsonString) { try { const data = JSON.parse(jsonString); data.forEach(item => { this.slideOverrides.set(item.slideIndex, { timestamp: item.timestamp, content: item.content, html: item.html }); }); console.log(`[SlideEditor] Imported ${data.length} overrides`); return true; } catch (error) { console.error('[SlideEditor] Failed to import overrides:', error); return false; } } /** * Show edit mode indicator */ showEditIndicator() { let indicator = document.getElementById('editModeIndicator'); if (!indicator) { indicator = document.createElement('div'); indicator.id = 'editModeIndicator'; indicator.className = 'edit-mode-indicator'; indicator.textContent = '✎ Edit Mode'; this.stage.appendChild(indicator); } } /** * Hide edit mode indicator */ hideEditIndicator() { const indicator = document.getElementById('editModeIndicator'); if (indicator) { indicator.remove(); } } /** * Show save/cancel buttons */ showSaveButtons() { if (this.saveBtn) this.saveBtn.classList.remove('hidden'); if (this.cancelBtn) this.cancelBtn.classList.remove('hidden'); } /** * Hide save/cancel buttons */ hideSaveButtons() { if (this.saveBtn) this.saveBtn.classList.add('hidden'); if (this.cancelBtn) this.cancelBtn.classList.add('hidden'); } /** * Show notification */ showNotification(message, type = 'info') { // Create notification element const notification = document.createElement('div'); notification.className = `slide-edit-notification notification-${type}`; notification.textContent = message; notification.style.cssText = ` position: fixed; top: 5rem; left: 50%; transform: translateX(-50%); z-index: 1000; background: ${type === 'success' ? 'rgba(16, 185, 129, 0.95)' : type === 'warning' ? 'rgba(245, 158, 11, 0.95)' : 'rgba(59, 130, 246, 0.95)'}; color: white; padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); animation: slideDown 0.3s ease-out; `; document.body.appendChild(notification); // Remove after 3 seconds setTimeout(() => { notification.style.animation = 'slideUp 0.3s ease-out'; setTimeout(() => notification.remove(), 300); }, 3000); } /** * Reset editor state */ reset() { this.exitEditMode(); this.exitDragMode(); this.currentSlideIndex = -1; this.hideEditButton(); this.hidePositionControls(); } // ═══════════════════════════════════════════════════════════════════════════ // DRAG & DROP METHODS // ═══════════════════════════════════════════════════════════════════════════ /** * เข้าสู่ Drag Mode */ /** * เข้าสู่ Drag Mode */ enterDragMode() { const activeScene = this.stage?.querySelector('.scene.active'); if (!activeScene) return; // สลับไปโหมด editor และปิดโหมดอื่นทั้งหมด switchToEditorMode(); this.isDragMode = true; // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง detach ที่นี่ this.dragDropManager.enableDragging(activeScene); this.showPositionControls(); // เปลี่ยนสีปุ่ม edit if (this.editBtn) { this.editBtn.style.background = 'rgba(139, 92, 246, 0.9)'; // สีม่วง } this.showNotification('⊕ Drag Mode - ลากเพื่อย้ายตำแหน่งบรรทัด', 'info'); } /** * ออกจาก Drag Mode */ exitDragMode() { const activeScene = this.stage?.querySelector('.scene.active'); if (activeScene) { this.dragDropManager.disableDragging(activeScene); } // กลับไปโหมด presentation และปิดโหมดอื่นทั้งหมด switchToPresentationMode(); this.isDragMode = false; this.hidePositionControls(); // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง reattach ที่นี่ // คืนสีปุ่ม edit if (this.editBtn) { this.editBtn.style.background = ''; } } /** * Toggle Drag Mode */ toggleDragMode() { if (this.isDragMode) { this.exitDragMode(); } else { // ออกจาก Edit Mode ก่อน (ถ้ากำลัง edit อยู่) if (this.isEditMode) { this.exitEditMode(); } this.enterDragMode(); } } /** * แสดง Position Controls */ showPositionControls() { if (this.positionControls) { this.positionControls.classList.remove('hidden'); } } /** * ซ่อน Position Controls */ hidePositionControls() { if (this.positionControls) { this.positionControls.classList.add('hidden'); } } /** * Toggle Safe Zone */ toggleSafeZone() { const isActive = this.dragDropManager.showSafeZone; this.dragDropManager.toggleSafeZone(!isActive); if (this.toggleSafeZoneBtn) { if (!isActive) { this.toggleSafeZoneBtn.classList.add('active'); this.showNotification('✓ Safe Zone เปิด', 'success'); } else { this.toggleSafeZoneBtn.classList.remove('active'); this.showNotification('✗ Safe Zone ปิด', 'info'); } } } /** * Toggle Snap to Grid */ toggleSnapGrid() { const isActive = this.dragDropManager.snapToGrid; this.dragDropManager.toggleSnapToGrid(!isActive); if (this.toggleSnapGridBtn) { if (!isActive) { this.toggleSnapGridBtn.classList.add('active'); this.showNotification('✓ Snap to Grid เปิด', 'success'); } else { this.toggleSnapGridBtn.classList.remove('active'); this.showNotification('✗ Snap to Grid ปิด', 'info'); } } } /** * รีเซ็ตตำแหน่งทั้งหมดของสไลด์ปัจจุบัน */ resetAllPositions() { if (!confirm('รีเซ็ตตำแหน่งและการแก้ไขทั้งหมดของสไลด์นี้?\n(การตั้งค่าจะถูกลบถาวร)')) { return; } const activeScene = this.stage?.querySelector('.scene.active'); if (!activeScene) return; // รีเซ็ตตำแหน่ง const elements = activeScene.querySelectorAll('.draggable-content'); elements.forEach(element => { this.dragDropManager.resetPosition(element); }); // ลบการแก้ไขเนื้อหา if (this.currentSlideIndex >= 0) { this.slideOverrides.delete(this.currentSlideIndex); } // ลบจาก localStorage if (this.currentFilePath && this.currentSlideIndex >= 0) { this.persistentStorage.clearSlide(this.currentFilePath, this.currentSlideIndex); } // ลบข้อมูล positions จาก dragDropManager this.dragDropManager.clearAllPositions(); this.showNotification('✓ รีเซ็ตทั้งหมดเรียบร้อย', 'success'); } /** * Export การตั้งค่าทั้งหมด */ exportAllSettings() { if (!this.currentFilePath) { this.showNotification('⚠ กรุณาเปิดไฟล์ก่อน', 'warning'); return; } const totalSlides = this.getTotalSlides(); this.persistentStorage.downloadJSON(this.currentFilePath, totalSlides); this.showNotification('✓ ส่งออกการตั้งค่าเรียบร้อย', 'success'); } /** * นับจำนวน slides ทั้งหมด */ getTotalSlides() { // ควร implement ตามโครงสร้างจริง return 10; // placeholder } /** * ตั้งค่าไฟล์ปัจจุบัน */ setCurrentFile(filePath) { this.currentFilePath = filePath; this.persistentStorage.setCurrentFile(filePath); } /** * Apply positions จาก storage */ applyPositions(slideIndex, scene) { if (!this.currentFilePath) return false; const positions = this.persistentStorage.loadPositions(this.currentFilePath, slideIndex); if (!positions) return false; this.dragDropManager.loadPositions(positions); return true; } /** * Save positions ไปยัง storage */ savePositions() { if (!this.currentFilePath || this.currentSlideIndex < 0) return; const positions = this.dragDropManager.exportPositions(); this.persistentStorage.savePositions( this.currentFilePath, this.currentSlideIndex, positions ); } // ═══════════════════════════════════════════════════════════════════════════ // CONTENT FINGERPRINTING // ═══════════════════════════════════════════════════════════════════════════ /** * สร้าง fingerprint map สำหรับ slide */ createFingerprintMap(scene) { return ContentFingerprint.mapSlideElements(scene); } /** * Match settings กับ content ใหม่ */ matchSettingsToContent(scene, savedSettings) { const elementMap = this.createFingerprintMap(scene); const matched = []; elementMap.forEach(({ element, fingerprint }) => { const setting = ContentFingerprint.match(fingerprint, savedSettings); if (setting) { matched.push({ element, setting, confidence: setting.matchConfidence }); } }); return matched; } } // CSS for notification animation const style = document.createElement('style'); style.textContent = ` @keyframes slideDown { from { opacity: 0; transform: translate(-50%, -20px); } to { opacity: 1; transform: translate(-50%, 0); } } @keyframes slideUp { from { opacity: 1; transform: translate(-50%, 0); } to { opacity: 0; transform: translate(-50%, -20px); } } `; document.head.appendChild(style);