Skip to content
D
Documentation

Models and the document

concept
5 min readUpdated

The document is the complete diagram data; its live model lets you query and change that data independently of the framework that draws it.

Beyond the specs and instance access covered in the Angular quick start, query relationships in the live DiagramModel and serialize the full document rather than projected spec arrays.

How the parts fit

mermaid
flowchart LR
  S["Node and edge specs"] --> B["Binding / instance"]
  B --> M["DiagramModel: live entities"]
  E["Engine: behavior and commands"] --> M
  M --> R["Renderer: pixels"]
  M --> D["Serializer: document envelope"]
  D --> L["Loader: restored DiagramModel"]

The model is the data container, not a second renderer. Its collections hold these shipped entities:

EntityWhat it represents
NodeModelA positioned, sized object with data, state and ports.
PortModelA connection point owned by a node. Its type is input, output or bi (bidirectional).
LinkModelA connection identified by source and target port ids.
GroupModelA named collection of member ids with its own frame and collapse state.
StrokeModelFreehand ink: points and style, not a box with ports or a participant in node layout.

All inherit DiagramEntity: identity, version, metadata, change subscriptions and serialization. Use setMetadata() rather than writing the metadata map directly when a change needs notification. getMetadata() reads a key. on() returns an unsubscribe function; its change event reports a change entry, not the entity itself.

Query and build a live model

This browser example starts from the JavaScript quick start. Keep its entry file and stylesheet wiring. Install the packages used here:

bash
npm install @grafloria/renderer @grafloria/engine

Usually you seed the instance with specs. Here you go below that input surface to inspect the model's ownership and connection relationships: construct the entities, then add them to the same model the mounted view uses. createDiagram mounts the view; it schedules painting after the mutations without a refresh call.

  1. Add this module. It creates two connected boxes inside a group and a blue ink annotation. The report shows the live queries, and both boxes start selected.
ts
import { createDiagram } from '@grafloria/renderer';
import type { DiagramInstance } from '@grafloria/renderer';
import {
  DiagramModel, GroupModel, LinkModel, NodeModel, PortModel, StrokeModel,
} from '@grafloria/engine';

export function mountModelExample(
  canvas: HTMLElement,
  report: HTMLElement,
): DiagramInstance {
  const instance = createDiagram(canvas);
  const model: DiagramModel = instance.getModel();
  const store = instance.getEngine().getStore();
  store.set('gridEnabled', false);

  const start = new NodeModel({
    id: 'start', type: 'rect', position: { x: 90, y: 110 },
    size: { width: 140, height: 70 },
  });
  const end = new NodeModel({
    id: 'end', type: 'rect', position: { x: 340, y: 110 },
    size: { width: 140, height: 70 },
  });
  start.setMetadata('label', 'Start');
  end.setMetadata('label', 'Review');
  const output = new PortModel({ id: 'start-out', type: 'output', side: 'right' });
  const input = new PortModel({ id: 'review-in', type: 'input', side: 'left' });
  start.addPort(output);
  end.addPort(input);
  model.addNode(start);
  model.addNode(end);

  const link = new LinkModel(output.id, input.id, 'orthogonal');
  model.addLink(link);
  const group = new GroupModel({ id: 'workflow', name: 'Approval' });
  model.addGroup(group);
  group.addMember(start.id, model);
  group.addMember(end.id, model);
  group.fitToContents(model);
  model.addStroke(new StrokeModel(
    [{ x: 95, y: 245 }, { x: 230, y: 255 }, { x: 475, y: 245 }],
    { color: '#2563eb', width: 4 },
    { id: 'annotation', label: 'Approval annotation' },
  ));

  // Preserve the existing feature sets, but enter the high-detail tier earlier.
  const lod = model.getLODConfig();
  model.setLODConfig({
    tiers: lod.tiers.map((tier) =>
      tier.name === 'high' ? { ...tier, minZoom: 0.8 } : tier,
    ),
  });

  const updateReport = (): void => {
    report.textContent = [
      `Nodes: ${model.getNodes().length}; links: ${model.getLinks().length}`,
      `Start label: ${String(model.getNode('start')?.getMetadata('label'))}`,
      `Links touching Start: ${model.getLinksForNode('start').length}`,
      `Link exists: ${model.getLink(link.id) !== undefined}`,
      `Output owner: ${model.getNodeByPortId(output.id)?.id}`,
      `Node at (100, 120): ${model.getNodeAtPosition(100, 120)?.id}`,
      `Nodes in world rectangle: ${model.getVisibleNodes({
        x: 0, y: 0, width: 600, height: 400,
      }).length}`,
      `Ink strokes: ${model.getStrokes().length}`,
      `Selected nodes: ${model.getSelectedNodes().length}`,
    ].join('\n');
  };
  // Read from the known model: change payloads are not NodeModel objects.
  start.on('change', updateReport);
  instance.on('selection:change', updateReport);
  model.selectNode(start);
  model.addToSelection(end);
  updateReport();
  return instance;
}

