Save the live document when you need to reopen an editable diagram, including its ports, groups, metadata and collaboration history. The document stores intent, not pixels: save the model behind the mounted instance, then mount the loaded document in a fresh view. These checkpoints preserve document data, not the current camera pan and zoom.
These examples start in the project left by your JavaScript, React, Vue, Angular or Qwik quick start. Keep the starter's entry files, configuration and stylesheet imports. Add the files below and render the new component from your existing app; for Qwik, import the default component from src/PersistenceQwik.tsx into your route and render it there.
The quick starts already install the packages used below. For a project that lacks them, the following commands add the packages for each binding.
JavaScript:
bashnpm install @grafloria/element @grafloria/engine @grafloria/renderer
React:
bashnpm install @grafloria/react @grafloria/element @grafloria/engine @grafloria/renderer
Vue:
bashnpm install @grafloria/vue @grafloria/element @grafloria/engine @grafloria/renderer
Angular:
bashnpm install @grafloria/angular @grafloria/element @grafloria/engine @grafloria/renderer
Qwik:
bashnpm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer
The Qwik command follows its starter's development-dependency convention.
Save & restore
The sample renders Author → Review. Save captures the current document and the peer's op-log tail. Restore opens the checkpoint in a second editable canvas; the original canvas and any edits made after saving remain intact.
- Create the shared persistence module. Put it at
src/persistence.tsin JavaScript, React, Vue and Qwik, orsrc/app/persistence.tsin Angular. - Mount the framework component in the next step.
- Move a node, choose Save, move it again, then choose Restore in separate view. The second canvas shows the saved positions without replacing your newer work.
DiagramSerializer writes a DiagramDocumentEnvelope with a checksum. fromDocument loads that envelope once and returns a LoadedDiagramSpec that restores live models and kit wiring. A fresh DiagramEngine owns that loaded model; passing it through RenderOptions also preserves diagram-level data rather than constructing another model from projected specs.
Replica captures edits on the mounted model. Save its history() and clock with the checkpoint. On reopening, start the fresh peer at the saved clock and call adopt() with the tail: the snapshot already contains those operations' effects, so they must not be applied again. The next local edit receives a clock greater than the saved watermark.
NodeSpec, EdgeSpec and RenderSpec type the seed data. DiagramInstance supplies the live model and export method. The application checkpoint contains library-owned document and Op types, not a replacement schema for nodes or links.
tsimport { DiagramEngine, DiagramSerializer, Replica } from '@grafloria/engine';
import type { DiagramDocumentEnvelope, Op } from '@grafloria/engine';
import { fromDocument } from '@grafloria/element';
import type { LoadedDiagramSpec, RenderOptions, RenderSpec } from '@grafloria/element';
import { extractModel } from '@grafloria/renderer';
import type { Artifact, DiagramInstance, EdgeSpec, NodeSpec } from '@grafloria/renderer';
export const nodes: NodeSpec[] = [
{ id: 'author', label: 'Author', position: { x: 60, y: 90 },
size: { width: 150, height: 66 }, data: { stage: 'draft' } },
{ id: 'review', label: 'Review', position: { x: 300, y: 90 },
size: { width: 150, height: 66 } },
];
export const edges: EdgeSpec[] = [
{ id: 'review-link', source: 'author', target: 'review' },
];
export const seed: RenderSpec = { nodes, edges };
export interface Checkpoint {
document: DiagramDocumentEnvelope;
tail: Op[];
clock: number;
}
export interface ReopenedView {
spec: LoadedDiagramSpec;
options: RenderOptions;
tail: Op[];
clock: number;
}
function viewOf(spec: LoadedDiagramSpec, tail: Op[], clock: number): ReopenedView {
const engine = new DiagramEngine();
engine.setDiagram(spec.model);
return {
spec,
options: {
engine,
viewport: { ...spec.model.viewport },
zoom: spec.model.viewport.zoom,
},
tail,
clock,
};
}
export function restore(saved: Checkpoint): ReopenedView {
return viewOf(fromDocument(saved.document), saved.tail, saved.clock);
}
export function reopen(artifact: Artifact): ReopenedView {
// Presence is useful for UI hints; it is not an integrity check.
const envelope = extractModel(artifact);
if (!envelope) throw new Error('This file carries no editable model.');
// This is the only document loader in this path. It verifies the checksum.
return viewOf(fromDocument(envelope), [], 0);
}
export class Persistence {
private peer: Replica;
private api: Pick<DiagramInstance, 'getModel' | 'getEngine' | 'export'>;
constructor(
api: Pick<DiagramInstance, 'getModel' | 'getEngine' | 'export'>,
restored?: ReopenedView,
) {
this.api = api;
this.peer = new Replica(api.getModel(), {
actor: Array.from(crypto.getRandomValues(new Uint8Array(16)),
(byte) => byte.toString(16).padStart(2, '0')).join(''),
startClock: restored?.clock ?? 0,
});
if (restored) this.peer.adopt(restored.tail);
}
save(): Checkpoint {
return {
document: new DiagramSerializer().serializeEnvelope(this.api.getModel()),
tail: [...this.peer.history()],
clock: this.peer.clock,
};
}
async exportAndReopen(format: 'svg' | 'png'): Promise<ReopenedView> {
return restore(await this.exportCheckpoint(format));
}
async exportCheckpoint(format: 'svg' | 'png'): Promise<Checkpoint> {
const artifact = await this.api.export(format, {
embedModel: true,
embedModelCreatedAt: '2020-01-01T00:00:00Z',
});
const envelope = extractModel(artifact);
if (!envelope) throw new Error('This file carries no editable model.');
// An image carries the document, not the session's op-log tail.
return { document: envelope, tail: [], clock: 0 };
}
close(): void {
this.peer.dispose();
}
}
Mount the two views
Each tab supplies Save, Restore in separate view, Reopen SVG and Reopen PNG controls. The restored peer attaches to the second canvas's actual model, not to a detached copy. Closing that view unsubscribes its peer.
For persistence, mount the loaded document in a second view with its restored engine and peer; see Edit nodes from your UI for the framework components and instance callbacks.
tsimport { render } from '@grafloria/element';
import { Persistence, restore, seed } from './persistence';
import type { Checkpoint, ReopenedView } from './persistence';
const root = document.getElementById('app')!;
root.innerHTML = `
<button id="save">Save</button>
<button id="restore">Restore in separate view</button>
<button id="svg">Reopen SVG</button>
<button id="png">Reopen PNG</button>
<button id="close">Close reopened view</button>
<p id="status">Author → Review; save before restoring.</p>
<div id="original" style="height:400px"></div>
<div id="reopened" style="height:400px"></div>`;
const original = render(seed, '#original');
const session = new Persistence(original);
let saved: Checkpoint | null = null;
let preview: ReturnType<typeof render> | null = null;
let peer: Persistence | null = null;
let view: ReopenedView | null = null;
const status = document.getElementById('status')!;
function closePreview(force = false): boolean {
if (preview && !force && !window.confirm('Discard the reopened view, including any edits?')) return false;
peer?.close();
preview?.dispose();
view?.options.engine?.dispose();
peer = null;
preview = null;
view = null;
return true;
}
function show(next: ReopenedView): void {
if (!closePreview()) { next.options.engine?.dispose(); return; }
view = next;
preview = render(next.spec, '#reopened', next.options);
peer = new Persistence(preview, next);
status.textContent = 'Reopened in a separate editable view.';
}
document.getElementById('save')!.onclick = () => {
saved = session.save();
status.textContent = 'Checkpoint and collaboration tail saved in memory.';
};
document.getElementById('restore')!.onclick = () => {
if (saved) {
try { show(restore(saved)); }
catch (error) { status.textContent = String(error); console.error(error); }
}
};
for (const format of ['svg', 'png'] as const) {
document.getElementById(format)!.onclick = async () => {
try { show(await session.exportAndReopen(format)); }
catch (error) { status.textContent = String(error); console.error(error); }
};
}
document.getElementById('close')!.onclick = () => { closePreview(); };
// An application router calls this cleanup when removing this screen.
const remove = document.createElement('button');
remove.textContent = 'Close editor';
remove.onclick = () => {
if (!closePreview()) return;
session.close();
original.dispose();
root.replaceChildren();
};
root.append(remove);
tsximport { useEffect, useRef, useState } from 'react';
import { GrafloriaDiagram } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { Persistence, restore, seed } from './persistence';
import type { Checkpoint, ReopenedView } from './persistence';
function Reopened({ view }: { view: ReopenedView }) {
const peer = useRef<Persistence | null>(null);
useEffect(() => () => {
peer.current?.close();
view.options.engine?.dispose();
}, [view]);
return <div style={{ height: 400 }}>
<GrafloriaDiagram spec={view.spec} options={view.options}
onReady={(api) => {
peer.current?.close();
peer.current = new Persistence(api, view);
}} />
</div>;
}
export function PersistenceEditor() {
const session = useRef<Persistence | null>(null);
const saved = useRef<Checkpoint | null>(null);
const [view, setView] = useState<ReopenedView | null>(null);
const [generation, setGeneration] = useState(0);
const [status, setStatus] = useState('Save before restoring.');
useEffect(() => () => session.current?.close(), []);
function ready(api: DiagramInstance): void {
session.current?.close();
session.current = new Persistence(api);
}
function replace(next: ReopenedView | null): void {
if (view && !window.confirm('Discard the reopened view, including any edits?')) {
next?.options.engine?.dispose();
return;
}
setView(next);
setGeneration((value) => value + 1);
}
async function open(format: 'svg' | 'png'): Promise<void> {
try {
if (session.current) {
replace(await session.current.exportAndReopen(format));
}
} catch (error) { setStatus(String(error)); console.error(error); }
}
return <section>
<button onClick={() => {
if (session.current) saved.current = session.current.save();
setStatus('Checkpoint and tail saved in memory.');
}}>Save</button>
<button onClick={() => {
try {
if (saved.current) {
replace(restore(saved.current));
}
}
catch (error) { setStatus(String(error)); console.error(error); }
}}>Restore in separate view</button>
<button onClick={() => void open('svg')}>Reopen SVG</button>
<button onClick={() => void open('png')}>Reopen PNG</button>
<button onClick={() => replace(null)}>Close reopened view</button>
<p>{status}</p>
<div style={{ height: 400 }}><GrafloriaDiagram spec={seed} onReady={ready} /></div>
{view && <Reopened key={generation} view={view} />}
</section>;
}
vue<script setup lang="ts"> import { defineComponent, h, onBeforeUnmount, ref, shallowRef } from 'vue'; import type { PropType } from 'vue'; import { GrafloriaDiagram } from '@grafloria/vue'; import type { DiagramInstance } from '@grafloria/renderer'; import { Persistence, restore, seed } from './persistence'; import type { Checkpoint, ReopenedView } from './persistence'; const Reopened = defineComponent({ props: { view: { type: Object as PropType<ReopenedView>, required: true } }, setup(props) { let peer: Persistence | null = null; onBeforeUnmount(() => { peer?.close(); props.view.options.engine?.dispose(); }); return () => h('div', { style: 'height:400px' }, [ h(GrafloriaDiagram, { spec: props.view.spec, options: props.view.options, onReady: (api: DiagramInstance) => { peer?.close(); peer = new Persistence(api, props.view); }, }), ]); }, }); const session = shallowRef<Persistence | null>(null); const saved = shallowRef<Checkpoint | null>(null); const view = shallowRef<ReopenedView | null>(null); const generation = ref(0); const status = ref('Save before restoring.'); function replace(next: ReopenedView | null): void { if (view.value && !window.confirm('Discard the reopened view, including any edits?')) { next?.options.engine?.dispose(); return; } view.value = next; generation.value++; } function ready(api: DiagramInstance): void { session.value?.close(); session.value = new Persistence(api); } function save(): void { if (session.value) saved.value = session.value.save(); status.value = 'Checkpoint and tail saved in memory.'; } function load(): void { try { if (saved.value) { replace(restore(saved.value)); } } catch (error) { status.value = String(error); } } async function open(format: 'svg' | 'png'): Promise<void> { try { if (session.value) { replace(await session.value.exportAndReopen(format)); } } catch (error) { status.value = String(error); } } onBeforeUnmount(() => session.value?.close()); </script> <template> <button @click="save">Save</button> <button @click="load">Restore in separate view</button> <button @click="open('svg')">Reopen SVG</button> <button @click="open('png')">Reopen PNG</button> <button @click="replace(null)">Close reopened view</button> <p>{{ status }}</p> <div style="height:400px"><GrafloriaDiagram :spec="seed" @ready="ready" /></div> <Reopened v-if="view" :key="generation" :view="view" /> </template>
tsimport { Component, signal } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { DiagramEngine } from '@grafloria/engine';
import { Persistence, restore, nodes, edges } from './persistence';
import type { Checkpoint, ReopenedView } from './persistence';
@Component({
selector: 'app-persistence-editor',
imports: [DiagramCanvasComponent],
template: `
<button (click)="save()">Save</button>
<button (click)="load()">Restore in separate view</button>
<button (click)="open('svg')">Reopen SVG</button>
<button (click)="open('png')">Reopen PNG</button>
<button (click)="close()">Close reopened view</button>
<p>{{ status() }}</p>
<grafloria-diagram-canvas [engine]="original" (ready)="ready($event)"
style="display:block;height:400px" />
@for (restored of views(); track restored) {
<grafloria-diagram-canvas [engine]="restored.options.engine"
[viewport]="restored.spec.model.viewport" [zoom]="restored.spec.model.viewport.zoom"
(ready)="previewReady($event)" style="display:block;height:400px" />
}
`,
})
export class PersistenceEditorComponent implements OnDestroy {
readonly original = new DiagramEngine();
readonly views = signal<ReopenedView[]>([]);
readonly status = signal('Save before restoring.');
private session: Persistence | null = null;
private peer: Persistence | null = null;
private saved: Checkpoint | null = null;
constructor() {
this.original.createDiagram('Authoring');
}
ready(api: GrafloriaCanvasInstance): void {
api.setNodes(nodes);
api.setEdges(edges);
this.session = new Persistence(api);
}
previewReady(api: GrafloriaCanvasInstance): void {
const restored = this.views()[0];
if (restored) this.peer = new Persistence(api, restored);
}
save(): void {
if (this.session) this.saved = this.session.save();
this.status.set('Checkpoint and tail saved in memory.');
}
load(): void {
try { if (this.saved) this.show(restore(this.saved)); }
catch (error) { this.status.set(String(error)); console.error(error); }
}
async open(format: 'svg' | 'png'): Promise<void> {
try { if (this.session) this.show(await this.session.exportAndReopen(format)); }
catch (error) { this.status.set(String(error)); console.error(error); }
}
private show(restored: ReopenedView): void {
if (!this.close()) { restored.options.engine?.dispose(); return; }
this.views.set([restored]);
}
close(force = false): boolean {
if (this.views().length && !force && !window.confirm('Discard the reopened view, including any edits?')) return false;
this.peer?.close();
this.peer = null;
this.views()[0]?.options.engine?.dispose();
this.views.set([]);
return true;
}
ngOnDestroy(): void {
this.close(true);
this.session?.close();
this.original.dispose();
}
}
tsximport { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaDiagram } from '@grafloria/qwik';
import { Persistence, restore, seed } from './persistence';
import type { Checkpoint, ReopenedView } from './persistence';
const SavedView = component$<{ saved: string }>(({ saved }) => {
const view = useSignal<NoSerialize<ReopenedView>>();
const peer = useSignal<NoSerialize<Persistence>>();
const error = useSignal('');
useVisibleTask$(({ cleanup }) => {
try {
// Decode the application wrapper once; restore loads its document once.
const checkpoint = JSON.parse(saved) as Checkpoint;
view.value = noSerialize(restore(checkpoint));
}
catch (cause) { error.value = String(cause); }
cleanup(() => {
peer.value?.close();
view.value?.options.engine?.dispose();
});
});
return <div style={{ height: '400px' }}>
{error.value && <p>{error.value}</p>}
{view.value && <GrafloriaDiagram options={noSerialize(view.value.options)}
spec$={() => {
const restored = view.value;
if (!restored) throw new Error('The reopened view is not mounted.');
return restored.spec;
}} onReady$={(api) => {
if (view.value) peer.value = noSerialize(new Persistence(api, view.value));
}} />}
</div>;
});
export default component$(() => {
const session = useSignal<NoSerialize<Persistence>>();
const saved = useSignal<string | null>(null);
const preview = useSignal<string | null>(null);
const generation = useSignal(0);
const status = useSignal('Save before restoring.');
useVisibleTask$(({ cleanup }) => {
cleanup(() => session.value?.close());
});
return <section>
<button onClick$={() => {
if (session.value) saved.value = JSON.stringify(session.value.save());
status.value = 'Checkpoint and tail saved in memory.';
}}>Save</button>
<button onClick$={() => {
if (preview.value && !window.confirm('Discard the reopened view, including any edits?')) return;
preview.value = saved.value;
generation.value++;
}}>Restore in separate view</button>
{(['svg', 'png'] as const).map((format) => <button key={format} onClick$={async () => {
try {
if (!session.value) return;
const checkpoint = await session.value.exportCheckpoint(format);
if (preview.value && !window.confirm('Discard the reopened view, including any edits?')) return;
preview.value = JSON.stringify(checkpoint);
generation.value++;
} catch (error) { status.value = String(error); console.error(error); }
}}>Reopen {format.toUpperCase()}</button>)}
<button onClick$={() => {
if (preview.value && !window.confirm('Discard the reopened view, including any edits?')) return;
preview.value = null;
}}>Close reopened view</button>
<p>{status.value}</p>
<div style={{ height: '400px' }}>
<GrafloriaDiagram spec={seed} onReady$={(api) => {
session.value?.close();
session.value = noSerialize(new Persistence(api));
}} />
</div>
{preview.value && <SavedView key={generation.value} saved={preview.value} />}
</section>;
});
Opening another checkpoint or image, or closing an existing reopened view, asks before discarding that view, including its edits. Cancel keeps it mounted. The original view remains intact.
The checkpoint in these examples lives in memory. To persist the document itself, write JSON.stringify(checkpoint.document) to your storage and pass the stored string directly to fromDocument() on a later visit. Do not parse it alongside a second document loader. Store the tail and watermark together with the checkpoint when reopening a collaborative session; image exports carry the model, not that separate tail.
Try the Save & restore demo to see snapshot and Lamport-clock resumption together. For a transport-backed session, continue with Sync collaborators.
Reopen model-bearing SVG and PNG
The Reopen SVG and Reopen PNG controls export the current original view and open a separate editable canvas from its embedded model. ExportOptions uses embedModel: true to put the envelope in SVG metadata or a PNG UTF-8 iTXt chunk. The fixed embedModelCreatedAt keeps the envelope timestamp stable for repeatable exports.
Artifact accepts SVG text, a data URL, or bytes. isEditableArtifact checks for a parseable embedded model; it does not verify its checksum. extractModel returns the envelope or null, and throws when a present payload cannot be parsed. The shared reopen() passes the extracted envelope to fromDocument() for checksum verification and mounting.
If you need the engine model rather than a kit-ready spec, use importDiagram as the single loader. This Angular component exports its mounted canvas, imports the SVG with strict validation and mounts the returned model on a second canvas.
tsimport { Component, signal } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { DiagramEngine } from '@grafloria/engine';
import { importDiagram, isEditableArtifact } from '@grafloria/renderer';
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';
@Component({
selector: 'app-artifact-model',
imports: [DiagramCanvasComponent],
template: `
<p>{{ status() }}</p>
<grafloria-diagram-canvas [nodes]="nodes" [edges]="edges"
(ready)="open($event)" style="display:block;height:400px" />
@if (restored(); as engine) {
<grafloria-diagram-canvas [engine]="engine" style="display:block;height:400px" />
}
`,
})
export class ArtifactModelComponent implements OnDestroy {
readonly nodes: NodeSpec[] = [
{ id: 'a', label: 'Author', position: { x: 60, y: 90 }, size: { width: 150, height: 66 } },
{ id: 'b', label: 'Review', position: { x: 300, y: 90 }, size: { width: 150, height: 66 } },
];
readonly edges: EdgeSpec[] = [{ id: 'e', source: 'a', target: 'b' }];
readonly restored = signal<DiagramEngine | null>(null);
readonly status = signal('Exporting the original view.');
async open(api: GrafloriaCanvasInstance): Promise<void> {
try {
const plain = await api.export('svg');
if (isEditableArtifact(plain)) throw new Error('Expected a plain SVG without an embedded model.');
const svg = await api.export('svg', {
embedModel: true, embedModelCreatedAt: '2020-01-01T00:00:00Z',
});
const model = importDiagram(svg, { validate: 'strict' });
if (!model) throw new Error('No embedded model.');
const engine = new DiagramEngine();
engine.setDiagram(model);
this.restored.set(engine);
this.status.set('The second canvas is editable and comes from the SVG.');
} catch (error) { this.status.set(String(error)); console.error(error); }
}
ngOnDestroy(): void { this.restored()?.dispose(); }
}
For a file selected by the reader, pass new Uint8Array(await file.arrayBuffer()) to reopen() or importDiagram(); SVG and PNG bytes use the same extraction entry point. Neither path needs the original diagram to remain available. A plain image without a model returns null from importDiagram() rather than inventing editable objects.
See the Editable round-trip demo for SVG and PNG side by side. Use Export images and vector PDF for downloading and export appearance.
What the round trip keeps
| Data | Kept or lost |
|---|---|
| Node geometry, data, style, metadata, ports and parent/child structure | Kept in the serialized node; restored as live models. |
| Links and groups | Kept in the full document, not reconstructed from selected spec fields. |
| Whiteboard strokes and comment registers | Kept when present in the full document. |
| Model viewport | Kept in the document; the shared restored view passes it to the renderer's camera options. |
| Current camera pan and zoom | Not captured by these checkpoints. The renderer's camera is separate from model.viewport; reopening uses the stored model viewport, not the last camera position. |
| Collaboration clock and op-log tail | Kept by the application checkpoint; not included in the SVG/PNG model envelope. |
| App functions and custom painters | Not serialized. Supply your custom painter again; fromDocument() reattaches shipped kit wiring and painters. |
| Dashboard responsive policy and app callbacks | Not serialized. Reattach these runtime policies in your application. |
Options and integrity checks
DiagramLoadOptions controls structural validation. Checksum verification is independent: even a load with validation off refuses an envelope whose checksum mismatches.
| Option | Type | Default | What it does |
|---|---|---|---|
validate | 'off' | 'warn' | 'strict' | 'off' | off skips structural validation; warn validates and logs a summary and report; strict throws on integrity errors. |
embedModel | boolean | Omitted: no embedded model | Embeds the document in SVG or PNG. JPEG and WebP ignore it. |
embedModelCreatedAt | string | Current timestamp | Overrides the embedded envelope's creation timestamp. |
validateSerializedDiagram returns a report with ok, errors and warnings without constructing models. It checks structure, not the envelope checksum. DIAGRAM_ENVELOPE_FORMAT is 'grafloria-diagram'; INCREMENTAL_FORMAT is 'grafloria-incremental', the discriminator for incremental patches rather than full documents.
IncrementalCapture watches a live model. hasChanges() checks the current window; commit() returns a patch or null and continues capturing; stop() unsubscribes permanently. Use patches for incremental persistence, not as a substitute for the full checkpoint and collaboration watermark.
The samples catch load failures and display the error instead of replacing the original canvas. A changed embedded document fails checksum verification; malformed embedded JSON throws during extraction; strict structural loading throws when the report contains errors.
Copy node and edge geometry with Angular snapshots
For an in-memory copy of node and edge geometry, call snapshot() on the mounted DiagramCanvasComponent, then pass the result to a second canvas's loadSnapshot(). This path reconciles nodes and edges; use the envelope-based restoration above for full document structure and integrity checks.
Add this component alongside the shared persistence module. Move Author, choose Save geometry, then choose Open geometry copy. The second canvas shows the saved positions while the original remains editable. Opening a copy asks before replacing anything in the second canvas.
tsimport { Component, signal, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { SerializedDiagram } from '@grafloria/engine';
import { nodes, edges } from './persistence';
@Component({
selector: 'app-geometry-snapshot',
imports: [DiagramCanvasComponent],
template: `
<button (click)="save()" [disabled]="!originalReady()">Save geometry</button>
<button (click)="open()" [disabled]="!saved() || !copyReady()">Open geometry copy</button>
<grafloria-diagram-canvas #original [nodes]="nodes" [edges]="edges"
(ready)="originalReady.set(true)" style="display:block;height:400px" />
<grafloria-diagram-canvas #copy [nodes]="nodes" [edges]="edges" (ready)="copyReady.set(true)"
style="display:block;height:400px" />
`,
})
export class GeometrySnapshotComponent {
readonly original = viewChild.required<DiagramCanvasComponent>('original');
readonly copy = viewChild.required<DiagramCanvasComponent>('copy');
readonly nodes = nodes;
readonly edges = edges;
readonly originalReady = signal(false);
readonly copyReady = signal(false);
readonly saved = signal<SerializedDiagram | null>(null);
save(): void {
this.saved.set(this.original().snapshot());
}
open(): void {
const snapshot = this.saved();
if (!snapshot || !window.confirm('Replace the geometry copy, including any edits?')) return;
this.copy().loadSnapshot(snapshot);
}
}
Engine and single-node snapshots
Use engine serialization when you also need the engine's mode. serialize() returns the flat document with mode, or null without a diagram; saveToJSON() returns its formatted JSON string or null. deserialize() and loadFromJSON() replace the engine's diagram and restore the saved mode. They accept structural validation options. For new durable persistence, prefer the checksum-bearing envelope above.
This Angular example retains the mode from serialize() and saves the document with serializeEnvelope(). It passes the combined object to deserialize() once; the loader recognizes the envelope, verifies its checksum and restores the mode before the second engine mounts. It also uses NodeModel's serialize() and fromJSON() to reopen one node in a third canvas. A node snapshot is not a full document: links and groups belong to the diagram.
tsimport { Component, signal } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { DiagramEngine, NodeModel } from '@grafloria/engine';
import type { NodeSpec } from '@grafloria/renderer';
@Component({
selector: 'app-engine-snapshots',
imports: [DiagramCanvasComponent],
template: `
<grafloria-diagram-canvas [nodes]="nodes" (ready)="copy($event)"
style="display:block;height:300px" />
@if (documentCopy(); as engine) {
<grafloria-diagram-canvas [engine]="engine" style="display:block;height:300px" />
}
@if (nodeCopy(); as engine) {
<grafloria-diagram-canvas [engine]="engine" style="display:block;height:300px" />
}
`,
})
export class EngineSnapshotsComponent implements OnDestroy {
readonly nodes: NodeSpec[] = [
{ id: 'author', label: 'Author', position: { x: 60, y: 90 }, size: { width: 150, height: 66 } },
];
readonly documentCopy = signal<DiagramEngine | null>(null);
readonly nodeCopy = signal<DiagramEngine | null>(null);
copy(api: GrafloriaCanvasInstance): void {
const data = api.getEngine().serialize();
if (!data) return;
const documentEngine = new DiagramEngine();
const envelope = api.getEngine().serializer.serializeEnvelope(api.getModel());
// Retain the flat fields required by the engine's input type and its mode.
// The loader recognizes the envelope and verifies its protected document.
documentEngine.deserialize(Object.assign(data, envelope), { validate: 'strict' });
this.documentCopy.set(documentEngine);
const node = api.getModel().getNode('author');
if (!node) return;
const nodeEngine = new DiagramEngine();
nodeEngine.createDiagram('Single-node snapshot');
nodeEngine.addNode(NodeModel.fromJSON(node.serialize()));
this.nodeCopy.set(nodeEngine);
}
ngOnDestroy(): void {
this.documentCopy()?.dispose();
this.nodeCopy()?.dispose();
}
}
Pitfalls and related tasks
Controlled node specs are a projection, not a lossless save format. Saving only selected spec fields drops ports, metadata and other structure. Serialize the live model and restore through fromDocument() with render() or a document-host component when the document is your source of truth. Do not use a nodes-only projection to reopen a kit-built document.
- Models and the document explains the persisted data and live models.
- Instance and lifecycle covers owning and tearing down mounted instances.
- Commands and history covers undoable edits; loading a document is a different intent from editing it.
Was this page helpful?