Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
2.7 KB
Raw Blame
/**
 * Save-as-you-go for a document a tool holds in memory.
 *
 * Call `schedule()` after every change; the write runs once the changes have
 * stopped for `delay` ms, so a slider drag is one save rather than sixty. Only one
 * write is ever in flight: a change made during it is written right after, never
 * alongside, because two racing writes can land in either order.
 *
 * `write` reads the document when it runs rather than when it was scheduled, so a
 * burst of edits is saved as it ended. It may resolve without writing anything
 * when nothing changed since the last save.
 *
 * `flush()` writes whatever is pending and waits for it. A tool calls it before it
 * lets go of the document: switching file, closing the case, leaving the tool. After
 * a failed write the document is still unsaved, so `flush()` tries it again: that is
 * what a Retry button calls. `unsaved` says whether it is still unsaved afterwards.
 */
export function createAutosave({ write, delay = 800 }) {
  const state = $state({ status: 'idle', error: '' });
  let timer = null;
  // The writes in flight, as one promise: it settles only once no rewrite is owed,
  // so a change made during a write is waited for along with it.
  let running = null;
  let again = false;

  function run() {
    clearTimeout(timer);
    timer = null;
    if (running) {
      again = true;
      return running;
    }
    const chain = (async () => {
      do {
        again = false;
        state.status = 'saving';
        try {
          await write();
          state.status = 'saved';
          state.error = '';
        } catch (e) {
          state.status = 'error';
          state.error = e?.message || 'save failed';
        }
      } while (again);
    })();
    running = chain;
    chain.then(() => {
      if (running === chain) running = null;
    });
    return chain;
  }

  return {
    state,
    schedule() {
      state.status = 'pending';
      clearTimeout(timer);
      timer = setTimeout(run, delay);
    },
    async flush() {
      if (timer || (state.status === 'error' && !running)) await run();
      else if (running) await running;
    },
    /** Forget a pending write, for a document that is being thrown away. */
    cancel() {
      clearTimeout(timer);
      timer = null;
      again = false;
      state.status = 'idle';
      state.error = '';
    },
    /** Whether a write is scheduled, running or failed, so a page closing can send it. */
    get pending() {
      return timer !== null || running !== null || state.status === 'error';
    },
    /** Whether the last write failed and the document holds edits no write has kept. */
    get unsaved() {
      return state.status === 'error';
    },
  };
}