// Crash recovery: periodically stores modified documents in IndexedDB and offers // to restore them on the next start. import { saveProject, loadProject } from './project.js'; import { confirmDialog } from '../ui/dialogs.js'; const DB = 'atelier'; const STORE = 'autosave'; const KEY = 'session'; const INTERVAL = 30000; function openDB() { return new Promise((resolve, reject) => { const req = indexedDB.open(DB, 1); req.onupgradeneeded = () => req.result.createObjectStore(STORE); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } async function tx(mode, fn) { const db = await openDB(); return new Promise((resolve, reject) => { const t = db.transaction(STORE, mode); const store = t.objectStore(STORE); const req = fn(store); t.oncomplete = () => { resolve(req?.result); db.close(); }; t.onerror = () => { reject(t.error); db.close(); }; }); } export class Autosave { constructor(app) { this.app = app; this.lastSignature = ''; this.enabled = typeof indexedDB !== 'undefined'; if (this.enabled) setInterval(() => this.tick(), INTERVAL); } signature() { return this.app.documents.map((d) => `${d.id}:${d.version}:${d.structureVersion}`).join('|'); } async tick(force = false) { if (!this.enabled || this.saving || !this.app.prefs.get('autosave', true)) return; const sig = this.signature(); if (!force && sig === this.lastSignature) return; const docs = this.app.documents.filter((d) => d.isModified); this.saving = true; try { if (!docs.length) await tx('readwrite', (s) => s.delete(KEY)); else { const blobs = []; for (const d of docs) blobs.push(await saveProject(d)); await tx('readwrite', (s) => s.put({ savedAt: Date.now(), blobs, names: docs.map((d) => d.name) }, KEY)); } this.lastSignature = sig; } catch (err) { console.warn('Autosave failed', err); } finally { this.saving = false; } } async offerRecovery(manual = false) { if (!this.enabled) return false; let rec; try { rec = await tx('readonly', (s) => s.get(KEY)); } catch { rec = null; } if (!rec?.blobs?.length) { if (manual) this.app.toast('No autosaved session found'); return false; } const when = new Date(rec.savedAt).toLocaleString(); const ok = await confirmDialog(`Found unsaved work from ${when}: ${rec.names.join(', ')}. Restore it?`, { title: 'Recover session', ok: 'Restore', cancel: 'Discard' }); if (!ok) { if (!manual) await tx('readwrite', (s) => s.delete(KEY)).catch(() => {}); return false; } for (const blob of rec.blobs) { try { const { doc } = await loadProject(blob); this.app.addDocument(doc); doc.history.savedIndex = -1; // still unsaved this.app.emit('docs'); // refresh the tab's modified marker } catch (err) { console.error(err); } } return true; } }