@fabrika/canvas-kernel 0.1.44 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +33 -67
  2. package/index.ts +19 -83
  3. package/package.json +68 -72
  4. package/src/client/AnnotationProvider.tsx +227 -268
  5. package/src/client/AnnotationSidebar.tsx +392 -338
  6. package/src/client/FileIcon.tsx +106 -65
  7. package/src/client/PlanRenderer.tsx +607 -551
  8. package/src/client/RenderErrorContext.ts +7 -7
  9. package/src/client/ResponsePreview.tsx +192 -173
  10. package/src/client/annotationDom.ts +43 -97
  11. package/src/client/annotationDraft.ts +98 -92
  12. package/src/client/appContext.tsx +40 -40
  13. package/src/client/components/Callout.tsx +20 -20
  14. package/src/client/components/Checklist.tsx +28 -28
  15. package/src/client/components/Choice.tsx +178 -159
  16. package/src/client/components/CodeBlock.tsx +26 -26
  17. package/src/client/components/Diff.tsx +17 -17
  18. package/src/client/components/FilePreview.tsx +99 -74
  19. package/src/client/components/Image.tsx +41 -39
  20. package/src/client/components/Markdown.tsx +33 -32
  21. package/src/client/components/Mermaid.tsx +592 -542
  22. package/src/client/components/Note.tsx +8 -8
  23. package/src/client/components/Priority.tsx +11 -11
  24. package/src/client/components/ResponseNote.tsx +17 -15
  25. package/src/client/components/Section.tsx +28 -26
  26. package/src/client/components/Table.tsx +34 -29
  27. package/src/client/components/Task.tsx +58 -60
  28. package/src/client/components/UserInput.tsx +169 -152
  29. package/src/client/components/index.ts +16 -16
  30. package/src/client/components/renderMarkdownChildren.tsx +86 -68
  31. package/src/client/diffLines.ts +51 -39
  32. package/src/client/generateMarkdown.ts +197 -191
  33. package/src/client/hostContext.tsx +34 -34
  34. package/src/client/index.ts +43 -125
  35. package/src/client/preact-all.ts +4 -4
  36. package/src/client/runtime.ts +58 -111
  37. package/src/client/styles.css +1 -74
  38. package/src/engine/compiler.ts +316 -313
  39. package/src/engine/paths.ts +44 -44
  40. package/src/engine/session.ts +623 -618
  41. package/src/engine/watcher.ts +63 -60
  42. package/src/engine/websocket.ts +123 -121
  43. package/annotate.ts +0 -94
  44. package/daemon.ts +0 -46
  45. package/src/client/AnnotationDraftFooter.tsx +0 -76
  46. package/src/client/AnnotationEditor.tsx +0 -320
  47. package/src/client/AnnotationList.tsx +0 -190
  48. package/src/client/Popover.tsx +0 -361
  49. package/src/client/SessionContext.tsx +0 -3
  50. package/src/client/annotationContext.ts +0 -130
  51. package/src/client/annotationMarkdown.ts +0 -102
  52. package/src/client/annotationTarget.ts +0 -73
  53. package/src/client/blockTarget.ts +0 -127
  54. package/src/client/highlightRange.ts +0 -262
  55. package/src/client/popoverPosition.ts +0 -46
  56. package/src/client/regionTarget.ts +0 -180
  57. package/src/client/testing/dom.ts +0 -58
  58. package/src/client/textTarget.ts +0 -31
  59. package/src/client/useRegionAnnotation.tsx +0 -188
  60. package/src/client/useTextAnnotation.tsx +0 -194
  61. package/src/client/utils.ts +0 -33
  62. package/src/engine/channel.ts +0 -278
  63. package/src/engine/http-utils.ts +0 -14
  64. package/src/engine/lifecycle.ts +0 -302
  65. package/src/engine/router.ts +0 -16
  66. package/src/engine/waiter.ts +0 -188
@@ -1,576 +1,626 @@
1
- import React, { useEffect, useRef, useState, useCallback } from "react";
2
- import ReactDOM from "react-dom";
3
- import { useAnnotations, useCanvasFile } from "#canvas/runtime";
4
- import type { Annotation } from "#canvas/runtime";
5
- import { AnnotationCreatePopover } from "../Popover";
1
+ // biome-ignore-all lint/security/noDangerouslySetInnerHtml: Canvas modules already execute as code in this document.
2
+ import { useAnnotations, useCanvasFile } from '#canvas/runtime'
3
+ import type { Annotation } from '#canvas/runtime'
4
+ import { AnnotationCreatePopover } from '@fabrika/annotations'
5
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
6
+ import ReactDOM from 'react-dom'
6
7
 
7
8
  interface MermaidProps {
8
- children?: React.ReactNode;
9
+ children?: React.ReactNode
9
10
  }
10
11
 
11
12
  interface NodePopoverState {
12
- anchorEl: HTMLElement;
13
- snippet: string;
14
- prefix: string;
13
+ anchorEl: HTMLElement
14
+ snippet: string
15
+ prefix: string
15
16
  }
16
17
 
17
- const ZOOM_STEP = 0.2;
18
- const ZOOM_MIN = 0.25;
19
- const ZOOM_MAX = 4;
18
+ const ZOOM_STEP = 0.2
19
+ const ZOOM_MIN = 0.25
20
+ const ZOOM_MAX = 4
20
21
 
21
22
  /** The wheel fields React's synthetic event and Preact's native one both carry.
22
23
  * Named structurally because preact/compat aliases no `React.WheelEvent`, and
23
24
  * a handler taking less than the event supplies is accepted by either. */
24
25
  interface WheelLike {
25
- deltaY: number;
26
- ctrlKey: boolean;
27
- metaKey: boolean;
28
- preventDefault(): void;
26
+ deltaY: number
27
+ ctrlKey: boolean
28
+ metaKey: boolean
29
+ preventDefault(): void
29
30
  }
30
31
 
