# Saving state

> Read when state outlives a reload. Save a computed projection of what to keep, restore before the watch starts, write one save per burst, and save state a visible stage shows from the records of Realm.onUpdate.

## Example

The chat keeps `$settings` ([Snapshots](../state/snapshots.md)) in
`localStorage` across reloads. The storage is passed in, so a test hands the
saver one that keeps saves in memory or refuses them. Disposing the saver stops
its watch and writes a save still queued.

```ts
import { Box, Computed, Model, Realm } from "@frondruntime/sorus";
import type { Settings } from "./snapshots.ts";

interface TextStorage {
  readonly load: () => string | undefined;
  // Throws when the storage refuses the write, as a full localStorage does.
  readonly save: (text: string) => void;
}

const browserStorage: TextStorage = {
  load: () => localStorage.getItem("chat-settings") ?? undefined,
  save: (text) => localStorage.setItem("chat-settings", text),
};

class SettingsSaver extends Model.Class implements Disposable {
  readonly $storageError = Box.make<string | undefined>(this.realm, undefined, {
    name: "storageError",
  });

  // The text to save, and nothing else: it reads $settings alone, so a write
  // to the open room or the hovered room leaves it, and the watch below,
  // untouched.
  private readonly $saved: Computed<string>;
  private readonly $settings: Box<Settings>;
  private readonly storage: TextStorage;
  private readonly stopSaving: () => void;
  private queued = false;
  private lastSaved: string;

  constructor(realm: Realm, $settings: Box<Settings>, storage: TextStorage) {
    super(realm);
    this.$settings = $settings;
    this.storage = storage;
    this.$saved = Computed.make(realm, (read) => JSON.stringify(read($settings)));
    // Restored before the watch starts, so restoring saves nothing back.
    this.restore();
    this.lastSaved = Realm.untracked(realm, (read) => read(this.$saved));
    this.stopSaving = Realm.watch(
      realm,
      (read) => read(this.$saved),
      () => {
        this.queue();
      },
    );
  }

  private restore() {
    const text = this.storage.load();
    if (text === undefined) return;
    let saved: { readonly notifications?: unknown; readonly theme?: unknown } | null;
    try {
      saved = JSON.parse(text);
    } catch {
      return; // a damaged save starts from the defaults
    }
    // Each field is taken only when it is valid, so one bad field keeps the rest.
    Realm.update(this.realm, (read, write) => {
      const settings = read(this.$settings);
      write(this.$settings, {
        notifications:
          typeof saved?.notifications === "boolean" ? saved.notifications : settings.notifications,
        theme: saved?.theme === "light" || saved?.theme === "dark" ? saved.theme : settings.theme,
      });
    });
  }

  // A burst of updates in one task queues one save, which reads the end state.
  private queue() {
    if (this.queued) return;
    this.queued = true;
    queueMicrotask(() => this.flush());
  }

  flush() {
    if (!this.queued) return;
    this.queued = false;
    const text = Realm.untracked(this.realm, (read) => read(this.$saved));
    if (text === this.lastSaved) {
      // The burst ended where it began: the storage already holds this text.
      Realm.update(this.realm, (_read, write) => write(this.$storageError, undefined));
      return;
    }
    try {
      this.storage.save(text);
      this.lastSaved = text;
      Realm.update(this.realm, (_read, write) => write(this.$storageError, undefined));
    } catch (error) {
      // Kept as state for the screen to show; the next change tries again.
      const message = error instanceof Error ? error.message : String(error);
      Realm.update(this.realm, (_read, write) => write(this.$storageError, message));
    }
  }

  [Symbol.dispose]() {
    this.stopSaving();
    this.flush(); // a save still queued is written now, not lost
  }
}
```

`$saved` reads `$settings` alone, so a write to the hovered room neither
recomputes it nor runs the watch.

## Rules

- Save a `Computed.make` that builds the stored text, not the boxes one by
  one: the watch runs only when it changes.
- Restore before starting the watch, taking each field only when valid and keeping the
  default for the rest; otherwise the restore queues a save of what it loaded.
  Set the last saved text from it.
- Queue the save with `queueMicrotask`, read the text when it runs, and skip it
  when it equals the last text written. A watch runs once per outermost update,
  so a burst saves once; one ending where it began saves nothing.
- Catch a storage error in `flush` and write it to a box: a microtask has no
  caller to receive a throw. The last saved text stays, so the next change saves again.
- Save state a visible stage writes from the records of `Realm.onUpdate`, never
  from a watch: a tracked read returns the shown guess, a record the confirmed
  value. Run the storage write after the update, not in its recipe
  ([Updates](../state/updates.md)).

## With Effect

`readSaved` decodes stored text through a schema, and each field recovers from a
refusal with `Schema.catchDecoding`, so one bad field keeps its default and the
others restore. `$settings` stays a plain box: only the restore needs the check.

```ts
import { Realm } from "@frondruntime/sorus-effect";
import { Effect, Option, Schema } from "effect";
import { app } from "./realm.ts";
import { $settings } from "./snapshots.ts";

// A field the schema refuses decodes to no field at all, so it keeps its
// default and the other fields still restore.
const SavedSettings = Schema.fromJsonString(
  Schema.Struct({
    theme: Schema.optionalKey(
      Schema.Literals(["light", "dark"]).pipe(Schema.catchDecoding(() => Effect.succeedNone)),
    ),
    notifications: Schema.optionalKey(
      Schema.Boolean.pipe(Schema.catchDecoding(() => Effect.succeedNone)),
    ),
  }),
);

// Text that does not parse decodes to no fields, so the settings keep their defaults.
const readSaved = (text: string): typeof SavedSettings.Type =>
  Schema.decodeUnknownOption(SavedSettings)(text).pipe(Option.getOrElse(() => ({})));

// Each field the save holds, over the current settings, in one update.
const restoreSaved = (text: string): void => {
  Realm.update(app, (read, write) => {
    write($settings, { ...read($settings), ...readSaved(text) });
  });
};
```

## See also

- [Snapshots](../state/snapshots.md): `$settings`, and a shape read as plain data.
- [Stages](../state/stages.md): a visible stage, shown and confirmed values.
- [Change stream](../state/changes.md): `Realm.onUpdate` and its records.
- [Reacting](../state/reacting.md): `Realm.watch` and `Realm.untracked`.
- [Testing](./testing.md): `testRealm`, and the dispose that checks for a running watch.