getNode() and getLink() return a live entity or undefined; the plural queries return arrays of live entities. getLinksForNode() includes either endpoint, including self-loops. getNodeByPortId() resolves ownership without parsing an id convention. getVisibleNodes() takes a rectangle in world coordinates, intersects node bounds and excludes nodes with state.visible === false. getNodeAtPosition() performs shape-aware containment in reverse node-array order; it is not a screen-coordinate query.

selectNode() replaces the node selection; addToSelection() keeps the existing selection and adds another selectable node. The report subscribes to the instance's selection event, so it follows later selection changes too. getLODConfig() reads the detail policy; setLODConfig() replaces it. Each tier declares its name, inclusive minimum zoom and feature set. See large-diagram navigation for using that policy in a viewer.

  1. Add the document module below, then add these lines to the quick start's entry file. This creates sized containers without replacing its existing imports or app wiring.
ts
import { mountModelExample } from './model-example';
import { mountDocumentControls } from './document-controls';

const section = document.createElement('section');
const canvas = document.createElement('div');
canvas.style.cssText = 'height:400px;width:100%;position:relative';
const report = document.createElement('pre');
const controls = document.createElement('div');
const previews = document.createElement('div');
const close = document.createElement('button');
close.textContent = 'Close example';
section.append(canvas, report, controls, previews, close);
document.body.append(section);

const example = mountModelExample(canvas, report);
const stopDocuments = mountDocumentControls(example, controls, previews);
close.addEventListener('click', () => {
  stopDocuments();
  example.dispose();
  section.remove();
});

These direct mutations build data without recording undo commands. For user-facing inspectors and edits, use commands and history instead.

getStore() returns the engine's state store; the sample sets its gridEnabled flag to false through set().

The document is more than spec arrays

The full model serializes diagram identity, name, metadata, nodes, links, groups and viewport, plus ink and comments when present. Node serialization includes ports, hierarchy, geometry, state, behavior, style and data. The loader reconstructs port connection registries from the links rather than storing their counters.

FormPurposeWhat it contains
Input specsDeclare or reconcile the objects your app supplies.The fields you provide to the binding.
Projected specsReturn live changes to controlled app state.A selected subset of model fields; node projections omit ports, arbitrary metadata and selection.
Document envelopePersist the complete document.Serialized entities and diagram-level fields, schema version, writer identity, timestamp and checksum.

The document is the shared persistence form, not the view's current pixels. A projected node array is not a lossless document. For application persistence and replacement policies, continue with Save and restore documents.

Save and load

Use DiagramSerializer to write the portable DiagramDocumentEnvelope and load it once through deserialize(). serialize() also produces a legacy flat object, but serializeEnvelope() includes the integrity checksum by default. deserialize() accepts both forms and runs the document migration path.

  1. Add this module to the same project. Save document captures the current mounted model and displays its JSON. The saved object stays in memory for this example.
  2. Press Load saved preview. The loader creates a model, and a new DiagramEngine attaches that model to a separate mounted view. The original remains editable: loading never overwrites newer work.
  3. Press Check altered copy to see an integrity failure. The sample alters a copy of the saved document without updating its checksum. The error appears in the status, and no partial preview mounts.
