# Serialization and export

> Save and load diagrams as JSON documents, export SVG and PNG images, and keep a backend in sync with incremental change events.

A diagram's state is its nodes, edges and viewport. `toJSON()` and `fromJSON()` move that state in and out as a small, versioned JSON document; `toSVG()` and `toPNG()` turn the drawing into images.

## JSON documents

```ts
const document = diagram.toJSON();
localStorage.setItem('draft:fulfilment', JSON.stringify(document));

const saved = localStorage.getItem('draft:fulfilment');
if (saved) diagram.fromJSON(saved);
```

`toJSON()` returns a `DiagramDocument`:

```json
{
  "format": "birchui-diagram",
  "version": 1,
  "nodes": [
    { "id": "request", "x": 40, "y": 16, "type": "ellipse", "label": "Purchase request" },
    { "id": "manager", "x": 264, "y": 0, "label": "Manager approval" }
  ],
  "edges": [{ "id": "request-manager", "source": { "node": "request" }, "target": { "node": "manager" } }],
  "viewport": { "x": 175, "y": 152, "zoom": 1 }
}
```

The nodes and edges are copies in exactly the shape described in [Nodes and edges](https://docs.birchui.com/diagram/nodes-and-edges.md), including your `data`, `style`, `ports` and `parentId`. Keep `data` JSON-serializable (no functions, class instances or `Date` objects) so documents round-trip.

`fromJSON(document)` accepts the object or its JSON string. It is forgiving with data from older or hand-edited files:

- A string that is not valid JSON, or a value that is not an object, logs a warning and leaves the current diagram untouched.
- A document from a newer version logs a warning and is read as version 1.
- Invalid entries are dropped with a warning: nodes without an id, duplicate ids, edges to missing nodes.
- The saved `viewport` is restored when present.

> **Warning**
>
> `fromJSON` replaces the whole diagram and **clears the undo history**, like `setNodes`, `setEdges` and `update({ nodes, edges })`. It emits `historyChange` but not `nodesChange` or `edgesChange`.

## SVG export

`toSVG(options?)` returns a standalone SVG document as a string, sized to the content:

```ts
function downloadSvg() {
  const svg = diagram.toSVG({ padding: 32 });
  const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml;charset=utf-8' }));
  const link = document.createElement('a');
  link.href = url;
  link.download = 'order-fulfilment.svg';
  link.click();
  URL.revokeObjectURL(url);
}
```

| Option | Default | Description |
| --- | --- | --- |
| `padding` | `24` | Space around the content, in diagram units. |
| `background` | `true` | Fill the background with the theme's color. `false` gives a transparent image. |
| `theme` | the diagram's theme | `'light'` or `'dark'` colors. With `theme: 'auto'` on the diagram, the user's current color scheme is used. |
| `includeHtml` | `true` | Include HTML node templates as `foreignObject`. `false` draws those nodes as their shape and label. |
| `nodes` | all | Export only these node ids, and the edges between them. |

The export contains every visible node, not only the part on screen. Children of collapsed groups are left out, like on screen. Templates are called with `isExport: true`; see [Templates and export](https://docs.birchui.com/diagram/node-templates.md#templates-and-export).

Export one swimlane on its own:

```ts
const financeIds = diagram
  .getNodes()
  .filter((node) => node.id === 'lane-finance' || node.parentId === 'lane-finance')
  .map((node) => node.id);
const financeSvg = diagram.toSVG({ nodes: financeIds, background: false });
```

## PNG export

`toPNG(options?)` resolves with a PNG `Blob`. It takes the SVG options plus `scale`, which defaults to the screen's `devicePixelRatio` for sharp images on high-density displays:

```ts
const png = await diagram.toPNG({ scale: 2, padding: 32 });
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]);
```

PNG export never includes HTML templates, because drawing `foreignObject` onto a canvas would taint it and make it unreadable; HTML nodes are drawn as their shape and label instead. The promise rejects when the browser has no canvas 2D support (for example in a server environment) or when the diagram has been destroyed.

To produce images on a server, export SVG in the browser and send it, or store the JSON document and render it with a headless browser.

## Saving to a backend

There are two good ways to persist edits. Both start from the change events.

### Save the whole document

The simplest approach: after each change, save `toJSON()`, debounced so a burst of edits becomes one request.

```ts
let saveTimer: ReturnType<typeof setTimeout> | undefined;

function scheduleSave() {
  clearTimeout(saveTimer);
  saveTimer = setTimeout(async () => {
    const response = await fetch(`/api/workflows/${workflowId}/diagram`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(diagram.toJSON()),
    });
    statusLine.textContent = response.ok ? 'All changes saved' : 'Changes could not be saved. Retrying in 30 seconds.';
    if (!response.ok) setTimeout(scheduleSave, 30_000);
  }, 800);
}

diagram.on('nodesChange', scheduleSave);
diagram.on('edgesChange', scheduleSave);
```

### Save incremental changes

For collaborative tools or large diagrams, send only what changed. `nodesChange` and `edgesChange` describe each change with the item before and after:

| Field | Description |
| --- | --- |
| `changes[].type` | `'add'`, `'remove'`, `'move'`, `'resize'` or `'update'` (edges have no `'move'` or `'resize'`). |
| `changes[].id` | The node or edge id. |
| `changes[].before`, `changes[].after` | The item before and after; `before` is missing for adds and `after` for removals. |
| `source` | `'user'`, `'api'`, `'history'` (undo or redo) or `'layout'`. |

```ts
diagram.on('nodesChange', ({ changes, source }) => {
  if (source === 'api') return;
  for (const change of changes) {
    if (change.type === 'remove') void api.delete(`/nodes/${change.id}`);
    else void api.put(`/nodes/${change.id}`, change.after);
  }
});

diagram.on('edgesChange', ({ changes, source }) => {
  if (source === 'api') return;
  for (const change of changes) {
    if (change.type === 'remove') void api.delete(`/edges/${change.id}`);
    else void api.put(`/edges/${change.id}`, change.after);
  }
});
```

Skipping `source: 'api'` avoids echoing back changes your own code applied, for example updates that arrived from other users and were applied with `updateNode`. Undo and redo arrive as ordinary changes with `source: 'history'`, so they are saved like any other edit.

### Loading and framework state

Load a saved diagram once with `fromJSON` (or the `nodes` and `edges` options) and let the diagram own the model while the user edits. Do not feed every change back into the `nodes` and `edges` props of a framework component: each new array reloads the document and clears the undo history. Keep your copy up to date from the change events or `toJSON()` instead, and pass new arrays only when you open a different diagram.

## Next steps

- [Performance](https://docs.birchui.com/diagram/performance.md) for large documents.
- [API and events](https://docs.birchui.com/diagram/api.md) for every payload type.
