/** * Persistent Storage Manager * * จัดการการบันทึกและโหลดการตั้งค่าทั้งหมด (positions, edits, layouts) * รองรับ localStorage และ Export/Import JSON * Auto-save ทุก 2-3 วินาที * * @author Chahua Development Co., Ltd. * @version 2.1.0 */ export class PersistentStorage { constructor() { this.currentFilePath = null; this.autoSaveInterval = null; this.autoSaveDelay = 2000; // 2 วินาที this.hasUnsavedChanges = false; // Storage keys this.STORAGE_PREFIX = 'chahua-md-presenter'; this.POSITIONS_KEY = 'positions'; this.EDITS_KEY = 'edits'; this.LAYOUTS_KEY = 'layouts'; this.SETTINGS_KEY = 'settings'; this.init(); } init() { // Listen for changes this.setupEventListeners(); // Auto-save on window close window.addEventListener('beforeunload', () => { if (this.hasUnsavedChanges) { this.save(); } }); } /** * Setup event listeners สำหรับ auto-save */ setupEventListeners() { // Listen for position changes document.addEventListener('positionChanged', () => { this.hasUnsavedChanges = true; this.scheduleAutoSave(); }); // Listen for content changes document.addEventListener('contentChanged', () => { this.hasUnsavedChanges = true; this.scheduleAutoSave(); }); // Listen for layout changes document.addEventListener('layoutChanged', () => { this.hasUnsavedChanges = true; this.scheduleAutoSave(); }); } /** * กำหนดไฟล์ปัจจุบัน * * @param {string} filePath */ setCurrentFile(filePath) { this.currentFilePath = filePath; } /** * สร้าง storage key จาก file path และ slide index * * @param {string} filePath * @param {number} slideIndex * @param {string} dataType - 'positions', 'edits', 'layouts', 'settings' * @returns {string} */ getStorageKey(filePath, slideIndex = null, dataType = 'positions') { const cleanPath = this.sanitizeFilePath(filePath); const slideKey = slideIndex !== null ? `:slide-${slideIndex}` : ''; return `${this.STORAGE_PREFIX}:${cleanPath}${slideKey}:${dataType}`; } /** * Sanitize file path สำหรับใช้เป็น key * * @param {string} filePath * @returns {string} */ sanitizeFilePath(filePath) { if (!filePath) return 'untitled'; // แปลง path เป็น hash เพื่อให้สั้นลง return this.simpleHash(filePath); } /** * Simple hash function * * @param {string} str * @returns {string} */ simpleHash(str) { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; } return Math.abs(hash).toString(36); } /** * บันทึก positions สำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex * @param {Object} positions */ savePositions(filePath, slideIndex, positions) { const key = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY); const data = { timestamp: Date.now(), filePath, slideIndex, positions }; try { localStorage.setItem(key, JSON.stringify(data)); return true; } catch (error) { console.error('Failed to save positions:', error); return false; } } /** * โหลด positions สำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex * @returns {Object|null} */ loadPositions(filePath, slideIndex) { const key = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY); try { const data = localStorage.getItem(key); if (!data) return null; const parsed = JSON.parse(data); return parsed.positions; } catch (error) { console.error('Failed to load positions:', error); return null; } } /** * บันทึก content edits สำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex * @param {Object} edits */ saveEdits(filePath, slideIndex, edits) { const key = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY); const data = { timestamp: Date.now(), filePath, slideIndex, edits }; try { localStorage.setItem(key, JSON.stringify(data)); return true; } catch (error) { console.error('Failed to save edits:', error); return false; } } /** * โหลด content edits สำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex * @returns {Object|null} */ loadEdits(filePath, slideIndex) { const key = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY); try { const data = localStorage.getItem(key); if (!data) return null; const parsed = JSON.parse(data); return parsed.edits; } catch (error) { console.error('Failed to load edits:', error); return null; } } /** * บันทึก layout settings สำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex * @param {Object} layout */ saveLayout(filePath, slideIndex, layout) { const key = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY); const data = { timestamp: Date.now(), filePath, slideIndex, layout }; try { localStorage.setItem(key, JSON.stringify(data)); return true; } catch (error) { console.error('Failed to save layout:', error); return false; } } /** * โหลด layout settings สำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex * @returns {Object|null} */ loadLayout(filePath, slideIndex) { const key = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY); try { const data = localStorage.getItem(key); if (!data) return null; const parsed = JSON.parse(data); return parsed.layout; } catch (error) { console.error('Failed to load layout:', error); return null; } } /** * บันทึกทุกอย่างสำหรับไฟล์ปัจจุบัน * * @param {Array} allData - Array of {slideIndex, positions, edits, layout} */ saveAll(filePath, allData) { let savedCount = 0; allData.forEach(slideData => { const { slideIndex, positions, edits, layout } = slideData; if (positions) { this.savePositions(filePath, slideIndex, positions); savedCount++; } if (edits) { this.saveEdits(filePath, slideIndex, edits); savedCount++; } if (layout) { this.saveLayout(filePath, slideIndex, layout); savedCount++; } }); this.hasUnsavedChanges = false; return savedCount; } /** * โหลดทุกอย่างสำหรับไฟล์ปัจจุบัน * * @param {string} filePath * @param {number} totalSlides * @returns {Array} */ loadAll(filePath, totalSlides) { const allData = []; for (let i = 0; i < totalSlides; i++) { const positions = this.loadPositions(filePath, i); const edits = this.loadEdits(filePath, i); const layout = this.loadLayout(filePath, i); if (positions || edits || layout) { allData.push({ slideIndex: i, positions, edits, layout }); } } return allData; } /** * Export ทุกอย่างเป็น JSON file * * @param {string} filePath * @param {number} totalSlides * @returns {string} - JSON string */ exportToJSON(filePath, totalSlides) { const allData = this.loadAll(filePath, totalSlides); const exportData = { version: '2.1.0', exportedAt: new Date().toISOString(), filePath, totalSlides, slides: allData }; return JSON.stringify(exportData, null, 2); } /** * Import จาก JSON file * * @param {string} jsonString * @returns {boolean} */ importFromJSON(jsonString) { try { const data = JSON.parse(jsonString); if (!data.version || !data.slides) { throw new Error('Invalid JSON format'); } const { filePath, slides } = data; slides.forEach(slideData => { const { slideIndex, positions, edits, layout } = slideData; if (positions) { this.savePositions(filePath, slideIndex, positions); } if (edits) { this.saveEdits(filePath, slideIndex, edits); } if (layout) { this.saveLayout(filePath, slideIndex, layout); } }); return true; } catch (error) { console.error('Failed to import JSON:', error); return false; } } /** * Download JSON file * * @param {string} filePath * @param {number} totalSlides */ downloadJSON(filePath, totalSlides) { const json = this.exportToJSON(filePath, totalSlides); const blob = new Blob([json], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `presentation-settings-${Date.now()}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } /** * Schedule auto-save */ scheduleAutoSave() { if (this.autoSaveInterval) { clearTimeout(this.autoSaveInterval); } this.autoSaveInterval = setTimeout(() => { this.save(); }, this.autoSaveDelay); } /** * บันทึกทันที (manual save) */ save() { if (!this.hasUnsavedChanges) return; // Trigger save event const event = new CustomEvent('persistentStorageSave', { detail: { filePath: this.currentFilePath, timestamp: Date.now() } }); document.dispatchEvent(event); this.hasUnsavedChanges = false; } /** * ลบข้อมูลสำหรับ slide หนึ่ง * * @param {string} filePath * @param {number} slideIndex */ clearSlide(filePath, slideIndex) { const posKey = this.getStorageKey(filePath, slideIndex, this.POSITIONS_KEY); const editKey = this.getStorageKey(filePath, slideIndex, this.EDITS_KEY); const layoutKey = this.getStorageKey(filePath, slideIndex, this.LAYOUTS_KEY); localStorage.removeItem(posKey); localStorage.removeItem(editKey); localStorage.removeItem(layoutKey); } /** * ลบข้อมูลทั้งหมดสำหรับไฟล์หนึ่ง * * @param {string} filePath */ clearFile(filePath) { const prefix = `${this.STORAGE_PREFIX}:${this.sanitizeFilePath(filePath)}`; // หา keys ทั้งหมดที่ตรงกับ prefix const keysToRemove = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key.startsWith(prefix)) { keysToRemove.push(key); } } // ลบทั้งหมด keysToRemove.forEach(key => localStorage.removeItem(key)); } /** * ลบข้อมูลทั้งหมด */ clearAll() { const keysToRemove = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key.startsWith(this.STORAGE_PREFIX)) { keysToRemove.push(key); } } keysToRemove.forEach(key => localStorage.removeItem(key)); } /** * Get storage usage info * * @returns {Object} */ getStorageInfo() { let totalSize = 0; let itemCount = 0; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key.startsWith(this.STORAGE_PREFIX)) { const value = localStorage.getItem(key); totalSize += key.length + value.length; itemCount++; } } return { itemCount, totalSize, totalSizeKB: (totalSize / 1024).toFixed(2), maxSize: 5120, // 5MB typical localStorage limit usagePercent: ((totalSize / (5 * 1024 * 1024)) * 100).toFixed(2) }; } /** * Cleanup old data (optional) * ลบข้อมูลที่เก่ากว่า X วัน * * @param {number} daysOld */ cleanupOldData(daysOld = 30) { const cutoffTime = Date.now() - (daysOld * 24 * 60 * 60 * 1000); const keysToRemove = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (!key.startsWith(this.STORAGE_PREFIX)) continue; try { const data = JSON.parse(localStorage.getItem(key)); if (data.timestamp && data.timestamp < cutoffTime) { keysToRemove.push(key); } } catch (error) { // Invalid JSON, skip } } keysToRemove.forEach(key => localStorage.removeItem(key)); return keysToRemove.length; } } export default PersistentStorage;