← System index

rating-store.js

Disk API persistence, browser drafts, retry and concurrent edits.

Download original source

Factory source f102c8669271902fe60d3189b0a54a566f64b07c · SHA-256 e0356a6a7b999d06c0dd545bd4e09b725e821c7dc3e1f7312bc661b6c67bfe33

// Thin comparison adapter for scene-bench/build-bench.mjs's disk + pending-draft workflow.
// The shared scene-bench/serve.mjs owns the API and append-only ledger; no client-local backend.
class RatingStore {
  constructor({storage, key, request, changed = () => {}}) {
    this.storage = storage; this.key = key; this.request = request; this.changed = changed;
    this.jobs = {}; this.status = {}; this.connected = false;
    try { this.rows = JSON.parse(storage.getItem(key) || '{}'); } catch { this.rows = {}; }
  }
  cache() {
    try { this.storage.setItem(this.key, JSON.stringify(this.rows)); }
    catch { this.cacheFailed = true; }
  }
  payload(id) {
    const r = this.rows[id] || {};
    return {id, score: r.score ?? null, vote: r.vote ?? null, tags: r.tags || [], note: r.note || ''};
  }
  update(id, patch) {
    const r = {...(this.rows[id] || {}), ...patch, pendingDisk: true};
    if ('score' in patch) r.vote = patch.score === null ? null : ['no','low','high','heart'][Math.min(3, Math.floor(patch.score / 25))];
    this.rows[id] = r; this.cache();
    this.status[id] = this.cacheFailed ? 'Unsaved · browser draft storage unavailable; keep this tab open' : 'Unsaved changes · draft kept in this browser';
    this.changed(id); this.schedule(id);
  }
  schedule(id, delay = 650) {
    const job = this.jobs[id] ||= {};
    clearTimeout(job.timer); job.timer = setTimeout(() => this.save(id), delay);
  }
  async load() {
    try {
      const response = await this.request('/api/ratings', {cache:'no-store'});
      if (!response.ok) throw new Error('HTTP '+response.status);
      const disk = await response.json();
      this.connected = true;
      for (const [id,row] of Object.entries(this.rows)) if (row.pendingDisk) disk[id] = row;
      this.rows = disk; this.cache(); this.changed();
      for (const [id,row] of Object.entries(this.rows)) if (row.pendingDisk) this.schedule(id, 0);
    } catch {
      this.connected = false; this.changed();
    }
  }
  async save(id) {
    const job = this.jobs[id] ||= {};
    clearTimeout(job.timer);
    if (job.inFlight) { job.again = true; return; }
    if (!this.rows[id]) { this.status[id] = 'Choose a rating or write feedback first'; this.changed(id); return; }
    if (!this.rows[id].pendingDisk) return;
    const encoded = JSON.stringify(this.payload(id));
    job.inFlight = true; job.again = false;
    this.status[id] = 'Saving to disk…'; this.changed(id);
    let succeeded = false;
    try {
      const response = await this.request('/api/rating', {method:'POST',headers:{'content-type':'application/json'},body:encoded});
      if (!response.ok) throw new Error('HTTP '+response.status);
      const saved = await response.json();
      if (saved.id !== id || !saved.at) throw new Error('Invalid save receipt');
      succeeded = true; this.connected = true;
      const current = this.rows[id];
      this.rows[id] = {...current, at:saved.at, pendingDisk:JSON.stringify(this.payload(id)) !== encoded};
      this.status[id] = this.rows[id].pendingDisk ? 'Newer changes waiting to save…' : 'Saved to disk · '+new Date(saved.at).toLocaleTimeString();
      this.cache(); this.changed(id);
    } catch {
      this.connected = false;
      this.status[id] = this.cacheFailed ? 'Not saved to disk · keep this tab open and retry Save' : 'Not saved to disk · draft kept in this browser; retry Save';
      this.changed(id);
    } finally {
      job.inFlight = false;
      if (succeeded && (job.again || this.rows[id].pendingDisk)) this.schedule(id, 0);
    }
  }
}
globalThis.RatingStore = RatingStore;