Persistence
Save JSON, choose storage and understand versioning and restoration.
Core supplies content access; your application chooses storage. Start by saving the current document in the browser, then add restoration and version checks.
Save current content
editor.getJSON() returns nodes, attributes and formatting. Browser storage accepts strings:
const snapshot = { version: 1, content: editor.getJSON() }
localStorage.setItem('my-document', JSON.stringify(snapshot))
version identifies your backup format for future migrations. localStorage belongs to this browser, without cross-device synchronization or image bytes.
Validate before restoring
Read and parse the backup, check its version, then validate content with the matching Schema. Create defaults only when no save exists. Preserve damaged or unsupported files for recovery.
These helpers show explicit save and read operations. recipes/save.ts handles storage and basic version checks; recipes/types.ts defines the envelope. Complete products also validate nodes and attributes against Schema; see files.
import type { Editor, JSONContent } from "@quirekit/core";
import type { DocumentSnapshot } from "./types";
/**
* Saves explicitly; storage failure propagates so callers cannot report false success.
* @param editor - The current document authority.
* @param storage - Host-selected browser or test storage.
* @param key - Document-specific storage key.
*/
export function saveDocument(editor: Pick<Editor, "getJSON">, storage: Pick<Storage, "setItem">, key: string): void {
const snapshot: DocumentSnapshot = { version: 1, content: editor.getJSON() };
storage.setItem(key, JSON.stringify(snapshot));
}
/**
* Reads the versioned envelope; the editor schema remains responsible for content admission.
* @param storage - The same host storage used for saving.
* @param key - Document-specific storage key.
* @returns Saved canonical JSON, or null when this document has not been saved.
*/
export function readDocument(storage: Pick<Storage, "getItem">, key: string): JSONContent | null {
const source = storage.getItem(key);
if (source === null) return null;
const value: unknown = JSON.parse(source);
if (!value || typeof value !== "object" || !("version" in value) || value.version !== 1 || !("content" in value)) {
throw new Error("Unsupported document snapshot version");
}
const content = value.content;
if (!content || typeof content !== "object" || !("type" in content) || content.type !== "doc") {
throw new Error("Invalid document snapshot");
}
return content as JSONContent;
}
Report success after writing
Storage can fail: show an error and retry. Clear unsaved state only after a successful write. During network saves users may continue editing, so an older completion must not clear a newer draft's unsaved state.
Autosave can observe content changes and coalesce requests, while still handling versions, failures and conflicts. Downloading JSON alone does not implement restoration or server synchronization.