Going further

Writing a store

Keep content anywhere by implementing four methods. This site's session storage store is the worked example.

A store is four methods over raw documents, by collection name and slug. createContent does everything else: validation, unique slugs, renames, references. So a store stays small.

interface ContentStore {
  list(collection: string): Promise<unknown[]>;
  get(collection: string, slug: string): Promise<unknown>;
  put(collection: string, doc: Doc): Promise<void>;
  remove(collection: string, slug: string): Promise<void>;
}
  • list returns every stored document of the collection, each with slug set, or [].
  • get returns the document under slug, or undefined. If it exists but can't be read, throw.
  • put stores the document under doc.slug, replacing what's there.
  • remove deletes the document under slug, and does nothing if there's none.

Return raw data: createContent normalizes and validates it. Keep every key of the document you were given: an orderable collection's manual order is the position key of each document, so a store that keeps whole documents supports it with no extra work.

Example: session storage

This site lets anyone edit it without a server. Its admin saves through createContent in the browser, over a store kept in the tab's session storage. Here's that store, slightly shortened.

It stores only changes on top of the published content, under one key: a saved document, or null for a deleted one. Clearing that key returns the reader to the published site, which is what the Reset button does.

import { isValidSlug, type ContentStore, type Doc } from '@mortar-kit/core';

type Changes = Record<string, Record<string, Doc | null>>;

export function createSessionStorageStore(options: {
  baseline: Record<string, Doc[]>;
  key?: string;
}): ContentStore & { hasChanges(): boolean; clear(): void } {
  const key = options.key ?? 'mortar:changes';
  const baseline = new Map(
    Object.entries(options.baseline).map(([c, docs]) => [c, new Map(docs.map((d) => [d.slug, d]))]),
  );
  const read = (): Changes => JSON.parse(sessionStorage.getItem(key) ?? '{}');
  const change = (collection: string, slug: string, doc: Doc | null) => {
    const changes = read();
    (changes[collection] ??= {})[slug] = doc;
    sessionStorage.setItem(key, JSON.stringify(changes));
  };

  return {
    async list(collection) {
      const merged = new Map(baseline.get(collection));
      for (const [slug, doc] of Object.entries(read()[collection] ?? {})) {
        if (doc === null) merged.delete(slug);
        else merged.set(slug, doc);
      }
      return [...merged].map(([slug, doc]) => ({ ...doc, slug }));
    },
    async get(collection, slug) {
      const changes = read()[collection] ?? {};
      const doc = slug in changes ? changes[slug] : baseline.get(collection)?.get(slug);
      return doc ? { ...doc, slug } : undefined;
    },
    async put(collection, doc) {
      if (!isValidSlug(doc.slug)) throw new Error(`Invalid slug "${doc.slug}"`);
      change(collection, doc.slug, doc);
    },
    async remove(collection, slug) {
      change(collection, slug, null);
    },
    hasChanges: () => Object.values(read()).some((folder) => Object.keys(folder).length > 0),
    clear: () => sessionStorage.removeItem(key),
  };
}

The full version is in docs/src/content/session-store.ts. It also copies documents in and out, survives storage that's missing or unreadable, and drops the change when you delete a document you created in the same tab.

Session storage belongs to one tab. Edits last while the tab is open and survive reloads. Same-origin iframes in the tab share it, which is how the admin's preview sees your saves. No one else ever sees them.

Using it

const store = createSessionStorageStore({ baseline });
const content = createContent({ store, collections, bricks });

// The admin saves into this tab:
<Admin content={content} ... />

// Reset to the published site:
store.clear();

On this site, the published documents (baseline) are JSON files bundled into the app, and the server renders them. Once a page has loaded in the browser, it reads again through the session storage store, so your edits replace the published content. See About this site.