@plannotator/ui 0.39.0 → 0.41.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 (52) hide show
  1. package/HANDOFF.md +140 -10
  2. package/README.md +9 -5
  3. package/components/AnnotationPanel.tsx +244 -13
  4. package/components/CommentPopover.tsx +91 -2
  5. package/components/DiagramBlock.tsx +376 -0
  6. package/components/GraphvizBlock.tsx +22 -597
  7. package/components/HtmlSurfaceControls.tsx +188 -23
  8. package/components/ListMarker.tsx +10 -1
  9. package/components/MermaidBlock.tsx +17 -630
  10. package/components/TableOfContents.tsx +5 -1
  11. package/components/TerminalToolsAnnouncementDialog.tsx +454 -0
  12. package/components/Viewer.tsx +67 -3
  13. package/components/blocks/AlertBlock.tsx +7 -2
  14. package/components/diagram/DiagramCanvas.tsx +431 -0
  15. package/components/diagram/DiagramComposer.tsx +135 -0
  16. package/components/diagram/DiagramOverlay.tsx +215 -0
  17. package/components/diagram/DiagramPopout.tsx +70 -0
  18. package/components/diagram/DiagramSourcePane.tsx +244 -0
  19. package/components/diagram/DiagramViewer.tsx +276 -0
  20. package/components/diagram/anchorClaims.ts +71 -0
  21. package/components/diagram/index.ts +36 -0
  22. package/components/diagram/useDiagramComments.ts +341 -0
  23. package/components/diagram/useDiagramRender.ts +91 -0
  24. package/components/diagram/useDiagramSourceDraft.ts +143 -0
  25. package/components/diagram/useDiagramViewport.ts +156 -0
  26. package/components/html-viewer/HtmlViewer.tsx +32 -0
  27. package/components/html-viewer/bridge-script.asset.js +121 -9
  28. package/components/html-viewer/bridge-script.lite.ts +1 -1
  29. package/components/html-viewer/bridge-script.ts +133 -9
  30. package/components/html-viewer/useHtmlAnnotation.ts +44 -151
  31. package/hooks/useAnnotationHighlighter.ts +469 -14
  32. package/hooks/useLinkedDoc.ts +100 -9
  33. package/package.json +6 -4
  34. package/shortcuts/plan-review/htmlAnnotate.shortcuts.ts +21 -7
  35. package/styles.css +1 -1
  36. package/theme.css +62 -0
  37. package/types.ts +5 -0
  38. package/utils/annotationScope.ts +159 -0
  39. package/utils/cssColor.ts +463 -0
  40. package/utils/diagram-anchor-graphviz.ts +143 -0
  41. package/utils/diagram-anchor.ts +401 -0
  42. package/utils/diagram-projection.ts +66 -0
  43. package/utils/diagram-render.ts +668 -0
  44. package/utils/graphviz.ts +93 -0
  45. package/utils/htmlChrome.ts +70 -5
  46. package/utils/htmlLinkNavigation.ts +196 -0
  47. package/utils/mermaid-eager.ts +13 -11
  48. package/utils/mermaid.ts +19 -10
  49. package/utils/mermaidTheme.ts +732 -0
  50. package/utils/parser.ts +36 -7
  51. package/utils/terminalToolsAnnouncement.ts +76 -0
  52. package/components/mermaidSvg.ts +0 -33
@@ -1,640 +1,27 @@
1
- import React, { useRef, useState, useEffect, useCallback } from 'react';
2
- import { createPortal } from 'react-dom';
3
- import type { Mermaid } from 'mermaid';
4
- import type { Block } from '../types';
5
- import { normalizeMermaidSvgMarkup } from './mermaidSvg';
6
- import {
7
- MERMAID_CONFIG,
8
- getMermaidRetryDelayMs,
9
- loadMermaidRuntime,
10
- __setMermaidRuntimeLoaderForTests,
11
- } from '../utils/mermaid';
12
- import { loadMathRenderer } from '../utils/math';
13
- import { hasMermaidMath } from '../utils/mermaid-math-slot';
14
- import { createRuntimeRetryEpoch } from '../utils/runtimeRetry';
15
-
16
- /** One Retry re-attempts every block whose runtime import failed (see utils/runtimeRetry). */
17
- const mermaidRetryEpoch = createRuntimeRetryEpoch();
1
+ import React from 'react';
2
+ import { MERMAID_CONFIG, __setMermaidRuntimeLoaderForTests } from '../utils/mermaid';
3
+ import { DiagramBlock, type DiagramBlockProps } from './DiagramBlock';
18
4
 