31
32
  function ZoomToolbar({ zoom, onZoomIn, onZoomOut, onZoomReset, onFullscreen }: {
32
- zoom: number;
33
- onZoomIn: () => void;
34
- onZoomOut: () => void;
35
- onZoomReset: () => void;
36
- onFullscreen?: () => void;
33
+ zoom: number
34
+ onZoomIn: () => void
35
+ onZoomOut: () => void
36
+ onZoomReset: () => void
37
+ onFullscreen?: () => void
37
38
  }) {
38
- const btnClass = "flex items-center justify-center w-7 h-7 rounded hover:bg-bg-elevated text-text-secondary hover:text-text-primary transition-colors";
39
- return (
40
- <div className="flex items-center gap-0.5 bg-bg-surface border border-border-subtle rounded-md px-1 py-0.5" style={{ fontSize: "12px" }}>
41
- <button className={btnClass} onClick={onZoomOut} title="Zoom out" disabled={zoom <= ZOOM_MIN}>
42
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="5" y1="12" x2="19" y2="12"/></svg>
43
- </button>
44
- <button className="px-1.5 h-7 rounded hover:bg-bg-elevated text-text-tertiary hover:text-text-primary transition-colors tabular-nums" onClick={onZoomReset} title="Reset zoom">
45
- {Math.round(zoom * 100)}%
46
- </button>
47
- <button className={btnClass} onClick={onZoomIn} title="Zoom in" disabled={zoom >= ZOOM_MAX}>
48
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
49
- </button>
50
- {onFullscreen && (
51
- <>
52
- <div className="w-px h-4 bg-border-subtle mx-0.5" />
53
- <button className={btnClass} onClick={onFullscreen} title="Fullscreen">
54
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
55
- </button>
56
- </>
57
- )}
58
- </div>
59
- );
39
+ const btnClass =
40
+ 'flex items-center justify-center w-7 h-7 rounded hover:bg-bg-elevated text-text-secondary hover:text-text-primary transition-colors'
41
+ return (
42
+ <div className="flex items-center gap-0.5 bg-bg-surface border border-border-subtle rounded-md px-1 py-0.5" style={{ fontSize: '12px' }}>
43
+ <button className={btnClass} onClick={onZoomOut} title="Zoom out" disabled={zoom <= ZOOM_MIN}>
44
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
45
+ <line x1="5" y1="12" x2="19" y2="12" />
46
+ </svg>
47
+ </button>
48
+ <button
49
+ className="px-1.5 h-7 rounded hover:bg-bg-elevated text-text-tertiary hover:text-text-primary transition-colors tabular-nums"
50
+ onClick={onZoomReset}
51
+ title="Reset zoom"
52
+ >
53
+ {Math.round(zoom * 100)}%
54
+ </button>
55
+ <button className={btnClass} onClick={onZoomIn} title="Zoom in" disabled={zoom >= ZOOM_MAX}>
56
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
57
+ <line x1="12" y1="5" x2="12" y2="19" />
58
+ <line x1="5" y1="12" x2="19" y2="12" />
59
+ </svg>
60
+ </button>
61
+ {onFullscreen && (
62
+ <>
63
+ <div className="w-px h-4 bg-border-subtle mx-0.5" />
64
+ <button className={btnClass} onClick={onFullscreen} title="Fullscreen">
65
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
66
+ <polyline points="15 3 21 3 21 9" />
67
+ <polyline points="9 21 3 21 3 15" />
68
+ <line x1="21" y1="3" x2="14" y2="10" />
69
+ <line x1="3" y1="21" x2="10" y2="14" />
70
+ </svg>
71
+ </button>
72
+ </>
73
+ )}
74
+ </div>
75
+ )
60
76
  }
61
77
 
62
78
  function useZoom(initialZoom = 1) {
63
- const [zoom, setZoom] = useState(initialZoom);
64
- const zoomIn = useCallback(() => setZoom(z => Math.min(ZOOM_MAX, +(z + ZOOM_STEP).toFixed(2))), []);
65
- const zoomOut = useCallback(() => setZoom(z => Math.max(ZOOM_MIN, +(z - ZOOM_STEP).toFixed(2))), []);
66
- const zoomReset = useCallback(() => setZoom(1), []);
67
- return { zoom, zoomIn, zoomOut, zoomReset, setZoom };
79
+ const [zoom, setZoom] = useState(initialZoom)
80
+ const zoomIn = useCallback(() => setZoom(z => Math.min(ZOOM_MAX, +(z + ZOOM_STEP).toFixed(2))), [])
81
+ const zoomOut = useCallback(() => setZoom(z => Math.max(ZOOM_MIN, +(z - ZOOM_STEP).toFixed(2))), [])
82
+ const zoomReset = useCallback(() => setZoom(1), [])
83
+ return { zoom, zoomIn, zoomOut, zoomReset, setZoom }
68
84
  }
69
85
 
