Use text import to bring an existing diagram onto the canvas, or to put an editable Mermaid pane beside it. The examples below draw a Plan → Build → Ship flow, accept supported Mermaid and draw.io files, and regenerate the document sidecar from the live model.
Start in the project left by your JavaScript, React, Vue, Angular, or Qwik quick start. Keep its entry files, configuration and stylesheet imports. Add the shared module below, then mount the component for your framework from the existing app. The quick starts already install the packages these samples import; no additional installation is needed.
1. Load supported Mermaid into the live canvas
Use loadText() on the mounted DiagramInstance. It imports and reconciles into that instance, preserving the live model's identity and its listeners. Empty text, unsupported diagram types and reported parse errors throw before changing the canvas. Do not reduce the imported model to a hand-written array of node fields: that projection is not a document loader.
The supported headers are flowchart / graph, erDiagram, classDiagram, stateDiagram / stateDiagram-v2, architecture-beta, and block-beta. See the Mermaid viewer for examples of flowchart shapes, styles, subgraphs and the graph-family notations. For type-specific editing after import, use database diagrams or UML diagrams.
importDiagramText is the headless import entry point. Its result contains diagram, source, bodyEdited, and optional sidecarMerged, sidecarInvalid, unsupported and errors. Unlike the canvas loader, it returns best-effort parsed content and diagnostics. The sample's Inspect text button uses it without changing the canvas; Apply text uses the instance loader once.
exportDiagramText exports a model; exportText() exports the instance's current model. Both add a document sidecar by default. stripGrafloriaSidecar removes the document and body-hash lines, not other Grafloria directives. The sample displays that readable body in the editor and keeps the complete exported text in a separate pane.
The two sidecar markers are GRAFLORIA_DOC_PREFIX and GRAFLORIA_HASH_PREFIX. Keep both when applying an edited body onto an exported document. The hash detects body edits; it is not a checksum protecting the sidecar JSON. Malformed sidecar JSON falls back to the text path and reports sidecarInvalid.
Keep the edit base in an integrity-checked envelope with DiagramSerializer. The sample calls serializeEnvelope() whenever it captures a base, then unwrapDiagramDocument verifies that envelope before its document becomes the draft's sidecar. A checksum mismatch throws before the canvas loader runs. The editor accepts body edits, not replacement sidecar JSON; the complete-text pane is read-only. For durable document restoration, including comments and the viewing session, use save and restore documents.
Add this browser-only module at src/text-editor.ts (Angular: src/app/text-editor.ts). Its host contains the editor controls; its canvas is the already-mounted instance. It never mounts a diagram itself.
tsimport {
BidirectionalSync, DSL, exportDiagramText, importDiagramText, importDrawio,
stripGrafloriaSidecar, GRAFLORIA_DOC_PREFIX, GRAFLORIA_HASH_PREFIX,
DiagramSerializer, unwrapDiagramDocument, Lexer, Parser, ASTTransformer, DSLGenerator,
} from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';
export function attachTextEditor(
canvas: Pick<DiagramInstance, 'getModel' | 'exportText' | 'loadText'>,
host: HTMLElement,
): () => void {
host.innerHTML = '';
const editor = document.createElement('textarea');
editor.setAttribute('aria-label', 'Mermaid body');
editor.style.cssText = 'display:block;width:100%;height:150px;box-sizing:border-box';
const output = document.createElement('textarea');
output.readOnly = true;
output.setAttribute('aria-label', 'Complete diagram text');
output.style.cssText = 'display:block;width:100%;height:90px;box-sizing:border-box';
const status = document.createElement('p');
status.setAttribute('role', 'status');
const file = document.createElement('input');
file.type = 'file';
file.accept = '.drawio,.xml';
file.setAttribute('aria-label', 'draw.io file');
const pages = document.createElement('select');
pages.setAttribute('aria-label', 'draw.io page');
pages.hidden = true;
const actions = document.createElement('div');
host.append(editor, actions, file, pages, status, output);
let disposed = false;
let applying = false;
let queued = false;
let sync: BidirectionalSync | undefined;
let stopSync: (() => void) | undefined;
let textTimer: ReturnType<typeof setTimeout> | undefined;
let textPending = false;
let pageTexts: string[] = [];
let pageWarnings: string[][] = [];
let baseDocument = '';
let baseBody = '';
let canvasChanged = false;
const serializer = new DiagramSerializer();
let baseEnvelope = serializer.serializeEnvelope(canvas.getModel());
const stopLive = () => {
clearTimeout(textTimer);
textPending = false;
stopSync?.();
sync?.dispose();
stopSync = undefined;
sync = undefined;
};
const refresh = () => {
if (disposed || applying) return;
const text = canvas.exportText();
output.value = text;
// Never overwrite a draft being edited in the text pane.
if (editor.value === baseBody) {
baseDocument = text;
baseEnvelope = serializer.serializeEnvelope(canvas.getModel());
baseBody = stripGrafloriaSidecar(text);
editor.value = baseBody;
canvasChanged = false;
}
};
const scheduleRefresh = () => {
if (!applying) canvasChanged = true;
// Cancel a queued replacement if the canvas changes before it runs.
if ((textPending || editor.value !== baseBody) && sync && !sync.getState().syncing) {
stopLive();
status.textContent = 'The canvas changed. Apply the draft to confirm replacement.';
}
if (queued || applying) return;
queued = true;
queueMicrotask(() => { queued = false; refresh(); });
};
const mayReplace = () => !canvasChanged ||
window.confirm('The canvas changed since this text was opened. Replace it with the text?');
const accept = (text: string) => {
if (!mayReplace()) return;
stopLive();
applying = true;
try {
const result = canvas.loadText(text);
baseDocument = canvas.exportText();
baseEnvelope = serializer.serializeEnvelope(canvas.getModel());
baseBody = stripGrafloriaSidecar(baseDocument);
editor.value = baseBody;
output.value = baseDocument;
canvasChanged = false;
status.textContent = result.sidecarInvalid
? 'Applied text; the document sidecar was unreadable.'
: result.sidecarMerged ? 'Applied body edits onto the sidecar document.'
: `Loaded from ${result.source}.`;
} catch (error) {
status.textContent = error instanceof Error ? error.message : String(error);
} finally {
applying = false;
}
};
const draftDocument = () => {
const { document } = unwrapDiagramDocument(baseEnvelope);
const hashLine = baseDocument.split('\n').find((line) =>
line.startsWith(GRAFLORIA_HASH_PREFIX));
return editor.value.replace(/\n*$/, '\n') +
GRAFLORIA_DOC_PREFIX + JSON.stringify(document) + '\n' + (hashLine ?? '') + '\n';
};
const button = (label: string, run: () => void) => {
const control = document.createElement('button');
control.type = 'button';
control.textContent = label;
control.addEventListener('click', run);
actions.append(control);
};
canvas.loadText('flowchart LR\n plan[Plan] --> build[Build]\n build --> ship[Ship]\n');
baseDocument = canvas.exportText();
baseEnvelope = serializer.serializeEnvelope(canvas.getModel());
baseBody = stripGrafloriaSidecar(baseDocument);
editor.value = baseBody;
output.value = baseDocument;
status.textContent = 'Plan → Build → Ship. Edit the body, then apply.';
button('Apply text', () => {
try { accept(draftDocument()); }
catch (error) { status.textContent = error instanceof Error ? error.message : String(error); }
});
button('Inspect text', () => {
try {
const result = importDiagramText(draftDocument());
status.textContent = result.unsupported ? `Unsupported: ${result.unsupported}`
: result.errors?.length ? result.errors.join('\n')
: `Source: ${result.source}; body edited: ${result.bodyEdited}; sidecar merged: ${result.sidecarMerged === true}`;
} catch (error) {
status.textContent = error instanceof Error ? error.message : String(error);
}
});
button('Export body with positions', () => {
output.value = canvas.exportText({ lossless: false, positions: true });
status.textContent = 'The output contains readable position directives, without the document sidecar.';
});
button('Build flowchart with DSL', () => {
const dsl = new DSL({ autoLayout: false, debug: true });
const model = dsl.parse('flowchart TD\n Commit[Commit] --> Build[Build]\n Build --> Test{Tests pass?}\n Test -->|yes| Deploy[Deploy]\n');
const generated = dsl.generate(model);
accept(exportDiagramText(model));
status.textContent += `\nGenerated Mermaid:\n${generated}`;
});
button('Inspect flowchart pipeline', () => {
try {
if (!/^(flowchart|graph)\b/.test(editor.value.trimStart())) {
status.textContent = 'Pipeline inspection requires a flowchart body.';
return;
}
const tokens = new Lexer(editor.value).tokenize();
const parser = new Parser();
const ast = parser.parse(tokens);
const errors = parser.getErrors();
if (errors.length > 0) {
status.textContent = errors.map((error) => error.message).join('\n');
return;
}
const model = new ASTTransformer().transform(ast);
const generated = new DSLGenerator().generate(model);
output.value = generated;
status.textContent = `AST: ${ast.diagramType}; ${ast.statements.length} statements.\nGenerated Mermaid:\n${generated}`;
} catch (error) {
status.textContent = error instanceof Error ? error.message : String(error);
}
});
button('Live flowchart sync', () => {
// Attach to the current flowchart without replacing its content.
if (canvas.getModel().getGroups().length > 0 ||
!/^(flowchart|graph)\b/.test(stripGrafloriaSidecar(canvas.exportText()).trimStart())) {
status.textContent = 'Live sync requires an ungrouped flowchart.';
return;
}
stopLive();
sync = new BidirectionalSync({ autoLayout: false, debounceMs: 0 });
sync.initialize(canvas.getModel(), editor.value);
sync.markVisualEdit();
stopSync = sync.onSync((direction, success) => {
if (!sync || disposed) return;
if (direction === 'visual-to-text' && editor.value !== baseBody) {
stopLive();
status.textContent = 'The canvas changed. Apply the draft to confirm replacement.';
return;
}
if (direction === 'text-to-visual') textPending = false;
if (success) {
baseDocument = canvas.exportText();
baseEnvelope = serializer.serializeEnvelope(canvas.getModel());
baseBody = stripGrafloriaSidecar(baseDocument);
editor.value = baseBody;
output.value = baseDocument;
canvasChanged = false;
}
sync.markVisualEdit();
status.textContent = `${direction}: ${success ? 'applied' : 'not applied'}`;
});
status.textContent = 'Live flowchart sync is active. Text changes apply after the debounce delay.';
});
editor.addEventListener('input', () => {
if (!sync) return;
clearTimeout(textTimer);
textPending = false;
const validation = new DSL({ autoLayout: false }).validate(editor.value);
if (!validation.valid) {
status.textContent = validation.errors.join('\n');
return;
}
const draft = editor.value;
textPending = true;
textTimer = setTimeout(() => {
// Check after the editor's debounce, immediately before queuing replacement.
if (!sync || !mayReplace()) { textPending = false; return; }
sync.onTextChange(draft);
}, 300);
});
file.addEventListener('change', async () => {
const selected = file.files?.[0];
if (!selected) return;
const result = await importDrawio(await selected.text());
if (disposed) return;
const importedPages = result.pages;
if (importedPages) {
pages.innerHTML = '';
pageWarnings = importedPages.map((page) => page.warnings);
pageTexts = importedPages.map((page, index) => {
const option = document.createElement('option');
option.value = String(index);
option.textContent = page.error ? `${page.name}: ${page.error}` : page.name;
option.disabled = !page.diagram;
pages.append(option);
return page.diagram ? exportDiagramText(page.diagram) : '';
});
pages.hidden = false;
} else {
pages.hidden = true;
pageTexts = [];
}
if (result.diagram) accept(exportDiagramText(result.diagram));
status.textContent += '\n' + [result.error, ...result.warnings].filter(Boolean).join('\n');
});
pages.addEventListener('change', () => {
const text = pageTexts[Number(pages.value)];
if (text) {
accept(text);
status.textContent += '\n' + (pageWarnings[Number(pages.value)] ?? []).join('\n');
}
});
const model = canvas.getModel();
const unsubscribe = [
'node:added', 'node:removed', 'node:changed', 'nodes:cleared',
'link:added', 'link:removed', 'link:changed', 'links:cleared',
'group:added', 'group:removed', 'group:changed', 'groups:cleared',
'stroke:added', 'stroke:removed', 'strokes:cleared',
].map((event) => model.on(event, scheduleRefresh));
return () => {
disposed = true;
stopLive();
unsubscribe.forEach((stop) => stop());
host.replaceChildren();
};
}
2. Mount the editor in your framework
Each tab places the same editor above a 400px canvas. The canvas owns its data: there are no controlled arrays that can overwrite a text import. Use the binding's initialization callback to attach the shared module, and release its subscriptions when the component unmounts.
Use the binding and instance setup from the node editor; here, the initialization callback attaches attachTextEditor() instead of the node inspector.
ts// src/import-editor.ts — import mountImportEditor from your existing entry.
import { render } from '@grafloria/element';
import { attachTextEditor } from './text-editor';
export function mountImportEditor(parent: HTMLElement): () => void {
const panel = document.createElement('div');
const stage = document.createElement('div');
stage.style.height = '400px';
parent.append(panel, stage);
const canvas = render({ nodes: [
{ id: 'plan', label: 'Plan', position: { x: 100, y: 100 } },
] }, stage);
const detach = attachTextEditor(canvas, panel);
return () => { detach(); canvas.dispose(); panel.remove(); stage.remove(); };
}
tsx// src/ImportEditor.tsx — render <ImportEditor /> from your existing App.
import { useEffect, useRef, useState } from 'react';
import { GrafloriaFlow } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { attachTextEditor } from './text-editor';
export function ImportEditor() {
const panel = useRef<HTMLDivElement>(null);
const [canvas, setCanvas] = useState<DiagramInstance | null>(null);
useEffect(() => {
if (canvas && panel.current) return attachTextEditor(canvas, panel.current);
}, [canvas]);
return <>
<div ref={panel} />
<div style={{ height: 400 }}><GrafloriaFlow onInit={setCanvas} /></div>
</>;
}
vue<!-- src/ImportEditor.vue — render <ImportEditor /> from your existing App. --> <script setup lang="ts"> import { onBeforeUnmount, ref } from 'vue'; import { GrafloriaFlow } from '@grafloria/vue'; import type { DiagramInstance } from '@grafloria/renderer'; import { attachTextEditor } from './text-editor'; const panel = ref<HTMLDivElement>(); let detach: (() => void) | undefined; function initialize(canvas: DiagramInstance) { if (panel.value) detach = attachTextEditor(canvas, panel.value); } onBeforeUnmount(() => detach?.()); </script> <template> <div ref="panel" /> <div style="height:400px"><GrafloriaFlow @init="initialize" /></div> </template>
ts// src/app/import-editor.ts — add ImportEditor to your existing root's imports
// and <app-import-editor /> to its template; keep the starter app configuration.
import { Component, DestroyRef, ElementRef, inject, viewChild } from '@angular/core';
import { DiagramCanvasComponent } from '@grafloria/angular';
import type { GrafloriaCanvasInstance } from '@grafloria/angular';
import { DiagramEngine } from '@grafloria/engine';
import { attachTextEditor } from './text-editor';
@Component({
selector: 'app-import-editor',
imports: [DiagramCanvasComponent],
template: `<div #panel></div><div style="height:400px">
<grafloria-diagram-canvas [engine]="engine" (ready)="initialize($event)" />
</div>`,
})
export class ImportEditor {
readonly engine = new DiagramEngine();
private readonly panel = viewChild.required<ElementRef<HTMLDivElement>>('panel');
private readonly destroy = inject(DestroyRef);
constructor() {
this.engine.createDiagram('Text editor');
this.destroy.onDestroy(() => this.engine.dispose());
}
initialize(canvas: GrafloriaCanvasInstance): void {
const detach = attachTextEditor(canvas, this.panel().nativeElement);
this.destroy.onDestroy(detach);
}
}
tsx// src/ImportEditor.tsx — render <ImportEditor /> from your existing route.
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaFlow } from '@grafloria/qwik';
import { attachTextEditor } from './text-editor';
export default component$(() => {
const panel = useSignal<HTMLDivElement>();
const detach = useSignal<NoSerialize<() => void>>();
useVisibleTask$(({ cleanup }) => { cleanup(() => detach.value?.()); });
return <>
<div ref={panel} />
<div style={{ height: '400px' }}>
<GrafloriaFlow onInit$={(canvas) => {
detach.value?.();
if (panel.value) detach.value = noSerialize(attachTextEditor(canvas, panel.value));
}} />
</div>
</>;
});
The Qwik sample replaces the node editor's inspector attachment with the text editor and omits node and edge defaults: the shared module loads the initial Mermaid flow.
You see three connected boxes and the generated Mermaid body. Change Build to Verify, then apply: the middle box changes its label. The document pane refreshes from the resulting canvas. If the canvas changes while you hold a text draft, the sample asks before replacing that newer work. Compare this interaction with the Mermaid text demo.
The Mermaid editor and its controls appear above the connected Plan, Build and Ship boxes.
3. Import a draw.io document and choose a page
Select a .drawio or XML file with the file input in the mounted sample. importDrawio accepts plain <mxGraphModel> XML and <mxfile> wrappers with compressed or uncompressed pages. It returns a promise, reports unreadable input as error, and includes named warnings for dropped or approximated constructs.
The sample converts the returned model with exportDiagramText() and passes that document through loadText() once. It does not reconstruct groups or ports from selected fields. Multi-page imports expose every page through pages; the select control switches between the already-imported page documents. A failed page is disabled without preventing other pages from importing. The top-level diagram is page one; the top-level warnings include page one's warnings and file-level warnings.
Try the authors' draw.io import demo for plain XML, its compressed equivalent, and a two-page file.
| Input feature | Kept | Lost or approximated |
|---|---|---|
| Vertex ids, labels and geometry | Ids, text labels, dimensions and world positions | HTML label markup becomes plain text; line breaks become spaces. Relative vertex geometry outside an edge produces a warning: its x/y values become literal offsets from the parent's origin, not proportional coordinates resolved against the parent's dimensions. |
| Parent containers and swimlanes | Group ids, names, frames, nested membership and parent-relative coordinates converted to world coordinates | Container fill, stroke, shape and swimlane appearance are not applied, including recognized style keys that produce no warning. Collapsed containers import expanded; multiple layers flatten onto one canvas, with warnings. |
| Edges | Label text, mapped styles, arrow counterparts, connection-side constraints and manual waypoints | Styled labels sit at the midpoint instead of their authored geometry. Thin markers use their base counterpart; circlePlus becomes a circle; mapped markers use size 10. Unresolvable endpoints skip the edge with a warning; unsupported marker tokens retain the default marker. |
| Container or fixed-point endpoints | Invisible anchor nodes keep the endpoints attached to their frames or points | These endpoints become engine anchor nodes rather than mxGraph endpoint objects. |
| Shape and style tokens | Supported counterparts, including ellipse, diamond, triangle, hexagon and cylinder | Unknown shapes become rectangles with warnings; unconsumed style keys are reported and dropped. Vertex font sizes are dropped without a warning. Rounded rectangles without explicit arc settings use a fixed 8px corner radius instead of draw.io's proportional default. |
| Wrapped object attributes | Ordinary vertices retain hyperlinks and custom attributes as drawioLink and drawioData metadata | Wrapped containers and edges do not retain these attributes. Retained vertex data does not import the draw.io interaction system. |
4. Synchronize edited text and its sidecar
For sidecar-aware editing, capture an enveloped document base and edit only the stripped export body. In the sample, Apply text verifies that base, combines its document with the edited body and original body-hash line, then calls loadText() once. Automatic preference detects the changed body and merges its structure, labels and shapes onto the sidecar document. Surviving nodes keep geometry and ports, but the parsed shape replaces the entire stored shape configuration: fill, stroke, stroke width and custom corner radius stored there can disappear even after a label edit. Deleted node ids disappear. Links match by endpoint pairs, including parallel-link counts.
Use body-only import with prefer: 'text' when class member or relationship notation edits must become authoritative; automatic sidecar merging updates surviving node labels and shapes and surviving link labels, not class attributes, methods, relationship operators or multiplicities. This choice also discards properties the body cannot express, as the table below describes.
For continuous editing of the current ungrouped flowchart, choose Live flowchart sync. It attaches without replacing the canvas; the status reads “Live flowchart sync is active.” BidirectionalSync receives the mounted model through initialize() and text edits through onTextChange(). It debounces both directions. markVisualEdit() enables its visual-change listeners; the successful sync callback sets it again after a text edit. The callback regenerates the complete export from the canvas, including a fresh sidecar and body hash.
Use the sidecar-aware apply path for documents with groups, custom ports, or other document-only content. Continuous DSL synchronization rebuilds flowchart nodes and links; it is not the document-preserving import path. Loading another text or draw.io document in the sample stops continuous synchronization first.
Choose which text source wins
ImportTextOptions controls prefer:
| Value | Effect |
|---|---|
auto | Default. An unchanged body loads the sidecar. An edited body merges onto a valid sidecar; without one it parses as text. |
sidecar | Loads a valid sidecar even when the body changed. Without a valid sidecar, falls back to text. |
text | Parses the body and ignores the sidecar, including its document-only fields. |
| Format | Kept | Lost or approximated |
|---|---|---|
| Unedited text with document sidecar | Headless import reads the serialized document. The mounted loadText() path transfers nodes, links, groups, ink, entity metadata and grammar metadata, including geometry, styles, ports and manual waypoints. | Export excludes per-viewer selected/hovered/focused state and derived routed points. The canvas loader does not transfer the saved viewport, comments or arbitrary diagram-level metadata; its current view position remains. |
Edited body with prefer: 'auto' | Body structure, node labels and parsed shapes, link labels, surviving geometry and ports | Parsed shapes replace stored shape configurations, including their paint and corner radius. Existing class attributes and methods, relationship operators and multiplicities remain from the sidecar rather than taking the body edits. New objects use parsed defaults; text deletions remove objects; surviving link matching uses endpoint pairs. The same mounted-loader limits on viewport, comments and diagram-level metadata apply. |
Body alone or prefer: 'text' | Parsed structure, labels and supported styles and Grafloria directives | Document-only properties not expressed in the body do not survive. Custom class display labels appear on the canvas but disappear from regenerated text, including the sample's refreshed editor body. The asymmetric flag shape draws as a rectangle. Class lollipop notation becomes realization notation; double-ended relationships lose one glyph. Class style, click, namespace and callback syntax is skipped. |
| Unsupported Mermaid header | Its name appears in unsupported for headless import | No canvas import: loadText() refuses it. |
Options that matter
ExportTextOptions, DSLOptions and SyncOptions apply at different boundaries. TransformOptions configures model construction; GeneratorOptions configures text generation.
| Option | Type | Default | What it does |
|---|---|---|---|
ExportTextOptions.lossless | boolean | true | Adds the document and body-hash sidecar. Set false for a body-only export. |
ExportTextOptions.positions | boolean | false | Writes readable %%grafloria:at id x,y WxH directives for node and zone geometry. |
DSLOptions.autoLayout | boolean | true | Detects a suggested layout and records its name, reasoning and confidence in metadata; it does not apply that suggestion. Text persistence import disables this detection. |
DSLOptions.debug | boolean | false | Enables DSL debug logging. |
DSLOptions.transformOptions | TransformOptions | Not supplied | Configures AST transformation, including default node size, spacing and starting position. |
SyncOptions.autoLayout | boolean | true | Passes automatic layout policy to the sync manager's DSL. |
SyncOptions.debounceMs | number | 300 | Delays text-to-visual and visual-to-text synchronization. |
SyncOptions.debug | boolean | false | Enables synchronization debug logging. |
SyncOptions.generatorOptions | GeneratorOptions | {} | Configures visual-to-text generation. |
SyncOptions.transformerOptions | TransformOptions | {} | Configures text-to-visual AST transformation. |
DSL is the parse/generate facade, not a persistence envelope: parse() returns a model, and generate() returns Mermaid-compatible text. The sample's Build flowchart with DSL button shows both on a Commit → Build → Test → Deploy flow, then loads a sidecar export of that model into the canvas. Use it when your app owns text generation; use the instance methods for document import and export.
Internally, the DSL coordinates tokenization, parsing an abstract syntax tree, transformation to a model, and generation back to text. Lexer tokenizes the input; extending the pipeline belongs in tools, layouts and transports, not in an ordinary import button.
Inspect the flowchart parsing pipeline
Choose Inspect flowchart pipeline in the mounted editor when you need to examine the AST before model construction. This diagnostic uses the individual stages rather than the facade: Parser turns the tokens into an AST, ASTTransformer constructs a model, and DSLGenerator generates Mermaid from that model. The status shows the diagram type and statement count; the read-only output shows regenerated text. Recovered parse errors appear instead of generated text. Inspection leaves the canvas and your draft unchanged; use Apply text to load the draft through the document-aware instance loader.
Pitfalls and related tasks
render()accepts diagram data, not a Mermaid string. Use the mounted instance's text loader.- Treat headless
errorsandunsupportedas diagnostics, not proof that a partial diagram is safe to apply. The instance loader rejects these before reconciliation. - Keep the complete sidecar export when you want document-preserving edits. A body-only export is an interchange format, not a substitute for a saved document.
- For controlled state ownership after import, see React state and content, Vue state and slots, or Angular state and tooling.
- For file integrity, durable saves and restoring without discarding newer edits, use save and restore documents.
For richer text-authored results, compare the AI-style diagrams demo, which uses styles and readable position directives, with Mermaid architecture and block diagrams, which expresses relationships and grids. Continue with layout to arrange imported data or image and PDF export to distribute the rendered result.
Was this page helpful?