@fabrika/canvas-kernel 0.1.44

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/annotate.ts +94 -0
  4. package/daemon.ts +46 -0
  5. package/index.ts +84 -0
  6. package/package.json +74 -0
  7. package/src/client/AnnotationDraftFooter.tsx +76 -0
  8. package/src/client/AnnotationEditor.tsx +320 -0
  9. package/src/client/AnnotationList.tsx +190 -0
  10. package/src/client/AnnotationProvider.tsx +294 -0
  11. package/src/client/AnnotationSidebar.tsx +374 -0
  12. package/src/client/FileIcon.tsx +76 -0
  13. package/src/client/PlanRenderer.tsx +587 -0
  14. package/src/client/Popover.tsx +361 -0
  15. package/src/client/RenderErrorContext.ts +11 -0
  16. package/src/client/ResponsePreview.tsx +186 -0
  17. package/src/client/SessionContext.tsx +3 -0
  18. package/src/client/annotationContext.ts +130 -0
  19. package/src/client/annotationDom.ts +115 -0
  20. package/src/client/annotationDraft.ts +130 -0
  21. package/src/client/annotationMarkdown.ts +102 -0
  22. package/src/client/annotationTarget.ts +73 -0
  23. package/src/client/appContext.tsx +61 -0
  24. package/src/client/blockTarget.ts +127 -0
  25. package/src/client/components/Callout.tsx +27 -0
  26. package/src/client/components/Checklist.tsx +37 -0
  27. package/src/client/components/Choice.tsx +178 -0
  28. package/src/client/components/CodeBlock.tsx +35 -0
  29. package/src/client/components/Diff.tsx +36 -0
  30. package/src/client/components/FilePreview.tsx +88 -0
  31. package/src/client/components/Image.tsx +48 -0
  32. package/src/client/components/Markdown.tsx +44 -0
  33. package/src/client/components/Mermaid.tsx +576 -0
  34. package/src/client/components/Note.tsx +14 -0
  35. package/src/client/components/Priority.tsx +19 -0
  36. package/src/client/components/ResponseNote.tsx +19 -0
  37. package/src/client/components/Section.tsx +33 -0
  38. package/src/client/components/Table.tsx +35 -0
  39. package/src/client/components/Task.tsx +76 -0
  40. package/src/client/components/UserInput.tsx +176 -0
  41. package/src/client/components/index.ts +18 -0
  42. package/src/client/components/renderMarkdownChildren.tsx +100 -0
  43. package/src/client/diffLines.ts +50 -0
  44. package/src/client/generateMarkdown.ts +250 -0
  45. package/src/client/highlightRange.ts +262 -0
  46. package/src/client/hostContext.tsx +55 -0
  47. package/src/client/index.ts +128 -0
  48. package/src/client/popoverPosition.ts +46 -0
  49. package/src/client/preact-all.ts +4 -0
  50. package/src/client/regionTarget.ts +180 -0
  51. package/src/client/runtime.ts +149 -0
  52. package/src/client/styles.css +492 -0
  53. package/src/client/testing/dom.ts +58 -0
  54. package/src/client/textTarget.ts +31 -0
  55. package/src/client/theme.css +66 -0
  56. package/src/client/useRegionAnnotation.tsx +188 -0
  57. package/src/client/useTextAnnotation.tsx +194 -0
  58. package/src/client/utils.ts +33 -0
  59. package/src/engine/channel.ts +278 -0
  60. package/src/engine/compiler.ts +415 -0
  61. package/src/engine/http-utils.ts +14 -0
  62. package/src/engine/lifecycle.ts +302 -0
  63. package/src/engine/paths.ts +63 -0
  64. package/src/engine/router.ts +16 -0
  65. package/src/engine/session.ts +678 -0
  66. package/src/engine/waiter.ts +188 -0
  67. package/src/engine/watcher.ts +84 -0
  68. package/src/engine/websocket.ts +159 -0