ts
import { createDiagram } from '@grafloria/renderer';
import type { DiagramInstance } from '@grafloria/renderer';
import { DiagramEngine, DiagramSerializer } from '@grafloria/engine';
import type { DiagramDocumentEnvelope } from '@grafloria/engine';

export function mountDocumentControls(
  instance: DiagramInstance,
  controls: HTMLElement,
  previews: HTMLElement,
): () => void {
  const serializer = new DiagramSerializer();
  let saved: DiagramDocumentEnvelope | undefined;
  const cleanups: Array<() => void> = [];
  const save = document.createElement('button');
  save.textContent = 'Save document';
  const load = document.createElement('button');
  load.textContent = 'Load saved preview';
  const check = document.createElement('button');
  check.textContent = 'Check altered copy';
  const status = document.createElement('p');
  const json = document.createElement('pre');
  json.style.cssText = 'max-height:180px;overflow:auto';
  load.disabled = true;
  check.disabled = true;
  controls.append(save, load, check, status, json);

  save.addEventListener('click', () => {
    saved = serializer.serializeEnvelope(instance.getModel());
    json.textContent = JSON.stringify(saved, null, 2);
    status.textContent = 'Document captured. Load it into a separate preview.';
    load.disabled = false;
    check.disabled = false;
  });

  const openPreview = (envelope: DiagramDocumentEnvelope): void => {
    try {
      const restored = serializer.deserialize(envelope, { validate: 'strict' });
      const engine = new DiagramEngine();
      engine.setDiagram(restored);
      const panel = document.createElement('section');
      const canvas = document.createElement('div');
      canvas.style.cssText = 'height:400px;width:100%;position:relative';
      const clear = document.createElement('button');
      clear.textContent = 'Clear preview objects';
      const close = document.createElement('button');
      close.textContent = 'Close preview';
      panel.append(canvas, clear, close);
      previews.append(panel);
      const preview = createDiagram(canvas, { engine });
      clear.addEventListener('click', () => {
        if (window.confirm('Remove all nodes, links, groups and ink from this preview?')) {
          preview.getModel().clear();
        }
      });
      let closed = false;
      const cleanup = (): void => {
        if (closed) return;
        closed = true;
        preview.dispose();
        engine.dispose();
        panel.remove();
      };
      close.addEventListener('click', cleanup);
      cleanups.push(cleanup);
      status.textContent = 'Saved document loaded into a separate preview.';
    } catch (error) {
      status.textContent = error instanceof Error ? error.message : String(error);
    }
  };

  load.addEventListener('click', () => {
    if (saved) openPreview(saved);
  });
  check.addEventListener('click', () => {
    if (!saved) return;
    const altered = structuredClone(saved);
    altered.document.name = 'Changed after saving';
    openPreview(altered);
  });
  return () => {
    cleanups.forEach((cleanup) => cleanup());
    controls.replaceChildren();
  };
}

clear() removes nodes, links, groups and strokes; it is not a complete reset of every document field. Here it is an explicitly confirmed destructive operation on a separate preview.

The loader restores the saved model viewport, identity, metadata and entity collections, including comments and ink. The mounted view's pan and zoom do not survive this example's round trip: camera changes do not update the model viewport, and the preview receives only the engine, so its camera starts at x: 0, y: 0 and zoom: 1. Derived port connection counts are rebuilt. The envelope does not contain the engine's undo stack, renderer configuration or model LOD policy. A checksum mismatch throws before model construction; strict structural validation also rejects an invalid document. The checksum detects changed data; it is not an authentication mechanism.

Other state APIs

NodeModel.replaceState() replaces document state, including error, warning, status and animateStatus, while preserving the viewer's selected, hovered, highlighted and focused values; it refuses writes while the document is locked.

generateId returns a short unique id for internal references.

DEFAULT_STROKE_STYLE supplies the style when you construct a stroke without one. The example changes the color and width to distinguish its ink annotation.

ConnectionStateManager holds connection-drag state: source port, pointer position, hovered target and validation. It is not the collection of persisted links; query those on the model. Use the binding's connection surface for port gestures and connection validation.

DiagramStore offers state subscriptions, path watches, batching and state snapshots. Its snapshots are store state, not the portable diagram document shown above. Use the serializer for document persistence.

Was this page helpful?