19
5
  // Re-exported: the config pin test and the lazy-retry test import them from here.
20
6
  export { MERMAID_CONFIG, __setMermaidRuntimeLoaderForTests };
21
7
 
22
8
  /**
23
- * The runtime comes from the slot in utils/mermaid: filled eagerly by
24
- * Plannotator (utils/mermaid-eager, imported by the editor App), loaded
25
- * lazily otherwise. See that module for the retry contract.
26
- */
27
- const getMermaid = loadMermaidRuntime;
28
-
29
- const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
30
-
31
- interface ViewBox {
32
- x: number;
33
- y: number;
34
- width: number;
35
- height: number;
36
- }
37
-
38
- const ZOOM_STEP = 0.25;
39
- const MIN_ZOOM = 0.25;
40
- const MAX_ZOOM = 8;
41
-
42
- function parseViewBox(svgEl: SVGSVGElement): ViewBox | null {
43
- const raw = svgEl.getAttribute('viewBox');
44
- if (!raw) return null;
45
-
46
- const values = raw
47
- .trim()
48
- .split(/[\s,]+/)
49
- .map((value) => Number.parseFloat(value));
50
-
51
- if (values.length !== 4 || values.some((value) => Number.isNaN(value))) {
52
- return null;
53
- }
54
-
55
- const [x, y, width, height] = values;
56
- if (width <= 0 || height <= 0) return null;
57
- return { x, y, width, height };
58
- }
59
-
60
- // Parse base viewBox from Mermaid SVG markup before DOM mount
61
- function parseViewBoxFromMarkup(markup: string): ViewBox | null {
62
- const viewBoxMatch = markup.match(/viewBox\s*=\s*"([^"]+)"/i);
63
- if (viewBoxMatch?.[1]) {
64
- const values = viewBoxMatch[1]
65
- .trim()
66
- .split(/[\s,]+/)
67
- .map((value) => Number.parseFloat(value));
68
-
69
- if (values.length === 4 && values.every((value) => Number.isFinite(value))) {
70
- const [x, y, width, height] = values;
71
- if (width > 0 && height > 0) {
72
- return { x, y, width, height };
73
- }
74
- }
75
- }
76
-
77
- const widthMatch = markup.match(/\bwidth\s*=\s*"([0-9.]+)(?:px)?"/i);
78
- const heightMatch = markup.match(/\bheight\s*=\s*"([0-9.]+)(?:px)?"/i);
79
- const width = widthMatch?.[1] ? Number.parseFloat(widthMatch[1]) : NaN;
80
- const height = heightMatch?.[1] ? Number.parseFloat(heightMatch[1]) : NaN;
81
- if (Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0) {
82
- return { x: 0, y: 0, width, height };
83
- }
84
-
85
- return null;
86
- }
87
-
88
- // Apply calculated viewBox from zoom and pan state
89
- function applyView(svgEl: SVGSVGElement, base: ViewBox, zoom: number, pan: { x: number; y: number }): void {
90
- const zoomedWidth = base.width / zoom;
91
- const zoomedHeight = base.height / zoom;
92
- const centerX = base.x + base.width / 2;
93
- const centerY = base.y + base.height / 2;
94
- const vbX = centerX - zoomedWidth / 2 + pan.x;
95
- const vbY = centerY - zoomedHeight / 2 + pan.y;
96
- svgEl.setAttribute('viewBox', `${vbX} ${vbY} ${zoomedWidth} ${zoomedHeight}`);
97
- }
98
-
99
- // Compute a fitted base viewBox for the current container ratio
100
- function fitBoundsToContainer(bounds: ViewBox, containerRect: DOMRect): ViewBox {
101
- const containerWidth = Math.max(containerRect.width, 1);
102
- const containerHeight = Math.max(containerRect.height, 1);
103
- const contentRatio = bounds.width / bounds.height;
104
- const containerRatio = containerWidth / containerHeight;
105
-
106
- if (contentRatio > containerRatio) {
107
- const targetHeight = bounds.width / containerRatio;
108
- const extra = (targetHeight - bounds.height) / 2;
109
- return {
110
- x: bounds.x,
111
- y: bounds.y - extra,
112
- width: bounds.width,
113
- height: targetHeight,
114
- };
115
- }
116
-
117
- const targetWidth = bounds.height * containerRatio;
118
- const extra = (targetWidth - bounds.width) / 2;
119
- return {
120
- x: bounds.x - extra,
121
- y: bounds.y,
122
- width: targetWidth,
123
- height: bounds.height,
124
- };
125
- }
126
-
127
- /**
128
- * Renders a mermaid diagram block with zoom controls.
9
+ * A mermaid fence. The engine, the canvas, the comment overlay and the
10
+ * popout are `DiagramBlock`'s (one code path with `GraphvizBlock`); this
11
+ * file keeps the fence's name and the test hooks. The runtime comes from the
12
+ * slot in `utils/mermaid`: loaded lazily on the first diagram, or already
13
+ * filled by a host that imported `utils/mermaid-eager`.
129
14
  */
