aboutsummaryrefslogtreecommitdiff
path: root/build/js/io/autosave.js
blob: c45904e63aef98ee4d394eedcea1d4059a959ef9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// 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;
  }
}