Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): Mermaid WYSIWYG editing via mermaid-wysiwyg (#2697)

Abraham2fd24e5b97f9
diff --git a/.changeset/mermaid-wysiwyg-canvas.md b/.changeset/mermaid-wysiwyg-canvas.md
new file mode 100644
index 000000000..12ec6d0e1
--- /dev/null
+++ b/.changeset/mermaid-wysiwyg-canvas.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Mermaid diagrams are now fully visually editable. The diagram renderer is powered by mermaid-wysiwyg: click any node, edge, participant, or message to select it and get an action popover right on the diagram (change node shape, edge type, colors, message arrows, participant types, duplicate, delete, and more), double-click any label to edit its text in place, drag between nodes to connect them, and drag sequence messages to reorder. Every gesture becomes a minimal edit to the underlying Mermaid source, so the code fence (or standalone .mmd doc) stays the source of truth and collaborative editing keeps working. Diagram styling, theming, and the pan/zoom controls are unchanged.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index b8499737f..f997ecd51 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -6477,6 +6477,22 @@ Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
---
+## Inkeep first-party packages (GPL-3.0-or-later)
+
+The packages below are authored and published by Inkeep and are licensed under GPL-3.0-or-later, the same license as OpenKnowledge itself (see the repository LICENSE for the full text). They are listed for completeness; they are not third-party material.
+
+### `@inkeep/[email protected]`
+Homepage: https://github.com/inkeep/mermaid-wysiwyg#readme
+
+Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+
+### `@inkeep/[email protected]`
+Homepage: https://github.com/inkeep/mermaid-wysiwyg#readme
+
+Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+
+---
+
## Patched dependencies
The following MIT-licensed packages are patched in this repository via Bun's `patchedDependencies` mechanism. Modifications are released under the same MIT license as the upstream package. Patch files live under `patches/` in the source repo; the bundled output of every shipped artifact incorporates the patched code.
@@ -6484,6 +6500,7 @@ The following MIT-licensed packages are patched in this repository via Bun's `pa
| Package | Patch file |
| --- | --- |
| `@handlewithcare/[email protected]` | `patches/@handlewithcare%[email protected]` |
+| `@inkeep/[email protected]` | `patches/@inkeep%[email protected]` |
| `@pierre/[email protected]` | `patches/@pierre%[email protected]` |
| `@tiptap/[email protected]` | `patches/@tiptap%[email protected]` |
| `@tiptap/[email protected]` | `patches/@tiptap%[email protected]` |
diff --git a/bun.lock b/bun.lock
index 3d6a6b0a8..e5a3a5cc7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -89,6 +89,8 @@
"@fontsource-variable/jetbrains-mono": "^5.2.8",
"@hocuspocus/provider": "4.0.0-rc.1",
"@hookform/resolvers": "^5.0.0",
+ "@inkeep/mermaid-wysiwyg-core": "^0.1.0",
+ "@inkeep/mermaid-wysiwyg-dom": "^0.1.0",
"@inkeep/open-knowledge-core": "workspace:*",
"@inkeep/open-knowledge-server": "workspace:*",
"@lezer/highlight": "^1.2.3",
@@ -434,6 +436,7 @@
},
},
"patchedDependencies": {
+ "@inkeep/[email protected]": "patches/@inkeep%[email protected]",
"@pierre/[email protected]": "patches/@pierre%[email protected]",
"@tiptap/[email protected]": "patches/@tiptap%[email protected]",
@@ -826,6 +829,10 @@
"@inkeep/cxkit-types": ["@inkeep/[email protected]", "", {}, "sha512-LTbfGyy/9QofivzyGCNN3bhZsuR0Xo0I1ZY8xwPbGwwVekCsZycOzExswUBOCAP+/LqsLSO0kJ98FTQgwWpa5g=="],
+ "@inkeep/mermaid-wysiwyg-core": ["@inkeep/[email protected]", "", {}, "sha512-h0NjJzoyYBTP41+ERIOSU1U682UbY1AGF2cFICFg0SAskTaa+Ih4wv2ihVoAhavsGBGESL2TXLVX446tuJtT3Q=="],
+
+ "@inkeep/mermaid-wysiwyg-dom": ["@inkeep/[email protected]", "", { "dependencies": { "@inkeep/mermaid-wysiwyg-core": "0.1.0" } }, "sha512-/kyARspcCz/Nz12Urp8U44MXMKp7SuY8ns7odkEvXVlgDsS40DgRlpjkB0qg3XQnwlwoqo2MDT5VJjtpJUTptg=="],
+
"@inkeep/open-knowledge": ["@inkeep/open-knowledge@workspace:packages/cli"],
"@inkeep/open-knowledge-app": ["@inkeep/open-knowledge-app@workspace:packages/app"],
@@ -4434,6 +4441,8 @@
"@electron/windows-sign/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA=="],
+ "@emnapi/wasi-threads/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
"@hocuspocus/provider/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
"@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="],
@@ -4604,6 +4613,8 @@
"@tiptap/starter-kit/@tiptap/pm": ["@tiptap/[email protected]", "", { "dependencies": { "prosemirror-changeset": "^2.3.0", "prosemirror-collab": "^1.3.1", "prosemirror-commands": "^1.6.2", "prosemirror-dropcursor": "^1.8.1", "prosemirror-gapcursor": "^1.3.2", "prosemirror-history": "^1.4.1", "prosemirror-inputrules": "^1.4.0", "prosemirror-keymap": "^1.2.2", "prosemirror-markdown": "^1.13.1", "prosemirror-menu": "^1.2.4", "prosemirror-model": "^1.24.1", "prosemirror-schema-basic": "^1.2.3", "prosemirror-schema-list": "^1.5.0", "prosemirror-state": "^1.4.3", "prosemirror-tables": "^1.6.4", "prosemirror-trailing-node": "^3.0.0", "prosemirror-transform": "^1.10.2", "prosemirror-view": "^1.38.1" } }, "sha512-NjfWjZuvrqmpICT+GZWNIjtOdhPyqFKDMtQy7tsQ5rErM9L2ZQdy/+T/BKSO1JdTeBhdg9OP+0yfsqoYp2aT6A=="],
+ "@tybys/wasm-util/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
"@types/busboy/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g=="],
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g=="],
@@ -5126,6 +5137,10 @@
"@radix-ui/react-popover/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jrBWOxZITuGcnjRCM2t2U5ZPkCLxD+Ym6DjfssS5haTj2iiak/DOb64JeN6OdLfLgptb6/e2kKR+ZuTrGoZTPA=="],
+ "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
"@types/busboy/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"@types/cacheable-request/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
diff --git a/bunfig.toml b/bunfig.toml
index a351389dd..0b59a950d 100644
--- a/bunfig.toml
+++ b/bunfig.toml
@@ -5,5 +5,13 @@ strictEngines = true
# 3 days ago, to dodge freshly-published malware. Unit = SECONDS (259200 = 3 days).
# Own-org packages (@inkeep/*) are exempt. NOTE: bun's exclude key is PLURAL
# (minimumReleaseAgeExcludes); pnpm's is singular (minimumReleaseAgeExclude).
+# bun 1.3.13 does not match the scope glob for freshly published packages —
+# resolution of a <3-day-old @inkeep package fails despite the wildcard — so
+# newly introduced own-org packages also need an exact-name entry until the
+# cooldown window passes (or the glob bug is fixed upstream).
minimumReleaseAge = 259200
-minimumReleaseAgeExcludes = ["@inkeep/*"]
+minimumReleaseAgeExcludes = [
+ "@inkeep/*",
+ "@inkeep/mermaid-wysiwyg-core",
+ "@inkeep/mermaid-wysiwyg-dom",
+]
diff --git a/package.json b/package.json
index b4b36cafe..150eff125 100644
--- a/package.json
+++ b/package.json
@@ -80,6 +80,7 @@
"@tiptap/[email protected]": "patches/@tiptap%[email protected]",
- "@pierre/[email protected]": "patches/@pierre%[email protected]"
+ "@pierre/[email protected]": "patches/@pierre%[email protected]",
+ "@inkeep/[email protected]": "patches/@inkeep%[email protected]"
}
}
diff --git a/packages/app/package.json b/packages/app/package.json
index 129d78c30..716e88523 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -52,7 +52,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3.17 MB",
+ "limit": "3.2 MB",
"gzip": true,
"running": false
},
@@ -96,6 +96,8 @@
"@lezer/markdown": "^1.6.3",
"@lingui/core": "^6.0.1",
"@lingui/react": "^6.0.1",
+ "@inkeep/mermaid-wysiwyg-core": "^0.1.0",
+ "@inkeep/mermaid-wysiwyg-dom": "^0.1.0",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.204.0",
"@opentelemetry/instrumentation": "^0.204.0",
diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsx
index fb5158ac2..2633c422d 100644
--- a/packages/app/src/components/MermaidDocEditor.tsx
+++ b/packages/app/src/components/MermaidDocEditor.tsx
@@ -158,7 +158,6 @@ export function MermaidDocEditor({
const editBinding: MermaidSourceBinding = {
canEdit: true,
- getChart: () => ytext.toString(),
commitChart: (next) => replaceYText(ytext, next, MERMAID_DIAGRAM_EDIT_ORIGIN),
};
diff --git a/packages/app/src/editor/components/Mermaid.dom.test.tsx b/packages/app/src/editor/components/Mermaid.dom.test.tsx
index 9ff41df10..1d714c46a 100644
--- a/packages/app/src/editor/components/Mermaid.dom.test.tsx
+++ b/packages/app/src/editor/components/Mermaid.dom.test.tsx
@@ -79,7 +79,7 @@ mock.module('@panzoom/panzoom', () => ({
default: createPanzoom,
}));
-const { MermaidView, flashLinkedLabels, collectLinkedLabelTargets } = await import('./Mermaid');
+const { MermaidView } = await import('./Mermaid');
const { TooltipProvider } = await import('@/components/ui/tooltip');
function renderMermaidView(chart: string) {
@@ -295,7 +295,6 @@ describe('MermaidView editBinding (standalone .mmd path)', () => {
chart="graph TD; A-->B;"
editBinding={{
canEdit: true,
- getChart: () => 'graph TD; A-->B;',
commitChart: (next) => {
committed = next;
},
@@ -309,63 +308,3 @@ describe('MermaidView editBinding (standalone .mmd path)', () => {
expect(committed).toBeNull();
});
});
-
-describe('flashLinkedLabels', () => {
- test('flashes every occurrence when a label appears 2+ times (linked)', () => {
- const c = document.createElement('div');
- c.innerHTML =
- '<svg><text class="actor">Test123</text></svg>' +
- '<svg><text class="actor">Test123</text></svg>' +
- '<span class="nodeLabel">Untouched</span>';
- expect(flashLinkedLabels(c, 'Test123')).toBe(2);
- expect(c.querySelectorAll('.mermaid-label-flash').length).toBe(2);
- // Non-matching label is left alone.
- expect(c.querySelector('.nodeLabel')?.classList.contains('mermaid-label-flash')).toBe(false);
- });
-
- test('stays quiet for a lone occurrence (no related text to signal)', () => {
- const c = document.createElement('div');
- c.innerHTML = '<span class="nodeLabel">Solo</span><span class="nodeLabel">Other</span>';
- expect(flashLinkedLabels(c, 'Solo')).toBe(0);
- expect(c.querySelector('.mermaid-label-flash')).toBeNull();
- });
-
- test('matches trimmed text and ignores blank values', () => {
- const c = document.createElement('div');
- c.innerHTML = '<text class="messageText"> Ping </text><text class="messageText">Ping</text>';
- expect(flashLinkedLabels(c, 'Ping')).toBe(2);
- const blank = document.createElement('div');
- blank.innerHTML = '<text class="actor"> </text><text class="actor"> </text>';
- expect(flashLinkedLabels(blank, ' ')).toBe(0);
- });
-});
-
-describe('collectLinkedLabelTargets (live-preview matching)', () => {
- test('returns the other occurrences of the token, excluding the edited one', () => {
- const c = document.createElement('div');
- c.innerHTML =
- '<text class="actor" id="top">Alice</text>' +
- '<text class="actor" id="bottom">Alice</text>' +
- '<text class="messageText">Alice waves</text>'; // different text: not a match
- const edited = c.querySelector('#top') as Element;
- const targets = collectLinkedLabelTargets(c, 'Alice', [edited]);
- expect(targets.length).toBe(1);
- expect((targets[0] as Element).id).toBe('bottom');
- });
-
- test('excludes nested/ancestor elements of an excluded node (either direction)', () => {
- const c = document.createElement('div');
- // The edited node's own text nests a matching span; excluding the outer
- // must also drop the inner (and vice versa) so we never preview onto the
- // element being typed into.
- c.innerHTML = '<span class="nodeLabel"><span class="nodeLabel">Foo</span></span>';
- const outer = c.querySelector('.nodeLabel') as Element;
- expect(collectLinkedLabelTargets(c, 'Foo', [outer])).toEqual([]);
- });
-
- test('empty needle matches nothing', () => {
- const c = document.createElement('div');
- c.innerHTML = '<text class="actor"> </text><text class="actor"> </text>';
- expect(collectLinkedLabelTargets(c, ' ')).toEqual([]);
- });
-});
diff --git a/packages/app/src/editor/components/Mermaid.test.tsx b/packages/app/src/editor/components/Mermaid.test.tsx
index b521294f8..284f1e189 100644
--- a/packages/app/src/editor/components/Mermaid.test.tsx
+++ b/packages/app/src/editor/components/Mermaid.test.tsx
@@ -3,10 +3,12 @@
*
* Same testing-library-free convention as Math.test.tsx: `renderToString`
* from `react-dom/server` is the substrate. Mermaid renders via `useEffect`
- * + an async lazy import + `mermaid.render()` call, so under
+ * + an async lazy import + the mermaid-wysiwyg canvas view, so under
* `renderToString` the component lands in its initial placeholder state
* (the effect fires only on real mount). Live SVG output is exercised via
- * the Playwright visual-regression suite.
+ * the Playwright visual-regression suite; canvas behavior (selection,
+ * popovers, in-place edits) is owned by the `mermaid-wysiwyg` package's
+ * own test suite.
*/
import { describe, expect, mock, test } from 'bun:test';
@@ -20,21 +22,7 @@ mock.module('@lingui/react/macro', () => ({
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-const {
- extractEdgeInfo,
- extractSourceNodeId,
- findEdgeLabelInSource,
- findFlowchartBareIdInSource,
- findLabelInSource,
- findSequenceBlockConditionInSource,
- findSequenceMessageInSource,
- findSequenceNoteInSource,
- MermaidView,
- resolveLabelCaretTarget,
- rewriteSequenceParticipant,
- spliceInsertBareIdLabel,
- spliceNewLabel,
-} = await import('./Mermaid.tsx');
+const { MermaidView } = await import('./Mermaid.tsx');
describe('MermaidView — placeholder branch', () => {
test('empty chart renders the placeholder shell with real height', () => {
@@ -60,546 +48,13 @@ describe('MermaidView — placeholder branch', () => {
});
describe('MermaidView — pre-render mount state', () => {
- test('non-empty chart starts in idle/rendering state under renderToString', () => {
+ test('non-empty chart starts in the rendering state under renderToString', () => {
// useEffect doesn't run under renderToString, so the component sits in
- // its initial state — `status: 'idle'` — which renders the same shell
- // as the empty placeholder branch except `chart.trim()` is non-empty.
- // We're asserting this for stability: SSR-style render must NOT crash
- // on mermaid mount and must produce visible markup.
+ // its initial state — `status: 'rendering'`. We're asserting this for
+ // stability: SSR-style render must NOT crash on mermaid mount and must
+ // produce visible markup.
const html = renderToString(<MermaidView chart="graph TD; A-->B;" />);
expect(html).toContain('data-component-type="mermaid"');
- });
-});
-
-describe('extractSourceNodeId', () => {
- test('parses `flowchart-<id>-<counter>` shape', () => {
- expect(extractSourceNodeId('mermaid-_r_cu_-flowchart-A-0')).toBe('A');
- expect(extractSourceNodeId('mermaid-_r_cu_-flowchart-Z-1')).toBe('Z');
- });
-
- test('preserves internal hyphens in the source id', () => {
- // Mermaid ids may include hyphens; the trailing `-<digits>` is always
- // the counter, so a greedy match over everything before the counter
- // hands back the whole id.
- expect(extractSourceNodeId('mermaid-scope-flowchart-A-B-3')).toBe('A-B');
- });
-
- test('returns null when the element id is not a flowchart node', () => {
- expect(extractSourceNodeId('mermaid-_r_cu_-actor0')).toBeNull();
- expect(extractSourceNodeId('random-svg-id')).toBeNull();
- });
-});
-
-describe('findLabelInSource', () => {
- const chart = [
- 'graph TD',
- ' A[Mobile app]-->Z',
- ' B[Web app]-->Z',
- ' Z(GraphQL API)-->E[REST API]',
- ' E-.->F{{Cache}}',
- ' F-->G((End))',
- ].join('\n');
-
- test('locates a `[Label]` shape', () => {
- const m = findLabelInSource(chart, 'A', 'Mobile app');
- if (!m) throw new Error('expected a match');
- expect(m.open).toBe('[');
- expect(m.close).toBe(']');
- expect(m.wasQuoted).toBe(false);
- expect(chart.slice(m.start, m.end)).toBe('Mobile app');
- });
-
- test('locates a `(Label)` shape', () => {
- const m = findLabelInSource(chart, 'Z', 'GraphQL API');
- expect(m?.open).toBe('(');
- expect(m?.close).toBe(')');
- });
-
- test('locates a `{{Label}}` shape before `{Label}` (open-length wins)', () => {
- const m = findLabelInSource(chart, 'F', 'Cache');
- expect(m?.open).toBe('{{');
- expect(m?.close).toBe('}}');
- });
-
- test('locates a `((Label))` shape before `(Label)` (open-length wins)', () => {
- const m = findLabelInSource(chart, 'G', 'End');
- expect(m?.open).toBe('((');
- expect(m?.close).toBe('))');
- });
-
- test('word-boundary check rejects a suffix-match on longer node ids', () => {
- // Looking up `B` should NOT match inside `AB[Web app]` — the preceding
- // `A` is a word char, which invalidates the boundary.
- const noBoundary = 'graph TD\n AB[Web app]-->Z\n';
- expect(findLabelInSource(noBoundary, 'B', 'Web app')).toBeNull();
- });
-
- test('quoted label form matches when source uses `"..."`', () => {
- const quoted = 'graph TD\n Z["API [gateway]"]-->E\n';
- const m = findLabelInSource(quoted, 'Z', 'API [gateway]');
- if (!m) throw new Error('expected a match');
- expect(m.wasQuoted).toBe(true);
- expect(quoted.slice(m.start, m.end)).toBe('"API [gateway]"');
- });
-
- test('returns null when no matching shape+label is found', () => {
- expect(findLabelInSource(chart, 'A', 'Not the label')).toBeNull();
- expect(findLabelInSource(chart, 'Missing', 'Mobile app')).toBeNull();
- });
-});
-
-describe('spliceNewLabel', () => {
- function locate(source: string, id: string, label: string) {
- const m = findLabelInSource(source, id, label);
- if (!m) throw new Error(`expected to find ${id}[${label}] in source`);
- return m;
- }
-
- test('replaces an unquoted label with an unquoted label', () => {
- const source = 'graph TD\n A[Mobile app]-->Z\n';
- const match = locate(source, 'A', 'Mobile app');
- expect(spliceNewLabel(source, match, 'iOS app')).toContain('A[iOS app]');
- });
-
- test('adds quotes when the new label contains mermaid-syntactic chars', () => {
- // `[` inside the new label would break unquoted shape parsing, so we
- // wrap in `"..."` even when the source form was unquoted.
- const source = 'graph TD\n Z[GraphQL API]-->E\n';
- const match = locate(source, 'Z', 'GraphQL API');
- const next = spliceNewLabel(source, match, 'API [gateway]');
- expect(next).toContain('Z["API [gateway]"]');
- });
-
- test('preserves quotes when source already used the quoted form', () => {
- const source = 'graph TD\n Z["Original"]-->E\n';
- const match = locate(source, 'Z', 'Original');
- // Even a plain replacement stays quoted — author explicitly quoted the
- // original, don't strip that decision.
- expect(spliceNewLabel(source, match, 'Plain')).toContain('Z["Plain"]');
- });
-
- test('encodes double quotes as `#quot;` entity refs inside a quoted label', () => {
- const source = 'graph TD\n Z[Plain]-->E\n';
- const match = locate(source, 'Z', 'Plain');
- expect(spliceNewLabel(source, match, 'She said "hi"')).toContain(
- 'Z["She said #quot;hi#quot;"]',
- );
- });
-
- test('quoted edge label round-trip preserves quoting through splice', () => {
- // `findEdgeLabelInSource` sets `open: ''` for edge labels, so the
- // `match.open !== ''` gate in `spliceNewLabel` skips auto-quoting.
- // But `wasQuoted: true` on the match must still cause the splice
- // to keep the surrounding quotes — the author explicitly opted in.
- const source = 'flowchart LR\n A -->|"multi word"| B\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'multi word');
- if (!m) throw new Error('expected a match');
- expect(m.wasQuoted).toBe(true);
- const out = spliceNewLabel(source, m, 'different phrase');
- expect(out).toContain('A -->|"different phrase"| B');
- });
-});
-
-describe('extractEdgeInfo', () => {
- test('parses `L_<from>_<to>_<counter>` shape', () => {
- expect(extractEdgeInfo('L_A_B_0')).toEqual({ from: 'A', to: 'B', index: 0 });
- expect(extractEdgeInfo('L_start_end_2')).toEqual({ from: 'start', to: 'end', index: 2 });
- });
-
- test('returns null for malformed ids', () => {
- expect(extractEdgeInfo('L_A_B')).toBeNull();
- expect(extractEdgeInfo('flowchart-A-0')).toBeNull();
- });
-});
-
-describe('findEdgeLabelInSource', () => {
- test('locates a pipe-form edge label (`A -->|Yes| B`)', () => {
- const source = 'flowchart LR\n A -->|Yes| B\n B -->|No| C\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'Yes');
- if (!m) throw new Error('expected a match');
- expect(source.slice(m.start, m.end)).toBe('Yes');
- expect(m.wasQuoted).toBe(false);
- expect(spliceNewLabel(source, m, 'Definitely')).toContain('A -->|Definitely| B');
- });
-
- test('locates an inline-form edge label (`A -- Yes --> B`)', () => {
- const source = 'flowchart LR\n A -- Yes --> B\n B -- No --> C\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'Yes');
- if (!m) throw new Error('expected a match');
- expect(source.slice(m.start, m.end)).toBe('Yes');
- expect(spliceNewLabel(source, m, 'OK')).toContain('A -- OK --> B');
- });
-
- test('locates a quoted pipe-form label', () => {
- const source = 'flowchart LR\n A -->|"multi word"| B\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'multi word');
- if (!m) throw new Error('expected a match');
- expect(m.wasQuoted).toBe(true);
- expect(source.slice(m.start, m.end)).toBe('"multi word"');
- });
-
- test('index tie-breaks when the same label appears on parallel edges', () => {
- // Two `A -->|dup| B` edges. Index 0 finds the first, index 1 finds
- // the second (mermaid's `L_A_B_<counter>` numbers each parallel
- // edge; when clicking the label we forward that counter as `index`).
- const source = ['flowchart LR', ' A -->|dup| B', ' A -->|dup| B'].join('\n');
- const m0 = findEdgeLabelInSource(source, 'A', 'B', 0, 'dup');
- const m1 = findEdgeLabelInSource(source, 'A', 'B', 1, 'dup');
- if (!m0 || !m1) throw new Error('expected both matches');
- expect(m0.start).toBeLessThan(m1.start);
- expect(source.slice(m0.start, m0.end)).toBe('dup');
- expect(source.slice(m1.start, m1.end)).toBe('dup');
- });
-
- test('returns null when no matching edge label exists', () => {
- const source = 'flowchart LR\n A --> B\n';
- expect(findEdgeLabelInSource(source, 'A', 'B', 0, 'Yes')).toBeNull();
- expect(findEdgeLabelInSource(source, 'A', 'Z', 0, 'Yes')).toBeNull();
- });
-
- test('label offset is exact even when the label text matches the from-id', () => {
- // Regression: `m[0].indexOf(label)` used to return 0 (the `A`
- // fromId) instead of the label's real position, corrupting the
- // splice range. `d` flag + `m.indices` avoids the search entirely.
- const source = 'flowchart LR\n A -->|A| B\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'A');
- if (!m) throw new Error('expected a match');
- expect(source.slice(m.start, m.end)).toBe('A');
- // Splicing must land inside the pipes, not at the fromId.
- expect(spliceNewLabel(source, m, 'Renamed')).toContain('A -->|Renamed| B');
- });
-
- test('locates label in thick-arrow variant `==>`', () => {
- const source = 'flowchart LR\n A -- Yes ==> B\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'Yes');
- if (!m) throw new Error('expected a match');
- expect(source.slice(m.start, m.end)).toBe('Yes');
- });
-
- test('locates label in dotted-arrow variant `-.->`', () => {
- const source = 'flowchart LR\n A -- Yes -.-> B\n';
- const m = findEdgeLabelInSource(source, 'A', 'B', 0, 'Yes');
- if (!m) throw new Error('expected a match');
- expect(source.slice(m.start, m.end)).toBe('Yes');
- });
-
- test('parallel edges with mixed quoting map by source order, not pattern order', () => {
- // Regression: the earlier walk-per-pattern accumulator picked
- // quoted matches first regardless of position, so `index=0` grabbed
- // the QUOTED edge on line 3 even though mermaid emits `L_A_B_0` for
- // the UNQUOTED one on line 2 (source order).
- const source = ['flowchart LR', ' A -->|Yes| B', ' A -->|"Yes"| B'].join('\n');
- const m0 = findEdgeLabelInSource(source, 'A', 'B', 0, 'Yes');
- const m1 = findEdgeLabelInSource(source, 'A', 'B', 1, 'Yes');
- if (!m0 || !m1) throw new Error('expected both matches');
- expect(m0.wasQuoted).toBe(false);
- expect(m1.wasQuoted).toBe(true);
- expect(m0.start).toBeLessThan(m1.start);
- });
-});
-
-describe('findSequenceMessageInSource', () => {
- const chart = [
- 'sequenceDiagram',
- ' Alice->>Bob: hello world',
- ' Bob-->>Alice: hi back',
- ' Alice->>Bob: hello world',
- ].join('\n');
-
- test('locates a message body after `:`', () => {
- const m = findSequenceMessageInSource(chart, 'hi back');
- if (!m) throw new Error('expected a match');
- expect(chart.slice(m.start, m.end)).toBe('hi back');
- expect(spliceNewLabel(chart, m, 'hello!')).toContain('Bob-->>Alice: hello!');
- });
-
- test('occurrence tie-breaks between duplicate messages', () => {
- const m0 = findSequenceMessageInSource(chart, 'hello world', 0);
- const m1 = findSequenceMessageInSource(chart, 'hello world', 1);
- if (!m0 || !m1) throw new Error('expected both matches');
- expect(m0.start).toBeLessThan(m1.start);
- });
-
- test('returns null for unmatched messages', () => {
- expect(findSequenceMessageInSource(chart, 'not present')).toBeNull();
- });
-
- test('splicing a message with mermaid-syntactic chars does NOT add literal quotes', () => {
- // Regression: sequence messages are free text after `:` and have
- // no quoting mechanism, so wrapping the replacement in `"..."`
- // renders visible quotes in the diagram. `spliceNewLabel` gates
- // auto-quoting on `match.open !== ''` — which is empty for
- // sequence messages — so this stays a plain replacement.
- const src = 'sequenceDiagram\n Alice->>Bob: hello\n';
- const m = findSequenceMessageInSource(src, 'hello');
- if (!m) throw new Error('expected a match');
- const out = spliceNewLabel(src, m, 'Status [OK]');
- expect(out).toContain('Alice->>Bob: Status [OK]');
- expect(out).not.toContain('"Status [OK]"');
- });
-});
-
-describe('rewriteSequenceParticipant', () => {
- test('bare `participant X` gets an `as New` alias to preserve arrow refs', () => {
- const src = ['sequenceDiagram', ' participant Author', ' Author->>Bob: hi'].join('\n');
- const out = rewriteSequenceParticipant(src, 'Author', 'Alice');
- // Simple identifier → unquoted alias (mermaid renders literal
- // quotes when they're used unnecessarily).
- expect(out).toContain('participant Author as Alice');
- // Author->>Bob preserved (renaming to Alice would break the id ref).
- expect(out).toContain('Author->>Bob: hi');
- });
-
- test('bare + display with whitespace stays unquoted (mermaid reads alias to end of line)', () => {
- const src = 'sequenceDiagram\n participant Author\n';
- const out = rewriteSequenceParticipant(src, 'Author', 'Alice Smith');
- expect(out).toContain('participant Author as Alice Smith');
- expect(out).not.toContain('"Alice Smith"');
- });
-
- test('bare + display with a mermaid-syntactic char forces quoted alias', () => {
- const src = 'sequenceDiagram\n participant Author\n';
- const out = rewriteSequenceParticipant(src, 'Author', 'Users[team]');
- // `[` is a mermaid-syntactic delimiter → quote wraps.
- expect(out).toContain('participant Author as "Users[team]"');
- });
-
- test('aliased quoted `X as "Display"` replaces in place', () => {
- const src = 'sequenceDiagram\n participant A as "Author"\n A->>Bob: hi';
- const out = rewriteSequenceParticipant(src, 'Author', 'Alice');
- expect(out).toContain('participant A as "Alice"');
- expect(out).toContain('A->>Bob: hi');
- });
-
- test('aliased unquoted `X as Display` — whitespace-only content stays unquoted (mermaid reads alias to end of line)', () => {
- const src = 'sequenceDiagram\n participant A as Author\n';
- const out = rewriteSequenceParticipant(src, 'Author', 'Two Words');
- // Whitespace is safe inside a participant alias — no wrapping quotes.
- expect(out).toContain('participant A as Two Words');
- expect(out).not.toContain('"Two Words"');
- });
-
- test('aliased unquoted → quotes only when the new display contains mermaid-syntactic chars', () => {
- const src = 'sequenceDiagram\n participant A as Author\n';
- const out = rewriteSequenceParticipant(src, 'Author', 'Users[team]');
- // `[` is a mermaid-syntactic delimiter → quote.
- expect(out).toContain('participant A as "Users[team]"');
- });
-
- test('aliased unquoted collapses back to bare when new display equals the id', () => {
- const src = 'sequenceDiagram\n participant Editor as EditorX\n';
- const out = rewriteSequenceParticipant(src, 'EditorX', 'Editor');
- // No redundant `Editor as Editor` — collapse to bare form.
- expect(out).toContain('participant Editor');
- expect(out).not.toContain('as Editor');
- });
-
- test('aliased quoted collapses back to bare when new display equals the id', () => {
- const src = 'sequenceDiagram\n participant Editor as "EditorX"\n';
- const out = rewriteSequenceParticipant(src, 'EditorX', 'Editor');
- expect(out).toContain('participant Editor');
- expect(out).not.toContain('as');
- });
-
- test('bare participant → space-in-alias stays unquoted', () => {
- const src = 'sequenceDiagram\n participant Author\n Author->>Bob: hi\n';
- const out = rewriteSequenceParticipant(src, 'Author', 'Author S');
- expect(out).toContain('participant Author as Author S');
- expect(out).not.toContain('"Author S"');
- });
-
- test('actor keyword also supported', () => {
- const src = 'sequenceDiagram\n actor Author\n Author->>Bob: hi';
- const out = rewriteSequenceParticipant(src, 'Author', 'Alice');
- expect(out).toContain('actor Author as Alice');
- });
-
- test('returns null when no participant matches', () => {
- const src = 'sequenceDiagram\n participant Author\n';
- expect(rewriteSequenceParticipant(src, 'NotThere', 'Alice')).toBeNull();
- });
-});
-
-describe('findFlowchartBareIdInSource', () => {
- // Bare-id nodes render the id itself as the visible label. Locator must
- // find the FIRST occurrence and reject anything already carrying a shape.
- test('locates the first bare id occurrence', () => {
- const src = 'flowchart LR\n Shopper --> Storefront\n';
- const hit = findFlowchartBareIdInSource(src, 'Shopper');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('Shopper');
- });
-
- test('does not match when id already has a shape', () => {
- const src = 'flowchart LR\n Shopper[Buyer] --> Storefront\n';
- expect(findFlowchartBareIdInSource(src, 'Shopper')).toBeNull();
- });
-
- test('does not steal a longer id prefix match', () => {
- const src = 'flowchart LR\n Shopper --> Storefront\n';
- expect(findFlowchartBareIdInSource(src, 'Shop')).toBeNull();
- });
-
- test('splices `[NewLabel]` after the id, preserving the id and later references', () => {
- const src = 'flowchart LR\n Shopper --> Storefront\n Shopper --> Cart\n';
- const hit = findFlowchartBareIdInSource(src, 'Shopper');
- if (!hit) throw new Error('no hit');
- const out = spliceInsertBareIdLabel(src, hit, 'Buyer');
- expect(out).toBe('flowchart LR\n Shopper[Buyer] --> Storefront\n Shopper --> Cart\n');
- });
-
- test('quotes labels that need quoting (mermaid-syntactic chars)', () => {
- const src = 'flowchart LR\n Shopper --> Storefront\n';
- const hit = findFlowchartBareIdInSource(src, 'Shopper');
- if (!hit) throw new Error('no hit');
- const out = spliceInsertBareIdLabel(src, hit, 'Buyer (v2)');
- expect(out).toContain('Shopper["Buyer (v2)"]');
- });
-});
-
-describe('findSequenceNoteInSource', () => {
- test('locates a `Note over` line body', () => {
- const src = 'sequenceDiagram\n A->>B: hi\n Note over A,B: JWT lives in cookie\n';
- const hit = findSequenceNoteInSource(src, 'JWT lives in cookie');
- if (!hit) throw new Error('no hit');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('JWT lives in cookie');
- });
-
- test('locates a `Note left of` line body', () => {
- const src = 'sequenceDiagram\n Note left of A: heads-up\n';
- const hit = findSequenceNoteInSource(src, 'heads-up');
- if (!hit) throw new Error('no hit');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('heads-up');
- });
-
- test('locates a `Note right of` line body', () => {
- const src = 'sequenceDiagram\n Note right of B: sidebar\n';
- const hit = findSequenceNoteInSource(src, 'sidebar');
- if (!hit) throw new Error('no hit');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('sidebar');
- });
-
- test('disambiguates identical bodies via occurrence', () => {
- const src = 'sequenceDiagram\n Note over A: same\n Note over B: same\n';
- const first = findSequenceNoteInSource(src, 'same', 0);
- if (!first) throw new Error('no first');
- const second = findSequenceNoteInSource(src, 'same', 1);
- if (!second) throw new Error('no second');
- expect(first.start).toBeLessThan(second.start);
- });
-
- test('returns null for a non-existent note body', () => {
- const src = 'sequenceDiagram\n Note over A: hi\n';
- expect(findSequenceNoteInSource(src, 'nope')).toBeNull();
- });
-});
-
-describe('findSequenceBlockConditionInSource', () => {
- test('locates an `alt <cond>` condition token', () => {
- const src = 'sequenceDiagram\n alt credentials valid\n A->>B: ok\n end\n';
- const hit = findSequenceBlockConditionInSource(src, 'credentials valid');
- if (!hit) throw new Error('no hit');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('credentials valid');
- });
-
- test('locates an `else <cond>` condition token', () => {
- const src = 'sequenceDiagram\n alt ok\n A->>B: hi\n else nope\n A->>B: bye\n end\n';
- const hit = findSequenceBlockConditionInSource(src, 'nope');
- if (!hit) throw new Error('no hit');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('nope');
- });
-
- test('supports opt/loop/par/critical/break as block keywords', () => {
- for (const kw of ['opt', 'loop', 'par', 'critical', 'break']) {
- const src = `sequenceDiagram\n ${kw} X\n A->>B: hi\n end\n`;
- const hit = findSequenceBlockConditionInSource(src, 'X');
- if (!hit) throw new Error('no hit');
- expect(hit).not.toBeNull();
- expect(src.slice(hit.start, hit.end)).toBe('X');
- }
- });
-
- test('returns null when no block matches', () => {
- const src = 'sequenceDiagram\n alt ok\n A->>B: hi\n end\n';
- expect(findSequenceBlockConditionInSource(src, 'nope')).toBeNull();
- });
-
- test('disambiguates duplicate condition text via occurrence', () => {
- const src =
- 'sequenceDiagram\n loop retry\n A->>B: hi\n end\n loop retry\n C->>D: bye\n end\n';
- const first = findSequenceBlockConditionInSource(src, 'retry', 0);
- const second = findSequenceBlockConditionInSource(src, 'retry', 1);
- if (!first || !second) throw new Error('expected both hits');
- expect(first.start).toBeLessThan(second.start);
- });
-});
-
-describe('spliceNewLabel round-trip via findSequenceNoteInSource', () => {
- test('located range is safe to feed straight into `spliceNewLabel`', () => {
- const src = 'sequenceDiagram\n A->>B: hi\n Note over A,B: token stored\n';
- const hit = findSequenceNoteInSource(src, 'token stored');
- if (!hit) throw new Error('expected note hit');
- const out = spliceNewLabel(src, hit, 'JWT stored in cookie');
- expect(out).toContain('Note over A,B: JWT stored in cookie');
- });
-});
-
-describe('spliceInsertBareIdLabel encoding', () => {
- test('encodes bare double-quotes in the new label as the mermaid entity ref', () => {
- const src = 'flowchart LR\n Shopper --> Storefront\n';
- const hit = findFlowchartBareIdInSource(src, 'Shopper');
- if (!hit) throw new Error('expected bare hit');
- // Contains a syntactic `"` — needs quoting; the inner `"` becomes `#quot;`
- const out = spliceInsertBareIdLabel(src, hit, 'The "Shopper" role');
- expect(out).toContain('Shopper["The #quot;Shopper#quot; role"]');
- });
-});
-
-describe('resolveLabelCaretTarget', () => {
- test('maps a mid-string click to the same index when there is no leading whitespace', () => {
- // domText === value; clicking char 3 keeps caret at 3.
- expect(resolveLabelCaretTarget('Source view', 3, undefined, 'Source view'.length)).toBe(3);
- });
-
- test('shifts left by the leading whitespace the value dropped via trim()', () => {
- // DOM text has two leading spaces the trimmed value does not: raw offset 6
- // (before "o" in " Hello") maps to value index 4.
- const dom = ' Hello';
- const value = dom.trim(); // "Hello"
- expect(resolveLabelCaretTarget(dom, 6, undefined, value.length)).toBe(4);
- });
-
- test('clamps a click on trailing whitespace to the end of the value', () => {
- const dom = 'Hi ';
- const value = dom.trim(); // "Hi"
- // Raw offset 4 sits in the trailing run; clamp to value length 2.
- expect(resolveLabelCaretTarget(dom, 4, undefined, value.length)).toBe(2);
- });
-
- test('clamps a negative mapped offset up to 0', () => {
- // Click landed in leading whitespace (offset 1 < leadingWhitespace 3).
- expect(resolveLabelCaretTarget(' abc', 1, undefined, 'abc'.length)).toBe(0);
- });
-
- test('falls back to end-of-text when no click offset resolved', () => {
- expect(resolveLabelCaretTarget('Source view', null, undefined, 'Source view'.length)).toBe(
- 'Source view'.length,
- );
- });
-
- test('falls back to end-of-text when sourceLabel diverges from the visible text', () => {
- // The `alt` case: DOM shows bracketed "[cond]" but the source form is "cond".
- // valueLength is the source form's length (4); a resolved DOM offset is unsound.
- expect(resolveLabelCaretTarget('[cond]', 3, 'cond', 'cond'.length)).toBe('cond'.length);
- });
-
- test('still maps the click when sourceLabel matches the trimmed visible text', () => {
- // sourceLabel supplied but equal to the visible text => mapping stays sound.
- expect(resolveLabelCaretTarget('cond', 2, 'cond', 'cond'.length)).toBe(2);
+ expect(html).toContain('mermaid-rendering');
});
});
diff --git a/packages/app/src/editor/components/Mermaid.tsx b/packages/app/src/editor/components/Mermaid.tsx
index 18bd71a69..f2611e7b9 100644
--- a/packages/app/src/editor/components/Mermaid.tsx
+++ b/packages/app/src/editor/components/Mermaid.tsx
@@ -1,5 +1,5 @@
/**
- * MermaidView — DIY renderer for the canonical `<Mermaid>` block descriptor.
+ * MermaidView — WYSIWYG renderer for the canonical `<Mermaid>` block descriptor.
*
* Mermaid is browser-only (no first-party SSR per upstream issue #3650),
* which fits OK's Vite + React 19 client perfectly. The library is lazy-
@@ -7,75 +7,39 @@
* for documents without diagrams; cost at first diagram is ~150 KB
* gzipped (entry ~11 KB + lazy diagram-type chunks 24-45 KB each).
*
- * `mermaid.render(id, chart)` is async and returns `{ svg }`. We
- * generate a unique id per render, await the result, and inject the SVG
- * via `dangerouslySetInnerHTML`. `securityLevel: 'strict'` (the default)
- * keeps Mermaid from emitting scripts inside the SVG; the storage layer
- * is unchanged either way (chart source is the prop value, render output
- * is rebuilt every mount).
+ * Rendering + editing are delegated to `mermaid-wysiwyg`
+ * (`@inkeep/mermaid-wysiwyg-core` + `@inkeep/mermaid-wysiwyg-dom`): the canvas view
+ * renders through our own lazy `mermaid` instance (full fidelity, same
+ * theming as before), correlates the SVG back to source entities, and
+ * overlays interaction — click-select with a per-entity action popover
+ * (shape / edge-type / color pickers, delete, …), double-click in-place
+ * label editing, drag-to-connect, sequence-message drag-reorder. Every
+ * gesture compiles to a minimal text edit against the chart source,
+ * which we commit through the same write paths the old inline editor
+ * used. There is deliberately NO external editing toolbar — all edit
+ * affordances live on the diagram itself.
*
- * On parse error: Mermaid throws a synchronous error from `parse()` and
- * an async rejection from `render()`. We render the chart source verbatim
- * inside a tagged error chrome (red border + tooltip) so authors see
- * what they typed and can fix it. Co-editor DoS via malformed mermaid is
- * not a concern — error path stays inside the React boundary.
+ * Source-of-truth flow: the `chart` prop is canonical. Canvas gestures
+ * mutate the package editor's internal code and surface through its
+ * `change` event (origin !== 'external'), which we commit outward
+ * (JSX-host `setNodeMarkup` or the standalone-doc `editBinding`). Remote
+ * CRDT edits arrive as a new `chart` prop and re-enter the package via
+ * `setCode(chart, 'external')`, which re-renders without echoing back.
*
- * Why this is a module-level Promise + `useEffect` instead of `React.lazy`
- * + `<Suspense>` (the pattern Math.tsx uses): KaTeX's `renderToString` is
- * synchronous after the module loads, so a single `lazy()` covers both
- * import resolution and render. Mermaid's `mermaid.render(id, chart)` is
- * async per call (it builds DOM scratch, runs layout, returns the SVG
- * string), so wrapping the import in `lazy()` would only cover the load
- * phase — every render still needs its own async await + cancellation
- * guard. The module-level Promise gives one cached load and the
- * `useEffect` gives per-render await + cancel-on-unmount, which matches
- * the actual two-phase shape. Don't normalize this to match Math.tsx
- * without addressing the per-render async work.
- *
- * ── Inline text editing ─────────────────────────────────────────────────
- *
- * Clicking any text in a rendered diagram — flowchart node label, edge
- * label, sequence-diagram message body, or sequence-diagram participant
- * — enters an in-place edit for just that piece of text. A plain
- * `<input>` (a `<textarea>` when mermaid wrapped the label onto
- * multiple lines, so the wrapped layout survives the swap) is portalled
- * to `document.body` (so ProseMirror never sees it) and positioned over
- * the clicked label, with the caret placed at the clicked character
- * (caret at the text end when the click can't be mapped to one)
- * instead of the whole label being selected, so it feels like
- * clicking into plain text. Enter commits, Escape reverts, clicking
- * away commits. On commit we splice the new value
- * back into the chart source and dispatch one `setNodeMarkup` with
- * `sourceDirty: true` (mirroring `Embed.tsx`'s resize-commit path).
- * Mermaid then re-renders the SVG from the updated source.
- *
- * Scope: flowchart node + edge labels, sequence message text, sequence
- * participants. Class / state / gantt / mindmap diagrams don't wire up
- * yet — clicking those falls through to the wrapper's normal
- * NodeSelection.
- *
- * Sequence participant renames PRESERVE the id: `participant Author`
- * becomes `participant Author as Alice`, so `Author->>Editor:` arrows
- * keep resolving.
- *
- * The find is exact-string against the CURRENT chart (re-read fresh
- * inside the commit handler, not closure-captured), so remote CRDT
- * edits that arrived between click and commit don't desync. If the
- * label was mermaid-quoted with entity refs (e.g. `#quot;`), the DOM
- * shows the decoded form but the source has the encoded form and no
- * match will be found — click silently no-ops in that case (rare).
- *
- * Why a portalled `<input>`/`<textarea>` and not a `contentEditable`
- * label: PM's
- * MutationObserver reacts to any DOM change inside its editor tree by
- * re-syncing to its own model, which surfaces as page jumps and focus
- * loss on the first keystroke. Mounting the input outside PM's DOM is
- * what actually stops that reaction. The position anchor is the
- * enclosing visual box (label `<p>` for flowchart labels, actor
- * `<rect>` for participants) so `text-align: center` centers the text
- * at the shape's visual center, not the tight glyph bbox.
+ * Why the canvas can host contenteditable labels inside ProseMirror's
+ * tree (the old implementation portalled inputs to `document.body`):
+ * PM's DOMObserver only reacts to selection changes while the PM view
+ * itself has focus (`hasFocusAndSelection`); the canvas moves focus to
+ * its own container / label, so PM stays out. Child-list/character
+ * mutations inside the NodeView body are ignored by TipTap's default
+ * `ignoreMutation` (they're outside the contentDOM). The remaining
+ * hazard — PM's own event handlers reacting to canvas clicks/keys — is
+ * closed by the bubble-phase stopPropagation guard on the canvas
+ * container below.
*/
+import type { MermaidWysiwygEditor } from '@inkeep/mermaid-wysiwyg-core';
+import type { MermaidCanvasView } from '@inkeep/mermaid-wysiwyg-dom';
import { Trans, useLingui } from '@lingui/react/macro';
import type { default as PanZoomNS, PanzoomObject } from '@panzoom/panzoom';
import {
@@ -89,7 +53,7 @@ import {
ZoomOut,
} from 'lucide-react';
import type { default as MermaidNS } from 'mermaid';
-import { type ComponentProps, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { type ComponentProps, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils.ts';
import { useJsxComponentHost } from './jsx-host-context.tsx';
@@ -100,16 +64,16 @@ import { useJsxComponentHost } from './jsx-host-context.tsx';
// promoter emits `{chart}` only). Re-adding either to this interface would
// create a parallel render-side surface that nothing reaches.
/**
- * Read/write binding for the chart source that backs inline WYSIWYG editing.
- * Decouples `MermaidView` from its edit host so the SAME label-splice machinery
- * serves two surfaces: a codefenced ` ```mermaid ` fence (source lives on a
- * TipTap `jsxComponent` node) and a standalone `.mmd` doc (source is a CRDT
- * `Y.Text`). `getChart` is read live at commit time (never closure-captured) so
- * a concurrent peer edit between click and commit doesn't desync.
+ * Write binding for the chart source that backs WYSIWYG editing. Decouples
+ * `MermaidView` from its edit host so the SAME canvas machinery serves two
+ * surfaces: a codefenced ` ```mermaid ` fence (source lives on a TipTap
+ * `jsxComponent` node) and a standalone `.mmd` doc (source is a CRDT
+ * `Y.Text`). Reads flow the other way — the `chart` prop is pushed into the
+ * canvas on every external change — so the binding only needs the commit
+ * direction.
*/
export interface MermaidSourceBinding {
canEdit: boolean;
- getChart: () => string;
commitChart: (next: string) => void;
}
@@ -117,7 +81,7 @@ interface MermaidProps {
chart?: string;
className?: string;
/**
- * When provided, inline editing writes back through this binding instead of
+ * When provided, WYSIWYG edits write back through this binding instead of
* the JSX-component host (the standalone `.mmd` doc path). Absent for
* codefenced fences, which derive the binding from `useJsxComponentHost()`.
*/
@@ -125,8 +89,7 @@ interface MermaidProps {
}
interface RenderState {
- status: 'idle' | 'rendering' | 'ready' | 'error';
- svg: string;
+ status: 'rendering' | 'ready' | 'error';
error: string;
}
@@ -161,6 +124,20 @@ function loadMermaid() {
return mermaidPromise;
}
+let wysiwygPromise: Promise<
+ [typeof import('@inkeep/mermaid-wysiwyg-core'), typeof import('@inkeep/mermaid-wysiwyg-dom')]
+> | null = null;
+function loadWysiwyg() {
+ wysiwygPromise ||= Promise.all([
+ import('@inkeep/mermaid-wysiwyg-core'),
+ import('@inkeep/mermaid-wysiwyg-dom'),
+ ]).catch((err) => {
+ wysiwygPromise = null;
+ throw err;
+ });
+ return wysiwygPromise;
+}
+
/**
* Read the app's active color mode from the `<html>` class list — the
* theme provider sets `.dark` / `.light` on `documentElement`; that's
@@ -249,19 +226,18 @@ const MERMAID_DARK_THEME_VARIABLES = {
} as const;
/**
- * Mermaid's global `initialize` is the only place theme flows in — the
- * `render` API doesn't take per-call config. Call this immediately
- * before every `render()` so the SVG picks up the current app mode.
- * Idempotent: re-initializing with the same options is cheap.
+ * Mermaid config for the canvas view. `MermaidCanvasView` owns the
+ * `initialize` calls (at construction and via `setMermaidConfig` on
+ * theme flips); this builder keeps the palette in one place.
*/
-function configureMermaid(m: typeof MermaidNS, colorMode: 'light' | 'dark'): void {
- m.initialize({
+function mermaidConfigFor(colorMode: 'light' | 'dark'): Record<string, unknown> {
+ return {
startOnLoad: false,
securityLevel: 'strict',
theme: colorMode === 'dark' ? 'dark' : 'default',
themeVariables: colorMode === 'dark' ? MERMAID_DARK_THEME_VARIABLES : undefined,
suppressErrorRendering: true,
- });
+ };
}
let panzoomPromise: Promise<typeof PanZoomNS> | null = null;
@@ -275,696 +251,36 @@ function loadPanzoom() {
return panzoomPromise;
}
-// ── Node-label source-splicing helpers ─────────────────────────────────
-
-// Mermaid flowchart shape delimiters, ordered by open-length DESC so
-// `((` matches before `(`, `[[` before `[`, etc. Otherwise the shorter
-// prefix wins and steals the label from the wider shape.
-const SHAPES: ReadonlyArray<{ open: string; close: string }> = [
- { open: '[[', close: ']]' },
- { open: '[(', close: ')]' },
- { open: '((', close: '))' },
- { open: '{{', close: '}}' },
- { open: '[/', close: '/]' },
- { open: '[\\', close: '\\]' },
- { open: '[/', close: '\\]' },
- { open: '[\\', close: '/]' },
- { open: '[', close: ']' },
- { open: '(', close: ')' },
- { open: '{', close: '}' },
- { open: '>', close: ']' },
-];
-
-export interface LabelMatch {
- start: number;
- end: number;
- wasQuoted: boolean;
- open: string;
- close: string;
-}
-
/**
- * Locate the `<nodeId><shape>currentLabel<shape>` span in `source`.
- * Returns the range of the label text between the shape delimiters
- * (INCLUDING surrounding quotes when the source used the quoted form),
- * or null if no unambiguous match is found.
- *
- * We search exact-string against the trimmed DOM label. If the source
- * used mermaid entity refs like `#quot;` the raw source form and the
- * DOM form diverge and this returns null — caller silently no-ops.
+ * Events that must never escape the canvas into ProseMirror while the
+ * diagram is editable. The canvas owns selection (click), label editing
+ * (dblclick + typing), entity deletion (Delete/Backspace), and its own
+ * undo (mod+Z) — any of these reaching PM would double-handle: PM would
+ * NodeSelect the block, delete the whole fence on Backspace, or run the
+ * document-level undo alongside the canvas one.
*/
-export function findLabelInSource(
- source: string,
- nodeId: string,
- currentLabel: string,
-): LabelMatch | null {
- for (const { open, close } of SHAPES) {
- // Try quoted first — quoting means author explicitly opted into
- // preserving special chars, so if both quoted and unquoted forms are
- // present, the quoted one is the authored intent.
- for (const quoted of [true, false]) {
- const inner = quoted ? `"${currentLabel}"` : currentLabel;
- const fragment = `${nodeId}${open}${inner}${close}`;
- const idx = source.indexOf(fragment);
- if (idx < 0) continue;
- // Boundary: preceding char must be non-word (arrow, whitespace,
- // pipe, edge close, or line start) so we don't match `AB[Label]`
- // when looking for id `B`.
- const prev = idx === 0 ? '' : source.charAt(idx - 1);
- if (prev && /\w/.test(prev)) continue;
- const labelStart = idx + nodeId.length + open.length;
- const labelEnd = labelStart + inner.length;
- return {
- start: labelStart,
- end: labelEnd,
- wasQuoted: quoted,
- open,
- close,
- };
- }
- }
- return null;
-}
-
-function labelNeedsQuoting(label: string): boolean {
- // Any mermaid-syntactic char in the new label → wrap in quotes so the
- // parser sees it as a literal instead of shape/arrow syntax. Newline
- // isn't allowed inside unquoted labels either.
- return /[[\](){}|;#<>&\n"]/.test(label);
-}
-
-export function spliceNewLabel(source: string, match: LabelMatch, newLabel: string): string {
- // Only surfaces with shape delimiters (`[`, `(`, `{`, ...) accept
- // quoted labels — flowchart node shapes. Sequence-diagram messages
- // and edge labels have `open === ''` because they don't get a shape:
- // sequence messages are free text after `:`, and edge labels are
- // delimiter-bounded by pipes / arrow dashes. Auto-quoting there
- // renders LITERAL `"..."` in the diagram (e.g. editing a sequence
- // message to `Status [OK]` used to produce `"Status [OK]"` with
- // visible quotes).
- const shouldQuote = match.wasQuoted || (match.open !== '' && labelNeedsQuoting(newLabel));
- // Encode quotes as mermaid's entity ref so the label stays inside its
- // own quoted region.
- const escaped = newLabel.replace(/"/g, '#quot;');
- const replacement = shouldQuote ? `"${escaped}"` : newLabel;
- return source.slice(0, match.start) + replacement + source.slice(match.end);
-}
-
-/**
- * Pull the source node id out of a mermaid-rendered `.node` element id.
- * Format: `mermaid-<renderScope>-flowchart-<sourceId>-<counter>`. The
- * `flowchart-` prefix is emitted for `graph`/`flowchart` diagrams; other
- * diagram types don't carry `.node` elements, so this scope is fine.
- */
-export function extractSourceNodeId(elementId: string): string | null {
- const m = /flowchart-(.+)-\d+$/.exec(elementId);
- return m ? m[1] : null;
-}
-
-export interface EdgeInfo {
- from: string;
- to: string;
- index: number;
-}
-
-/**
- * Pull `{from, to, index}` out of an edge-label's `data-id` attribute.
- * Format: `L_<from>_<to>_<counter>` — mermaid emits this on the inner
- * `<g class="label">` element inside a `.edgeLabel` group.
- */
-export function extractEdgeInfo(dataId: string): EdgeInfo | null {
- // Underscores may appear inside from/to (rare) — match greedily on the
- // trailing counter and split the rest by the last remaining underscore.
- const m = /^L_(.+)_(\d+)$/.exec(dataId);
- if (!m) return null;
- const body = m[1];
- const index = Number(m[2]);
- const underscore = body.lastIndexOf('_');
- if (underscore < 0) return null;
- return {
- from: body.slice(0, underscore),
- to: body.slice(underscore + 1),
- index,
- };
-}
-
-/**
- * Locate an edge-label span in `source`. Handles the two most common
- * mermaid flowchart edge-label forms:
- * 1. Pipe form: `A -->|label| B` (or `-.->`, `==>`, `~~~>`)
- * 2. Inline form: `A -- label --> B` (or `A --label--> B`)
- * Both quoted (`"..."`) and unquoted. Arrow variants: `-->`, `==>`,
- * `-.->`, `-.-`, `~~~`. Skips as many prior occurrences as `index`
- * requests so parallel edges between the same pair map to the right
- * source span.
- *
- * Returns the label text span (excluding pipes / delimiter dashes) so
- * `spliceNewLabel` can reuse the same replacement machinery as node
- * labels.
- */
-export function findEdgeLabelInSource(
- source: string,
- fromId: string,
- toId: string,
- index: number,
- currentLabel: string,
-): LabelMatch | null {
- const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const f = esc(fromId);
- const t = esc(toId);
- const l = esc(currentLabel);
- // Arrow body: dash/equal/tilde runs, optional dotted, optional label-
- // ending head. Match generously since we anchor on labels.
- const arrowHead = '(?:-->|==>|-\\.->|~~~>|<--)';
- const arrowBody = '(?:--|==|-\\.|~~~)';
- const patterns: { re: RegExp; quoted: boolean; groupIndex: number }[] = [
- // A -->|"label"| B — pipe form, quoted
- {
- re: new RegExp(`${f}\\s*${arrowBody}[->=]*\\s*\\|\\s*("${l}")\\s*\\|\\s*${t}`, 'gd'),
- quoted: true,
- groupIndex: 1,
- },
- // A -->|label| B — pipe form, unquoted
- {
- re: new RegExp(`${f}\\s*${arrowBody}[->=]*\\s*\\|\\s*(${l})\\s*\\|\\s*${t}`, 'gd'),
- quoted: false,
- groupIndex: 1,
- },
- // A -- "label" --> B — inline form, quoted
- {
- re: new RegExp(`${f}\\s*${arrowBody}\\s*("${l}")\\s*${arrowHead}\\s*${t}`, 'gd'),
- quoted: true,
- groupIndex: 1,
- },
- // A -- label --> B — inline form, unquoted
- {
- re: new RegExp(`${f}\\s*${arrowBody}\\s*(${l})\\s*${arrowHead}\\s*${t}`, 'gd'),
- quoted: false,
- groupIndex: 1,
- },
- ];
- // Gather every match across all four patterns, then sort by source
- // position so `index` maps to source order — matching mermaid's
- // `L_<from>_<to>_<counter>` numbering, which follows the arrow's
- // definition order in source. A naive per-pattern accumulator (the
- // earlier version) picked the wrong parallel edge when the source
- // mixed quoting styles: pattern-order walked all quoted matches
- // first, so `index=0` grabbed a quoted edge even when the DOM
- // `L_A_B_0` referred to the earlier unquoted one.
- //
- // The regex `d` (hasIndices) flag gives us exact capture-group
- // offsets from `m.indices[groupIndex]`, dodging a `m[0].indexOf(label)`
- // hunt that would misfire when the label text also appears earlier
- // in the match (e.g. `A -->|A| B` — fromId and label both "A").
- const matches: { start: number; end: number; wasQuoted: boolean }[] = [];
- for (const { re, quoted, groupIndex } of patterns) {
- re.lastIndex = 0;
- let m: RegExpExecArray | null = re.exec(source);
- while (m) {
- const groupRange = m.indices?.[groupIndex];
- if (groupRange) {
- matches.push({ start: groupRange[0], end: groupRange[1], wasQuoted: quoted });
- }
- m = re.exec(source);
- }
- }
- matches.sort((a, b) => a.start - b.start);
- const chosen = matches[index];
- if (!chosen) return null;
- return { start: chosen.start, end: chosen.end, wasQuoted: chosen.wasQuoted, open: '', close: '' };
-}
-
-/**
- * Locate a sequence-diagram message body in source. Sequence messages
- * live on lines like `Actor1->>Actor2: message text` (or `-->>`, `-x`,
- * `-)`, etc). The message body — everything after the `:` and one
- * required space — is what mermaid renders as `.messageText`.
- *
- * We match on the message text alone since mermaid's SVG doesn't expose
- * the actor pair on the `<text>` element. That's fine when the message
- * text is unique in the chart; when it isn't, `occurrence` picks which
- * one (0-indexed, from top of source).
- */
-export function findSequenceMessageInSource(
- source: string,
- currentMessage: string,
- occurrence = 0,
-): LabelMatch | null {
- const esc = currentMessage.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- // `:` then at least one whitespace, then the message body up to
- // end-of-line. Multiline so `$` matches line boundaries. `d` flag so
- // we can read the exact capture-group offset without hunting via
- // `indexOf` (which would misfire if the message text also appears in
- // the arrow prefix).
- const re = new RegExp(`:[ \\t]+(${esc})[ \\t]*(?=\\r?\\n|$)`, 'gmd');
- let seen = 0;
- let m: RegExpExecArray | null = re.exec(source);
- while (m) {
- if (seen === occurrence) {
- const groupRange = m.indices?.[1];
- if (!groupRange) return null;
- const [labelStart, labelEnd] = groupRange;
- return {
- start: labelStart,
- end: labelEnd,
- wasQuoted: false,
- open: '',
- close: '',
- };
- }
- seen += 1;
- m = re.exec(source);
- }
- return null;
-}
-
-/**
- * Rewrite a sequence-diagram participant's display name in source.
- *
- * Handles all three supported source forms:
- * 1. `participant Author` (bare — display doubles as id)
- * 2. `participant A as Author` (aliased, unquoted display)
- * 3. `participant A as "Author"` (aliased, quoted display)
- *
- * The `actor` keyword variant maps to the same three shapes.
- *
- * Aliased forms (2, 3) are pure replacements of the display span. Case
- * 1 is different: naively rewriting `participant Author` to
- * `participant Alice` would also break every `Author->>` arrow that
- * references the id. Instead we ADD an `as "..."` alias so the id
- * stays intact and only the display changes.
- *
- * Returns the new source, or null when no participant statement
- * matches the display name.
- */
-export function rewriteSequenceParticipant(
- source: string,
- currentDisplay: string,
- newDisplay: string,
- occurrence = 0,
-): string | null {
- const esc = currentDisplay.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const escapedNew = newDisplay.replace(/"/g, '#quot;');
-
- interface Match {
- range: [number, number];
- replacement: string;
- }
- const findMatch = (re: RegExp, mkReplacement: (m: RegExpExecArray) => string): Match | null => {
- let seen = 0;
- re.lastIndex = 0;
- let m = re.exec(source);
- while (m) {
- if (seen === occurrence) {
- return { range: [m.index, m.index + m[0].length], replacement: mkReplacement(m) };
- }
- seen += 1;
- m = re.exec(source);
- }
- return null;
- };
-
- const kw = '(?:participant|actor)';
-
- // Aliased, quoted: `participant Id as "Display"`. If the new display
- // equals the id, collapse back to bare so we don't leave a redundant
- // `X as X` in the source.
- const rQuoted = new RegExp(
- `^([ \\t]*${kw}[ \\t]+)(\\S+)([ \\t]+as[ \\t]+")${esc}(")([ \\t]*)$`,
- 'gm',
- );
- const mQuoted = findMatch(rQuoted, (m) => {
- const idToken = m[2];
- if (newDisplay === idToken) return `${m[1]}${idToken}${m[5]}`;
- return `${m[1]}${idToken}${m[3]}${escapedNew}${m[4]}${m[5]}`;
- });
- if (mQuoted)
- return source.slice(0, mQuoted.range[0]) + mQuoted.replacement + source.slice(mQuoted.range[1]);
-
- // Aliased, unquoted: `participant Id as Display`. Same collapse rule
- // as the quoted variant when the new display matches the id.
- const rUnquoted = new RegExp(
- `^([ \\t]*${kw}[ \\t]+)(\\S+)([ \\t]+as[ \\t]+)${esc}([ \\t]*)$`,
- 'gm',
- );
- const mUnquoted = findMatch(rUnquoted, (m) => {
- const idToken = m[2];
- if (newDisplay === idToken) return `${m[1]}${idToken}${m[4]}`;
- const rendered = labelNeedsQuoting(newDisplay) ? `"${escapedNew}"` : newDisplay;
- return `${m[1]}${idToken}${m[3]}${rendered}${m[4]}`;
- });
- if (mUnquoted)
- return (
- source.slice(0, mUnquoted.range[0]) + mUnquoted.replacement + source.slice(mUnquoted.range[1])
- );
-
- // Bare: `participant Display` — the display IS the id, referenced
- // elsewhere via `Display->>Other`, so preserve it and add an
- // `as "New"` alias instead of overwriting. Quoting rule unified with
- // the aliased variants: whitespace is safe in a participant alias
- // (mermaid reads the alias to end of line), so only quote when the
- // new label contains an actual mermaid-syntactic delimiter.
- const rBare = new RegExp(`^([ \\t]*${kw}[ \\t]+)${esc}([ \\t]*)$`, 'gm');
- const mBare = findMatch(rBare, (m) => {
- const rendered = labelNeedsQuoting(newDisplay) ? `"${escapedNew}"` : newDisplay;
- return `${m[1]}${currentDisplay}${m[2]} as ${rendered}`;
- });
- if (mBare)
- return source.slice(0, mBare.range[0]) + mBare.replacement + source.slice(mBare.range[1]);
-
- return null;
-}
-
-/**
- * Locate a bare-id flowchart node reference in `source`. Used when the
- * DOM label equals the node id AND `findLabelInSource` returned null —
- * that combination means the author wrote the node without a shape
- * (`Shopper --> Storefront`) so the id renders as its own label.
- *
- * Returns the range of the id token to rewrite (the id stays, the label
- * gets APPENDED as `[NewLabel]` in `spliceInsertBareIdLabel` — keeping
- * the id preserves every `Shopper -->` arrow elsewhere in the chart).
- */
-export function findFlowchartBareIdInSource(source: string, nodeId: string): LabelMatch | null {
- const esc = nodeId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- // Bare id: not preceded by a word char (so `AB` doesn't match id
- // `B`), and NOT followed by any character that starts a mermaid
- // shape or id extension. The negative lookahead rejects the shape
- // openers `[`, `(`, `{`, `<`, `>` (all valid mermaid shape starts),
- // any word char (would extend the id), and `@`/`:` (namespaced ids).
- // What CAN follow: whitespace, arrow heads (`-`, `=`, `.`, `~`,
- // `x`, `o`, `|`), semicolon, comma, or line end — none of those are
- // in the negative lookahead.
- const re = new RegExp(`(?<![\\w])${esc}(?![\\w[({<>@:])`, 'gd');
- const m = re.exec(source);
- if (!m) return null;
- const range = m.indices?.[0];
- if (!range) return null;
- return { start: range[0], end: range[1], wasQuoted: false, open: '', close: '' };
-}
-
-/**
- * Rewrite a bare-id flowchart reference to `<id>[NewLabel]`. Preserves
- * the id token verbatim; only inserts the shape+label after it, so
- * arrows referencing the id keep resolving.
- *
- * Auto-quotes `NewLabel` when it contains mermaid-syntactic chars
- * (matches `spliceNewLabel`'s policy). Encodes double-quotes as the
- * mermaid entity ref `#quot;`.
- */
-export function spliceInsertBareIdLabel(
- source: string,
- match: LabelMatch,
- newLabel: string,
-): string {
- const escaped = newLabel.replace(/"/g, '#quot;');
- const shouldQuote = labelNeedsQuoting(newLabel);
- const shape = shouldQuote ? `["${escaped}"]` : `[${newLabel}]`;
- // `match` is the id token itself; append the shape directly after it.
- return source.slice(0, match.end) + shape + source.slice(match.end);
-}
-
-/**
- * Locate a sequence-diagram `Note over|left of|right of <actors>: <text>`
- * line in `source`. Returns the range of the note body (the text after
- * the colon-space), or null if no unambiguous match is found.
- *
- * The DOM `.noteText` only exposes the body — actor participation and
- * position (`over`/`left of`/`right of`) live in the source line only,
- * so the search matches on the note body across all three note kinds
- * and disambiguates identical bodies via `occurrence`.
- */
-export function findSequenceNoteInSource(
- source: string,
- currentNote: string,
- occurrence = 0,
-): LabelMatch | null {
- const esc = currentNote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- // `Note (over|left of|right of) <actors>: <body>` — actors segment
- // stops at the first `:` (mermaid syntax; actor names can't contain
- // colons). The body captures up to end-of-line, trimmed. `d` flag
- // exposes the capture-group offset.
- const re = new RegExp(
- `^[ \\t]*Note[ \\t]+(?:over|left of|right of)[ \\t]+[^:\\n]+:[ \\t]+(${esc})[ \\t]*(?=\\r?\\n|$)`,
- 'gmd',
- );
- let seen = 0;
- let m: RegExpExecArray | null = re.exec(source);
- while (m) {
- if (seen === occurrence) {
- const groupRange = m.indices?.[1];
- if (!groupRange) return null;
- return { start: groupRange[0], end: groupRange[1], wasQuoted: false, open: '', close: '' };
- }
- seen += 1;
- m = re.exec(source);
- }
- return null;
-}
-
-/**
- * Locate a sequence-diagram block-condition line (`alt <cond>`,
- * `else <cond>`, `opt <cond>`, `loop <cond>`, `par <cond>`,
- * `critical <cond>`, `break <cond>`) in `source`. Returns the range of
- * the condition token so the caller can rewrite it in place.
- *
- * The mermaid renderer wraps the condition in visible brackets
- * (`[credentials valid]`) inside `.loopText`; the DOM click yields
- * `[credentials valid]`, but the source form is unbracketed. Callers
- * strip the DOM brackets before invoking this locator.
- */
-export function findSequenceBlockConditionInSource(
- source: string,
- currentCondition: string,
- occurrence = 0,
-): LabelMatch | null {
- const esc = currentCondition.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const kw = '(?:alt|else|opt|loop|par|par_and|critical|option|and|break|rect)';
- const re = new RegExp(`^([ \\t]*${kw}[ \\t]+)(${esc})[ \\t]*(?=\\r?\\n|$)`, 'gmd');
- let seen = 0;
- let m: RegExpExecArray | null = re.exec(source);
- while (m) {
- if (seen === occurrence) {
- const groupRange = m.indices?.[2];
- if (!groupRange) return null;
- return { start: groupRange[0], end: groupRange[1], wasQuoted: false, open: '', close: '' };
- }
- seen += 1;
- m = re.exec(source);
- }
- return null;
-}
-
-// Label selectors that carry visible text across the diagram types inline
-// editing supports (flowchart node/edge labels are HTML spans; sequence
-// actors/messages/notes/loops are SVG `<text>`).
-const FLASHABLE_LABEL_SELECTOR =
- '.nodeLabel, .edgeLabel, text.actor, text.messageText, text.noteText, text.loopText';
-
-/**
- * Flash the rendered label occurrences whose text matches `value` — the "this
- * text changed too" cue used after a WYSIWYG label edit propagates to LINKED
- * occurrences (a renamed sequence participant renders in BOTH its top and
- * bottom actor boxes, so renaming once changes both). Adds the
- * `mermaid-label-flash` class (globals.css) to each match.
- *
- * Flashes only when 2+ occurrences match: a lone label edit has no "related"
- * text to signal, so it stays quiet. Mermaid re-renders the whole SVG on every
- * edit, so the class lands on fresh nodes and the one-shot animation plays
- * without a restart dance. Returns the count flashed.
- */
-/**
- * Rendered label occurrences whose text matches `value`, minus `exclude` (and
- * anything nested within an excluded element, either direction). Used by the
- * live-typing preview to find the OTHER occurrences of the token being edited —
- * e.g. the second actor box of the sequence participant under the inline input.
- */
-export function collectLinkedLabelTargets(
- container: HTMLElement,
- value: string,
- exclude: readonly Element[] = [],
-): Element[] {
- const needle = value.trim();
- if (!needle) return [];
- return Array.from(container.querySelectorAll<Element>(FLASHABLE_LABEL_SELECTOR)).filter(
- (el) =>
- !exclude.some((ex) => ex === el || ex.contains(el) || el.contains(ex)) &&
- (el.textContent ?? '').trim() === needle,
- );
-}
-
-/**
- * Count the rendered line boxes of an HTML (foreignObject) label.
- * Mermaid soft-wraps long flowchart labels at its `wrappingWidth`, so a
- * label can occupy several visual lines — the edit overlay needs the
- * count to pick a wrap-capable surface and to restore the label's line
- * rhythm (see `tryEnterEditWithTarget`). Fragments are grouped by top
- * edge because one visual line can emit multiple client rects (nested
- * spans). Returns 1 when the environment reports no layout (happy-dom
- * returns no client rects), which lands on the single-line path.
- */
-function countRenderedLabelLines(el: HTMLElement): number {
- try {
- const range = document.createRange();
- range.selectNodeContents(el);
- const lineTops: number[] = [];
- for (const rect of Array.from(range.getClientRects())) {
- if (rect.width <= 0 || rect.height <= 0) continue;
- if (!lineTops.some((top) => Math.abs(top - rect.top) < 1)) lineTops.push(rect.top);
- }
- return Math.max(lineTops.length, 1);
- } catch {
- return 1;
- }
-}
-
-/**
- * Absolute character offset within `root`'s text content at a click point,
- * or `null` when the point can't be resolved to a character. Lets the inline
- * label editor drop the caret where the user clicked instead of selecting the
- * whole label. `caretPositionFromPoint` is the standard API; `caretRangeFromPoint`
- * is the older WebKit/Chromium spelling — happy-dom ships neither, so the
- * `typeof` guards keep unit tests on the end-of-text fallback (the tree walk
- * below never runs there).
- */
-function caretOffsetFromClick(root: HTMLElement, clientX: number, clientY: number): number | null {
- const doc = root.ownerDocument;
- let node: Node | null = null;
- let offsetInNode = 0;
- if (typeof doc.caretPositionFromPoint === 'function') {
- const pos = doc.caretPositionFromPoint(clientX, clientY);
- if (pos) {
- node = pos.offsetNode;
- offsetInNode = pos.offset;
- }
- } else {
- // Fall back to `caretRangeFromPoint`, the legacy WebKit / older-Chromium
- // point->offset API for engines that predate `caretPositionFromPoint`.
- // Typed locally because the method can be absent at runtime.
- const rangeFromPoint = (
- doc as unknown as { caretRangeFromPoint?: (x: number, y: number) => Range | null }
- ).caretRangeFromPoint;
- if (typeof rangeFromPoint === 'function') {
- const range = rangeFromPoint.call(doc, clientX, clientY);
- if (range) {
- node = range.startContainer;
- offsetInNode = range.startOffset;
- }
- }
- }
- // Only a click that lands on a text node INSIDE the label has a meaningful
- // character index; a hit on the shape rect, padding, or a sibling maps to no
- // label character, so bail to the caller's end-of-text fallback. `!node`
- // short-circuits first so happy-dom (no caret API => node stays null) never
- // touches `Node.TEXT_NODE`.
- if (!node || node.nodeType !== Node.TEXT_NODE || !root.contains(node)) return null;
- // Sum the lengths of every text node before the hit node in document order,
- // then add the in-node offset: a wrapped label (foreignObject `<p>`) or an
- // SVG label split across `<tspan>`s spans several text nodes, so a
- // single-node assumption would misplace the caret on every line after the
- // first.
- let absolute = 0;
- const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
- let current = walker.nextNode();
- while (current) {
- if (current === node) return absolute + offsetInNode;
- absolute += (current.textContent ?? '').length;
- current = walker.nextNode();
- }
- return null;
-}
-
-/**
- * Map a click offset within the ORIGINAL label's text content onto an index in
- * the edit overlay's `value`. Two hazards make a raw offset wrong: (a) the value
- * is `.trim()`-ed, so it drops leading whitespace the DOM text still carries —
- * shift left by that width; (b) a supplied `sourceLabel` can diverge from the
- * visible glyphs (an `alt` condition renders bracketed `[cond]` but its source
- * form is `cond`), which makes any click->source mapping unsound. In (b), or when
- * no offset resolved, return the end of the text — never a whole-label selection.
- */
-export function resolveLabelCaretTarget(
- domText: string,
- clickOffset: number | null,
- sourceLabel: string | undefined,
- valueLength: number,
-): number {
- const sourceDiverges = sourceLabel != null && sourceLabel !== domText.trim();
- if (clickOffset === null || sourceDiverges) return valueLength;
- const leadingWhitespace = domText.length - domText.trimStart().length;
- const mapped = clickOffset - leadingWhitespace;
- return Math.max(0, Math.min(mapped, valueLength));
-}
-
-/**
- * Pulse one label's glyph paint to the agent accent and back, twice, by
- * toggling INLINE `!important` fill/color. Why inline `!important` and not a CSS
- * class animation: mermaid injects a `<style>` into every rendered SVG whose
- * `.actor` / `tspan` fill rules can out-specify (or `!important`-beat) a
- * class-based `fill` animation, silently cancelling it. An inline `!important`
- * declaration beats those, so the pulse always shows. `fill` colors SVG
- * `<tspan>` glyphs; `color` colors HTML (`.nodeLabel`/`.edgeLabel`) labels —
- * setting both covers either carrier. Honors reduce-motion with one softer
- * pulse. Self-cleans via `removeProperty`; safe if a later re-render detaches
- * the node (the timers just no-op on a detached element).
- */
-function pulseGlyphPaint(el: Element): void {
- const style = (el as SVGElement | HTMLElement).style as CSSStyleDeclaration | undefined;
- if (!style) return;
- const on = () => {
- style.setProperty('fill', 'var(--color-agent)', 'important');
- style.setProperty('color', 'var(--color-agent)', 'important');
- };
- const off = () => {
- style.removeProperty('fill');
- style.removeProperty('color');
- };
- const reduce =
- typeof window !== 'undefined' &&
- window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;
- if (reduce) {
- on();
- setTimeout(off, 600);
- return;
- }
- const beat = 170;
- on();
- setTimeout(off, beat);
- setTimeout(on, beat * 2);
- setTimeout(off, beat * 3);
-}
-
-export function flashLinkedLabels(container: HTMLElement, value: string): number {
- const needle = value.trim();
- if (!needle) return 0;
- const matches = Array.from(container.querySelectorAll<Element>(FLASHABLE_LABEL_SELECTOR)).filter(
- (el) => (el.textContent ?? '').trim() === needle,
- );
- if (matches.length < 2) return 0;
- for (const el of matches) {
- // Flash the innermost paint carrier, not the outer element. Mermaid paints
- // the glyph color on an inner `<tspan>` (SVG text) / `<p>` (foreignObject
- // label). The carrier collapses to the element itself when there's no
- // inner tspan/p. The `mermaid-label-flash` class is kept as a semantic
- // marker (and a bonus CSS glow for HTML labels, where `filter` isn't
- // clipped); `pulseGlyphPaint` drives the guaranteed-visible color pulse.
- const carrier = el.querySelector('tspan') ?? el.querySelector('p') ?? el;
- carrier.classList.add('mermaid-label-flash');
- pulseGlyphPaint(carrier);
- }
- return matches.length;
-}
+const CANVAS_CONTAINED_EVENTS = [
+ 'mousedown',
+ 'mouseup',
+ 'click',
+ 'dblclick',
+ 'pointerdown',
+ 'pointerup',
+ 'keydown',
+ 'keyup',
+ 'keypress',
+] as const;
export function MermaidView({ chart = '', className, editBinding }: MermaidProps) {
- const reactId = useId();
- const renderId = `mermaid-${reactId.replaceAll(':', '_')}`;
- const [state, setState] = useState<RenderState>({ status: 'idle', svg: '', error: '' });
+ const [state, setState] = useState<RenderState>({ status: 'rendering', error: '' });
+ // Bumped to re-run the canvas-creation effect after a lazy-import
+ // failure so a later chart edit retries the load (the module-level
+ // promise caches clear themselves on rejection).
+ const [loadAttempt, setLoadAttempt] = useState(0);
// Track the app's color mode so mermaid's palette can flip with the
// theme provider — reading it once at mount + observing the `<html>`
// class list keeps SVG contrast aligned even when the user toggles
- // themes with a diagram already on screen. Ties into the `chart`
- // render effect below via the dependency array so a theme flip
- // schedules the same re-render path as a chart edit.
+ // themes with a diagram already on screen.
const [colorMode, setColorMode] = useState<'light' | 'dark'>(() => readDocumentColorMode());
useEffect(() => {
if (typeof document === 'undefined') return;
@@ -982,13 +298,13 @@ export function MermaidView({ chart = '', className, editBinding }: MermaidProps
// An explicit `editBinding` (standalone `.mmd` doc) wins; otherwise editing is
// gated on the JSX host being editable (codefenced fence).
const canEdit = editBinding ? editBinding.canEdit : (host?.editor.isEditable ?? false);
- const containerRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLDivElement>(null);
// `useJsxComponentHost()` returns a fresh object literal on every
// parent render (JsxComponentView constructs `{editor, getPos, ...}`
// inline), so putting `host` directly in a `useEffect` dep would
- // re-tear-down the edit session on every unrelated re-render of the
- // wrapper. Keep effect deps stable and read the live host through a
- // ref that we sync on each render.
+ // re-create the canvas on every unrelated re-render of the wrapper.
+ // Keep effect deps stable and read the live host through a ref that
+ // we sync on each render.
const hostRef = useRef(host);
// Sync the ref in a layout effect (runs after render, before paint).
// Handlers can only fire after paint, so this is early enough to
@@ -999,105 +315,44 @@ export function MermaidView({ chart = '', className, editBinding }: MermaidProps
}, [host]);
// Same ref treatment for the optional standalone binding: the parent may
// hand a fresh object each render, so read it live through the ref inside
- // handlers to keep the edit-session effect deps (`[state.status, canEdit]`)
- // stable.
+ // handlers to keep the canvas-creation effect deps stable.
const editBindingRef = useRef(editBinding);
useLayoutEffect(() => {
editBindingRef.current = editBinding;
}, [editBinding]);
- // Tracks the currently-editing label so we can tear it down cleanly
- // when the SVG re-renders (or component unmounts) mid-edit.
- const editSessionRef = useRef<{ cleanup: () => void } | null>(null);
- // Set to the just-committed label value when a WYSIWYG edit changed the
- // chart; consumed by the post-render effect below to flash the LINKED
- // occurrences (e.g. a renamed participant's other actor box) once the SVG
- // re-renders. Null when no flash is pending.
- const flashValueRef = useRef<string | null>(null);
-
- useEffect(() => {
- if (!chart.trim()) {
- setState({ status: 'idle', svg: '', error: '' });
- return;
- }
- let cancelled = false;
- setState((prev) => ({ ...prev, status: 'rendering' }));
- void loadPanzoom().catch(() => undefined);
- loadMermaid()
- .then(async (m) => {
- // Re-initialize per render so a color-mode flip picks up the
- // right palette. Config writes are cheap; the render itself is
- // the expensive step.
- configureMermaid(m, colorMode);
- // Mermaid's `render` builds a hidden `<div id={renderId}>`
- // off-screen, computes layout, and returns the inert SVG
- // string. The DOM scratchpad is cleaned up by Mermaid itself.
- const result = await m.render(renderId, chart);
- if (!cancelled) {
- setState({ status: 'ready', svg: result.svg, error: '' });
- }
- })
- .catch((err) => {
- if (!cancelled) {
- const msg = err instanceof Error ? err.message : String(err);
- setState({ status: 'error', svg: '', error: msg });
- }
- });
- return () => {
- cancelled = true;
- };
- }, [chart, renderId, colorMode]);
+ const chartRef = useRef(chart);
+ useLayoutEffect(() => {
+ chartRef.current = chart;
+ }, [chart]);
+ const canEditRef = useRef(canEdit);
+ useLayoutEffect(() => {
+ canEditRef.current = canEdit;
+ }, [canEdit]);
+ const colorModeRef = useRef(colorMode);
+ useLayoutEffect(() => {
+ colorModeRef.current = colorMode;
+ }, [colorMode]);
+ const editorRef = useRef<MermaidWysiwygEditor | null>(null);
+ const viewRef = useRef<MermaidCanvasView | null>(null);
+ const panzoomRef = useRef<PanzoomObject | null>(null);
+ const loadFailedRef = useRef(false);
- // After a WYSIWYG edit re-renders the SVG, flash the linked occurrences of
- // the just-committed value (armed by `commitLabelChangeGeneric`). Keyed on
- // `state.svg`, NOT `state.status`: a warm re-render can batch the
- // `rendering`→`ready` transition so `status` collapses `ready`→`ready` and a
- // `[state.status]` effect never re-runs. The svg string changes on every
- // successful render, so keying on it fires reliably once the new SVG is in
- // the DOM. Consume-and-clear so an unrelated re-render (theme flip, remote
- // edit) never replays a stale flash.
- useEffect(() => {
- const value = flashValueRef.current;
- if (value === null) return;
- // A successful render always produces a non-empty svg; skip the idle/error
- // renders (svg === '') where there are no nodes to flash.
- if (!state.svg) return;
- flashValueRef.current = null;
- const container = containerRef.current;
- if (container) flashLinkedLabels(container, value);
- }, [state.svg]);
+ const hasChart = Boolean(chart.trim());
+ // Create the package editor + canvas view once the lazy modules land.
+ // Lives for the whole non-empty life of the component; chart / theme /
+ // editability updates are applied by the sync effects below.
useEffect(() => {
- if (state.status !== 'ready') return;
- if (!canEdit) return;
- const container = containerRef.current;
- if (!container) return;
-
- // Discoverability hint — set cursor to `text` on every rendered node
- // label so the "you can type here" affordance is obvious before the
- // user commits to a double-click. Applied post-mermaid-render so it
- // survives the SVG rebuild.
- for (const label of container.querySelectorAll<HTMLElement>('.nodeLabel, .edgeLabel')) {
- label.style.cursor = 'text';
- }
- // The full pointer-events + cursor treatment for the SVG-text
- // surfaces (`text.actor`, `text.messageText`, `text.noteText`,
- // `text.loopText`, `rect.note`) is applied inside the click-
- // handler effect below so the same helper owns both the widened
- // hit-testing and the delegated click routing.
-
- // Read the current chart source live at call time. Standalone binding wins;
- // otherwise read the JSX-host `jsxComponent` node's `chart` prop.
- function readChartSource(): string | null {
- const binding = editBindingRef.current;
- if (binding) return binding.getChart();
- const h = hostRef.current;
- if (!h) return null;
- const pos = h.getPos();
- if (typeof pos !== 'number') return null;
- const node = h.editor.state.doc.nodeAt(pos);
- if (!node || node.type.name !== 'jsxComponent') return null;
- return ((node.attrs.props as Record<string, unknown>)?.chart as string) ?? '';
- }
+ // `loadAttempt` re-arms this effect after a failed lazy import (bumped by
+ // the chart-sync effect below); its value is otherwise unused.
+ void loadAttempt;
+ if (!hasChart) return;
+ let disposed = false;
+ let view: MermaidCanvasView | null = null;
+ const offs: Array<() => void> = [];
+ let hasRendered = false;
+ setState({ status: 'rendering', error: '' });
+ void loadPanzoom().catch(() => undefined);
// Write the new chart source back. Standalone binding wins; otherwise
// dispatch one `setNodeMarkup` on the JSX-host `jsxComponent` node.
@@ -1132,766 +387,140 @@ export function MermaidView({ chart = '', className, editBinding }: MermaidProps
}
}
- function commitLabelChangeGeneric(target: EditTarget, newLabel: string): void {
- const chartNow = readChartSource();
- if (chartNow === null) return;
- // Prefer applyRewrite (participant paths); otherwise fall back
- // to locate + spliceNewLabel.
- let newChart: string | null = null;
- if (target.applyRewrite) {
- newChart = target.applyRewrite(chartNow, newLabel);
- } else if (target.locate) {
- const match = target.locate(chartNow);
- if (match) newChart = spliceNewLabel(chartNow, match, newLabel);
- }
- if (newChart === null) return;
- // Arm the linked-occurrence flash only when the edit actually changed the
- // source — so the post-render effect fires once on the resulting re-render
- // (a no-op edit produces no re-render, which would otherwise leave a stale
- // value to flash on the next unrelated render).
- if (newChart !== chartNow) flashValueRef.current = newLabel.trim();
- commitChartSource(newChart);
- }
-
- interface EditTarget {
- labelSpan: HTMLElement;
- // The SVG element (rect/polygon/path...) whose stroke we widen to
- // signal "this thing is being edited". Null when the target has
- // no single shape to tint (edge labels, sequence messages,
- // sequence participants).
- outlineShape: SVGElement | null;
- // Optional visual anchor used to POSITION the input. Defaults to
- // `labelSpan`. Provide when the label sits inside a bigger
- // container that better represents the visual box the user
- // clicked — e.g. sequence-diagram actors, where the `<text>`
- // element's tight glyph bbox doesn't match the actor `<rect>`
- // box the label appears inside, causing the text to visibly
- // shift when replaced by an HTML input whose text-align: center
- // is over a narrower rect.
- positionAnchor?: Element;
- // Preferred: `applyRewrite` returns the new chart source directly.
- // Used for surfaces where the edit isn't a pure span replacement
- // — e.g. participant renames may need to ADD an `as "..."` alias
- // instead of overwriting the id. Called against the CURRENT chart
- // source so a peer edit between click and commit doesn't desync.
- applyRewrite?: (chartNow: string, newLabel: string) => string | null;
- // Fallback: locate a span, then `spliceNewLabel` replaces it. Used
- // for node/edge/message labels where the edit is a pure span
- // replacement. Ignored when `applyRewrite` is set.
- locate?: (chartNow: string) => LabelMatch | null;
- // Optional override for the string the input opens with (and the
- // no-op comparison at commit). Defaults to the DOM label text.
- // Provide when the DOM renders decoration around the source token
- // — e.g. mermaid wraps `alt <cond>` conditions in visible brackets
- // `[cond]`, but the source form is unbracketed, so the input
- // should open with the source form and the rewrite should replace
- // the source range with what the user typed.
- sourceLabel?: string;
- }
-
- function tryEnterEditWithTarget(target: EditTarget, event: MouseEvent): boolean {
- const { labelSpan, outlineShape } = target;
- const currentChart = readChartSource();
- if (currentChart === null) return false;
- const currentLabel = target.sourceLabel ?? (labelSpan.textContent ?? '').trim();
- if (!currentLabel) return false;
- const rewriteHit = target.applyRewrite?.(currentChart, currentLabel);
- const locateHit = target.locate?.(currentChart);
- // Consider the edit "possible" if either path produces a match.
- // For `applyRewrite`, rewriting `currentLabel` → `currentLabel`
- // is a no-op transform that still returns non-null on success.
- if (!locateHit && rewriteHit == null) return false;
-
- event.preventDefault();
- event.stopPropagation();
-
- // Portal-based edit surface. The `.nodeLabel` lives inside PM's
- // editor tree (`.ProseMirror` -> JsxComponentView wrapper -> SVG
- // -> foreignObject -> span -> p). Any contenteditable / input
- // mounted inside that tree is watched by PM's MutationObserver
- // AND its beforeinput/input handlers, no matter how many events
- // we stop -- PM reacts to any DOM change it did not authorize by
- // re-syncing the tree to its own model, which manifests as page
- // jumps + focus shifts on the first keystroke.
- //
- // The fix that actually holds: mount the input as a sibling of
- // <body> (outside PM entirely), position it absolutely to cover
- // the label rectangle, and hide the underlying label while the
- // overlay is present. PM sees no DOM inside its tree change
- // during typing; on commit we dispatch one `setNodeMarkup` and
- // mermaid re-renders the SVG normally.
- const labelP = (labelSpan.querySelector('p') ?? labelSpan) as HTMLElement;
- // Capture where the click landed within the ORIGINAL label now, while it's
- // still visible and in its rendered position: the overlay below hides it and
- // mounts on top, so a later read would miss. Reconciling this into an
- // `input.value` index (trim + sourceLabel) happens at focus time.
- const clickCaretOffset = caretOffsetFromClick(labelP, event.clientX, event.clientY);
- const labelStyles = window.getComputedStyle(labelP);
- // Mermaid often paints the visible glyph color on an inner
- // `<tspan>` while the outer `<text>` carries a background-
- // matching fill so theme overrides cascade cleanly. Resolve the
- // innermost paint carrier once so both the input color and the
- // font metrics below read from the same source.
- const paintCarrier: Element =
- labelP instanceof SVGGraphicsElement ? (labelP.querySelector('tspan') ?? labelP) : labelP;
- const paintStyles = window.getComputedStyle(paintCarrier);
- // SVG `<text>` colors its glyphs via `fill`, not CSS `color`.
- // Copy that paint into the HTML input's `color`; without this
- // the input inherits the browser's dark-mode default (near-
- // white) and reads as invisible against the actor's light box.
- const svgTextColor = ((): string | null => {
- if (!(labelP instanceof SVGGraphicsElement)) return null;
- const fill = paintStyles.fill;
- return fill && fill !== 'none' ? fill : null;
- })();
- const inputColor = svgTextColor ?? labelStyles.color;
- const nodeShape = outlineShape;
- const nodeShapeStrokeBefore: string | null = nodeShape?.getAttribute('stroke') ?? null;
- const nodeShapeStrokeWidthBefore: string | null =
- nodeShape?.getAttribute('stroke-width') ?? null;
-
- // A wrapped label needs a wrap-capable edit surface: an
- // `<input type="text">` is single-line by construction, so a label
- // mermaid wrapped onto N lines would visibly reflow onto one long
- // line the moment editing starts. Only HTML (foreignObject) labels
- // ever wrap — SVG `<text>` labels lay out per-tspan and always
- // take the single-line path.
- const labelLineCount =
- labelP instanceof SVGGraphicsElement ? 1 : countRenderedLabelLines(labelP);
- const multiline = labelLineCount > 1;
- const input = multiline
- ? document.createElement('textarea')
- : document.createElement('input');
- if (input instanceof HTMLInputElement) input.type = 'text';
- // Keydown wiring goes through the `HTMLElement` view of the
- // surface: on the input|textarea union TS resolves
- // `addEventListener` to the bare `EventListener` overload and
- // loses the KeyboardEvent mapping.
- const inputEventHost: HTMLElement = input;
- input.value = currentLabel;
- input.setAttribute('data-mermaid-editing', 'true');
- input.setAttribute('spellcheck', 'true');
- // The overlay lives at <body> to sit outside PM's DOM (so PM can't
- // see the typing) but visually the goal is "the label is now an
- // input" — no dark box, no heavy border, no color shift. We copy
- // the label's own typography exactly, leave the background fully
- // transparent so mermaid's own node fill shows through, and
- // suppress every hint of an input-frame the browser adds by
- // default (border, outline, shadow, autofill background). The
- // caret is the only editing signal on the label itself; the node
- // outline (widened via `nodeShape` below) confirms which shape is
- // being edited without slapping a modal chrome over the diagram.
- // SVG `<text>` elements don't reliably populate the `font`
- // shorthand in `getComputedStyle` — Chrome fills it, WebKit
- // often doesn't, and either can drop the SVG-declared font-family
- // in favor of the UA default. Read the font primitives directly
- // from the same paint carrier resolved above so the overlay
- // input renders with the SVG-declared face + size.
- Object.assign(input.style, {
- position: 'fixed',
- margin: '0',
- padding: '0',
- fontFamily: paintStyles.fontFamily,
- fontSize: paintStyles.fontSize,
- fontWeight: paintStyles.fontWeight,
- fontStyle: paintStyles.fontStyle,
- fontFeatureSettings: paintStyles.fontFeatureSettings,
- letterSpacing: paintStyles.letterSpacing,
- color: inputColor,
- textAlign: 'center',
- border: 'none',
- outline: 'none',
- boxShadow: 'none',
- boxSizing: 'border-box',
- // Chrome respects the page `color-scheme: dark` on inputs by
- // slapping a dark fill onto them regardless of `background` —
- // force the light rendering path and clear every fill vector
- // (background, backdrop-filter, appearance chrome) explicitly.
- colorScheme: 'light',
- appearance: 'none',
- WebkitAppearance: 'none',
- caretColor: inputColor,
- zIndex: '2147483647',
- });
- if (multiline) {
- // Reproduce the label's own wrapping context so the text keeps
- // its exact line breaks while editable. Width stays pinned to
- // the label rect in `positionInput` (widening it would move the
- // wrap points); `overflow: hidden` because the box is sized to
- // its content and must never show a scrollbar.
- Object.assign(input.style, {
- whiteSpace: labelStyles.whiteSpace,
- overflowWrap: labelStyles.overflowWrap,
- wordBreak: labelStyles.wordBreak,
- resize: 'none',
- overflow: 'hidden',
+ // (Re-)attach the pan/zoom controller to the freshly rendered SVG —
+ // the canvas view replaces its SVG host's innerHTML on every render,
+ // so the previous Panzoom target is gone.
+ function attachPanzoom(): void {
+ const svgElement = canvasRef.current?.querySelector<SVGElement>('svg');
+ const previous = panzoomRef.current;
+ panzoomRef.current = null;
+ previous?.destroy();
+ if (svgElement?.namespaceURI !== 'http://www.w3.org/2000/svg') return;
+ // The package pins the SVG's inline max-width to 100%; restore
+ // mermaid's own natural-width cap (the viewBox width) so small
+ // diagrams don't upscale past their rendered size — matching how
+ // the SVG string used to land verbatim. Structural check (not
+ // `instanceof SVGSVGElement`) so DOM-emulated test substrates
+ // without the SVG constructor globals stay on the happy path.
+ const viewBox = (svgElement as Partial<SVGSVGElement>).viewBox?.baseVal;
+ if (viewBox && viewBox.width > 0) svgElement.style.maxWidth = `${viewBox.width}px`;
+ loadPanzoom()
+ .then((Panzoom) => {
+ if (disposed) return;
+ // A newer render may have replaced the SVG while Panzoom loaded.
+ if (canvasRef.current?.querySelector('svg') !== svgElement) return;
+ panzoomRef.current?.destroy();
+ panzoomRef.current = Panzoom(svgElement, {
+ canvas: true,
+ cursor: 'default',
+ maxScale: MERMAID_ZOOM_MAX,
+ minScale: MERMAID_ZOOM_MIN,
+ noBind: true,
+ step: MERMAID_ZOOM_STEP,
+ touchAction: 'auto',
+ });
+ })
+ .catch((err) => {
+ console.warn('[Mermaid] panzoom setup failed:', err);
});
- }
- // `background: transparent` in a plain Object.assign gets ignored
- // by Chrome's forced-color-scheme rendering path. `setProperty`
- // with `!important` beats the UA stylesheet, which is what we
- // need for the input to actually disappear behind the label.
- input.style.setProperty('background', 'transparent', 'important');
- input.style.setProperty('background-color', 'transparent', 'important');
- // Widen and tint the SVG node's own stroke to signal "this node
- // is being edited" — this is the visual affordance instead of a
- // heavy input frame. Restored on cleanup below.
- if (nodeShape) {
- nodeShape.setAttribute('stroke', 'var(--ring, #3b82f6)');
- nodeShape.setAttribute('stroke-width', '2');
- }
- // Hide the underlying SVG label while the overlay is present so
- // there's no double-render / peek-through.
- const prevLabelVisibility = labelP.style.visibility;
- labelP.style.visibility = 'hidden';
-
- // Live preview: mirror each keystroke into the OTHER rendered occurrences
- // of the same token (e.g. a sequence participant's second actor box) so
- // the whole diagram tracks the edit before commit. DOM-only — `Y.Text` is
- // untouched until commit, so a concurrent editor sees nothing mid-type,
- // and a remote edit that re-renders tears this down via the edit-session
- // cleanup. Each target's `innerHTML` is captured so cleanup can restore it
- // (Escape reverts; commit re-renders over it — mermaid re-lays-out box
- // geometry, which stays fixed during the preview).
- const visibleLabel = (labelSpan.textContent ?? '').trim();
- const linkedPreview: Array<{ el: Element; html: string }> = containerRef.current
- ? collectLinkedLabelTargets(containerRef.current, visibleLabel, [labelSpan, labelP]).map(
- (el) => ({ el, html: el.innerHTML }),
- )
- : [];
- function syncLinkedPreview(): void {
- const next = input.value;
- for (const { el } of linkedPreview) {
- // Write into the innermost paint carrier so the occurrence keeps its
- // glyph fill. Mermaid paints the visible color on an inner `<tspan>`
- // (SVG text) or `<p>` (foreignObject label) while the outer element
- // carries only a background-matching fill (see the input-color note
- // above). Replacing the whole element's `textContent` drops that
- // carrier, so the preview text falls back to the near-invisible
- // background fill and reads as a faded "ghost". Targeting the carrier
- // keeps it the same weight/color as the committed label.
- const carrier = el.querySelector('tspan') ?? el.querySelector('p') ?? el;
- carrier.textContent = next;
- }
- }
-
- document.body.appendChild(input);
- // Position the input *after* it's in the DOM so we can use its
- // own measured metrics — the browser hasn't laid it out until
- // then, and matching the label's rect exactly is what makes the
- // swap feel like the label just became typeable.
- // Use the caller-supplied positioning anchor if any (better for
- // labels whose visible box is BIGGER than the text glyph bbox —
- // sequence actors, edge labels wrapped in a bg rect); otherwise
- // fall back to the label element itself.
- const anchor: Element = target.positionAnchor ?? labelP;
- // Minimum comfortable typing space. Short bare-id actors like
- // `User` render into a rect that's ~14px wide — enough for the
- // static glyphs but not enough to type past the current label
- // without immediate clipping. `ch` is Chrome-accurate for
- // monospace glyphs; for the proportional fonts mermaid uses it
- // rounds up conservatively (roughly one em of headroom either
- // side of the current text).
- const inputMinCh = Math.max(currentLabel.length + 4, 8);
- // Declared font size on the SVG (or the foreignObject HTML label)
- // lives in the SVG user coordinate space. Mermaid's SVG uses a
- // `viewBox` so the on-screen glyph size is the declared size
- // multiplied by the viewBox-to-screen scale — the input mounts
- // outside the SVG at absolute screen coordinates and would
- // otherwise render at the raw declared size (~16 px screen)
- // while the underlying label renders at ~9-10 px screen, blowing
- // the size mismatch that reads as "not WYSIWYG". Capture the
- // declared size once and compute the effective scale per
- // reposition so the input tracks the label even after resizes
- // or zoom changes.
- const declaredFontSizePx = parseFloat(paintStyles.fontSize) || 16;
- function computeSvgRenderScale(): number {
- // For SVG shapes we own directly (rect.actor, rect.note, node
- // outlines) the anchor's own bbox-vs-screen ratio is the tightest
- // measurement — no assumption about `preserveAspectRatio`.
- if (anchor instanceof SVGGraphicsElement) {
- try {
- const bbox = anchor.getBBox();
- if (bbox.height > 0) {
- return anchor.getBoundingClientRect().height / bbox.height;
- }
- } catch {
- // getBBox throws on detached nodes / mid-transition SVGs.
- }
- }
- // Flowchart node labels live inside a `<foreignObject>` — the
- // HTML `<p>` isn't an SVGGraphicsElement, so anchor to the
- // owning SVG's overall viewBox scale instead. Mermaid emits
- // SVGs with `preserveAspectRatio="xMinYMin meet"` (default),
- // so the content scale is uniform and equals
- // `min(rectWidth / vbWidth, rectHeight / vbHeight)`. The
- // rendered box can be wider or taller than the viewBox needs
- // (letterboxing / pillarboxing outside the diagram area), so
- // picking the smaller axis matches the actual glyph scale.
- const svg =
- (labelP instanceof SVGElement ? labelP.ownerSVGElement : null) ??
- (labelP instanceof Element ? labelP.closest('svg') : null);
- if (svg instanceof SVGSVGElement) {
- const vb = svg.viewBox.baseVal;
- if (vb.width > 0 && vb.height > 0) {
- const rect = svg.getBoundingClientRect();
- return Math.min(rect.width / vb.width, rect.height / vb.height);
- }
- }
- return 1;
- }
- function positionInput(): void {
- const r = anchor.getBoundingClientRect();
- // Pin the input's CENTER to the anchor's center rather than
- // its left edge. Without this, the min-width widens the input
- // past the anchor's natural width and the (text-align: center)
- // text ends up offset from where the SVG glyphs were sitting —
- // which reads as the label "jumping" the moment you click it.
- // Centering keeps the glyphs pinned regardless of how wide we
- // grow the typing surface.
- input.style.top = `${r.top}px`;
- input.style.width = `${r.width}px`;
- // The min-width typing headroom would move a wrapped label's
- // wrap points (wider box = later breaks), so multiline keeps
- // the label's exact width and grows downward instead.
- input.style.minWidth = multiline ? '0' : `${inputMinCh}ch`;
- input.style.height = `${r.height}px`;
- // One line centers its glyphs by making the line as tall as the
- // box; a wrapped label needs its own line rhythm back, which
- // `boxHeight / lineCount` reproduces without trusting
- // `getComputedStyle().lineHeight` (it can be 'normal').
- input.style.lineHeight = `${r.height / labelLineCount}px`;
- const scale = computeSvgRenderScale();
- input.style.fontSize = `${declaredFontSizePx * scale}px`;
- // Typing past the original text adds wrapped lines; grow the
- // box downward so they stay visible (the node box itself only
- // re-lays-out on commit).
- if (multiline && input.scrollHeight > Math.ceil(r.height)) {
- input.style.height = `${input.scrollHeight}px`;
- }
- // Read the effective width after `min-width` clamps so we can
- // offset the input left to keep its horizontal center matched
- // to the anchor's. `getBoundingClientRect` after the width
- // writes above gives us the actually-rendered width, which is
- // what `text-align: center` will use to place the glyphs.
- input.style.left = `${r.left}px`;
- const effective = input.getBoundingClientRect();
- const anchorCenter = r.left + r.width / 2;
- const inputLeft = anchorCenter - effective.width / 2;
- input.style.left = `${inputLeft}px`;
- }
- positionInput();
- // Character-accurate for CSS-wrapped labels; for a label mermaid hard-wraps
- // (`<br>` / split `<tspan>`s) the value loses the break, so the caret is
- // right by character but may sit on a different visual line than the click.
- const caretTarget = resolveLabelCaretTarget(
- labelP.textContent ?? '',
- clickCaretOffset,
- target.sourceLabel,
- input.value.length,
- );
- // Focus + place the caret at the clicked character after the next paint, so
- // it feels like clicking into ordinary text. Sync focus() sometimes loses to
- // whatever else is settling from the click that started the edit; rAF hands
- // us the frame after PM/JsxComponentView have finished reacting.
- const focusRafHandle = requestAnimationFrame(() => {
- input.focus();
- input.setSelectionRange(caretTarget, caretTarget);
- });
-
- // Keep the overlay pinned if the page scrolls or the label moves.
- window.addEventListener('scroll', positionInput, true);
- window.addEventListener('resize', positionInput);
- input.addEventListener('input', syncLinkedPreview);
- // Re-measure per keystroke so the multiline auto-grow above
- // tracks the wrapped content.
- input.addEventListener('input', positionInput);
-
- let done = false;
- function cleanup(): void {
- cancelAnimationFrame(focusRafHandle);
- window.removeEventListener('scroll', positionInput, true);
- window.removeEventListener('resize', positionInput);
- inputEventHost.removeEventListener('keydown', onKeyDown);
- input.removeEventListener('blur', onBlur);
- input.removeEventListener('input', syncLinkedPreview);
- input.removeEventListener('input', positionInput);
- input.remove();
- // Restore the live-previewed occurrences to their original markup. On
- // Escape this reverts them; on commit the ensuing re-render replaces
- // them with the new value (and PR-1's flash fires on the linked ones).
- for (const { el, html } of linkedPreview) el.innerHTML = html;
- labelP.style.visibility = prevLabelVisibility;
- if (nodeShape) {
- if (nodeShapeStrokeBefore === null) {
- nodeShape.removeAttribute('stroke');
- } else {
- nodeShape.setAttribute('stroke', nodeShapeStrokeBefore);
- }
- if (nodeShapeStrokeWidthBefore === null) {
- nodeShape.removeAttribute('stroke-width');
- } else {
- nodeShape.setAttribute('stroke-width', nodeShapeStrokeWidthBefore);
- }
- }
- editSessionRef.current = null;
- }
- function commit(): void {
- if (done) return;
- done = true;
- const next = input.value.trim();
- cleanup();
- if (!next || next === currentLabel) return;
- commitLabelChangeGeneric(target, next);
- }
- function discard(): void {
- if (done) return;
- done = true;
- cleanup();
- }
- function onKeyDown(ev: KeyboardEvent): void {
- if (ev.key === 'Escape') {
- ev.preventDefault();
- ev.stopPropagation();
- discard();
- return;
- }
- if (ev.key === 'Enter') {
- ev.preventDefault();
- ev.stopPropagation();
- // Shift+Enter is swallowed rather than committed: on the
- // textarea surface it would otherwise insert a raw newline,
- // which the single-line label splice can't represent.
- if (!ev.shiftKey) commit();
- return;
- }
- // Any other key: stop propagation so PM's editor-level
- // handlers (attached higher up the tree) don't see a keystroke
- // that "escaped" our overlay.
- ev.stopPropagation();
- }
- function onBlur(): void {
- commit();
- }
- inputEventHost.addEventListener('keydown', onKeyDown);
- input.addEventListener('blur', onBlur);
- // Force-discard on cleanup path (SVG re-render / unmount mid-edit).
- editSessionRef.current = {
- cleanup: () => {
- if (!done) discard();
- },
- };
- return true;
}
- // Single-click enters edit — matches how the rest of the WYSIWYG
- // behaves (click text, start typing). Clicks outside a label still
- // fall through to JsxComponentView's `handleBodyClick` for
- // NodeSelection, so both affordances survive.
- function onLabelClick(event: MouseEvent): void {
- if (editSessionRef.current) return;
- const target = event.target;
- if (!(target instanceof Element)) return;
-
- const nodeLabelSpan = target.closest<HTMLElement>('.nodeLabel');
- if (nodeLabelSpan) {
- const nodeGroup = target.closest<HTMLElement>('.node[id]');
- if (!nodeGroup) return;
- const nodeIdRaw = extractSourceNodeId(nodeGroup.id);
- if (!nodeIdRaw) return;
- const nodeId: string = nodeIdRaw;
- const currentLabel = (nodeLabelSpan.textContent ?? '').trim();
- if (!currentLabel) return;
- // Bare-id nodes (`Shopper --> Storefront` — no `Shopper[…]`
- // shape) render the id itself as the visible label. When the
- // shape-splice locator misses AND the DOM label equals the node
- // id, fall through to appending `[NewLabel]` after the first
- // bare id occurrence. Preserving the id keeps every
- // `Shopper -->` arrow elsewhere in the chart resolving. Both
- // `locate` and `applyRewrite` route through this resolver so
- // the editability probe and the commit path can never disagree.
- function resolveFlowchartNodeHit(chartNow: string): {
- match: LabelMatch;
- splice: (source: string, m: LabelMatch, next: string) => string;
- } | null {
- const shapeHit = findLabelInSource(chartNow, nodeId, currentLabel);
- if (shapeHit) return { match: shapeHit, splice: spliceNewLabel };
- if (currentLabel !== nodeId) return null;
- const bareHit = findFlowchartBareIdInSource(chartNow, nodeId);
- if (!bareHit) return null;
- return { match: bareHit, splice: spliceInsertBareIdLabel };
- }
- tryEnterEditWithTarget(
- {
- labelSpan: nodeLabelSpan,
- outlineShape: nodeGroup.querySelector<SVGElement>(
- 'rect, polygon, path, circle, ellipse',
- ),
- locate: (chartNow) => resolveFlowchartNodeHit(chartNow)?.match ?? null,
- applyRewrite: (chartNow, newLabel) => {
- const hit = resolveFlowchartNodeHit(chartNow);
- return hit ? hit.splice(chartNow, hit.match, newLabel) : null;
- },
- },
- event,
- );
- return;
- }
-
- const actorText = target.closest<SVGTextElement>('text.actor');
- if (actorText) {
- // Sequence-diagram participant. The DOM class `.actor.actor-box`
- // sits on both the top and bottom labels (mermaid duplicates
- // them at each end of the timeline), so the source occurrence
- // count is `DOM order / 2`.
- const currentDisplay = (actorText.textContent ?? '').trim();
- if (!currentDisplay) return;
- const svg = actorText.ownerSVGElement;
- let occurrence = 0;
- if (svg) {
- const all = Array.from(svg.querySelectorAll<SVGTextElement>('text.actor'));
- let seen = 0;
- for (const el of all) {
- if (el === actorText) {
- occurrence = Math.floor(seen / 2);
- break;
+ Promise.all([loadMermaid(), loadWysiwyg()])
+ .then(([mermaid, [core, dom]]) => {
+ const container = canvasRef.current;
+ if (disposed || !container) return;
+ const editor = new core.MermaidWysiwygEditor({ code: chartRef.current });
+ view = new dom.MermaidCanvasView({
+ editor,
+ container,
+ mermaid,
+ mermaidConfig: mermaidConfigFor(colorModeRef.current),
+ readOnly: !canEditRef.current,
+ accentColor: 'var(--ring)',
+ });
+ editorRef.current = editor;
+ viewRef.current = view;
+ offs.push(
+ editor.on('change', ({ code, origin }) => {
+ // 'external' marks our own prop-driven `setCode` round-trips;
+ // everything else (canvas gestures, package history) is a user
+ // edit that must land in the real source of truth.
+ if (origin === 'external') return;
+ commitChartSource(code);
+ }),
+ view.on('render', ({ ok, error }) => {
+ if (disposed) return;
+ if (ok) {
+ hasRendered = true;
+ setState({ status: 'ready', error: '' });
+ attachPanzoom();
+ } else if (!hasRendered) {
+ // Before the first successful render there is no diagram to
+ // keep on screen — surface the full error chrome. After one,
+ // the canvas keeps the last good SVG and shows the package's
+ // compact error badge instead (error-tolerant mid-edit).
+ setState({ status: 'error', error: error ?? '' });
}
- if ((el.textContent ?? '').trim() === currentDisplay) seen += 1;
- }
- }
- // Positioning anchor: the actor's own `<rect>` sibling (the
- // visible actor box). Not every actor kind renders one — the
- // `actor` keyword produces the stick-figure `actor-man` group
- // whose bounding rect extends from head to the label below.
- // Using the group's rect there mounts the input at the group
- // top with lineHeight = group height, so the input's centered
- // text lands ~20 px above the SVG label. Leave `positionAnchor`
- // undefined in that case and fall back to the text glyph's own
- // bbox, which sits exactly where the user clicked.
- const actorGroup = actorText.parentElement;
- const actorRectSibling = actorGroup?.querySelector<SVGGraphicsElement>('rect.actor');
- tryEnterEditWithTarget(
- {
- labelSpan: actorText as unknown as HTMLElement,
- outlineShape: null,
- positionAnchor: actorRectSibling ?? undefined,
- applyRewrite: (chartNow, newLabel) =>
- rewriteSequenceParticipant(chartNow, currentDisplay, newLabel, occurrence),
- },
- event,
- );
- return;
- }
-
- const messageText = target.closest<SVGTextElement>('text.messageText');
- if (messageText) {
- // Sequence-diagram message body. The DOM `<text.messageText>`
- // element doesn't carry actor pair info, so the source match
- // is by text alone. Duplicate identical messages tie-break on
- // `occurrence` (DOM order of same-text messages before this one).
- const currentLabel = (messageText.textContent ?? '').trim();
- if (!currentLabel) return;
- const svg = messageText.ownerSVGElement;
- let occurrence = 0;
- if (svg) {
- const all = Array.from(svg.querySelectorAll<SVGTextElement>('text.messageText'));
- for (const el of all) {
- if (el === messageText) break;
- if ((el.textContent ?? '').trim() === currentLabel) occurrence += 1;
- }
- }
- tryEnterEditWithTarget(
- {
- labelSpan: messageText as unknown as HTMLElement,
- outlineShape: null,
- locate: (chartNow) => findSequenceMessageInSource(chartNow, currentLabel, occurrence),
- },
- event,
- );
- return;
- }
-
- const edgeLabelSpan = target.closest<HTMLElement>('.edgeLabel');
- if (edgeLabelSpan) {
- // Mermaid wraps the edge label in `<g class="label" data-id="L_<from>_<to>_<idx>">`
- // — that's the only place the from/to/index is emitted. Walk up
- // to the nearest `[data-id^="L_"]` ancestor for the identifier.
- const labelGroup = edgeLabelSpan.closest<HTMLElement>('g[data-id^="L_"]');
- const dataId = labelGroup?.getAttribute('data-id');
- if (!dataId) return;
- const info = extractEdgeInfo(dataId);
- if (!info) return;
- const currentLabel = (edgeLabelSpan.textContent ?? '').trim();
- if (!currentLabel) return;
- tryEnterEditWithTarget(
- {
- labelSpan: edgeLabelSpan,
- // Edge stroke is on a `<path>` outside the label group — not
- // reliably tied to this label's rect — so we skip the
- // stroke-widen affordance for edges. The input's caret and
- // the surrounding text still make edit mode obvious.
- outlineShape: null,
- locate: (chartNow) =>
- findEdgeLabelInSource(chartNow, info.from, info.to, info.index, currentLabel),
- },
- event,
+ }),
);
- return;
- }
+ })
+ .catch((err) => {
+ if (disposed) return;
+ loadFailedRef.current = true;
+ const msg = err instanceof Error ? err.message : String(err);
+ setState({ status: 'error', error: msg });
+ });
- // Sequence-diagram Note over|left of|right of. Same locate-then-
- // splice shape as messageText. The DOM only exposes the body, so
- // duplicate bodies tie-break via `occurrence` (DOM order among
- // same-body notes before this one). Clicks in the note box's
- // padding (between text glyphs, or on the left/right of the
- // label inside the yellow rect) land on `rect.note` — walk to
- // the sibling `text.noteText` so the padding is treated as part
- // of the note surface.
- const noteRectHit = target.closest<SVGRectElement>('rect.note');
- const noteText =
- target.closest<SVGTextElement>('text.noteText') ??
- noteRectHit?.parentElement?.querySelector<SVGTextElement>('text.noteText') ??
- null;
- if (noteText) {
- const currentNote = (noteText.textContent ?? '').trim();
- if (!currentNote) return;
- const svg = noteText.ownerSVGElement;
- let occurrence = 0;
- if (svg) {
- const all = Array.from(svg.querySelectorAll<SVGTextElement>('text.noteText'));
- for (const el of all) {
- if (el === noteText) break;
- if ((el.textContent ?? '').trim() === currentNote) occurrence += 1;
- }
- }
- // Position anchor: the yellow note `<rect>` sibling — always
- // wider than the glyph bbox so the input covers the visible box
- // rather than tightly around the text.
- const noteGroup = noteText.parentElement;
- const noteRect =
- noteGroup?.querySelector<SVGGraphicsElement>('rect.note') ??
- (noteText.previousElementSibling instanceof SVGGraphicsElement
- ? noteText.previousElementSibling
- : null);
- tryEnterEditWithTarget(
- {
- labelSpan: noteText as unknown as HTMLElement,
- outlineShape: null,
- positionAnchor: noteRect ?? undefined,
- locate: (chartNow) => findSequenceNoteInSource(chartNow, currentNote, occurrence),
- },
- event,
- );
- return;
- }
+ return () => {
+ disposed = true;
+ for (const off of offs) off();
+ panzoomRef.current?.destroy();
+ panzoomRef.current = null;
+ view?.destroy();
+ editorRef.current = null;
+ viewRef.current = null;
+ };
+ }, [hasChart, loadAttempt]);
- // Sequence-diagram alt/else/opt/loop/par/critical block header.
- // The DOM `text.loopText` renders the condition wrapped in visible
- // brackets (`[credentials valid]`); the source form is
- // unbracketed. Strip brackets before locating.
- const loopText = target.closest<SVGTextElement>('text.loopText');
- if (loopText) {
- const displayed = (loopText.textContent ?? '').trim();
- // Strip surrounding brackets (`[…]`) that mermaid renders around
- // the condition. Fall through untouched if the author didn't use
- // brackets (rare / non-standard mermaid).
- const currentCondition =
- displayed.startsWith('[') && displayed.endsWith(']')
- ? displayed.slice(1, -1).trim()
- : displayed;
- if (!currentCondition) return;
- const svg = loopText.ownerSVGElement;
- let occurrence = 0;
- if (svg) {
- const all = Array.from(svg.querySelectorAll<SVGTextElement>('text.loopText'));
- for (const el of all) {
- if (el === loopText) break;
- const other = (el.textContent ?? '').trim();
- const otherCondition =
- other.startsWith('[') && other.endsWith(']') ? other.slice(1, -1).trim() : other;
- if (otherCondition === currentCondition) occurrence += 1;
- }
- }
- tryEnterEditWithTarget(
- {
- labelSpan: loopText as unknown as HTMLElement,
- outlineShape: null,
- sourceLabel: currentCondition,
- locate: (chartNow) =>
- findSequenceBlockConditionInSource(chartNow, currentCondition, occurrence),
- },
- event,
- );
- }
+ // External chart updates (remote CRDT edits, source-mode typing) re-enter
+ // the package editor without echoing back through the commit path.
+ useEffect(() => {
+ const editor = editorRef.current;
+ if (editor && chart !== editor.code) {
+ editor.setCode(chart, 'external');
+ } else if (!editorRef.current && loadFailedRef.current && chart.trim()) {
+ // The lazy import failed before a canvas existed — retry on the next
+ // chart change (mirrors the old per-render retry behavior).
+ loadFailedRef.current = false;
+ setLoadAttempt((n) => n + 1);
}
+ }, [chart]);
- // Click handling runs in capture-phase so we intercept BEFORE
- // JsxComponentView's `handleBodyClick` (attached as a React onClick
- // that delegates through the React root, bubble-phase). This does
- // three things at once for a click inside `.nodeLabel`:
- // 1. Stop propagation so the wrapper never `setNodeSelection`s and
- // re-renders the JsxComponentView subtree (which would tear
- // down our label DOM between the first and second click).
- // 2. Feed our own two-click-within-threshold detection.
- // 3. On the second click, enter edit mode.
- // Mousedown is captured too for the same stopPropagation reason —
- // PM's own selection handling runs at mousedown time. Clicks outside
- // `.nodeLabel` (edges, blank canvas) still reach the wrapper and
- // still NodeSelect the block, so both affordances survive.
- function onLabelMouseDown(event: MouseEvent): void {
- const t = event.target;
- if (!(t instanceof Element)) return;
- if (
- !t.closest(
- '.nodeLabel, .edgeLabel, text.messageText, text.actor, text.noteText, text.loopText, rect.note',
- )
- )
- return;
- event.stopPropagation();
- }
- function onLabelClickCapture(event: MouseEvent): void {
- const t = event.target;
- if (!(t instanceof Element)) return;
- if (
- !t.closest(
- '.nodeLabel, .edgeLabel, text.messageText, text.actor, text.noteText, text.loopText, rect.note',
- )
- )
- return;
- event.stopPropagation();
- onLabelClick(event);
- }
+ useEffect(() => {
+ viewRef.current?.setReadOnly(!canEdit);
+ }, [canEdit]);
- // SVG `<text>` defaults to `pointer-events: painted`, which sends
- // clicks BETWEEN glyphs (the ~2 px gaps that are unpainted) through
- // to whatever is behind. For flowchart node labels + edge labels
- // that's fine because the outline shape catches those clicks and
- // the closest-selector walk handles them. For sequence-diagram
- // actors, messages, notes, and loop-condition labels there IS no
- // downstream catcher inside the group — the click would fall
- // through to the SVG background. Force `pointer-events: all` on
- // every editable text surface + the note rect so the whole visible
- // bbox is clickable. The cursor hint reinforces that the text is
- // editable on hover.
- for (const el of container.querySelectorAll<SVGElement>(
- 'text.actor, text.messageText, text.noteText, text.loopText, rect.note',
- )) {
- el.style.pointerEvents = 'all';
- el.style.cursor = 'text';
- }
- container.addEventListener('mousedown', onLabelMouseDown, { capture: true });
- container.addEventListener('click', onLabelClickCapture, { capture: true });
+ useEffect(() => {
+ viewRef.current?.setMermaidConfig(mermaidConfigFor(colorMode));
+ }, [colorMode]);
+
+ // Keep every canvas interaction out of ProseMirror's reach while
+ // editable. Bubble-phase on the container: the package's own handlers
+ // (svg-level, and its container keydown) still run — stopPropagation
+ // only severs the path UP into PM's editor DOM. Read-only surfaces
+ // (file viewer, read-only docs) leave events alone so the block keeps
+ // its normal NodeSelection behavior.
+ useEffect(() => {
+ const container = canvasRef.current;
+ if (!container || !canEdit || !hasChart) return;
+ const stop = (e: Event) => e.stopPropagation();
+ for (const type of CANVAS_CONTAINED_EVENTS) container.addEventListener(type, stop);
return () => {
- container.removeEventListener('mousedown', onLabelMouseDown, { capture: true });
- container.removeEventListener('click', onLabelClickCapture, { capture: true });
- editSessionRef.current?.cleanup();
- editSessionRef.current = null;
+ for (const type of CANVAS_CONTAINED_EVENTS) container.removeEventListener(type, stop);
};
- // host intentionally NOT in deps — it's a fresh object every render
- // (see hostRef comment above). Handlers use hostRef.current.
- }, [state.status, canEdit]);
+ }, [canEdit, hasChart]);
- if (!chart.trim()) {
+ if (!hasChart) {
// Reached in read-only render contexts and the edit-modal preview with an
// empty draft. The editor's authoring path renders a click-to-edit
// placeholder card upstream (JsxComponentView), so this stays passive and
@@ -1912,70 +541,71 @@ export function MermaidView({ chart = '', className, editBinding }: MermaidProps
);
}
- if (state.status === 'error') {
- // Error banner sits ABOVE the source — readers' eyes land on the
- // diagnosis first, then the offending code. Putting the message below
- // (the original order) read as a stray paragraph because the unstyled
- // text blended into body content. The destructive-toned chrome here
- // mirrors `PropertyPanel`'s malformed-FM banner so the same visual
- // language signals "agent-visible error" across surfaces.
- return (
- <div className="mermaid mermaid-error" data-component-type="mermaid" title={state.error}>
- <div
- role="alert"
- className="mermaid-error-message mb-2 flex items-start gap-2 rounded border border-destructive/30 bg-destructive/5 px-3 py-2 text-[12px] text-destructive"
- >
- <AlertTriangle className="size-3.5 shrink-0 mt-0.5" aria-hidden />
- <div className="min-w-0">
- <div className="font-medium">
- <Trans>Mermaid diagram failed to render.</Trans>
+ const showCanvas = state.status === 'ready';
+
+ return (
+ <div
+ className={cn(
+ 'mermaid',
+ showCanvas &&
+ cn(
+ 'mermaid-ready flex h-full min-h-64 w-full overflow-hidden rounded-md border border-border/60 bg-background',
+ className,
+ ),
+ state.status === 'error' && 'mermaid-error',
+ state.status === 'rendering' && 'mermaid-rendering',
+ )}
+ data-component-type="mermaid"
+ title={state.status === 'error' ? state.error : undefined}
+ >
+ {state.status === 'error' && (
+ // Error banner sits ABOVE the source — readers' eyes land on the
+ // diagnosis first, then the offending code. The destructive-toned
+ // chrome here mirrors `PropertyPanel`'s malformed-FM banner so the
+ // same visual language signals "agent-visible error" across surfaces.
+ <>
+ <div
+ role="alert"
+ className="mermaid-error-message mb-2 flex items-start gap-2 rounded border border-destructive/30 bg-destructive/5 px-3 py-2 text-[12px] text-destructive"
+ >
+ <AlertTriangle className="size-3.5 shrink-0 mt-0.5" aria-hidden />
+ <div className="min-w-0">
+ <div className="font-medium">
+ <Trans>Mermaid diagram failed to render.</Trans>
+ </div>
+ <pre className="mt-1 whitespace-pre-wrap break-words font-mono text-[11px] opacity-90">
+ {state.error}
+ </pre>
</div>
- <pre className="mt-1 whitespace-pre-wrap break-words font-mono text-[11px] opacity-90">
- {state.error}
- </pre>
</div>
- </div>
- {/* The chart source shows WHAT the author wrote so they can locate
- the offending line/column the parser message refers to. */}
- <pre className="mermaid-error-source">{chart}</pre>
- </div>
- );
- }
-
- if (state.status === 'ready') {
- return (
+ {/* The chart source shows WHAT the author wrote so they can locate
+ the offending line/column the parser message refers to. */}
+ <pre className="mermaid-error-source">{chart}</pre>
+ </>
+ )}
+ {/* The canvas stays mounted across error/rendering states so the
+ package view (and any in-flight edit session) survives — a fixed
+ source re-renders straight back to `ready` without a remount. */}
<div
- ref={containerRef}
+ contentEditable={false}
className={cn(
- 'mermaid mermaid-ready flex h-full min-h-64 w-full overflow-hidden rounded-md border border-border/60 bg-background',
- className,
+ 'relative min-h-0 flex-1 overflow-hidden bg-muted/20',
+ showCanvas ? 'flex' : 'hidden',
)}
- data-component-type="mermaid"
>
- <MermaidInteractiveView svg={state.svg} />
+ <div ref={canvasRef} className="ok-mermaid-svg flex min-h-0 flex-1" />
+ {showCanvas && <MermaidViewControls panzoomRef={panzoomRef} />}
</div>
- );
- }
-
- return (
- <div
- ref={containerRef}
- // Class follows the actual render state. Before the async
- // `mermaid.render()` resolves the chart is non-empty but `state.svg`
- // is `''` and `state.status` is `idle` or `rendering` — emitting
- // `mermaid-ready` in that window mislabels the DOM for any inspector
- // (devtools, theming hooks, screen-reader CSS). `mermaid-${status}`
- // narrows the rendered class to one of `idle`/`rendering`/`ready`.
- className={`mermaid mermaid-${state.status}`}
- data-component-type="mermaid"
- />
+ </div>
);
}
-function MermaidInteractiveView({ svg }: { svg: string }) {
+function MermaidViewControls({
+ panzoomRef,
+}: {
+ panzoomRef: React.RefObject<PanzoomObject | null>;
+}) {
const { t } = useLingui();
- const svgHostRef = useRef<HTMLDivElement | null>(null);
- const panzoomRef = useRef<PanzoomObject | null>(null);
const labels = {
zoomIn: t`Zoom in`,
zoomOut: t`Zoom out`,
@@ -1987,125 +617,75 @@ function MermaidInteractiveView({ svg }: { svg: string }) {
toolbar: t`Mermaid diagram controls`,
} as const;
- useEffect(() => {
- if (!svg.trim()) return;
- const svgElement = svgHostRef.current?.querySelector<SVGElement>('svg');
- if (svgElement?.namespaceURI !== 'http://www.w3.org/2000/svg') return;
-
- let disposed = false;
- let panzoom: PanzoomObject | null = null;
-
- loadPanzoom()
- .then((Panzoom) => {
- if (disposed) return;
-
- panzoom = Panzoom(svgElement, {
- canvas: true,
- cursor: 'default',
- maxScale: MERMAID_ZOOM_MAX,
- minScale: MERMAID_ZOOM_MIN,
- noBind: true,
- step: MERMAID_ZOOM_STEP,
- touchAction: 'auto',
- });
- panzoomRef.current = panzoom;
- })
- .catch((err) => {
- console.warn('[Mermaid] panzoom setup failed:', err);
- if (panzoomRef.current === panzoom) {
- panzoomRef.current = null;
- }
- });
-
- return () => {
- disposed = true;
- if (panzoomRef.current === panzoom) {
- panzoomRef.current = null;
- }
- panzoom?.destroy();
- };
- }, [svg]);
-
const panBy = (x: number, y: number) => {
panzoomRef.current?.pan(x, y, { relative: true });
};
return (
<div
- className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/20"
- contentEditable={false}
+ className="absolute right-3 bottom-3 grid grid-cols-3 gap-1"
+ data-testid="mermaid-actions"
+ role="toolbar"
+ aria-label={labels.toolbar}
>
- <div
- ref={svgHostRef}
- className="ok-mermaid-svg flex min-h-0 flex-1 items-center justify-center [&>svg]:size-full [&>svg]:select-none"
- // biome-ignore lint/security/noDangerouslySetInnerHtml: mermaid.render with securityLevel:'strict' returns a sanitized SVG string with no script execution; this is the documented integration path.
- dangerouslySetInnerHTML={{ __html: svg }}
- />
- <div
- className="absolute right-3 bottom-3 grid grid-cols-3 gap-1"
- data-testid="mermaid-actions"
- role="toolbar"
- aria-label={labels.toolbar}
+ <span aria-hidden="true" />
+ <Button
+ {...buttonProps}
+ title={labels.panUp}
+ aria-label={labels.panUp}
+ onClick={() => panBy(0, -MERMAID_PAN_STEP)}
>
- <span aria-hidden="true" />
- <Button
- {...buttonProps}
- title={labels.panUp}
- aria-label={labels.panUp}
- onClick={() => panBy(0, -MERMAID_PAN_STEP)}
- >
- <ArrowUp className="size-4" aria-hidden="true" />
- </Button>
- <Button
- {...buttonProps}
- title={labels.zoomIn}
- aria-label={labels.zoomIn}
- onClick={() => panzoomRef.current?.zoomIn()}
- >
- <ZoomIn className="size-4" aria-hidden="true" />
- </Button>
- <Button
- {...buttonProps}
- title={labels.panLeft}
- aria-label={labels.panLeft}
- onClick={() => panBy(-MERMAID_PAN_STEP, 0)}
- >
- <ArrowLeft className="size-4" aria-hidden="true" />
- </Button>
- <Button
- {...buttonProps}
- title={labels.reset}
- aria-label={labels.reset}
- onClick={() => panzoomRef.current?.reset()}
- >
- <RefreshCcw className="size-4" aria-hidden="true" />
- </Button>
- <Button
- {...buttonProps}
- title={labels.panRight}
- aria-label={labels.panRight}
- onClick={() => panBy(MERMAID_PAN_STEP, 0)}
- >
- <ArrowRight className="size-4" aria-hidden="true" />
- </Button>
- <span aria-hidden="true" />
- <Button
- {...buttonProps}
- title={labels.panDown}
- aria-label={labels.panDown}
- onClick={() => panBy(0, MERMAID_PAN_STEP)}
- >
- <ArrowDown className="size-4" aria-hidden="true" />
- </Button>
- <Button
- {...buttonProps}
- title={labels.zoomOut}
- aria-label={labels.zoomOut}
- onClick={() => panzoomRef.current?.zoomOut()}
- >
- <ZoomOut className="size-4" aria-hidden="true" />
- </Button>
- </div>
+ <ArrowUp className="size-4" aria-hidden="true" />
+ </Button>
+ <Button
+ {...buttonProps}
+ title={labels.zoomIn}
+ aria-label={labels.zoomIn}
+ onClick={() => panzoomRef.current?.zoomIn()}
+ >
+ <ZoomIn className="size-4" aria-hidden="true" />
+ </Button>
+ <Button
+ {...buttonProps}
+ title={labels.panLeft}
+ aria-label={labels.panLeft}
+ onClick={() => panBy(-MERMAID_PAN_STEP, 0)}
+ >
+ <ArrowLeft className="size-4" aria-hidden="true" />
+ </Button>
+ <Button
+ {...buttonProps}
+ title={labels.reset}
+ aria-label={labels.reset}
+ onClick={() => panzoomRef.current?.reset()}
+ >
+ <RefreshCcw className="size-4" aria-hidden="true" />
+ </Button>
+ <Button
+ {...buttonProps}
+ title={labels.panRight}
+ aria-label={labels.panRight}
+ onClick={() => panBy(MERMAID_PAN_STEP, 0)}
+ >
+ <ArrowRight className="size-4" aria-hidden="true" />
+ </Button>
+ <span aria-hidden="true" />
+ <Button
+ {...buttonProps}
+ title={labels.panDown}
+ aria-label={labels.panDown}
+ onClick={() => panBy(0, MERMAID_PAN_STEP)}
+ >
+ <ArrowDown className="size-4" aria-hidden="true" />
+ </Button>
+ <Button
+ {...buttonProps}
+ title={labels.zoomOut}
+ aria-label={labels.zoomOut}
+ onClick={() => panzoomRef.current?.zoomOut()}
+ >
+ <ZoomOut className="size-4" aria-hidden="true" />
+ </Button>
</div>
);
}
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index e774d1356..c39b16ce6 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -846,46 +846,6 @@
padding-bottom: var(--ask-composer-height, 0px);
}
-/* Mermaid label flash — the "this text just changed too" cue when a WYSIWYG
- label edit propagates to linked occurrences (e.g. a renamed sequence
- participant appears in its top AND bottom actor boxes). Same accent family
- as the agent flash (`--color-agent`), but a `filter` glow rather than the
- box-shadow/background agent-flash keyframes use — filter renders on SVG
- `<text>` (sequence actors/messages) as well as HTML label spans (flowchart
- nodes), where box-shadow/background do not. */
-@keyframes mermaid-label-flash {
- 0%,
- 100% {
- /* Unset paint at the ends so the element returns to its own base
- fill/color when the animation finishes. */
- filter: none;
- }
- 25% {
- /* Pulse the glyph paint itself to the agent accent — `fill` colors SVG
- `<tspan>` glyphs, `color` colors HTML labels (`.nodeLabel`/`.edgeLabel`).
- This is the loud, UNCLIPPED cue: an SVG `filter` drop-shadow on small
- `<text>` gets clipped by the default filter region and reads as nothing.
- The small glow is a bonus for HTML labels, where `filter` isn't clipped. */
- fill: var(--color-agent);
- color: var(--color-agent);
- filter: drop-shadow(0 0 4px var(--color-agent));
- }
-}
-.mermaid-label-flash {
- /* Two quick pulses (~1s total) read unmistakably as "this changed too",
- where a single slow fade went unnoticed. No `forwards` — the animation
- ends on its natural 100% (base paint), restoring the label. */
- animation: mermaid-label-flash 0.5s var(--ease-out-strong) 2;
-}
-@media (prefers-reduced-motion: reduce) {
- .mermaid-label-flash {
- /* Reduced cue: one slower color pulse — no repeated flashing, but
- reduce-motion users still get the "this changed too" signal (a color
- fade, not vestibular motion). */
- animation: mermaid-label-flash 0.9s var(--ease-out-strong) 1;
- }
-}
-
/* Conflict-mode DiffView scroller: same composer inset so the last hunks (and
their inline Accept/Reject controls) can scroll clear of the floating
composer. The content-side padding rule lives next to the
@@ -5384,3 +5344,69 @@ html.electron-mode [data-slot="sidebar-inner"] {
.inline-code {
@apply font-mono bg-muted text-inherit border border-border rounded-md px-1 py-0.5 text-sm;
}
+
+/* Mermaid WYSIWYG canvas (`mermaid-wysiwyg` package). The package injects its
+ own `<style data-mw>` at runtime with `--mw-*` custom-property hooks for all
+ interaction chrome (selection glow, popovers, in-place editors, plus-menus).
+ Map those hooks onto OK's design tokens, and pin the SVG host back to the
+ exact pre-package layout (centered, filling, non-selectable) so the rendered
+ diagram is pixel-identical to the previous DIY renderer. Selectors ride on
+ `.ok-mermaid-svg.mw-canvas` — two classes out-specify every single-class
+ rule in the runtime-injected sheet regardless of load order. */
+.ok-mermaid-svg.mw-canvas {
+ --mw-accent: var(--ring);
+ --mw-chrome-bg: var(--popover);
+ --mw-chrome-border: var(--border);
+ --mw-chrome-hover: var(--accent);
+ --mw-chrome-fg: var(--popover-foreground);
+ --mw-chrome-dim: var(--muted-foreground);
+ --mw-editor-bg: var(--background);
+ /* Package default is `overflow: auto`; OK pans/zooms the SVG in place. */
+ overflow: hidden;
+}
+.ok-mermaid-svg.mw-canvas .mw-svg-host {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+}
+.ok-mermaid-svg.mw-canvas .mw-svg-host > svg {
+ width: 100%;
+ height: 100%;
+ user-select: none;
+ -webkit-user-select: none;
+}
+/* Mid-edit parse failures keep the last good diagram on canvas; restyle the
+ package's red badge to OK's destructive banner language. */
+.ok-mermaid-svg.mw-canvas .mw-error-badge {
+ background: var(--background);
+ color: var(--destructive);
+ border: 1px solid color-mix(in srgb, var(--destructive) 30%, transparent);
+ box-shadow: none;
+}
+/* Selection / hover / connect chrome: the package defaults to a stacked
+ drop-shadow bloom, which with OK's near-white `--ring` accent reads as a
+ blown-out halo on dark canvases (and puts a glow on text glyphs while
+ editing). Replace with a single tight edge tint. `!important` is required
+ to beat the package's own `!important` on `.mw-selected`. */
+.ok-mermaid-svg.mw-canvas [data-mw-entity]:hover {
+ filter: drop-shadow(0 0 1px color-mix(in srgb, var(--mw-accent) 55%, transparent));
+}
+.ok-mermaid-svg.mw-canvas .mw-selected,
+.ok-mermaid-svg.mw-canvas .mw-connect-source {
+ /* biome-ignore lint/complexity/noImportantStyles: the package's injected `.mw-selected` rule is itself `!important`; matching importance is the only way to replace its stacked-bloom filter. */
+ filter: drop-shadow(0 0 1.25px var(--mw-accent)) !important;
+}
+/* In-place label editing shows the caret only — no outline, no underline, no
+ backdrop — matching how the previous inline editor read as "the label just
+ became typeable". */
+.ok-mermaid-svg.mw-canvas [contenteditable="true"] {
+ outline: none;
+ box-shadow: none;
+}
+.ok-mermaid-svg.mw-canvas .mw-inplace-editor {
+ box-shadow: none;
+ background: transparent;
+}
diff --git a/patches/@inkeep%[email protected] b/patches/@inkeep%[email protected]
new file mode 100644
index 000000000..239ea25b0
--- /dev/null
+++ b/patches/@inkeep%[email protected]
@@ -0,0 +1,33 @@
+diff --git a/dist/index.js b/dist/index.js
+index 7bb142de61632addf365b5ad2416957f29a38016..516af0a3d480b0171f2bc99b5f0e28929e35f90a 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -1317,13 +1317,17 @@ var MermaidCanvasView = class {
+ findTextTarget(anchor, current) {
+ const isLeafText = (el) => (el.tagName === "text" || el.tagName === "SPAN" || el.tagName === "P" || el.tagName === "DIV" || el.tagName === "tspan") && (el.children.length === 0 || el.tagName === "text") && (el.textContent?.trim().length ?? 0) > 0;
+ if (isLeafText(anchor)) return anchor;
+- const leaves = [...anchor.querySelectorAll("text, tspan, span, p, div")].filter(isLeafText);
++ let leaves = [...anchor.querySelectorAll("text, tspan, span, p, div")].filter(isLeafText);
++ if (!leaves.length && anchor.parentElement) {
++ leaves = [...anchor.parentElement.querySelectorAll("text, tspan, span, p, div")].filter(isLeafText);
++ }
+ return leaves.find((el) => el.textContent?.trim() === current.trim()) ?? leaves.find((el) => current.trim().startsWith(el.textContent?.trim() ?? "\0")) ?? leaves[0] ?? anchor;
+ }
+ openOverlayEditor(anchor, current, commitValue) {
+ anchor = this.findTextTarget(anchor, current);
+ const box = this.hostRect(anchor);
+- const cs = window.getComputedStyle(anchor);
++ const paintSource = anchor.querySelector("tspan") ?? anchor;
++ const cs = window.getComputedStyle(paintSource);
+ const div = document.createElement("div");
+ div.className = "mw-inplace-editor";
+ div.contentEditable = "true";
+@@ -1339,7 +1343,7 @@ var MermaidCanvasView = class {
+ div.style.fontWeight = cs.fontWeight;
+ div.style.fontSize = cs.fontSize;
+ div.style.fontFamily = cs.fontFamily;
+- const fill = cs.fill && cs.fill !== "none" && anchor instanceof SVGElement ? cs.fill : cs.color;
++ const fill = cs.fill && cs.fill !== "none" && paintSource instanceof SVGElement ? cs.fill : cs.color;
+ div.style.color = fill || "inherit";
+ this.overlayHost.appendChild(div);
+ this.inlineInput = div;
diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjs
index 8831664f7..3e9c04d0a 100644
--- a/scripts/generate-third-party-notices.mjs
+++ b/scripts/generate-third-party-notices.mjs
@@ -245,6 +245,17 @@ function readNoticeText(pkgDir) {
* Keep this list small and audited — every entry should cite the LICENSE
* file path that proved the override at the time of inclusion.
*/
+/**
+ * Inkeep first-party packages consumed from npm rather than the workspace.
+ * They ship under the same GPL-3.0-or-later license as OpenKnowledge itself,
+ * so they are not third-party audit surface — list them in their own section
+ * instead of the fail-closed audit bucket.
+ */
+const FIRST_PARTY_GPL_PACKAGES = new Set([
+ '@inkeep/mermaid-wysiwyg-core',
+ '@inkeep/mermaid-wysiwyg-dom',
+]);
+
const SPDX_OVERRIDES = {
// khroma's package.json has no `license` field, but `node_modules/khroma/license`
// contains the MIT permission notice ("The MIT License (MIT) ...").
@@ -695,7 +706,7 @@ function build() {
if (seenKeys.has(key)) continue;
seenKeys.add(key);
const spdx = normalizeSpdx(pkg.license || pkg.licenses, pkg.name);
- const category = categorize(spdx);
+ const category = FIRST_PARTY_GPL_PACKAGES.has(pkg.name) ? 'FIRST_PARTY_GPL' : categorize(spdx);
const entry = {
pkg,
dir,
@@ -909,6 +920,19 @@ function build() {
hr();
}
+ // Inkeep first-party packages (same license as this repository).
+ if (grouped.has('FIRST_PARTY_GPL')) {
+ push('## Inkeep first-party packages (GPL-3.0-or-later)', '');
+ push(
+ 'The packages below are authored and published by Inkeep and are licensed under GPL-3.0-or-later, the same license as OpenKnowledge itself (see the repository LICENSE for the full text). They are listed for completeness; they are not third-party material.',
+ '',
+ );
+ for (const e of grouped.get('FIRST_PARTY_GPL')) {
+ push(shortEntry(e), '');
+ }
+ hr();
+ }
+
// Patched deps
push('## Patched dependencies', '');
push(