Skip to Content
dashfoo

Persisting layouts

Save and restore a layout with the persist prop or the store's persist option, storage adapters, validation, and SSR.

A dashfoo layout is a plain serializable model. The user rearranges tabs, drags a panel to a new region, drags a splitter, and each of those changes produces a new Dashfoo value. Persisting the layout means saving that value somewhere on every change and loading it back on the next visit.

For most apps, use the persist prop: pass a localStorage key and DashfooLayout wires up the whole loop. It loads once, validates the stored payload, debounce-saves every change, and flushes on page hide and unmount. A ref exposes resetLayout() to clear the saved copy and return to the default.

import type { DashfooHandle } from "@dashfoo/react";
import { DashfooLayout } from "@dashfoo/react";
import { useRef } from "react";

const layout = useRef<DashfooHandle>(null);

<DashfooLayout
  defaultModel={defaultModel}
  factory={renderPanel}
  persist="dashfoo:my-app"
  ref={layout}
/>;

// elsewhere, e.g. a "Reset layout" button:
layout.current?.resetLayout();

persist accepts a bare key (localStorage) or a full target with a custom store and debounce:

persist={{ key: "dashfoo:my-app", storage: sessionStorage, debounceMs: 500 }}

The full target also takes mapTab, which upgrades or drops tabs from layouts an older version of your app saved. See Evolving persisted layouts.

It is part of the uncontrolled half of the props union (you pass defaultModel), so passing it with model does not compile. In controlled mode, where you pass model + onModelChange and already own the state, skip persist and save the model yourself in onModelChange.

Everything below maps to packages/react/src/store/persistence.ts and the validation pipeline in packages/core/src/model/serialize.ts. The persist prop is the persist option of useDashfooStore, so hand-built layouts get the same behaviour from the hook (see Using the store directly).

Storage adapter

The storage option is the only injection point, and its shape is the three localStorage methods persistence calls:

type StorageAdapter = {
  getItem: (key: string) => string | null;
  removeItem: (key: string) => void;
  setItem: (key: string, value: string) => void;
};

Anything matching that shape works: localStorage, sessionStorage, an in-memory map, or a custom store that batches writes to a server. The adapter is synchronous: backend synchronization belongs in controlled mode, not in an adapter that returns promises. Two adapters ship from @dashfoo/react.

localStorageAdapter (default)

The default. Each method calls window.localStorage directly and throws wherever localStorage throws. The persistence loop catches errors from any adapter, this one included:

  • Storage is only touched after mount (the restore runs in an effect, saves run on a timer, page hide or unmount), so the server render never reaches it.
  • A read that throws (private mode, blocked storage) warns [dashfoo] failed to load persisted layout and the layout keeps defaultModel.
  • A write that throws (quota exceeded, private mode) warns [dashfoo] failed to persist layout. The layout keeps working; only persistence is degraded.

A custom adapter can throw the same way; it does not need its own try/catch.

memoryStorageAdapter for SSR and tests

memoryStorageAdapter() is a factory that returns a fresh Map-backed adapter. Pass it to the persist prop's full form when you want isolation rather than the real browser store:

import { memoryStorageAdapter } from "@dashfoo/react";

// In a test, or per-request on the server, a clean store every time.
const storage = useMemo(() => memoryStorageAdapter(), []);

<DashfooLayout defaultModel={model} persist={{ key: "dashfoo:my-app", storage }} />;

Keep the adapter instance stable across renders (a module constant or a useMemo/useState initializer), or each render hands persistence a brand-new empty store and nothing persists.

Validation on load

Persistence never trusts what comes out of storage. Loading parses the raw string with JSON.parse, then hands the value to restoreModel from @dashfoo/core, the tolerant form of the untrusted-input pipeline in serialize.ts:

restoreModel(value: unknown, options?: { mapTab?: MapTab }): Dashfoo | null;

Three things happen in order:

  1. dashfooSchema.safeParse validates against the zod schema. A hand-edited, truncated, or corrupt payload fails here, warns, and restoreModel returns null. The schema pins the payload's version to 1, so a payload in any other format is rejected rather than loaded lossily.
  2. mapTab, when given, receives every saved tab (floats included) and returns the app's current version of it, or null to drop it. The selected tab stays selected when tabs before it are dropped.
  3. parseModel validates the mapped model again and runs normalize, so emptied tabsets and rows collapse, selections are clamped, and a valid-but-noncanonical payload loads as the engine would store it. It also warns (without throwing) on duplicate node ids, since duplicates corrupt React keys.

Unreadable JSON or a null from restoreModel falls back to defaultModel, and the corrupt entry is pruned with storage.removeItem(key) so it does not sit there failing on every load. A user with a broken saved layout gets the default and a clean slate, not a crash.

fromJSON and parseModel stay the strict forms: they throw instead of returning null, for callers that want the error.

Evolving persisted layouts