70
86
  function MermaidFullscreenModal({ svgHtml, source, onClose }: {
71
- svgHtml: string;
72
- source: string;
73
- onClose: () => void;
87
+ svgHtml: string
88
+ source: string
89
+ onClose: () => void
74
90
  }) {
75
- const modalContentRef = useRef<HTMLDivElement>(null);
76
- const { zoom, zoomIn, zoomOut, zoomReset, setZoom } = useZoom(1);
77
- const [pan, setPan] = useState({ x: 0, y: 0 });
78
- const dragging = useRef<{ startX: number; startY: number; panX: number; panY: number } | null>(null);
79
-
80
- useEffect(() => {
81
- const onKeyDown = (e: KeyboardEvent) => {
82
- if (e.key === "Escape") onClose();
83
- };
84
- window.addEventListener("keydown", onKeyDown);
85
- return () => window.removeEventListener("keydown", onKeyDown);
86
- }, [onClose]);
87
-
88
- // Wheel zoom
89
- const handleWheel = useCallback((e: WheelLike) => {
90
- e.preventDefault();
91
- const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
92
- setZoom(z => Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, +(z + delta).toFixed(2))));
93
- }, [setZoom]);
94
-
95
- // Pan via mouse drag
96
- const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
97
- if (e.button !== 0) return;
98
- dragging.current = { startX: e.clientX, startY: e.clientY, panX: pan.x, panY: pan.y };
99
- e.preventDefault();
100
- }, [pan]);
101
-
102
- const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
103
- if (!dragging.current) return;
104
- setPan({
105
- x: dragging.current.panX + (e.clientX - dragging.current.startX),
106
- y: dragging.current.panY + (e.clientY - dragging.current.startY),
107
- });
108
- }, []);
109
-
110
- const handleMouseUp = useCallback(() => {
111
- dragging.current = null;
112
- }, []);
113
-
114
- const handleResetView = useCallback(() => {
115
- zoomReset();
116
- setPan({ x: 0, y: 0 });
117
- }, [zoomReset]);
118
-
119
- return ReactDOM.createPortal(
120
- <div
121
- style={{ position: "fixed", inset: 0, zIndex: 9999, background: "var(--color-bg-base)", display: "flex", flexDirection: "column" }}
122
- onMouseMove={handleMouseMove}
123
- onMouseUp={handleMouseUp}
124
- onMouseLeave={handleMouseUp}
125
- >
126
- {/* Header bar */}
127
- <div className="flex items-center justify-between px-4 py-2 border-b border-border-subtle" style={{ flexShrink: 0, background: "var(--color-bg-surface)" }}>
128
- <span className="text-body text-text-secondary" style={{ fontSize: "13px" }}>Mermaid Diagram</span>
129
- <div className="flex items-center gap-2">
130
- <ZoomToolbar zoom={zoom} onZoomIn={zoomIn} onZoomOut={zoomOut} onZoomReset={handleResetView} />
131
- <button
132
- className="flex items-center justify-center w-8 h-8 rounded hover:bg-bg-elevated text-text-secondary hover:text-text-primary transition-colors"
133
- onClick={onClose}
134
- title="Close (Esc)"
135
- >
136
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
137
- </button>
138
- </div>
139
- </div>
140
- {/* Diagram area */}
141
- <div
142
- style={{ flex: 1, overflow: "hidden", cursor: dragging.current ? "grabbing" : "grab" }}
143
- onWheel={handleWheel}
144
- onMouseDown={handleMouseDown}
145
- >
146
- <div
147
- ref={modalContentRef}
148
- style={{
149
- width: "100%",
150
- height: "100%",
151
- display: "flex",
152
- alignItems: "center",
153
- justifyContent: "center",
154
- transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
155
- transformOrigin: "center center",
156
- transition: dragging.current ? "none" : "transform 0.1s ease-out",
157
- }}
158
- dangerouslySetInnerHTML={{ __html: svgHtml }}
159
- />
160
- </div>
161
- </div>,
162
- document.body,
163
- );
91
+ const modalContentRef = useRef<HTMLDivElement>(null)
92
+ const { zoom, zoomIn, zoomOut, zoomReset, setZoom } = useZoom(1)
93
+ const [pan, setPan] = useState({ x: 0, y: 0 })
94
+ const dragging = useRef<{ startX: number; startY: number; panX: number; panY: number } | null>(null)
95
+
96
+ useEffect(() => {
97
+ const onKeyDown = (e: KeyboardEvent) => {
98
+ if (e.key === 'Escape') onClose()
99
+ }
100
+ window.addEventListener('keydown', onKeyDown)
101
+ return () => window.removeEventListener('keydown', onKeyDown)
102
+ }, [onClose])
103
+
104
+ // Wheel zoom
105
+ const handleWheel = useCallback((e: WheelLike) => {
106
+ e.preventDefault()
107
+ const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP
108
+ setZoom(z => Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, +(z + delta).toFixed(2))))
109
+ }, [setZoom])
110
+
111
+ // Pan via mouse drag
112
+ const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
113
+ if (e.button !== 0) return
114
+ dragging.current = { startX: e.clientX, startY: e.clientY, panX: pan.x, panY: pan.y }
115
+ e.preventDefault()
116
+ }, [pan])
117
+
118
+ const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
119
+ if (!dragging.current) return
120
+ setPan({
121
+ x: dragging.current.panX + (e.clientX - dragging.current.startX),
122
+ y: dragging.current.panY + (e.clientY - dragging.current.startY),
123
+ })
124
+ }, [])
125
+
126
+ const handleMouseUp = useCallback(() => {
127
+ dragging.current = null
128
+ }, [])
129
+
130
+ const handleResetView = useCallback(() => {
131
+ zoomReset()
132
+ setPan({ x: 0, y: 0 })
133
+ }, [zoomReset])
134
+
135
+ return ReactDOM.createPortal(
136
+ <div
137
+ style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'var(--color-bg-base)', display: 'flex', flexDirection: 'column' }}
138
+ onMouseMove={handleMouseMove}
139
+ onMouseUp={handleMouseUp}
140
+ onMouseLeave={handleMouseUp}
141
+ >
142
+ {/* Header bar */}
143
+ <div
144
+ className="flex items-center justify-between px-4 py-2 border-b border-border-subtle"
145
+ style={{ flexShrink: 0, background: 'var(--color-bg-surface)' }}
146
+ >
147
+ <span className="text-body text-text-secondary" style={{ fontSize: '13px' }}>Mermaid Diagram</span>
148
+ <div className="flex items-center gap-2">
149
+ <ZoomToolbar zoom={zoom} onZoomIn={zoomIn} onZoomOut={zoomOut} onZoomReset={handleResetView} />
150
+ <button
151
+ className="flex items-center justify-center w-8 h-8 rounded hover:bg-bg-elevated text-text-secondary hover:text-text-primary transition-colors"
152
+ onClick={onClose}
153
+ title="Close (Esc)"
154
+ >
155
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
156
+ <line x1="18" y1="6" x2="6" y2="18" />
157
+ <line x1="6" y1="6" x2="18" y2="18" />
158
+ </svg>
159
+ </button>
160
+ </div>
161
+ </div>
162
+ {/* Diagram area */}
163
+ <div
164
+ style={{ flex: 1, overflow: 'hidden', cursor: dragging.current ? 'grabbing' : 'grab' }}
165
+ onWheel={handleWheel}
166
+ onMouseDown={handleMouseDown}
167
+ >
168
+ <div
169
+ ref={modalContentRef}
170
+ style={{
171
+ width: '100%',
172
+ height: '100%',
173
+ display: 'flex',
174
+ alignItems: 'center',
175
+ justifyContent: 'center',
176
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
177
+ transformOrigin: 'center center',
178
+ transition: dragging.current ? 'none' : 'transform 0.1s ease-out',
179
+ }}
180
+ dangerouslySetInnerHTML={{ __html: svgHtml }}
181
+ />
182
+ </div>
183
+ </div>,
184
+ document.body,
185
+ )
164
186
  }
165
187
 