@@ -0,0 +1,576 @@
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";
6
+
7
+ interface MermaidProps {
8
+ children?: React.ReactNode;
9
+ }
10
+
11
+ interface NodePopoverState {
12
+ anchorEl: HTMLElement;
13
+ snippet: string;
14
+ prefix: string;
15
+ }
16
+
17
+ const ZOOM_STEP = 0.2;
18
+ const ZOOM_MIN = 0.25;
19
+ const ZOOM_MAX = 4;
20
+
21
+ /** The wheel fields React's synthetic event and Preact's native one both carry.
22
+ * Named structurally because preact/compat aliases no `React.WheelEvent`, and
23
+ * a handler taking less than the event supplies is accepted by either. */
24
+ interface WheelLike {
25
+ deltaY: number;
26
+ ctrlKey: boolean;
27
+ metaKey: boolean;
28
+ preventDefault(): void;
29
+ }
30
+
31
+ function ZoomToolbar({ zoom, onZoomIn, onZoomOut, onZoomReset, onFullscreen }: {
32
+ zoom: number;
33
+ onZoomIn: () => void;
34
+ onZoomOut: () => void;
35
+ onZoomReset: () => void;
36
+ onFullscreen?: () => void;
37
+ }) {
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
+ );
60
+ }
61
+
62
+ 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 };
68
+ }
69
+
70
+ function MermaidFullscreenModal({ svgHtml, source, onClose }: {
71
+ svgHtml: string;
72
+ source: string;
73
+ onClose: () => void;
74
+ }) {
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
+ );
164
+ }
165
+
166
+ 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
+ );
308
+ }
309
+
310
+ function setupNodeAnnotations(
311
+ container: HTMLElement,
312
+ showPopover: (anchorEl: HTMLElement, snippet: string, prefix: string) => void,
313
+ ) {
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
+ }
437
+ }
438
+
439
+ 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);
576
+ }
@@ -0,0 +1,14 @@
1
+ import React from "react";
2
+ import { renderMarkdownChildren } from "./renderMarkdownChildren";
3
+
4
+ interface NoteProps {
5
+ children?: React.ReactNode;
6
+ }
7
+
8
+ export function Note({ children }: NoteProps) {
9
+ return (
10
+ <div className="relative bg-bg-elevated rounded-lg px-5 py-4 mt-3 text-body text-text-secondary italic leading-relaxed" data-md="note">
11
+ {renderMarkdownChildren(children)}
12
+ </div>
13
+ );
14
+ }
@@ -0,0 +1,19 @@
1
+ import React from "react";
2
+
3
+ interface PriorityProps {
4
+ level: "high" | "medium" | "low";
5
+ }
6
+
7
+ const config = {
8
+ high: "text-accent-red bg-accent-red-muted",
9
+ medium: "text-accent-amber bg-accent-amber-muted",
10
+ low: "text-text-tertiary bg-border-subtle",
11
+ };
12
+
13
+ export function Priority({ level }: PriorityProps) {
14
+ return (
15
+ <span className={`inline text-tiny font-medium font-body ml-2 px-1.5 py-0.5 rounded ${config[level]}`} data-md="priority" data-md-level={level}>
16
+ {level}
17
+ </span>
18
+ );
19
+ }
@@ -0,0 +1,19 @@
1
+ import React from "react";
2
+ import { autoResizeTextarea } from "../utils";
3
+
4
+ /** Seamless note input for response components */
5
+ export function ResponseNote({ note, onChange }: { show?: boolean; note: string; onToggle?: () => void; onChange: (n: string) => void }) {
6
+ return (
7
+ <div className="mt-1.5">
8
+ <textarea
9
+ value={note}
10
+ onChange={(e) => onChange(e.currentTarget.value)}
11
+ className="w-full bg-transparent text-[12px] font-body text-text-primary resize-none focus:outline-none border-none placeholder:text-text-disabled transition-colors min-h-[20px] p-0 leading-relaxed"
12
+ placeholder="Add a note..."
13
+ rows={1}
14
+ onInput={(e) => autoResizeTextarea(e.currentTarget)}
15
+ ref={(el) => { if (el) autoResizeTextarea(el); }}
16
+ />
17
+ </div>
18
+ );
19
+ }
@@ -0,0 +1,33 @@
1
+ import React, { useState } from "react";
2
+ import { renderMarkdownChildren } from "./renderMarkdownChildren";
3
+
4
+ interface SectionProps {
5
+ title: string;
6
+ children?: React.ReactNode;
7
+ }
8
+
9
+ export function Section({ title, children }: SectionProps) {
10
+ const [collapsed, setCollapsed] = useState(false);
11
+
12
+ return (
13
+ <div className="relative mb-8 p-4 group/section" data-md="section" data-md-title={title}>
14
+ <div className="relative mb-2">
15
+ <button
16
+ onClick={() => setCollapsed(!collapsed)}
17
+ className={`absolute -left-8 top-1/2 -translate-y-1/2 text-text-tertiary opacity-0 group-hover/section:opacity-50 hover:!opacity-100 transition-all duration-150 p-0.5 ${collapsed ? "-rotate-90" : ""}`}
18
+ >
19
+ <svg width="14" height="14" viewBox="0 0 12 12" fill="none">
20
+ <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
21
+ </svg>
22
+ </button>
23
+ <h2
24
+ className="font-heading text-section text-text-primary"
25
+ style={{ fontWeight: 400 }}
26
+ >
27
+ {title}
28
+ </h2>
29
+ </div>
30
+ <div className={collapsed ? "mt-6 hidden" : "mt-6"}>{renderMarkdownChildren(children)}</div>
31
+ </div>
32
+ );
33
+ }