The pinned version has a consequence worth planning for: when a future release bumps the format, every stored payload in the old format fails validation and loads the default instead. Invalidating old payloads on a format bump is the design.

Your own app evolves faster than the format: components get renamed, widgets get removed. That is what mapTab is for. Pass it in persist and every restored tab goes through it:

persist={{
  key: "dashfoo:my-app",
  mapTab: (tab) => {
    if (tab.component === "legacy-chart") {
      return { ...tab, component: "chart" };
    }

    return tab.component in components ? tab : null;
  },
}}

Hosts that read storage outside the persist prop call restoreModel directly and pass the result as defaultModel:

import type { Dashfoo } from "@dashfoo/core";
import { restoreModel } from "@dashfoo/core";

const loadLayout = (key: string, fallback: Dashfoo): Dashfoo => {
  const raw = localStorage.getItem(key);

  if (raw === null) {
    return fallback;
  }

  try {
    return restoreModel(JSON.parse(raw), { mapTab }) ?? fallback;
  } catch {
    return fallback;
  }
};

Debounced save and flush

Persistence does not write on every change. Each change serializes the model with toJSON, stashes it as a pending write, and schedules a flush debounceMs (default 300 ms) later. A burst of changes (dragging a splitter produces many) collapses into one write.

The pending write carries the key and storage it was produced for. If the config changes while a save is queued, the flush still writes to the original target, so a config switch can never write the old model into the new one.

A change still in the debounce window when the page goes away can be lost: a reload or tab close never unmounts React, so the debounce timer dies with the page. Persistence flushes the pending write on pagehide and when the page becomes hidden (visibilitychange), as well as in a cleanup effect on unmount, so reloading right after a drag still saves the last change.

resetLayout() (on the imperative handle, and reset() on the store) is the inverse: it cancels any pending timer, drops the pending write, removes the stored key, and resets the live model to defaultModel without an undo entry.

Every other change to the document is saved: dispatched actions, undo, redo, and setModel. Only the restore after mount and reset skip the save.

Worked example: the demo overview page

The demo's overview route (apps/demo-vite/src/pages/overview.tsx) is the whole pattern in one component:

import type { DashfooHandle } from "@dashfoo/react";
import { DashfooLayout } from "@dashfoo/react";
import { useMemo, useRef } from "react";

import { OverviewPanel } from "../components/overview-panel";
import { Button, DemoStage } from "../components/demo-stage";
import { overviewModel } from "../models";

const OverviewPage = () => {
  const defaultModel = useMemo(() => overviewModel(), []);
  const layout = useRef<DashfooHandle>(null);

  return (
    <DemoStage
      actions={<Button onClick={() => layout.current?.resetLayout()}>Clear saved layout</Button>}
      description="Saved to localStorage on every change (validated on load). Rearrange it, then reload; your arrangement survives."
      title="Overview"
    >
      <DashfooLayout
        defaultModel={defaultModel}
        factory={OverviewPanel}
        persist="dashfoo:demo:overview"
        ref={layout}
      />
    </DemoStage>
  );
};

Points worth copying:

  • defaultModel is wrapped in useMemo so the model identity is stable across renders (the persist prop loads from storage once on mount).
  • persist="…" passes a bare key, so it uses localStorageAdapter. Rearrange the layout, reload, and the arrangement is restored from localStorage.
  • "Clear saved layout" calls ref.current.resetLayout(), which clears the saved copy and resets the live model to defaultModel without a remount.

SSR safety

Persistence does not crash during a server render because it never reads storage while rendering: the server and the first client render both show defaultModel and agree. The browser then loads the saved model after mount, applies it without an undo entry, and does not save the seed over the restored data. Read, write, and remove failures from any adapter, the default included, warn without taking down the layout.

If you want each request to start from an isolated store (no shared module state between requests), pass a per-request memoryStorageAdapter() and hydrate it from your own request-scoped source. For the common case, client-side persistence to localStorage, the default needs no extra wiring.

Using the store directly

A hand-built layout passes the same option to useDashfooStore and gets the whole loop: the seed renders first, the saved layout is restored once after mount without an undo entry, a save, or an onModelChange call, every edit is debounce-saved, and reset() clears the saved copy.

import { Layout, useDashfooStore } from "@dashfoo/react";

const HandBuilt = () => {
  const store = useDashfooStore({ defaultModel, persist: "dashfoo:my-app" });

  return (
    <>
      <button onClick={store.reset} type="button">
        Reset layout
      </button>
      <Layout.Root dispatch={store.dispatch} model={store.model} renderers={{ tab: renderPanel }}>
        <Layout.DragLayer>
          <Layout.Rows node={store.model.layout} />
        </Layout.DragLayer>
      </Layout.Root>
    </>
  );
};

persist only applies while the store is uncontrolled; with model it warns once and does nothing. Changing a mounted persistence key warns; remount with a React key to load another arrangement.

See also