166
188
  export function Mermaid({ children }: MermaidProps) {
167
- const containerRef = useRef<HTMLDivElement>(null);
168
- const [error, setError] = useState<string | null>(null);
169
- const [showFullscreen, setShowFullscreen] = useState(false);
170
- const [svgHtml, setSvgHtml] = useState("");
171
- const source = typeof children === "string" ? children : String(children ?? "");
172
- const { annotations, addAnnotationWithId, activeAnnotationId, setActiveAnnotationId } = useAnnotations();
173
- const canvasFile = useCanvasFile();
174
- const [nodePopover, setNodePopover] = useState<NodePopoverState | null>(null);
175
- const { zoom, zoomIn, zoomOut, zoomReset, setZoom } = useZoom(1);
176
-
177
- const annotationsRef = useRef(annotations);
178
- annotationsRef.current = annotations;
179
-
180
- const handleNodeClick = useCallback((anchorEl: HTMLElement, snippet: string, prefix: string) => {
181
- const diagramSnippet = `[Diagram ${prefix.toLowerCase()}] ${snippet}`;
182
- const existing = annotationsRef.current.find((a) => a.snippet === diagramSnippet);
183
- if (existing) {
184
- setActiveAnnotationId(existing.id);
185
- } else {
186
- setNodePopover({ anchorEl, snippet, prefix });
187
- }
188
- }, [setActiveAnnotationId]);
189
-
190
- const handleNodeClickRef = useRef(handleNodeClick);
191
- handleNodeClickRef.current = handleNodeClick;
192
-
193
- useEffect(() => {
194
- let cancelled = false;
195
- const render = async () => {
196
- try {
197
- const mermaid = (window as any).mermaid;
198
- if (!mermaid) { setError("Mermaid library not loaded"); return; }
199
- const theme = document.documentElement.dataset.theme === "light" ? "default" : "dark";
200
- mermaid.initialize({ startOnLoad: false, theme });
201
- const id = `mermaid-${Math.random().toString(36).slice(2)}`;
202
- const { svg } = await mermaid.render(id, source.trim());
203
- if (!cancelled && containerRef.current) {
204
- containerRef.current.innerHTML = svg;
205
- setSvgHtml(svg);
206
- setupNodeAnnotations(containerRef.current, (el, snippet, prefix) => handleNodeClickRef.current(el, snippet, prefix));
207
- highlightAnnotatedNodes(containerRef.current, annotationsRef.current);
208
- }
209
- setError(null);
210
- } catch (e: any) {
211
- if (!cancelled) setError(e.message || "Invalid diagram");
212
- }
213
- };
214
- render();
215
-
216
- // Re-render on theme change
217
- const observer = new MutationObserver((mutations) => {
218
- for (const m of mutations) {
219
- if (m.attributeName === "data-theme") render();
220
- }
221
- });
222
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
223
-
224
- return () => { cancelled = true; observer.disconnect(); };
225
- }, [source]);
226
-
227
- // Update visual highlights when annotations change
228
- useEffect(() => {
229
- if (containerRef.current) {
230
- highlightAnnotatedNodes(containerRef.current, annotations, activeAnnotationId);
231
- }
232
- }, [annotations, activeAnnotationId]);
233
-
234
- // Wheel zoom on inline diagram
235
- const handleWheel = useCallback((e: WheelLike) => {
236
- if (!e.ctrlKey && !e.metaKey) return;
237
- e.preventDefault();
238
- const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
239
- setZoom(z => Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, +(z + delta).toFixed(2))));
240
- }, [setZoom]);
241
-
242
- if (error) {
243
- return (
244
- <div className="bg-accent-red-muted rounded-md p-4 mt-3 text-body text-accent-red">
245
- Mermaid error: {error}
246
- <pre className="mt-2 text-tiny text-text-tertiary whitespace-pre-wrap">{source}</pre>
247
- </div>
248
- );
249
- }
250
-
251
- const scrollContainer = containerRef.current?.closest("#plan-scroll-container") as HTMLElement | null;
252
-
253
- return (
254
- <>
255
- <div className="mt-3 mermaid-container" data-md="mermaid" data-md-source={source.trim()}>
256
- {/* Zoom toolbar */}
257
- <div className="flex justify-end mb-1">
258
- <ZoomToolbar
259
- zoom={zoom}
260
- onZoomIn={zoomIn}
261
- onZoomOut={zoomOut}
262
- onZoomReset={zoomReset}
263
- onFullscreen={() => setShowFullscreen(true)}
264
- />
265
- </div>
266
- {/* Zoomable diagram */}
267
- <div style={{ overflow: "auto", maxHeight: "70vh" }} onWheel={handleWheel}>
268
- <div
269
- ref={containerRef}
270
- className="flex justify-center"
271
- style={{
272
- transform: `scale(${zoom})`,
273
- transformOrigin: "top center",
274
- transition: "transform 0.1s ease-out",
275
- minHeight: zoom < 1 ? undefined : undefined,
276
- }}
277
- />
278
- </div>
279
- </div>
280
- {nodePopover && (
281
- <AnnotationCreatePopover
282
- anchorEl={nodePopover.anchorEl}
283
- scrollContainer={scrollContainer}
284
- snippet={nodePopover.snippet}
285
- header={
286
- <div style={{ fontSize: "12px", color: "var(--color-text-tertiary)", marginBottom: "8px", lineHeight: "1.4", display: "flex", alignItems: "center", gap: "6px" }}>
287
- <span style={{ width: "8px", height: "8px", borderRadius: "50%", background: "var(--color-accent-amber)", flexShrink: 0 }} />
288
- {nodePopover.snippet}
289
- </div>
290
- }
291
- onAdd={(note, images) => {
292
- const id = `ann-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
293
- addAnnotationWithId(id, `[Diagram ${nodePopover.prefix.toLowerCase()}] ${nodePopover.snippet}`, note, undefined, undefined, images, canvasFile || undefined);
294
- setNodePopover(null);
295
- }}
296
- onCancel={() => setNodePopover(null)}
297
- />
298
- )}
299
- {showFullscreen && svgHtml && (
300
- <MermaidFullscreenModal
301
- svgHtml={svgHtml}
302
- source={source}
303
- onClose={() => setShowFullscreen(false)}
304
- />
305
- )}
306
- </>
307
- );
189
+ const containerRef = useRef<HTMLDivElement>(null)
190
+ const [error, setError] = useState<string | null>(null)
191
+ const [showFullscreen, setShowFullscreen] = useState(false)
192
+ const [svgHtml, setSvgHtml] = useState('')
193
+ const source = typeof children === 'string' ? children : String(children ?? '')
194
+ const { annotations, addAnnotationWithId, activeAnnotationId, setActiveAnnotationId } = useAnnotations()
195
+ const canvasFile = useCanvasFile()
196
+ const [nodePopover, setNodePopover] = useState<NodePopoverState | null>(null)
197
+ const { zoom, zoomIn, zoomOut, zoomReset, setZoom } = useZoom(1)
198
+
199
+ const annotationsRef = useRef(annotations)
200
+ annotationsRef.current = annotations
201
+
202
+ const handleNodeClick = useCallback((anchorEl: HTMLElement, snippet: string, prefix: string) => {
203
+ const diagramSnippet = `[Diagram ${prefix.toLowerCase()}] ${snippet}`
204
+ const existing = annotationsRef.current.find((a) => a.snippet === diagramSnippet)
205
+ if (existing) {
206
+ setActiveAnnotationId(existing.id)
207
+ } else {
208
+ setNodePopover({ anchorEl, snippet, prefix })
209
+ }
210
+ }, [setActiveAnnotationId])
211
+
212
+ const handleNodeClickRef = useRef(handleNodeClick)
213
+ handleNodeClickRef.current = handleNodeClick
214
+
215
+ useEffect(() => {
216
+ let cancelled = false
217
+ const render = async () => {
218
+ try {
219
+ const mermaid = (window as any).mermaid
220
+ if (!mermaid) {
221
+ setError('Mermaid library not loaded')
222
+ return
223
+ }
224
+ const theme = document.documentElement.dataset['theme'] === 'light' ? 'default' : 'dark'
225
+ mermaid.initialize({ startOnLoad: false, theme })
226
+ const id = `mermaid-${Math.random().toString(36).slice(2)}`
227
+ const { svg } = await mermaid.render(id, source.trim())
228
+ if (!cancelled && containerRef.current) {
229
+ containerRef.current.innerHTML = svg
230
+ setSvgHtml(svg)
231
+ setupNodeAnnotations(containerRef.current, (el, snippet, prefix) => handleNodeClickRef.current(el, snippet, prefix))
232
+ highlightAnnotatedNodes(containerRef.current, annotationsRef.current)
233
+ }
234
+ setError(null)
235
+ } catch (e: any) {
236
+ if (!cancelled) setError(e.message || 'Invalid diagram')
237
+ }
238
+ }
239
+ render()
240
+
241
+ // Re-render on theme change
242
+ const observer = new MutationObserver((mutations) => {
243
+ for (const m of mutations) {
244
+ if (m.attributeName === 'data-theme') render()
245
+ }
246
+ })
247
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
248
+
249
+ return () => {
250
+ cancelled = true
251
+ observer.disconnect()
252
+ }
253
+ }, [source])
254
+
255
+ // Update visual highlights when annotations change
256
+ useEffect(() => {
257
+ if (containerRef.current) {
258
+ highlightAnnotatedNodes(containerRef.current, annotations, activeAnnotationId)
259
+ }
260
+ }, [annotations, activeAnnotationId])
261
+
262
+ // Wheel zoom on inline diagram
263
+ const handleWheel = useCallback((e: WheelLike) => {
264
+ if (!e.ctrlKey && !e.metaKey) return
265
+ e.preventDefault()
266
+ const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP
267
+ setZoom(z => Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, +(z + delta).toFixed(2))))
268
+ }, [setZoom])
269
+
270
+ if (error) {
271
+ return (
272
+ <div className="bg-accent-red-muted rounded-md p-4 mt-3 text-body text-accent-red">
273
+ Mermaid error: {error}
274
+ <pre className="mt-2 text-tiny text-text-tertiary whitespace-pre-wrap">{source}</pre>
275
+ </div>
276
+ )
277
+ }
278
+
279
+ const scrollContainer = containerRef.current?.closest('#plan-scroll-container') as HTMLElement | null
280
+
281
+ return (
282
+ <>
283
+ <div className="mt-3 mermaid-container" data-md="mermaid" data-md-source={source.trim()}>
284
+ {/* Zoom toolbar */}
285
+ <div className="flex justify-end mb-1">
286
+ <ZoomToolbar
287
+ zoom={zoom}
288
+ onZoomIn={zoomIn}
289
+ onZoomOut={zoomOut}
290
+ onZoomReset={zoomReset}
291
+ onFullscreen={() => setShowFullscreen(true)}
292
+ />
293
+ </div>
294
+ {/* Zoomable diagram */}
295
+ <div style={{ overflow: 'auto', maxHeight: '70vh' }} onWheel={handleWheel}>
296
+ <div
297
+ ref={containerRef}
298
+ className="flex justify-center"
299
+ style={{
300
+ transform: `scale(${zoom})`,
301
+ transformOrigin: 'top center',
302
+ transition: 'transform 0.1s ease-out',
303
+ minHeight: zoom < 1 ? undefined : undefined,
304
+ }}
305
+ />
306
+ </div>
307
+ </div>
308
+ {nodePopover && (
309
+ <AnnotationCreatePopover
310
+ anchorEl={nodePopover.anchorEl}
311
+ scrollContainer={scrollContainer}
312
+ snippet={nodePopover.snippet}
313
+ header={
314
+ <div
315
+ style={{
316
+ fontSize: '12px',
317
+ color: 'var(--color-text-tertiary)',
318
+ marginBottom: '8px',
319
+ lineHeight: '1.4',
320
+ display: 'flex',
321
+ alignItems: 'center',
322
+ gap: '6px',
323
+ }}
324
+ >
325
+ <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: 'var(--color-accent-amber)', flexShrink: 0 }} />
326
+ {nodePopover.snippet}
327
+ </div>
328
+ }
329
+ onAdd={(note, images) => {
330
+ const id = `ann-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`
331
+ addAnnotationWithId(
332
+ id,
333
+ `[Diagram ${nodePopover.prefix.toLowerCase()}] ${nodePopover.snippet}`,
334
+ note,
335
+ undefined,
336
+ undefined,
337
+ images,
338
+ canvasFile || undefined,
339
+ )
340
+ setNodePopover(null)
341
+ }}
342
+ onCancel={() => setNodePopover(null)}
343
+ />
344
+ )}
345
+ {showFullscreen && svgHtml && (
346
+ <MermaidFullscreenModal
347
+ svgHtml={svgHtml}
348
+ source={source}
349
+ onClose={() => setShowFullscreen(false)}
350
+ />
351
+ )}
352
+ </>
353
+ )
308
354
  }
309
355
 
310
356
  function setupNodeAnnotations(
311
- container: HTMLElement,
312
- showPopover: (anchorEl: HTMLElement, snippet: string, prefix: string) => void,
357
+ container: HTMLElement,
358
+ showPopover: (anchorEl: HTMLElement, snippet: string, prefix: string) => void,
313
359
  ) {
314
- const makeClickable = (el: SVGElement, getSnippet: () => string, prefix: string) => {
315
- el.style.cursor = "pointer";
316
- el.addEventListener("mouseenter", () => { el.style.filter = "brightness(1.2)"; });
317
- el.addEventListener("mouseleave", () => { el.style.filter = ""; });
318
- el.addEventListener("click", (e) => {
319
- e.stopPropagation();
320
- e.preventDefault();
321
- showPopover(el as unknown as HTMLElement, getSnippet(), prefix);
322
- });
323
- };
324
-
325
- // Nodes
326
- for (const node of container.querySelectorAll(".node")) {
327
- makeClickable(node as SVGElement, () => {
328
- const labelEl = node.querySelector(".nodeLabel") || node.querySelector("foreignObject span") || node.querySelector("text");
329
- return labelEl?.textContent?.trim() || "Node";
330
- }, "Node");
331
- }
332
-
333
- // Edge paths (connections)
334
- for (const edge of container.querySelectorAll(".edgePath")) {
335
- const el = edge as SVGElement;
336
- // Widen hit area for thin lines
337
- const path = el.querySelector("path");
338
- if (path) {
339
- path.style.strokeWidth = Math.max(parseFloat(path.style.strokeWidth || "1"), 8) + "px";
340
- path.style.strokeOpacity = "0";
341
- const clone = path.cloneNode(true) as SVGPathElement;
342
- clone.style.strokeWidth = "";
343
- clone.style.strokeOpacity = "";
344
- el.insertBefore(clone, path);
345
- }
346
- // Find the label for this edge (sibling edgeLabel)
347
- const edgeId = el.id || "";
348
- makeClickable(el, () => {
349
- // Try to find matching edge label
350
- const labels = container.querySelectorAll(".edgeLabel");
351
- for (const label of labels) {
352
- if (label.id && edgeId && label.id.replace("label", "").includes(edgeId.replace("L-", "").replace("edge", ""))) {
353
- const text = label.textContent?.trim();
354
- if (text) return text;
355
- }
356
- }
357
- // Fallback: find nearest edge label by position
358
- return "Connection";
359
- }, "Edge");
360
- }
361
-
362
- // Edge labels
363
- for (const label of container.querySelectorAll(".edgeLabel")) {
364
- const text = label.textContent?.trim();
365
- if (!text) continue;
366
- makeClickable(label as SVGElement, () => text, "Edge");
367
- }
368
-
369
- // Sequence diagram: actors (participants)
370
- for (const actor of container.querySelectorAll(".actor")) {
371
- const textEl = actor.closest("g")?.querySelector("text") || actor.parentElement?.querySelector("text");
372
- if (!textEl) continue;
373
- // The actor rect and text are siblings in a <g> — make the whole <g> clickable
374
- const group = actor.closest("g") as SVGElement | null;
375
- if (!group || group.hasAttribute("data-clickable")) continue;
376
- group.setAttribute("data-clickable", "true");
377
- makeClickable(group, () => textEl.textContent?.trim() || "Participant", "Node");
378
- }
379
-
380
- // Sequence diagram: message labels
381
- for (const msgText of container.querySelectorAll(".messageText")) {
382
- const text = msgText.textContent?.trim();
383
- if (!text) continue;
384
- makeClickable(msgText as SVGElement, () => text, "Edge");
385
- }
386
-
387
- // ER diagram: entities
388
- for (const entity of container.querySelectorAll(".entityBox")) {
389
- const group = entity.closest("g") as SVGElement | null;
390
- if (!group || group.hasAttribute("data-clickable")) continue;
391
- const labelEl = group.querySelector(".entityLabel");
392
- if (!labelEl) continue;
393
- group.setAttribute("data-clickable", "true");
394
- makeClickable(group, () => labelEl.textContent?.trim() || "Entity", "Node");
395
- }
396
-
397
- // ER diagram: relationship labels
398
- for (const label of container.querySelectorAll(".relationshipLabel")) {
399
- const text = label.textContent?.trim();
400
- if (!text) continue;
401
- const group = label.closest("g") as SVGElement | null;
402
- const target = group || label as SVGElement;
403
- if (target.hasAttribute("data-clickable")) continue;
404
- target.setAttribute("data-clickable", "true");
405
- makeClickable(target, () => text, "Edge");
406
- }
407
-
408
- // Class diagram: class groups
409
- for (const classGroup of container.querySelectorAll(".classGroup")) {
410
- const el = classGroup as SVGElement;
411
- if (el.hasAttribute("data-clickable")) continue;
412
- const labelEl = el.querySelector(".classTitle, .classTitleText, text");
413
- if (!labelEl) continue;
414
- el.setAttribute("data-clickable", "true");
415
- makeClickable(el, () => labelEl.textContent?.trim() || "Class", "Node");
416
- }
417
-
418
- // State diagram: states
419
- for (const state of container.querySelectorAll(".statediagram-state")) {
420
- const el = state as SVGElement;
421
- if (el.hasAttribute("data-clickable")) continue;
422
- const labelEl = el.querySelector(".state-title, text");
423
- if (!labelEl) continue;
424
- el.setAttribute("data-clickable", "true");
425
- makeClickable(el, () => labelEl.textContent?.trim() || "State", "Node");
426
- }
427
-
428
- // Mindmap: nodes
429
- for (const node of container.querySelectorAll(".mindmap-node")) {
430
- const el = node as SVGElement;
431
- if (el.hasAttribute("data-clickable")) continue;
432
- const labelEl = el.querySelector(".mindmap-node-label, text");
433
- if (!labelEl) continue;
434
- el.setAttribute("data-clickable", "true");
435
- makeClickable(el, () => labelEl.textContent?.trim() || "Node", "Node");
436
- }
360
+ const makeClickable = (el: SVGElement, getSnippet: () => string, prefix: string) => {
361
+ el.style.cursor = 'pointer'
362
+ el.addEventListener('mouseenter', () => {
363
+ el.style.filter = 'brightness(1.2)'
364
+ })
365
+ el.addEventListener('mouseleave', () => {
366
+ el.style.filter = ''
367
+ })
368
+ el.addEventListener('click', (e) => {
369
+ e.stopPropagation()
370
+ e.preventDefault()
371
+ showPopover(el as unknown as HTMLElement, getSnippet(), prefix)
372
+ })
373
+ }
374
+
375
+ // Nodes
376
+ for (const node of container.querySelectorAll('.node')) {
377
+ makeClickable(node as SVGElement, () => {
378
+ const labelEl = node.querySelector('.nodeLabel') || node.querySelector('foreignObject span') || node.querySelector('text')
379
+ return labelEl?.textContent?.trim() || 'Node'
380
+ }, 'Node')
381
+ }
382
+
383
+ // Edge paths (connections)
384
+ for (const edge of container.querySelectorAll('.edgePath')) {
385
+ const el = edge as SVGElement
386
+ // Widen hit area for thin lines
387
+ const path = el.querySelector('path')
388
+ if (path) {
389
+ path.style.strokeWidth = Math.max(parseFloat(path.style.strokeWidth || '1'), 8) + 'px'
390
+ path.style.strokeOpacity = '0'
391
+ const clone = path.cloneNode(true) as SVGPathElement
392
+ clone.style.strokeWidth = ''
393
+ clone.style.strokeOpacity = ''
394
+ el.insertBefore(clone, path)
395
+ }
396
+ // Find the label for this edge (sibling edgeLabel)
397
+ const edgeId = el.id || ''
398
+ makeClickable(el, () => {
399
+ // Try to find matching edge label
400
+ const labels = container.querySelectorAll('.edgeLabel')
401
+ for (const label of labels) {
402
+ if (label.id && edgeId && label.id.replace('label', '').includes(edgeId.replace('L-', '').replace('edge', ''))) {
403
+ const text = label.textContent?.trim()
404
+ if (text) return text
405
+ }
406
+ }
407
+ // Fallback: find nearest edge label by position
408
+ return 'Connection'
409
+ }, 'Edge')
410
+ }
411
+
412
+ // Edge labels
413
+ for (const label of container.querySelectorAll('.edgeLabel')) {
414
+ const text = label.textContent?.trim()
415
+ if (!text) continue
416
+ makeClickable(label as SVGElement, () => text, 'Edge')
417
+ }
418
+
419
+ // Sequence diagram: actors (participants)
420
+ for (const actor of container.querySelectorAll('.actor')) {
421
+ const textEl = actor.closest('g')?.querySelector('text') || actor.parentElement?.querySelector('text')
422
+ if (!textEl) continue
423
+ // The actor rect and text are siblings in a <g> — make the whole <g> clickable
424
+ const group = actor.closest('g') as SVGElement | null
425
+ if (!group || group.hasAttribute('data-clickable')) continue
426
+ group.setAttribute('data-clickable', 'true')
427
+ makeClickable(group, () => textEl.textContent?.trim() || 'Participant', 'Node')
428
+ }
429
+
430
+ // Sequence diagram: message labels
431
+ for (const msgText of container.querySelectorAll('.messageText')) {
432
+ const text = msgText.textContent?.trim()
433
+ if (!text) continue
434
+ makeClickable(msgText as SVGElement, () => text, 'Edge')
435
+ }
436
+
437
+ // ER diagram: entities
438
+ for (const entity of container.querySelectorAll('.entityBox')) {
439
+ const group = entity.closest('g') as SVGElement | null
440
+ if (!group || group.hasAttribute('data-clickable')) continue
441
+ const labelEl = group.querySelector('.entityLabel')
442
+ if (!labelEl) continue
443
+ group.setAttribute('data-clickable', 'true')
444
+ makeClickable(group, () => labelEl.textContent?.trim() || 'Entity', 'Node')
445
+ }
446
+
447
+ // ER diagram: relationship labels
448
+ for (const label of container.querySelectorAll('.relationshipLabel')) {
449
+ const text = label.textContent?.trim()
450
+ if (!text) continue
451
+ const group = label.closest('g') as SVGElement | null
452
+ const target = group || label as SVGElement
453
+ if (target.hasAttribute('data-clickable')) continue
454
+ target.setAttribute('data-clickable', 'true')
455
+ makeClickable(target, () => text, 'Edge')
456
+ }
457
+
458
+ // Class diagram: class groups
459
+ for (const classGroup of container.querySelectorAll('.classGroup')) {
460
+ const el = classGroup as SVGElement
461
+ if (el.hasAttribute('data-clickable')) continue
462
+ const labelEl = el.querySelector('.classTitle, .classTitleText, text')
463
+ if (!labelEl) continue
464
+ el.setAttribute('data-clickable', 'true')
465
+ makeClickable(el, () => labelEl.textContent?.trim() || 'Class', 'Node')
466
+ }
467
+
468
+ // State diagram: states
469
+ for (const state of container.querySelectorAll('.statediagram-state')) {
470
+ const el = state as SVGElement
471
+ if (el.hasAttribute('data-clickable')) continue
472
+ const labelEl = el.querySelector('.state-title, text')
473
+ if (!labelEl) continue
474
+ el.setAttribute('data-clickable', 'true')
475
+ makeClickable(el, () => labelEl.textContent?.trim() || 'State', 'Node')
476
+ }
477
+
478
+ // Mindmap: nodes
479
+ for (const node of container.querySelectorAll('.mindmap-node')) {
480
+ const el = node as SVGElement
481
+ if (el.hasAttribute('data-clickable')) continue
482
+ const labelEl = el.querySelector('.mindmap-node-label, text')
483
+ if (!labelEl) continue
484
+ el.setAttribute('data-clickable', 'true')
485
+ makeClickable(el, () => labelEl.textContent?.trim() || 'Node', 'Node')
486
+ }
437
487
  }
438
488
 
439
489
  function highlightAnnotatedNodes(container: HTMLElement, annotations: Annotation[], activeId?: string | null) {
440
- // Collect annotated diagram snippets
441
- const annotatedSnippets = new Map<string, string>();
442
- for (const ann of annotations) {
443
- const label = ann.snippet.match(/^\[Diagram (?:node|edge)\] (.+)$/)?.[1];
444
- if (label) annotatedSnippets.set(label, ann.id);
445
- }
446
-
447
- // Reset all node outlines
448
- for (const el of container.querySelectorAll("[data-annotated]")) {
449
- (el as SVGElement).style.outline = "";
450
- (el as SVGElement).style.outlineOffset = "";
451
- (el as SVGElement).style.borderRadius = "";
452
- el.removeAttribute("data-annotated");
453
- }
454
-
455
- if (annotatedSnippets.size === 0) return;
456
-
457
- // Highlight nodes
458
- for (const node of container.querySelectorAll(".node")) {
459
- const labelEl = node.querySelector(".nodeLabel") || node.querySelector("foreignObject span") || node.querySelector("text");
460
- const text = labelEl?.textContent?.trim();
461
- if (!text || !annotatedSnippets.has(text)) continue;
462
- const annId = annotatedSnippets.get(text)!;
463
- const el = node as SVGElement;
464
- el.setAttribute("data-annotated", annId);
465
- const isActive = annId === activeId;
466
- el.style.outline = isActive
467
- ? "2px solid var(--color-highlight-border)"
468
- : "2px solid var(--color-highlight-annotation)";
469
- el.style.outlineOffset = "2px";
470
- el.style.borderRadius = "4px";
471
- }
472
-
473
- // Highlight edge labels
474
- for (const label of container.querySelectorAll(".edgeLabel")) {
475
- const text = label.textContent?.trim();
476
- if (!text || !annotatedSnippets.has(text)) continue;
477
- const annId = annotatedSnippets.get(text)!;
478
- const el = label as SVGElement;
479
- el.setAttribute("data-annotated", annId);
480
- const isActive = annId === activeId;
481
- el.style.outline = isActive
482
- ? "2px solid var(--color-highlight-border)"
483
- : "2px solid var(--color-highlight-annotation)";
484
- el.style.outlineOffset = "2px";
485
- el.style.borderRadius = "4px";
486
- }
487
-
488
- // Highlight sequence diagram actors
489
- for (const actor of container.querySelectorAll(".actor")) {
490
- const group = actor.closest("g") as SVGElement | null;
491
- if (!group) continue;
492
- const textEl = group.querySelector("text");
493
- const text = textEl?.textContent?.trim();
494
- if (!text || !annotatedSnippets.has(text)) continue;
495
- if (group.hasAttribute("data-annotated")) continue;
496
- const annId = annotatedSnippets.get(text)!;
497
- group.setAttribute("data-annotated", annId);
498
- const isActive = annId === activeId;
499
- const rect = group.querySelector("rect");
500
- if (rect) {
501
- rect.style.outline = isActive
502
- ? "2px solid var(--color-highlight-border)"
503
- : "2px solid var(--color-highlight-annotation)";
504
- rect.style.outlineOffset = "2px";
505
- rect.style.borderRadius = "4px";
506
- }
507
- }
508
-
509
- // Highlight sequence diagram message labels
510
- for (const msgText of container.querySelectorAll(".messageText")) {
511
- const text = msgText.textContent?.trim();
512
- if (!text || !annotatedSnippets.has(text)) continue;
513
- const annId = annotatedSnippets.get(text)!;
514
- const el = msgText as SVGElement;
515
- el.setAttribute("data-annotated", annId);
516
- const isActive = annId === activeId;
517
- el.style.outline = isActive
518
- ? "2px solid var(--color-highlight-border)"
519
- : "2px solid var(--color-highlight-annotation)";
520
- el.style.outlineOffset = "2px";
521
- el.style.borderRadius = "4px";
522
- }
523
-
524
- // Helper for group-based highlights (ER entities, class groups, states, mindmap nodes)
525
- const highlightGroups = (
526
- selector: string,
527
- labelSelector: string,
528
- findGroup: (el: Element) => SVGElement | null,
529
- ) => {
530
- for (const el of container.querySelectorAll(selector)) {
531
- const group = findGroup(el);
532
- if (!group || group.hasAttribute("data-annotated")) continue;
533
- const labelEl = group.querySelector(labelSelector);
534
- const text = labelEl?.textContent?.trim();
535
- if (!text || !annotatedSnippets.has(text)) continue;
536
- const annId = annotatedSnippets.get(text)!;
537
- group.setAttribute("data-annotated", annId);
538
- const isActive = annId === activeId;
539
- const target = group.querySelector("rect, circle, ellipse, polygon") as SVGElement || group;
540
- target.style.outline = isActive
541
- ? "2px solid var(--color-highlight-border)"
542
- : "2px solid var(--color-highlight-annotation)";
543
- target.style.outlineOffset = "2px";
544
- target.style.borderRadius = "4px";
545
- }
546
- };
547
-
548
- // ER diagram: entities
549
- highlightGroups(".entityBox", ".entityLabel", (el) => el.closest("g") as SVGElement | null);
550
-
551
- // ER diagram: relationship labels
552
- for (const label of container.querySelectorAll(".relationshipLabel")) {
553
- const group = label.closest("g") as SVGElement | null;
554
- const target = group || label as SVGElement;
555
- if (target.hasAttribute("data-annotated")) continue;
556
- const text = label.textContent?.trim();
557
- if (!text || !annotatedSnippets.has(text)) continue;
558
- const annId = annotatedSnippets.get(text)!;
559
- target.setAttribute("data-annotated", annId);
560
- const isActive = annId === activeId;
561
- (target as SVGElement).style.outline = isActive
562
- ? "2px solid var(--color-highlight-border)"
563
- : "2px solid var(--color-highlight-annotation)";
564
- (target as SVGElement).style.outlineOffset = "2px";
565
- (target as SVGElement).style.borderRadius = "4px";
566
- }
567
-
568
- // Class diagram
569
- highlightGroups(".classGroup", ".classTitle, .classTitleText, text", (el) => el as SVGElement);
570
-
571
- // State diagram
572
- highlightGroups(".statediagram-state", ".state-title, text", (el) => el as SVGElement);
573
-
574
- // Mindmap
575
- highlightGroups(".mindmap-node", ".mindmap-node-label, text", (el) => el as SVGElement);
490
+ // Collect annotated diagram snippets
491
+ const annotatedSnippets = new Map<string, string>()
492
+ for (const ann of annotations) {
493
+ const label = ann.snippet.match(/^\[Diagram (?:node|edge)\] (.+)$/)?.[1]
494
+ if (label) annotatedSnippets.set(label, ann.id)
495
+ }
496
+
497
+ // Reset all node outlines
498
+ for (const el of container.querySelectorAll('[data-annotated]')) {
499
+ ;(el as SVGElement).style.outline = ''
500
+ ;(el as SVGElement).style.outlineOffset = ''
501
+ ;(el as SVGElement).style.borderRadius = ''
502
+ el.removeAttribute('data-annotated')
503
+ }
504
+
505
+ if (annotatedSnippets.size === 0) return
506
+
507
+ // Highlight nodes
508
+ for (const node of container.querySelectorAll('.node')) {
509
+ const labelEl = node.querySelector('.nodeLabel') || node.querySelector('foreignObject span') || node.querySelector('text')
510
+ const text = labelEl?.textContent?.trim()
511
+ if (!text || !annotatedSnippets.has(text)) continue
512
+ const annId = annotatedSnippets.get(text)!
513
+ const el = node as SVGElement
514
+ el.setAttribute('data-annotated', annId)
515
+ const isActive = annId === activeId
516
+ el.style.outline = isActive
517
+ ? '2px solid var(--color-highlight-border)'
518
+ : '2px solid var(--color-highlight-annotation)'
519
+ el.style.outlineOffset = '2px'
520
+ el.style.borderRadius = '4px'
521
+ }
522
+
523
+ // Highlight edge labels
524
+ for (const label of container.querySelectorAll('.edgeLabel')) {
525
+ const text = label.textContent?.trim()
526
+ if (!text || !annotatedSnippets.has(text)) continue
527
+ const annId = annotatedSnippets.get(text)!
528
+ const el = label as SVGElement
529
+ el.setAttribute('data-annotated', annId)
530
+ const isActive = annId === activeId
531
+ el.style.outline = isActive
532
+ ? '2px solid var(--color-highlight-border)'
533
+ : '2px solid var(--color-highlight-annotation)'
534
+ el.style.outlineOffset = '2px'
535
+ el.style.borderRadius = '4px'
536
+ }
537
+
538
+ // Highlight sequence diagram actors
539
+ for (const actor of container.querySelectorAll('.actor')) {
540
+ const group = actor.closest('g') as SVGElement | null
541
+ if (!group) continue
542
+ const textEl = group.querySelector('text')
543
+ const text = textEl?.textContent?.trim()
544
+ if (!text || !annotatedSnippets.has(text)) continue
545
+ if (group.hasAttribute('data-annotated')) continue
546
+ const annId = annotatedSnippets.get(text)!
547
+ group.setAttribute('data-annotated', annId)
548
+ const isActive = annId === activeId
549
+ const rect = group.querySelector('rect')
550
+ if (rect) {
551
+ rect.style.outline = isActive
552
+ ? '2px solid var(--color-highlight-border)'
553
+ : '2px solid var(--color-highlight-annotation)'
554
+ rect.style.outlineOffset = '2px'
555
+ rect.style.borderRadius = '4px'
556
+ }
557
+ }
558
+
559
+ // Highlight sequence diagram message labels
560
+ for (const msgText of container.querySelectorAll('.messageText')) {
561
+ const text = msgText.textContent?.trim()
562
+ if (!text || !annotatedSnippets.has(text)) continue
563
+ const annId = annotatedSnippets.get(text)!
564
+ const el = msgText as SVGElement
565
+ el.setAttribute('data-annotated', annId)
566
+ const isActive = annId === activeId
567
+ el.style.outline = isActive
568
+ ? '2px solid var(--color-highlight-border)'
569
+ : '2px solid var(--color-highlight-annotation)'
570
+ el.style.outlineOffset = '2px'
571
+ el.style.borderRadius = '4px'
572
+ }
573
+
574
+ // Helper for group-based highlights (ER entities, class groups, states, mindmap nodes)
575
+ const highlightGroups = (
576
+ selector: string,
577
+ labelSelector: string,
578
+ findGroup: (el: Element) => SVGElement | null,
579
+ ) => {
580
+ for (const el of container.querySelectorAll(selector)) {
581
+ const group = findGroup(el)
582
+ if (!group || group.hasAttribute('data-annotated')) continue
583
+ const labelEl = group.querySelector(labelSelector)
584
+ const text = labelEl?.textContent?.trim()
585
+ if (!text || !annotatedSnippets.has(text)) continue
586
+ const annId = annotatedSnippets.get(text)!
587
+ group.setAttribute('data-annotated', annId)
588
+ const isActive = annId === activeId
589
+ const target = group.querySelector('rect, circle, ellipse, polygon') as SVGElement || group
590
+ target.style.outline = isActive
591
+ ? '2px solid var(--color-highlight-border)'
592
+ : '2px solid var(--color-highlight-annotation)'
593
+ target.style.outlineOffset = '2px'
594
+ target.style.borderRadius = '4px'
595
+ }
596
+ }
597
+
598
+ // ER diagram: entities
599
+ highlightGroups('.entityBox', '.entityLabel', (el) => el.closest('g') as SVGElement | null)
600
+
601
+ // ER diagram: relationship labels
602
+ for (const label of container.querySelectorAll('.relationshipLabel')) {
603
+ const group = label.closest('g') as SVGElement | null
604
+ const target = group || label as SVGElement
605
+ if (target.hasAttribute('data-annotated')) continue
606
+ const text = label.textContent?.trim()
607
+ if (!text || !annotatedSnippets.has(text)) continue
608
+ const annId = annotatedSnippets.get(text)!
609
+ target.setAttribute('data-annotated', annId)
610
+ const isActive = annId === activeId
611
+ ;(target as SVGElement).style.outline = isActive
612
+ ? '2px solid var(--color-highlight-border)'
613
+ : '2px solid var(--color-highlight-annotation)'
614
+ ;(target as SVGElement).style.outlineOffset = '2px'
615
+ ;(target as SVGElement).style.borderRadius = '4px'
616
+ }
617
+
618
+ // Class diagram
619
+ highlightGroups('.classGroup', '.classTitle, .classTitleText, text', (el) => el as SVGElement)
620
+
621
+ // State diagram
622
+ highlightGroups('.statediagram-state', '.state-title, text', (el) => el as SVGElement)
623
+
624
+ // Mindmap
625
+ highlightGroups('.mindmap-node', '.mindmap-node-label, text', (el) => el as SVGElement)
576
626
  }