Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): click Mermaid text to edit it in place (#2354)

Abraham541c8ef04941
diff --git a/packages/app/src/editor/components/Mermaid.test.tsx b/packages/app/src/editor/components/Mermaid.test.tsx
index 5ad2f912c..ac6125be7 100644
--- a/packages/app/src/editor/components/Mermaid.test.tsx
+++ b/packages/app/src/editor/components/Mermaid.test.tsx
@@ -1,6 +1,15 @@
import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
-import { MermaidView } from './Mermaid.tsx';
+import {
+ extractEdgeInfo,
+ extractSourceNodeId,
+ findEdgeLabelInSource,
+ findLabelInSource,
+ findSequenceMessageInSource,
+ MermaidView,
+ rewriteSequenceParticipant,
+ spliceNewLabel,
+} from './Mermaid.tsx';
describe('MermaidView — placeholder branch', () => {
test('empty chart renders the placeholder shell', () => {
@@ -26,3 +35,281 @@ describe('MermaidView — pre-render mount state', () => {
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', () => {
+ 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', () => {
+ 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', () => {
+ 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');
+ 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', () => {
+ 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', () => {
+ 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', () => {
+ 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');
+ 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', () => {
+ 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', () => {
+ 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');
+ expect(out).toContain('participant Author as Alice');
+ expect(out).toContain('Author->>Bob: hi');
+ });
+
+ test('bare + display with whitespace forces quoted alias', () => {
+ const src = 'sequenceDiagram\n participant Author\n';
+ const out = rewriteSequenceParticipant(src, 'Author', 'Alice Smith');
+ expect(out).toContain('participant Author as "Alice Smith"');
+ });
+
+ 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` replaces in place, adds quotes for special chars', () => {
+ const src = 'sequenceDiagram\n participant A as Author\n';
+ const out = rewriteSequenceParticipant(src, 'Author', 'Two Words');
+ expect(out).toContain('participant A as "Two Words"');
+ });
+
+ 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();
+ });
+});
diff --git a/packages/app/src/editor/components/Mermaid.tsx b/packages/app/src/editor/components/Mermaid.tsx
index 85ab8c775..aa7edf666 100644
--- a/packages/app/src/editor/components/Mermaid.tsx
+++ b/packages/app/src/editor/components/Mermaid.tsx
@@ -1,6 +1,7 @@
import { Trans } from '@lingui/react/macro';
import { AlertTriangle } from 'lucide-react';
-import { useEffect, useId, useState } from 'react';
+import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { useJsxComponentHost } from './jsx-host-context.tsx';
interface MermaidProps {
chart?: string;
@@ -32,11 +33,243 @@ function loadMermaid() {
return mermaidPromise;
}
+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;
+}
+
+export function findLabelInSource(
+ source: string,
+ nodeId: string,
+ currentLabel: string,
+): LabelMatch | null {
+ for (const { open, close } of SHAPES) {
+ 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;
+ 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 {
+ return /[[\](){}|;#<>&\n"]/.test(label);
+}
+
+export function spliceNewLabel(source: string, match: LabelMatch, newLabel: string): string {
+ const shouldQuote = match.wasQuoted || (match.open !== '' && labelNeedsQuoting(newLabel));
+ const escaped = newLabel.replace(/"/g, '#quot;');
+ const replacement = shouldQuote ? `"${escaped}"` : newLabel;
+ return source.slice(0, match.start) + replacement + source.slice(match.end);
+}
+
+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;
+}
+
+export function extractEdgeInfo(dataId: string): EdgeInfo | null {
+ 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,
+ };
+}
+
+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);
+ const arrowHead = '(?:-->|==>|-\\.->|~~~>|<--)';
+ const arrowBody = '(?:--|==|-\\.|~~~)';
+ const patterns: { re: RegExp; quoted: boolean; groupIndex: number }[] = [
+ {
+ re: new RegExp(`${f}\\s*${arrowBody}[->=]*\\s*\\|\\s*("${l}")\\s*\\|\\s*${t}`, 'gd'),
+ quoted: true,
+ groupIndex: 1,
+ },
+ {
+ re: new RegExp(`${f}\\s*${arrowBody}[->=]*\\s*\\|\\s*(${l})\\s*\\|\\s*${t}`, 'gd'),
+ quoted: false,
+ groupIndex: 1,
+ },
+ {
+ re: new RegExp(`${f}\\s*${arrowBody}\\s*("${l}")\\s*${arrowHead}\\s*${t}`, 'gd'),
+ quoted: true,
+ groupIndex: 1,
+ },
+ {
+ re: new RegExp(`${f}\\s*${arrowBody}\\s*(${l})\\s*${arrowHead}\\s*${t}`, 'gd'),
+ quoted: false,
+ groupIndex: 1,
+ },
+ ];
+ 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: '' };
+}
+
+export function findSequenceMessageInSource(
+ source: string,
+ currentMessage: string,
+ occurrence = 0,
+): LabelMatch | null {
+ const esc = currentMessage.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ 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;
+}
+
+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)';
+
+ const rQuoted = new RegExp(`^([ \\t]*${kw}[ \\t]+\\S+[ \\t]+as[ \\t]+")${esc}(")`, 'gm');
+ const mQuoted = findMatch(rQuoted, (m) => `${m[1]}${escapedNew}${m[2]}`);
+ if (mQuoted)
+ return source.slice(0, mQuoted.range[0]) + mQuoted.replacement + source.slice(mQuoted.range[1]);
+
+ const rUnquoted = new RegExp(`^([ \\t]*${kw}[ \\t]+\\S+[ \\t]+as[ \\t]+)${esc}([ \\t]*)$`, 'gm');
+ const mUnquoted = findMatch(rUnquoted, (m) => {
+ const needsQuote = /[\s"#|;<>&]/.test(newDisplay);
+ const rendered = needsQuote ? `"${escapedNew}"` : newDisplay;
+ return `${m[1]}${rendered}${m[2]}`;
+ });
+ if (mUnquoted)
+ return (
+ source.slice(0, mUnquoted.range[0]) + mUnquoted.replacement + source.slice(mUnquoted.range[1])
+ );
+
+ const rBare = new RegExp(`^([ \\t]*${kw}[ \\t]+)${esc}([ \\t]*)$`, 'gm');
+ const mBare = findMatch(rBare, (m) => {
+ const needsQuote = /[^\w]/.test(newDisplay);
+ const rendered = needsQuote ? `"${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;
+}
+
export function MermaidView(props: MermaidProps) {
const chart = props.chart ?? '';
const reactId = useId();
const renderId = `mermaid-${reactId.replace(/:/g, '_')}`;
const [state, setState] = useState<RenderState>({ status: 'idle', svg: '', error: '' });
+ const host = useJsxComponentHost();
+ const canEdit = host?.editor.isEditable ?? false;
+ const containerRef = useRef<HTMLDivElement>(null);
+ const hostRef = useRef(host);
+ useLayoutEffect(() => {
+ hostRef.current = host;
+ }, [host]);
+ const editSessionRef = useRef<{ cleanup: () => void } | null>(null);
useEffect(() => {
if (!chart.trim()) {
@@ -63,6 +296,339 @@ export function MermaidView(props: MermaidProps) {
};
}, [chart, renderId]);
+ useEffect(() => {
+ if (state.status !== 'ready') return;
+ if (!canEdit) return;
+ const container = containerRef.current;
+ if (!container) return;
+
+ for (const label of container.querySelectorAll<HTMLElement>('.nodeLabel, .edgeLabel')) {
+ label.style.cursor = 'text';
+ }
+ for (const label of container.querySelectorAll<SVGTextElement>(
+ 'text.messageText, text.actor',
+ )) {
+ label.style.cursor = 'text';
+ label.style.pointerEvents = 'all';
+ }
+
+ function commitLabelChangeGeneric(target: EditTarget, newLabel: string): void {
+ const h = hostRef.current;
+ if (!h) return;
+ const pos = h.getPos();
+ if (typeof pos !== 'number') return;
+ const node = h.editor.state.doc.nodeAt(pos);
+ if (!node || node.type.name !== 'jsxComponent') return;
+ const currentProps = (node.attrs.props as Record<string, unknown>) ?? {};
+ const chartNow = (currentProps.chart as string) ?? '';
+ 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;
+ try {
+ h.editor.view.dispatch(
+ h.editor.state.tr.setNodeMarkup(pos, null, {
+ ...node.attrs,
+ props: { ...currentProps, chart: newChart },
+ sourceDirty: true,
+ }),
+ );
+ } catch (err) {
+ if (!(err instanceof RangeError)) throw err;
+ }
+ }
+
+ interface EditTarget {
+ labelSpan: HTMLElement;
+ outlineShape: SVGElement | null;
+ positionAnchor?: Element;
+ applyRewrite?: (chartNow: string, newLabel: string) => string | null;
+ locate?: (chartNow: string) => LabelMatch | null;
+ }
+
+ function tryEnterEditWithTarget(target: EditTarget, event: MouseEvent): boolean {
+ const { labelSpan, outlineShape } = target;
+ const h = hostRef.current;
+ if (!h) return false;
+ const pos = h.getPos();
+ if (typeof pos !== 'number') return false;
+ const pmNode = h.editor.state.doc.nodeAt(pos);
+ if (!pmNode || pmNode.type.name !== 'jsxComponent') return false;
+ const currentChart = ((pmNode.attrs.props as Record<string, unknown>)?.chart as string) ?? '';
+ const currentLabel = (labelSpan.textContent ?? '').trim();
+ if (!currentLabel) return false;
+ const rewriteHit = target.applyRewrite?.(currentChart, currentLabel);
+ const locateHit = target.locate?.(currentChart);
+ if (!locateHit && rewriteHit == null) return false;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const labelP = (labelSpan.querySelector('p') ?? labelSpan) as HTMLElement;
+ const labelStyles = window.getComputedStyle(labelP);
+ const svgTextColor = ((): string | null => {
+ if (!(labelP instanceof SVGGraphicsElement)) return null;
+ const tspan = labelP.querySelector('tspan');
+ const fill = tspan
+ ? window.getComputedStyle(tspan).fill
+ : window.getComputedStyle(labelP).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;
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.value = currentLabel;
+ input.setAttribute('data-mermaid-editing', 'true');
+ input.setAttribute('spellcheck', 'true');
+ Object.assign(input.style, {
+ position: 'fixed',
+ margin: '0',
+ padding: '0',
+ font: labelStyles.font,
+ fontFeatureSettings: labelStyles.fontFeatureSettings,
+ letterSpacing: labelStyles.letterSpacing,
+ color: inputColor,
+ textAlign: 'center',
+ border: 'none',
+ outline: 'none',
+ boxShadow: 'none',
+ boxSizing: 'border-box',
+ colorScheme: 'light',
+ appearance: 'none',
+ WebkitAppearance: 'none',
+ caretColor: inputColor,
+ zIndex: '2147483647',
+ });
+ input.style.setProperty('background', 'transparent', 'important');
+ input.style.setProperty('background-color', 'transparent', 'important');
+ if (nodeShape) {
+ nodeShape.setAttribute('stroke', 'var(--ring, #3b82f6)');
+ nodeShape.setAttribute('stroke-width', '2');
+ }
+ const prevLabelVisibility = labelP.style.visibility;
+ labelP.style.visibility = 'hidden';
+
+ document.body.appendChild(input);
+ const anchor: Element = target.positionAnchor ?? labelP;
+ function positionInput(): void {
+ const r = anchor.getBoundingClientRect();
+ input.style.left = `${r.left}px`;
+ input.style.top = `${r.top}px`;
+ input.style.width = `${r.width}px`;
+ input.style.height = `${r.height}px`;
+ input.style.lineHeight = `${r.height}px`;
+ }
+ positionInput();
+ const focusRafHandle = requestAnimationFrame(() => {
+ input.focus();
+ input.select();
+ });
+
+ window.addEventListener('scroll', positionInput, true);
+ window.addEventListener('resize', positionInput);
+
+ let done = false;
+ function cleanup(): void {
+ cancelAnimationFrame(focusRafHandle);
+ window.removeEventListener('scroll', positionInput, true);
+ window.removeEventListener('resize', positionInput);
+ input.removeEventListener('keydown', onKeyDown);
+ input.removeEventListener('blur', onBlur);
+ input.remove();
+ 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.shiftKey) {
+ ev.preventDefault();
+ ev.stopPropagation();
+ commit();
+ return;
+ }
+ ev.stopPropagation();
+ }
+ function onBlur(): void {
+ commit();
+ }
+ input.addEventListener('keydown', onKeyDown);
+ input.addEventListener('blur', onBlur);
+ editSessionRef.current = {
+ cleanup: () => {
+ if (!done) discard();
+ },
+ };
+ return true;
+ }
+
+ 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;
+ tryEnterEditWithTarget(
+ {
+ labelSpan: nodeLabelSpan,
+ outlineShape: nodeGroup.querySelector<SVGElement>(
+ 'rect, polygon, path, circle, ellipse',
+ ),
+ locate: (chartNow) => findLabelInSource(chartNow, nodeId, currentLabel),
+ },
+ event,
+ );
+ return;
+ }
+
+ const actorText = target.closest<SVGTextElement>('text.actor');
+ if (actorText) {
+ 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;
+ }
+ if ((el.textContent ?? '').trim() === currentDisplay) seen += 1;
+ }
+ }
+ const actorGroup = actorText.parentElement;
+ const rectSibling =
+ actorGroup?.querySelector<SVGGraphicsElement>('rect.actor') ?? actorGroup;
+ tryEnterEditWithTarget(
+ {
+ labelSpan: actorText as unknown as HTMLElement,
+ outlineShape: null,
+ positionAnchor: rectSibling ?? undefined,
+ applyRewrite: (chartNow, newLabel) =>
+ rewriteSequenceParticipant(chartNow, currentDisplay, newLabel, occurrence),
+ },
+ event,
+ );
+ return;
+ }
+
+ const messageText = target.closest<SVGTextElement>('text.messageText');
+ if (messageText) {
+ 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) {
+ 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,
+ outlineShape: null,
+ locate: (chartNow) =>
+ findEdgeLabelInSource(chartNow, info.from, info.to, info.index, currentLabel),
+ },
+ event,
+ );
+ }
+ }
+
+ function onLabelMouseDown(event: MouseEvent): void {
+ const t = event.target;
+ if (!(t instanceof Element)) return;
+ if (!t.closest('.nodeLabel, .edgeLabel, text.messageText, text.actor')) 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')) return;
+ event.stopPropagation();
+ onLabelClick(event);
+ }
+
+ container.addEventListener('mousedown', onLabelMouseDown, { capture: true });
+ container.addEventListener('click', onLabelClickCapture, { capture: true });
+ return () => {
+ container.removeEventListener('mousedown', onLabelMouseDown, { capture: true });
+ container.removeEventListener('click', onLabelClickCapture, { capture: true });
+ editSessionRef.current?.cleanup();
+ editSessionRef.current = null;
+ };
+ }, [state.status, canEdit]);
+
if (!chart.trim()) {
return (
<div className="mermaid mermaid-placeholder" data-component-type="mermaid">
@@ -97,6 +663,7 @@ export function MermaidView(props: MermaidProps) {
return (
<div
+ ref={containerRef}
className={`mermaid mermaid-${state.status}`}
data-component-type="mermaid"
// 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.