130
- const MermaidBlockImpl: React.FC<{ block: Block }> = ({ block }) => {
131
- const containerRef = useRef<HTMLDivElement>(null);
132
- const expandedOverlayRef = useRef<HTMLDivElement>(null);
133
- const [svg, setSvg] = useState('');
134
- const [error, setError] = useState<string | null>(null);
135
- // True when the failure was the runtime import itself (a chunking host's
136
- // fetch), which is the only failure a Retry can change; a diagram syntax
137
- // error keeps the panel exactly as it always was.
138
- const [runtimeUnavailable, setRuntimeUnavailable] = useState(false);
139
- const [retryToken, setRetryToken] = useState(0);
140
- const [showSource, setShowSource] = useState(false);
141
- const [isExpanded, setIsExpanded] = useState(false);
142
- // A sibling's Retry re-attempts this block too, but only while its own
143
- // failure was the shared runtime import; a healthy block or a diagram
144
- // syntax error is left alone.
145
- const runtimeUnavailableRef = useRef(runtimeUnavailable);
146
- runtimeUnavailableRef.current = runtimeUnavailable;
147
- useEffect(() => mermaidRetryEpoch.subscribe(() => {
148
- if (!runtimeUnavailableRef.current) return;
149
- setError(null);
150
- setRetryToken((token) => token + 1);
151
- }), []);
152
-
153
- // All zoom/pan state as refs to avoid re-renders
154
- const zoomLevelRef = useRef(1);
155
- const isDraggingRef = useRef(false);
156
- const naturalBoundsRef = useRef<ViewBox | null>(null);
157
- const baseViewBoxRef = useRef<ViewBox | null>(null);
158
- const panOffsetRef = useRef({ x: 0, y: 0 });
159
- const dragStartRef = useRef({ x: 0, y: 0 });
160
- const panStartRef = useRef({ x: 0, y: 0 });
161
-
162
- // UI refs for zoom controls
163
- const zoomInBtnRef = useRef<HTMLButtonElement>(null);
164
- const zoomOutBtnRef = useRef<HTMLButtonElement>(null);
165
- const zoomDisplayRef = useRef<HTMLSpanElement>(null);
166
-
167
- // Update zoom level, viewBox, and UI without React re-render
168
- const updateZoom = useCallback((newZoom: number) => {
169
- zoomLevelRef.current = newZoom;
170
-
171
- if (containerRef.current && baseViewBoxRef.current) {
172
- const svgEl = containerRef.current.querySelector('svg');
173
- if (svgEl instanceof SVGSVGElement) {
174
- applyView(svgEl, baseViewBoxRef.current, newZoom, panOffsetRef.current);
175
- }
176
- }
177
-
178
- if (zoomInBtnRef.current) zoomInBtnRef.current.disabled = newZoom >= MAX_ZOOM;
179
- if (zoomOutBtnRef.current) zoomOutBtnRef.current.disabled = newZoom <= MIN_ZOOM;
180
- if (zoomDisplayRef.current) {
181
- const show = Math.abs(newZoom - 1) > 0.001;
182
- zoomDisplayRef.current.textContent = show ? `${Math.round(newZoom * 100)}%` : '';
183
- zoomDisplayRef.current.hidden = !show;
184
- }
185
- }, []);
186
-
187
- const fitToCurrentViewport = useCallback(() => {
188
- if (!containerRef.current || !naturalBoundsRef.current) return;
189
-
190
- const svgEl = containerRef.current.querySelector('svg');
191
- if (!(svgEl instanceof SVGSVGElement)) return;
192
-
193
- const fitted = fitBoundsToContainer(naturalBoundsRef.current, containerRef.current.getBoundingClientRect());
194
- baseViewBoxRef.current = fitted;
195
- panOffsetRef.current = { x: 0, y: 0 };
196
- updateZoom(1);
197
- applyView(svgEl, fitted, 1, { x: 0, y: 0 });
198
- }, [updateZoom]);
199
-
200
- useEffect(() => {
201
- let cancelled = false;
202
-
203
- // Render mermaid diagram
204
- const renderDiagram = async () => {
205
- let mermaid: Mermaid;
206
- try {
207
- try {
208
- mermaid = await getMermaid();
209
- } catch {
210
- // Transient chunk failure on a chunking host: one automatic
211
- // re-attempt with a fresh import() after a short delay. In a
212
- // single-file build the first await never rejects, so this branch
213
- // is unreachable there and the success path is unchanged.
214
- await wait(getMermaidRetryDelayMs());
215
- if (cancelled) return;
216
- mermaid = await getMermaid();
217
- }
218
- } catch (err) {
219
- if (!cancelled) {
220
- setError(err instanceof Error ? err.message : 'Failed to render diagram');
221
- setRuntimeUnavailable(true);
222
- setSvg('');
223
- }
224
- return;
225
- }
226
- try {
227
- // A `$$` label makes Mermaid render KaTeX. On a host that redirects
228
- // Mermaid's `katex` import to `utils/mermaid-math-slot` the label is
229
- // typeset through the math slot, which must be filled by then: warm
230
- // it with the registered loader first. A filled slot (Plannotator's
231
- // eager entry) resolves at once; a load failure is left to the
232
- // render, whose error panel names it with the source.
233
- if (hasMermaidMath(block.content)) {
234
- try {
235
- await loadMathRenderer();
236
- } catch {
237
- // Reported by the render below.
238
- }
239
- if (cancelled) return;
240
- }
241
- const id = `mermaid-${block.id}`;
242
- const { svg: renderedSvg } = await mermaid.render(id, block.content);
243
- if (!cancelled) {
244
- const normalizedSvg = normalizeMermaidSvgMarkup(renderedSvg);
245
- naturalBoundsRef.current = parseViewBoxFromMarkup(normalizedSvg);
246
- setSvg(normalizedSvg);
247
- setError(null);
248
- setRuntimeUnavailable(false);
249
- }
250
- } catch (err) {
251
- if (!cancelled) {
252
- setError(err instanceof Error ? err.message : 'Failed to render diagram');
253
- setRuntimeUnavailable(false);
254
- setSvg('');
255
- }
256
- }
257
- };
258
-
259
- renderDiagram();
260
-
261
- return () => {
262
- cancelled = true;
263
- };
264
- }, [block.content, block.id, retryToken]);
265
-
266
- // Reset zoom and pan when content changes
267
- useEffect(() => {
268
- zoomLevelRef.current = 1;
269
- naturalBoundsRef.current = null;
270
- baseViewBoxRef.current = null;
271
- panOffsetRef.current = { x: 0, y: 0 };
272
- setIsExpanded(false);
273
- }, [block.content]);
274
-
275
- // Reset zoom and pan when switching from source back to diagram
276
- useEffect(() => {
277
- if (showSource) {
278
- setIsExpanded(false);
279
- return;
280
- }
281
-
282
- zoomLevelRef.current = 1;
283
- panOffsetRef.current = { x: 0, y: 0 };
284
- baseViewBoxRef.current = null;
285
- }, [showSource]);
286
-
287
- useEffect(() => {
288
- if (!isExpanded) return undefined;
289
-
290
- const previousOverflow = document.body.style.overflow;
291
- document.body.style.overflow = 'hidden';
292
-
293
- const handleKeyDown = (event: KeyboardEvent) => {
294
- if (event.key === 'Escape') {
295
- setIsExpanded(false);
296
- }
297
- };
298
-
299
- window.addEventListener('keydown', handleKeyDown);
300
-
301
- return () => {
302
- document.body.style.overflow = previousOverflow;
303
- window.removeEventListener('keydown', handleKeyDown);
304
- };
305
- }, [isExpanded]);
306
-
307
- // Compute base viewBox from rendered SVG and apply initial view
308
- useEffect(() => {
309
- if (!svg || showSource || !containerRef.current) return;
310
-
311
- const svgEl = containerRef.current.querySelector('svg');
312
- if (!(svgEl instanceof SVGSVGElement)) return;
313
-
314
- svgEl.style.maxWidth = 'none';
315
- svgEl.style.width = '100%';
316
- svgEl.style.height = '100%';
317
- svgEl.style.display = 'block';
318
- svgEl.style.filter = 'none';
319
- svgEl.style.willChange = 'auto';
320
- svgEl.setAttribute('width', '100%');
321
- svgEl.setAttribute('height', '100%');
322
- svgEl.setAttribute('preserveAspectRatio', 'xMidYMid meet');
323
-
324
- let cancelled = false;
325
-
326
- const applyInitialView = () => {
327
- if (cancelled) return;
328
-
329
- try {
330
- const base = naturalBoundsRef.current ?? parseViewBox(svgEl);
331
-
332
- if (!base) return;
333
-
334
- naturalBoundsRef.current = base;
335
- fitToCurrentViewport();
336
- } catch {
337
- setError('Failed to measure diagram bounds');
338
- setSvg('');
339
- }
340
- };
341
-
342
- const raf = requestAnimationFrame(() => requestAnimationFrame(applyInitialView));
343
- const timer = window.setTimeout(applyInitialView, 120);
344
-
345
- return () => {
346
- cancelled = true;
347
- cancelAnimationFrame(raf);
348
- window.clearTimeout(timer);
349
- };
350
- }, [fitToCurrentViewport, isExpanded, showSource, svg]);
351
-
352
- const applyWheelZoomDelta = useCallback((deltaY: number) => {
353
- if (Math.abs(deltaY) < 0.1) {
354
- return;
355
- }
356
-
357
- const delta = deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
358
- const newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoomLevelRef.current + delta));
359
- updateZoom(newZoom);
360
- }, [updateZoom]);
361
-
362
- useEffect(() => {
363
- if (showSource || !containerRef.current) return;
364
-
365
- const container = containerRef.current;
366
- const handleWheel = (event: WheelEvent) => {
367
- if (Math.abs(event.deltaY) < 0.1) return;
368
- event.preventDefault();
369
- applyWheelZoomDelta(event.deltaY);
370
- };
371
-
372
- container.addEventListener('wheel', handleWheel, { passive: false });
373
-
374
- return () => {
375
- container.removeEventListener('wheel', handleWheel);
376
- };
377
- }, [applyWheelZoomDelta, showSource]);
378
-
379
- useEffect(() => {
380
- if (showSource || !isExpanded) return;
381
-
382
- const handleExpandedPinchWheel = (event: WheelEvent) => {
383
- if (!event.ctrlKey && !event.metaKey) return;
384
- if (!expandedOverlayRef.current) return;
385
-
386
- const eventTarget = event.target;
387
- if (!(eventTarget instanceof Node) || !expandedOverlayRef.current.contains(eventTarget)) return;
388
-
389
- event.preventDefault();
390
- event.stopPropagation();
391
- applyWheelZoomDelta(event.deltaY);
392
- };
393
-
394
- window.addEventListener('wheel', handleExpandedPinchWheel, { passive: false, capture: true });
395
-
396
- return () => {
397
- window.removeEventListener('wheel', handleExpandedPinchWheel, { capture: true });
398
- };
399
- }, [applyWheelZoomDelta, isExpanded, showSource]);
400
-
401
- const handleZoomIn = useCallback(() => {
402
- updateZoom(Math.min(zoomLevelRef.current + ZOOM_STEP, MAX_ZOOM));
403
- }, [updateZoom]);
404
-
405
- const handleZoomOut = useCallback(() => {
406
- updateZoom(Math.max(zoomLevelRef.current - ZOOM_STEP, MIN_ZOOM));
407
- }, [updateZoom]);
408
-
409
- const handleFitToScreen = useCallback(() => {
410
- fitToCurrentViewport();
411
- }, [fitToCurrentViewport]);
412
-
413
- useEffect(() => {
414
- if (showSource || !containerRef.current || !naturalBoundsRef.current) return;
415
- if (typeof ResizeObserver === 'undefined') return;
416
-
417
- const observer = new ResizeObserver(() => {
418
- if (Math.abs(zoomLevelRef.current - 1) > 0.001) return;
419
- fitToCurrentViewport();
420
- });
421
-
422
- observer.observe(containerRef.current);
423
- return () => observer.disconnect();
424
- }, [fitToCurrentViewport, isExpanded, showSource, svg]);
425
-
426
- // Drag-to-pan handlers (all ref-based to avoid re-renders)
427
- const handleMouseDown = useCallback((event: React.MouseEvent) => {
428
- if (event.button !== 0) return;
429
- event.preventDefault();
430
- isDraggingRef.current = true;
431
- dragStartRef.current = { x: event.clientX, y: event.clientY };
432
- panStartRef.current = { ...panOffsetRef.current };
433
- if (containerRef.current) containerRef.current.style.cursor = 'grabbing';
434
- }, []);
435
-
436
- const handleMouseMove = useCallback((event: React.MouseEvent) => {
437
- if (!isDraggingRef.current || !containerRef.current || !baseViewBoxRef.current) return;
438
-
439
- const svgEl = containerRef.current.querySelector('svg');
440
- if (!(svgEl instanceof SVGSVGElement)) return;
441
-
442
- const rect = svgEl.getBoundingClientRect();
443
- const base = baseViewBoxRef.current;
444
- const zoom = zoomLevelRef.current;
445
- const scaleX = (base.width / zoom) / rect.width;
446
- const scaleY = (base.height / zoom) / rect.height;
447
-
448
- const dx = event.clientX - dragStartRef.current.x;
449
- const dy = event.clientY - dragStartRef.current.y;
450
-
451
- panOffsetRef.current = {
452
- x: panStartRef.current.x - dx * scaleX,
453
- y: panStartRef.current.y - dy * scaleY,
454
- };
455
-
456
- applyView(svgEl, base, zoom, panOffsetRef.current);
457
- }, []);
458
-
459
- const stopDragging = useCallback(() => {
460
- if (!isDraggingRef.current) return;
461
- isDraggingRef.current = false;
462
- if (containerRef.current) containerRef.current.style.cursor = 'grab';
463
- }, []);
464
-
465
- if (error) {
466
- return (
467
- <div className="my-5 rounded-lg border border-destructive/30 bg-destructive/5 overflow-hidden">
468
- <div className="px-3 py-2 bg-destructive/10 border-b border-destructive/20 flex items-center gap-2">
469
- <svg className="w-4 h-4 text-destructive" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
470
- <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
471
- </svg>
472
- <span className="text-xs text-destructive font-medium">Mermaid Error</span>
473
- {runtimeUnavailable && (
474
- <button
475
- type="button"
476
- onClick={() => mermaidRetryEpoch.bump()}
477
- className="ml-auto rounded-md border border-destructive/30 px-2 py-0.5 text-xs text-destructive hover:bg-destructive/10"
478
- title="Retry loading the diagram renderer"
479
- >
480
- Retry
481
- </button>
482
- )}
483
- </div>
484
- <pre className="p-3 text-xs text-destructive/80 overflow-x-auto">{error}</pre>
485
- <pre className="p-3 text-xs text-muted-foreground bg-muted/30 border-t border-border/30 overflow-x-auto">
486
- <code>{block.content}</code>
487
- </pre>
488
- </div>
489
- );
490
- }
491
-
492
- const controls = (
493
- /* Controls container */
494
- <div className={`absolute top-2 right-2 flex flex-col gap-1 items-center z-10 ${isExpanded ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 transition-opacity'}`}>
495
- {/* Toggle source/diagram button */}
496
- <button
497
- onClick={() => setShowSource(!showSource)}
498
- className="p-1.5 rounded-md bg-muted/85 hover:bg-muted text-muted-foreground hover:text-foreground"
499
- title={showSource ? 'Show diagram' : 'Show source'}
500
- >
501
- {showSource ? (
502
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
503
- <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
504
- </svg>
505
- ) : (
506
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
507
- <path strokeLinecap="round" strokeLinejoin="round" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
508
- </svg>
509
- )}
510
- </button>
511
-
512
- {!showSource && svg && (
513
- <>
514
- {/* Diagram interaction controls */}
515
- <div className="flex w-10 flex-col items-center gap-0.5 bg-muted/85 rounded-md p-0.5">
516
- {/* Expand/exit expanded button */}
517
- <button
518
- onClick={() => setIsExpanded(!isExpanded)}
519
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
520
- title={isExpanded ? 'Exit expanded view' : 'Expand diagram'}
521
- aria-label={isExpanded ? 'Exit expanded view' : 'Expand diagram'}
522
- >
523
- {isExpanded ? (
524
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
525
- <path strokeLinecap="round" strokeLinejoin="round" d="M6 10h4V6M18 10h-4V6M6 14h4v4M18 14h-4v4" />
526
- </svg>
527
- ) : (
528
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
529
- <path strokeLinecap="round" strokeLinejoin="round" d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />
530
- </svg>
531
- )}
532
- </button>
533
-
534
- {/* Zoom in button */}
535
- <button
536
- ref={zoomInBtnRef}
537
- onClick={handleZoomIn}
538
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-not-allowed"
539
- title="Zoom in"
540
- aria-label="Zoom in"
541
- >
542
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
543
- <path strokeLinecap="round" strokeLinejoin="round" d="M12 5v14M5 12h14" />
544
- </svg>
545
- </button>
546
-
547
- {/* Fit to view button */}
548
- <button
549
- onClick={handleFitToScreen}
550
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
551
- title="Fit to view"
552
- aria-label="Fit to view"
553
- >
554
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
555
- <circle cx="12" cy="12" r="4" strokeLinecap="round" strokeLinejoin="round" />
556
- <path strokeLinecap="round" strokeLinejoin="round" d="M12 2v4M12 18v4M2 12h4M18 12h4" />
557
- </svg>
558
- </button>
559
-
560
- {/* Zoom out button */}
561
- <button
562
- ref={zoomOutBtnRef}
563
- onClick={handleZoomOut}
564
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-not-allowed"
565
- title="Zoom out"
566
- aria-label="Zoom out"
567
- >
568
- <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
569
- <path strokeLinecap="round" strokeLinejoin="round" d="M5 12h14" />
570
- </svg>
571
- </button>
572
- </div>
573
-
574
- {/* Zoom percentage badge */}
575
- <span
576
- ref={zoomDisplayRef}
577
- hidden
578
- className="min-w-10 rounded bg-muted/85 px-1 py-0.5 text-[10px] text-center text-muted-foreground tabular-nums leading-tight"
579
- />
580
- </>
581
- )}
582
- </div>
583
- );
584
-
585
- const inlineSource = (
586
- <pre className="rounded-lg text-[13px] overflow-x-auto bg-muted/50 border border-border/30 p-4">
587
- <code className="pn-code font-mono language-mermaid">{block.content}</code>
588
- </pre>
589
- );
590
-
591
- const diagramBody = (
592
- <div
593
- ref={containerRef}
594
- data-pinpoint-ignore=""
595
- className={`rounded-xl bg-muted/30 border border-border/30 overflow-hidden select-none cursor-grab ${isExpanded ? 'h-full min-h-0' : 'h-[min(65vh,36rem)] min-h-[20rem]'}`}
596
- dangerouslySetInnerHTML={{ __html: svg }}
597
- onMouseDown={handleMouseDown}
598
- onMouseMove={handleMouseMove}
599
- onMouseUp={stopDragging}
600
- onMouseLeave={stopDragging}
601
- />
602
- );
603
-
604
- return (
605
- <>
606
- <div className="my-5 group relative" data-block-id={block.id}>
607
- {!isExpanded && controls}
608
- {showSource || !svg ? inlineSource : !isExpanded ? diagramBody : <div className="rounded-xl border border-border/30 bg-muted/10 h-[min(65vh,36rem)] min-h-[20rem]" />}
609
- </div>
610
-
611
- {!showSource && svg && isExpanded && typeof document !== 'undefined' && createPortal(
612
- <div ref={expandedOverlayRef} className="fixed inset-0 z-[9999] bg-background/90 backdrop-blur-sm p-4 md:p-6">
613
- <div className="mx-auto flex h-full max-w-[min(96vw,110rem)] flex-col gap-3">
614
- <div className="flex items-center justify-between gap-4 text-xs text-muted-foreground">
615
- <span className="truncate">Mermaid diagram</span>
616
- <button
617
- onClick={() => setIsExpanded(false)}
618
- className="rounded-md border border-border/60 bg-card/70 px-2.5 py-1.5 text-foreground hover:bg-card"
619
- >
620
- Close
621
- </button>
622
- </div>
623
- <div className="group relative flex-1 min-h-0">
624
- {controls}
625
- {diagramBody}
626
- </div>
627
- </div>
628
- </div>,
629
- document.body
630
- )}
631
- </>
632
- );
633
- };
634
-
635
15
  export const MermaidBlock = React.memo(
636
- MermaidBlockImpl,
16
+ (props: DiagramBlockProps) => <DiagramBlock kind="mermaid" {...props} />,
637
17
  (prev, next) =>
638
18
  prev.block.id === next.block.id &&
639
- prev.block.content === next.block.content,
19
+ prev.block.content === next.block.content &&
20
+ prev.block.startLine === next.block.startLine &&
21
+ prev.annotations === next.annotations &&
22
+ prev.selectedAnnotationId === next.selectedAnnotationId &&
23
+ prev.onSelectAnnotation === next.onSelectAnnotation &&
24
+ prev.onAddAnnotation === next.onAddAnnotation &&
25
+ prev.readOnly === next.readOnly &&
26
+ prev.onRestoreReport === next.onRestoreReport,
640
27
  );
@@ -97,7 +97,11 @@ export function TableOfContents({
97
97
  [onNavigate, scrollViewport]
98
98
  );
99
99
 
100
- if (tocItems.length === 0) {
100
+ // A linked document with no headings of its own — most obviously a raw-HTML
101
+ // one, which is never parsed into blocks — still needs the "Viewing / Back
102
+ // to …" header, which lives here. Without it, opening such a document from
103
+ // a link leaves no visible way back.
104
+ if (tocItems.length === 0 && !linkedDocFilepath) {
101
105
  return null;
102
106
  }
103
107