@flamingo-stack/openframe-frontend-core 0.0.646 → 0.0.647

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 (105) hide show
  1. package/dist/{chunk-XJH5M2B7.js → chunk-5DCRDV7Y.js} +6 -6
  2. package/dist/{chunk-C6QUB6IS.cjs → chunk-5XBO6URE.cjs} +22 -22
  3. package/dist/{chunk-C6QUB6IS.cjs.map → chunk-5XBO6URE.cjs.map} +1 -1
  4. package/dist/{chunk-7UWJMWDH.cjs → chunk-5YW3GAUR.cjs} +660 -494
  5. package/dist/chunk-5YW3GAUR.cjs.map +1 -0
  6. package/dist/{chunk-ZDIDA4QG.js → chunk-6Z4GSQPB.js} +2 -2
  7. package/dist/{chunk-JFBUXYDK.cjs → chunk-ABVOAYYS.cjs} +15 -15
  8. package/dist/{chunk-JFBUXYDK.cjs.map → chunk-ABVOAYYS.cjs.map} +1 -1
  9. package/dist/{chunk-NWYSHZG7.cjs → chunk-AKM4AIZY.cjs} +22 -22
  10. package/dist/{chunk-NWYSHZG7.cjs.map → chunk-AKM4AIZY.cjs.map} +1 -1
  11. package/dist/{chunk-N2E26OD6.cjs → chunk-ASPNYVGE.cjs} +45 -45
  12. package/dist/{chunk-N2E26OD6.cjs.map → chunk-ASPNYVGE.cjs.map} +1 -1
  13. package/dist/{chunk-TZO743LD.cjs → chunk-DBSU5RAE.cjs} +3 -3
  14. package/dist/{chunk-TZO743LD.cjs.map → chunk-DBSU5RAE.cjs.map} +1 -1
  15. package/dist/{chunk-PD47DDHS.js → chunk-DIGCERY4.js} +3 -3
  16. package/dist/{chunk-NKMXFBV5.js → chunk-DLJHXLFG.js} +4 -4
  17. package/dist/{chunk-NZ66W56D.cjs → chunk-EG3PA7L2.cjs} +10 -10
  18. package/dist/{chunk-NZ66W56D.cjs.map → chunk-EG3PA7L2.cjs.map} +1 -1
  19. package/dist/{chunk-5C7GMRJU.js → chunk-ERLGZPCY.js} +5 -5
  20. package/dist/{chunk-2V7SCIOG.cjs → chunk-EZ6HGRLP.cjs} +33 -33
  21. package/dist/{chunk-2V7SCIOG.cjs.map → chunk-EZ6HGRLP.cjs.map} +1 -1
  22. package/dist/{chunk-X2VTQ3TL.cjs → chunk-F4I46MKF.cjs} +10 -10
  23. package/dist/{chunk-X2VTQ3TL.cjs.map → chunk-F4I46MKF.cjs.map} +1 -1
  24. package/dist/{chunk-WJ7PDBPK.cjs → chunk-IBTOED4M.cjs} +4 -4
  25. package/dist/{chunk-WJ7PDBPK.cjs.map → chunk-IBTOED4M.cjs.map} +1 -1
  26. package/dist/{chunk-XATBOM3X.js → chunk-IKMETQWQ.js} +5 -5
  27. package/dist/{chunk-QS55P2TA.js → chunk-L6ES7O6B.js} +6 -6
  28. package/dist/chunk-L6ES7O6B.js.map +1 -0
  29. package/dist/{chunk-H4FQRA5O.cjs → chunk-MKGAIWQ5.cjs} +3 -3
  30. package/dist/{chunk-H4FQRA5O.cjs.map → chunk-MKGAIWQ5.cjs.map} +1 -1
  31. package/dist/{chunk-DULSS7R6.js → chunk-N6ZYJXVJ.js} +709 -543
  32. package/dist/chunk-N6ZYJXVJ.js.map +1 -0
  33. package/dist/{chunk-ZW2BEEX2.cjs → chunk-Q2XH3HW6.cjs} +25 -25
  34. package/dist/{chunk-ZW2BEEX2.cjs.map → chunk-Q2XH3HW6.cjs.map} +1 -1
  35. package/dist/{chunk-XPPGI7SD.js → chunk-QPAQEPA3.js} +2 -2
  36. package/dist/{chunk-ZGWXD2S3.js → chunk-RIOWS34T.js} +3 -3
  37. package/dist/{chunk-AYAZU3BO.cjs → chunk-RSRYEVGZ.cjs} +5 -5
  38. package/dist/{chunk-AYAZU3BO.cjs.map → chunk-RSRYEVGZ.cjs.map} +1 -1
  39. package/dist/{chunk-UR7BC74V.js → chunk-RUEVZAPN.js} +3 -3
  40. package/dist/{chunk-5MZZFTME.js → chunk-RXIFYEL7.js} +5 -5
  41. package/dist/{chunk-LDJ4TIDC.cjs → chunk-SS2RN4TU.cjs} +9 -9
  42. package/dist/{chunk-LDJ4TIDC.cjs.map → chunk-SS2RN4TU.cjs.map} +1 -1
  43. package/dist/{chunk-GBZ3IR3S.js → chunk-T7NBMDDE.js} +2 -2
  44. package/dist/{chunk-5JVN3EVT.cjs → chunk-TO4UY3P5.cjs} +71 -71
  45. package/dist/{chunk-5JVN3EVT.cjs.map → chunk-TO4UY3P5.cjs.map} +1 -1
  46. package/dist/{chunk-4GOJFHJY.js → chunk-V33TSVUR.js} +2 -2
  47. package/dist/{chunk-LLT5XMP2.js → chunk-VXG43NJD.js} +3 -3
  48. package/dist/{chunk-RRSR2XHJ.cjs → chunk-YCSYKAT2.cjs} +167 -167
  49. package/dist/chunk-YCSYKAT2.cjs.map +1 -0
  50. package/dist/{chunk-ETEM2ZD4.js → chunk-ZNSBWM2D.js} +3 -3
  51. package/dist/components/case-studies/index.cjs +14 -14
  52. package/dist/components/case-studies/index.js +3 -3
  53. package/dist/components/chat/index.cjs +2 -2
  54. package/dist/components/chat/index.js +1 -1
  55. package/dist/components/contact/index.cjs +4 -4
  56. package/dist/components/contact/index.js +3 -3
  57. package/dist/components/docs/index.cjs +7 -7
  58. package/dist/components/docs/index.js +6 -6
  59. package/dist/components/embeds/index.cjs +4 -4
  60. package/dist/components/embeds/index.js +3 -3
  61. package/dist/components/faq/index.cjs +4 -4
  62. package/dist/components/faq/index.js +3 -3
  63. package/dist/components/features/index.cjs +3 -3
  64. package/dist/components/features/index.js +2 -2
  65. package/dist/components/help-center-pages/index.cjs +23 -23
  66. package/dist/components/help-center-pages/index.js +14 -14
  67. package/dist/components/index.cjs +39 -39
  68. package/dist/components/index.js +13 -13
  69. package/dist/components/meeting-scheduler/index.cjs +24 -24
  70. package/dist/components/meeting-scheduler/index.js +2 -2
  71. package/dist/components/navigation/index.cjs +6 -6
  72. package/dist/components/navigation/index.js +5 -5
  73. package/dist/components/onboarding-guides/index.cjs +6 -6
  74. package/dist/components/onboarding-guides/index.js +5 -5
  75. package/dist/components/tickets/index.cjs +7 -7
  76. package/dist/components/tickets/index.js +6 -6
  77. package/dist/components/ui/data-table/data-table-skeleton.d.ts.map +1 -1
  78. package/dist/components/ui/index.cjs +3 -3
  79. package/dist/components/ui/index.js +2 -2
  80. package/dist/components/ui/markdown/mermaid-diagram.d.ts +31 -9
  81. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +1 -1
  82. package/dist/index.cjs +7 -7
  83. package/dist/index.js +6 -6
  84. package/package.json +1 -1
  85. package/src/components/ui/data-table/data-table-skeleton.tsx +15 -7
  86. package/src/components/ui/markdown/__tests__/mermaid-zoom.test.tsx +115 -0
  87. package/src/components/ui/markdown/mermaid-diagram.tsx +279 -59
  88. package/dist/chunk-7UWJMWDH.cjs.map +0 -1
  89. package/dist/chunk-DULSS7R6.js.map +0 -1
  90. package/dist/chunk-QS55P2TA.js.map +0 -1
  91. package/dist/chunk-RRSR2XHJ.cjs.map +0 -1
  92. /package/dist/{chunk-XJH5M2B7.js.map → chunk-5DCRDV7Y.js.map} +0 -0
  93. /package/dist/{chunk-ZDIDA4QG.js.map → chunk-6Z4GSQPB.js.map} +0 -0
  94. /package/dist/{chunk-PD47DDHS.js.map → chunk-DIGCERY4.js.map} +0 -0
  95. /package/dist/{chunk-NKMXFBV5.js.map → chunk-DLJHXLFG.js.map} +0 -0
  96. /package/dist/{chunk-5C7GMRJU.js.map → chunk-ERLGZPCY.js.map} +0 -0
  97. /package/dist/{chunk-XATBOM3X.js.map → chunk-IKMETQWQ.js.map} +0 -0
  98. /package/dist/{chunk-XPPGI7SD.js.map → chunk-QPAQEPA3.js.map} +0 -0
  99. /package/dist/{chunk-ZGWXD2S3.js.map → chunk-RIOWS34T.js.map} +0 -0
  100. /package/dist/{chunk-UR7BC74V.js.map → chunk-RUEVZAPN.js.map} +0 -0
  101. /package/dist/{chunk-5MZZFTME.js.map → chunk-RXIFYEL7.js.map} +0 -0
  102. /package/dist/{chunk-GBZ3IR3S.js.map → chunk-T7NBMDDE.js.map} +0 -0
  103. /package/dist/{chunk-4GOJFHJY.js.map → chunk-V33TSVUR.js.map} +0 -0
  104. /package/dist/{chunk-LLT5XMP2.js.map → chunk-VXG43NJD.js.map} +0 -0
  105. /package/dist/{chunk-ETEM2ZD4.js.map → chunk-ZNSBWM2D.js.map} +0 -0
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The zoom toolbar lives in the ONE MermaidDiagram, so every diagram (a
3
+ * markdown fence, a server-rendered admin chart) zooms the same way. Pins:
4
+ * the buttons change the container's CSS `zoom`, the bounds hold, reset
5
+ * returns to 100%, and `zoomable={false}` renders no toolbar.
6
+ */
7
+ import { render, act, screen, fireEvent } from '@testing-library/react';
8
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
9
+
10
+ const renders: Array<{ resolve: (value: { svg: string }) => void }> = [];
11
+
12
+ vi.mock('mermaid', () => ({
13
+ default: {
14
+ initialize: vi.fn(),
15
+ render: vi.fn(
16
+ () =>
17
+ new Promise<{ svg: string }>(resolve => {
18
+ renders.push({ resolve });
19
+ }),
20
+ ),
21
+ },
22
+ }));
23
+
24
+ import { MERMAID_ZOOM_MAX, MERMAID_ZOOM_MIN, MermaidDiagram } from '../mermaid-diagram';
25
+
26
+ const flushUntil = async (done: () => boolean, what: string) => {
27
+ for (let i = 0; i < 50; i++) {
28
+ await act(async () => {
29
+ await new Promise(resolve => setTimeout(resolve, 0));
30
+ });
31
+ if (done()) return;
32
+ }
33
+ throw new Error(`timed out waiting for ${what}`);
34
+ };
35
+
36
+ const mountRendered = async (props: { zoomable?: boolean } = {}) => {
37
+ render(<MermaidDiagram chart="flowchart LR; a-->b" {...props} />);
38
+ await flushUntil(() => renders.length >= 1, 'a mermaid.render call');
39
+ await act(async () => {
40
+ renders[0].resolve({ svg: '<svg width="10" height="10"><g/></svg>' });
41
+ });
42
+ await flushUntil(() => !!screen.queryByTestId('mermaid-svg-container'), 'the rendered diagram');
43
+ };
44
+
45
+ const zoomOf = () => Number(screen.getByTestId('mermaid-svg-container').getAttribute('data-zoom'));
46
+
47
+ describe('MermaidDiagram zoom', () => {
48
+ beforeEach(() => {
49
+ renders.length = 0;
50
+ });
51
+
52
+ it('zooms in and out from the toolbar and resets to 100%', async () => {
53
+ await mountRendered();
54
+ expect(zoomOf()).toBe(1);
55
+ fireEvent.click(screen.getByRole('button', { name: 'Zoom in' }));
56
+ expect(zoomOf()).toBe(1.25);
57
+ fireEvent.click(screen.getByRole('button', { name: 'Zoom in' }));
58
+ expect(zoomOf()).toBeCloseTo(1.56, 2);
59
+ fireEvent.click(screen.getByRole('button', { name: 'Reset zoom' }));
60
+ expect(zoomOf()).toBe(1);
61
+ fireEvent.click(screen.getByRole('button', { name: 'Zoom out' }));
62
+ expect(zoomOf()).toBe(0.8);
63
+ });
64
+
65
+ it('stays inside the bounds and disables the button at each end', async () => {
66
+ await mountRendered();
67
+ const zoomIn = screen.getByRole('button', { name: 'Zoom in' });
68
+ for (let i = 0; i < 20; i++) fireEvent.click(zoomIn);
69
+ expect(zoomOf()).toBe(MERMAID_ZOOM_MAX);
70
+ expect(zoomIn).toBeDisabled();
71
+ const zoomOut = screen.getByRole('button', { name: 'Zoom out' });
72
+ for (let i = 0; i < 40; i++) fireEvent.click(zoomOut);
73
+ expect(zoomOf()).toBe(MERMAID_ZOOM_MIN);
74
+ expect(zoomOut).toBeDisabled();
75
+ });
76
+
77
+ it('holds the skeleton for an empty chart instead of asking mermaid to parse it', async () => {
78
+ const { rerender } = render(<MermaidDiagram chart="" frame="fold" />);
79
+ await act(async () => {
80
+ await new Promise(resolve => setTimeout(resolve, 20));
81
+ });
82
+ expect(renders).toHaveLength(0);
83
+ expect(screen.getByTestId('mermaid-frame').getAttribute('data-frame')).toBe('fold');
84
+ expect(screen.queryByTestId('mermaid-svg-container')).toBeNull();
85
+ rerender(<MermaidDiagram chart="flowchart LR; a-->b" frame="fold" />);
86
+ await flushUntil(() => renders.length >= 1, 'the first real render');
87
+ });
88
+
89
+ it('pans by dragging the frame, and zooms from the keyboard and a ⌘/Ctrl wheel', async () => {
90
+ await mountRendered();
91
+ const frame = screen.getByTestId('mermaid-frame');
92
+ fireEvent.pointerDown(frame, { button: 0, pointerType: 'mouse', clientX: 100, clientY: 100, pointerId: 1 });
93
+ fireEvent.pointerMove(frame, { clientX: 60, clientY: 75, pointerId: 1 });
94
+ expect(frame.scrollLeft).toBe(40);
95
+ expect(frame.scrollTop).toBe(25);
96
+ fireEvent.pointerUp(frame, { pointerId: 1 });
97
+ fireEvent.pointerMove(frame, { clientX: 0, clientY: 0, pointerId: 1 });
98
+ expect(frame.scrollLeft).toBe(40);
99
+
100
+ fireEvent.keyDown(frame, { key: '+' });
101
+ expect(zoomOf()).toBe(1.25);
102
+ fireEvent.keyDown(frame, { key: '0' });
103
+ expect(zoomOf()).toBe(1);
104
+ fireEvent.wheel(frame, { deltaY: -400, ctrlKey: true, clientX: 10, clientY: 10 });
105
+ expect(zoomOf()).toBeGreaterThan(1);
106
+ fireEvent.wheel(frame, { deltaY: 400 });
107
+ expect(zoomOf()).toBeGreaterThan(1); // a plain wheel scrolls, it never zooms
108
+ });
109
+
110
+ it('renders no toolbar when zoom is turned off', async () => {
111
+ await mountRendered({ zoomable: false });
112
+ expect(screen.queryByRole('group', { name: 'Diagram zoom' })).toBeNull();
113
+ expect(zoomOf()).toBe(1);
114
+ });
115
+ });
@@ -1,6 +1,5 @@
1
1
  'use client';
2
2
 
3
- import type { MermaidConfig } from 'mermaid';
4
3
  /**
5
4
  * Single MermaidDiagram for the unified markdown engine (dark theme only —
6
5
  * the old RichMarkdownRenderer's light-theme branch was dead code behind a
@@ -9,10 +8,13 @@ import type { MermaidConfig } from 'mermaid';
9
8
  * `mermaid` stays a dynamic import so neither chat nor content bundles pay
10
9
  * for it unless a diagram is actually rendered.
11
10
  */
11
+ import { Maximize2, ZoomIn, ZoomOut } from 'lucide-react';
12
+ import type { MermaidConfig } from 'mermaid';
12
13
  import type React from 'react';
13
- import { useEffect, useState } from 'react';
14
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
14
15
  import { useIsHydrated } from '../../../hooks/ui/use-is-hydrated';
15
16
  import { AlertCircleIcon } from '../../icons-v2-generated';
17
+ import { Button } from '../button';
16
18
 
17
19
  /**
18
20
  * SECURITY SSOT for the mermaid renderer — the ONLY place these knobs are
@@ -123,38 +125,17 @@ async function withRenderTimeout<T>(promise: Promise<T>, ms: number): Promise<T>
123
125
  * module uses ODS semantic classes.
124
126
  */
125
127
  export const mermaidStyles = `
128
+ /* The pan surface is a scroll region with NO scrollbars: drag, wheel,
129
+ arrows and the toolbar move it (a canvas, the way dbdiagram, Figma and
130
+ Excalidraw draw one). Two mechanisms for one motion read as a bug. */
131
+ .mermaid-frame-pan { scrollbar-width: none; -ms-overflow-style: none; }
132
+ .mermaid-frame-pan::-webkit-scrollbar { display: none; }
126
133
  .mermaid-svg-container svg {
127
- max-width: 100% !important;
128
- height: auto !important;
129
- min-height: 200px;
134
+ max-width: 100%;
135
+ height: auto;
130
136
  font-family: 'DM Sans', sans-serif !important;
131
137
  font-size: 14px !important;
132
138
  }
133
- @media (min-width: 1520px) {
134
- .mermaid-svg-container svg {
135
- max-width: 900px !important;
136
- max-height: 700px !important;
137
- min-height: 300px;
138
- font-size: 16px !important;
139
- }
140
- }
141
- @media (min-width: 768px) and (max-width: 1519px) {
142
- .mermaid-svg-container svg {
143
- max-width: 700px !important;
144
- max-height: 600px !important;
145
- min-height: 250px;
146
- font-size: 15px !important;
147
- }
148
- }
149
- @media (max-width: 767px) {
150
- .mermaid-svg-container svg {
151
- max-width: 90vw !important;
152
- max-height: 400px !important;
153
- min-height: 200px;
154
- font-size: 13px !important;
155
- }
156
- }
157
- .mermaid-svg-container svg[width] { width: 100% !important; }
158
139
  .mermaid-svg-container .node rect,
159
140
  .mermaid-svg-container .node circle,
160
141
  .mermaid-svg-container .node ellipse,
@@ -170,16 +151,172 @@ export const mermaidStyles = `
170
151
  }
171
152
  `;
172
153
 
154
+ /**
155
+ * The VIEWER — every rendered diagram gets it, here in the ONE component, so
156
+ * a markdown fence in the knowledge base and a server-rendered admin diagram
157
+ * behave the same way. The contract is the one diagram tools converge on
158
+ * (dbdiagram, Excalidraw, Mermaid Live):
159
+ * - drag to pan (mouse / pen; touch pans the frame natively) — the frame
160
+ * shows NO scrollbars, so panning has one visible mechanism;
161
+ * - ⌘/Ctrl + wheel (and trackpad pinch, which browsers deliver the same
162
+ * way) zooms TOWARD THE CURSOR — the point under the pointer stays put;
163
+ * a plain wheel scrolls the frame, like any other scroll region;
164
+ * - toolbar: zoom out, the percentage (click = back to 100%), zoom in, fit;
165
+ * - keyboard, with the frame focused: arrows scroll (native), `+` / `-`
166
+ * zoom, `0` resets, `f` fits.
167
+ * Applied through the CSS `zoom` property (a LAYOUT scale, unlike
168
+ * `transform`), so the frame's own scrollbars reach every corner of a
169
+ * magnified diagram and the zoom math is plain arithmetic on scroll offsets.
170
+ */
171
+ export const MERMAID_ZOOM_MIN = 0.25;
172
+ export const MERMAID_ZOOM_MAX = 4;
173
+ export const MERMAID_ZOOM_STEP = 1.25;
174
+ const clampZoom = (z: number) => Math.min(MERMAID_ZOOM_MAX, Math.max(MERMAID_ZOOM_MIN, z));
175
+
173
176
  /** Monotonic render id. `Date.now()` was ambiguous: two renders started in the
174
177
  * same millisecond (routine while a diagram streams in) share an id, and
175
178
  * mermaid removes any pre-existing element with that id at the start of a
176
179
  * render — so one render would delete the other's working container. */
177
180
  let mermaidRenderSeq = 0;
178
181
 
179
- export const MermaidDiagram: React.FC<{ chart: string }> = ({ chart }) => {
182
+ /**
183
+ * How tall the diagram's FRAME is. The frame is a scroll container in both
184
+ * modes, so a zoomed diagram scrolls inside it instead of growing the page:
185
+ * - `content`: as tall as the diagram, capped at 70svh (markdown, chat);
186
+ * - `fold`: a fixed 70svh, skeleton and diagram alike — a page whose main
187
+ * element is the diagram never jumps when it lands (the admin graphs).
188
+ */
189
+ export type MermaidFrame = 'content' | 'fold';
190
+ const FRAME_CLASS: Record<MermaidFrame, string> = {
191
+ content: 'min-h-[200px] max-h-[70svh] md:min-h-[250px]',
192
+ fold: 'h-[70svh] min-h-[320px]',
193
+ };
194
+
195
+ export const MermaidDiagram: React.FC<{ chart: string; zoomable?: boolean; frame?: MermaidFrame }> = ({
196
+ chart,
197
+ zoomable = true,
198
+ frame = 'content',
199
+ }) => {
180
200
  const [svg, setSvg] = useState<string>('');
181
201
  const [error, setError] = useState<string>('');
182
202
  const [isLoading, setIsLoading] = useState<boolean>(true);
203
+ const [zoom, setZoom] = useState<number>(1);
204
+ const [dragging, setDragging] = useState(false);
205
+ const empty = !chart.trim();
206
+ // Mermaid (`useMaxWidth`) states the diagram's natural width as an inline
207
+ // `max-width: <n>px` on the SVG. The container takes that width, capped at
208
+ // the frame, so CSS `zoom` has a fixed box to scale: an auto-width block
209
+ // would re-fit the frame at every zoom and never overflow into it. Inside a
210
+ // zoomed element `100%` is the frame divided by the zoom, so the cap is
211
+ // `calc(100% * zoom)` — the frame's real width — and what fit at 100% is
212
+ // what grows: at 200% a frame-wide diagram is two frames wide and scrolls.
213
+ const naturalWidth = useMemo(() => {
214
+ const px = Number(svg.match(/max-width:\s*([\d.]+)px/)?.[1]);
215
+ return Number.isFinite(px) && px > 0 ? Math.ceil(px) : null;
216
+ }, [svg]);
217
+ const scrollRef = useRef<HTMLDivElement>(null);
218
+
219
+ // Anchor-preserving zoom: the content scales linearly with `zoom`, so the
220
+ // point under the anchor stays put when the scroll offset is scaled by the
221
+ // same ratio around it. The offset is applied in a layout effect, AFTER
222
+ // React has re-rendered the new zoom, so the scroll range already exists.
223
+ const pendingAnchor = useRef<{ ratio: number; ax: number; ay: number } | null>(null);
224
+ const applyZoom = useCallback((next: number, anchor?: { ax: number; ay: number }) => {
225
+ setZoom(current => {
226
+ const target = clampZoom(Math.round(next * 100) / 100);
227
+ if (target === current) return current;
228
+ const el = scrollRef.current;
229
+ const ax = anchor?.ax ?? (el ? el.clientWidth / 2 : 0);
230
+ const ay = anchor?.ay ?? (el ? el.clientHeight / 2 : 0);
231
+ pendingAnchor.current = { ratio: target / current, ax, ay };
232
+ return target;
233
+ });
234
+ }, []);
235
+ useLayoutEffect(() => {
236
+ const el = scrollRef.current;
237
+ const pending = pendingAnchor.current;
238
+ if (!el || !pending) return;
239
+ pendingAnchor.current = null;
240
+ el.scrollLeft = (el.scrollLeft + pending.ax) * pending.ratio - pending.ax;
241
+ el.scrollTop = (el.scrollTop + pending.ay) * pending.ratio - pending.ay;
242
+ }, [zoom]);
243
+ const zoomBy = useCallback(
244
+ (factor: number, anchor?: { ax: number; ay: number }) => applyZoom(zoom * factor, anchor),
245
+ [applyZoom, zoom],
246
+ );
247
+
248
+ // Fit: the whole diagram inside the frame, never above 100% — the natural
249
+ // size is the rendered box divided by the zoom it was measured under.
250
+ const fit = useCallback(() => {
251
+ const el = scrollRef.current;
252
+ const svgEl = el?.querySelector('svg');
253
+ if (!el || !svgEl) return;
254
+ const box = svgEl.getBoundingClientRect();
255
+ const w = box.width / zoom;
256
+ const h = box.height / zoom;
257
+ if (!(w > 0 && h > 0)) return;
258
+ const next = Math.min(1, el.clientWidth / w, el.clientHeight / h);
259
+ pendingAnchor.current = null;
260
+ setZoom(clampZoom(Math.floor(next * 100) / 100));
261
+ el.scrollTo({ left: 0, top: 0 });
262
+ }, [zoom]);
263
+
264
+ // ⌘/Ctrl + wheel (and pinch) zooms toward the cursor instead of scrolling
265
+ // the page. A native listener registered non-passive: React attaches
266
+ // `wheel` passively, so `preventDefault` from an `onWheel` prop is ignored.
267
+ useEffect(() => {
268
+ const el = scrollRef.current;
269
+ if (!el || !zoomable) return undefined;
270
+ const onWheel = (e: WheelEvent) => {
271
+ if (!(e.ctrlKey || e.metaKey)) return;
272
+ e.preventDefault();
273
+ const rect = el.getBoundingClientRect();
274
+ // Exponential in deltaY: a wheel notch is one step, a pinch is smooth.
275
+ applyZoom(zoom * Math.exp(-e.deltaY * 0.0025), { ax: e.clientX - rect.left, ay: e.clientY - rect.top });
276
+ };
277
+ el.addEventListener('wheel', onWheel, { passive: false });
278
+ return () => el.removeEventListener('wheel', onWheel);
279
+ // `svg` is a dependency on purpose: the scroll container mounts with the diagram.
280
+ }, [zoomable, svg, zoom, applyZoom]);
281
+
282
+ // Drag to pan — scrolls the frame, so the scrollbars, the wheel and the
283
+ // keyboard stay the source of truth for the position. Mouse and pen only:
284
+ // a finger already pans a scroll region natively.
285
+ const drag = useRef<{ x: number; y: number; left: number; top: number } | null>(null);
286
+ const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
287
+ if (!zoomable || e.button !== 0 || e.pointerType === 'touch') return;
288
+ const el = scrollRef.current;
289
+ if (!el) return;
290
+ // The default action of a press on text is to start a selection — the
291
+ // one thing a pan must never do. Focus is restored by hand below.
292
+ e.preventDefault();
293
+ drag.current = { x: e.clientX, y: e.clientY, left: el.scrollLeft, top: el.scrollTop };
294
+ el.setPointerCapture?.(e.pointerId);
295
+ el.focus({ preventScroll: true });
296
+ setDragging(true);
297
+ };
298
+ const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
299
+ const d = drag.current;
300
+ const el = scrollRef.current;
301
+ if (!d || !el) return;
302
+ el.scrollLeft = d.left - (e.clientX - d.x);
303
+ el.scrollTop = d.top - (e.clientY - d.y);
304
+ };
305
+ const endDrag = (e: React.PointerEvent<HTMLDivElement>) => {
306
+ if (!drag.current) return;
307
+ drag.current = null;
308
+ scrollRef.current?.releasePointerCapture?.(e.pointerId);
309
+ setDragging(false);
310
+ };
311
+ const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
312
+ if (!zoomable || !svg) return;
313
+ if (e.key === '+' || e.key === '=') zoomBy(MERMAID_ZOOM_STEP);
314
+ else if (e.key === '-') zoomBy(1 / MERMAID_ZOOM_STEP);
315
+ else if (e.key === '0') applyZoom(1);
316
+ else if (e.key === 'f' || e.key === 'F') fit();
317
+ else return;
318
+ e.preventDefault();
319
+ };
183
320
  // `useSyncExternalStore` hydration gate rather than the `useState(false)` +
184
321
  // `useEffect(setMounted)` idiom — same one extra render, no setState inside
185
322
  // an effect body.
@@ -195,6 +332,16 @@ export const MermaidDiagram: React.FC<{ chart: string }> = ({ chart }) => {
195
332
  let cancelled = false;
196
333
  const renderId = `mermaid-${(mermaidRenderSeq += 1)}`;
197
334
 
335
+ // Nothing to draw yet (a host whose chart is still loading, a stream that
336
+ // has not produced its first token): never ask mermaid to parse an empty
337
+ // string — that is an "UnknownDiagramError" it would paint as a failure.
338
+ // The render below shows the skeleton for an empty chart on its own.
339
+ if (empty) {
340
+ return () => {
341
+ cancelled = true;
342
+ };
343
+ }
344
+
198
345
  const renderMermaid = async () => {
199
346
  try {
200
347
  setIsLoading(true);
@@ -253,6 +400,9 @@ export const MermaidDiagram: React.FC<{ chart: string }> = ({ chart }) => {
253
400
  );
254
401
  if (cancelled) return;
255
402
  setSvg(renderedSvg);
403
+ // A new diagram starts at 100%, top-left — zoom is per diagram, not per host.
404
+ pendingAnchor.current = null;
405
+ setZoom(1);
256
406
  // CLEAR the previous failure. The render body checks `error` BEFORE
257
407
  // `svg`, so a stale message pins the "Diagram Error" card forever and
258
408
  // the diagram that just rendered successfully never appears. Transient
@@ -283,11 +433,17 @@ export const MermaidDiagram: React.FC<{ chart: string }> = ({ chart }) => {
283
433
  document.getElementById(`d${renderId}`)?.remove();
284
434
  document.getElementById(renderId)?.remove();
285
435
  };
286
- }, [chart, mounted]);
436
+ }, [chart, empty, mounted]);
287
437
 
288
- if (error) {
289
- return (
290
- <div className="error-state my-6 rounded-lg border border-ods-border bg-ods-card p-6">
438
+ // `safe center` on both axes: a zoomed diagram larger than the frame scrolls
439
+ // from its top-left corner instead of losing those edges to flex centering.
440
+ const frameClass = `${FRAME_CLASS[frame]} flex w-full overflow-auto outline-none focus-visible:ring-1 focus-visible:ring-ods-accent ${
441
+ zoomable && svg ? `mermaid-frame-pan select-none ${dragging ? 'cursor-grabbing' : 'cursor-grab'}` : ''
442
+ }`;
443
+ const frameStyle = { justifyContent: 'safe center', alignItems: 'safe center' } as const;
444
+ const body =
445
+ error && !empty ? (
446
+ <div className="error-state m-auto rounded-lg border border-ods-border bg-ods-card p-6">
291
447
  <div className="error-icon mb-4 flex justify-center">
292
448
  <AlertCircleIcon className="h-12 w-12 text-ods-error" />
293
449
  </div>
@@ -298,39 +454,103 @@ export const MermaidDiagram: React.FC<{ chart: string }> = ({ chart }) => {
298
454
  </div>
299
455
  </div>
300
456
  </div>
301
- );
302
- }
303
-
304
- if (isLoading || !svg) {
305
- return (
306
- <div className="skeleton-code flex min-h-[120px] items-center justify-center rounded-lg border border-ods-border bg-ods-card p-6">
307
- <div className="animate-pulse font-sans text-ods-text-tertiary">
308
- {isLoading ? 'Loading diagram renderer...' : 'Rendering diagram...'}
309
- </div>
457
+ ) : empty || isLoading || !svg ? (
458
+ <div className="skeleton-code m-auto animate-pulse font-sans text-ods-text-tertiary">
459
+ {isLoading ? 'Loading diagram renderer...' : 'Rendering diagram...'}
310
460
  </div>
461
+ ) : (
462
+ <div
463
+ className="mermaid-svg-container flex shrink-0 justify-center"
464
+ // The class is a styling hook for the injected SVG (see the <style>
465
+ // block above); the test id is the stable handle for "which SVG is
466
+ // mounted right now", which the stale-render guard has to assert on.
467
+ data-testid="mermaid-svg-container"
468
+ data-zoom={zoom}
469
+ style={{
470
+ fontSize: '14px',
471
+ zoom,
472
+ width: naturalWidth ? `min(${naturalWidth}px, calc(100% * ${zoom}))` : '100%',
473
+ }}
474
+ dangerouslySetInnerHTML={{ __html: svg }}
475
+ />
311
476
  );
312
- }
313
477
 
314
478
  return (
315
- <div className="mermaid-container my-6 overflow-x-auto rounded-lg border border-ods-border bg-ods-card p-4 md:p-6 lg:p-8">
479
+ <div className="mermaid-container relative my-6 rounded-lg border border-ods-border bg-ods-card p-4 md:p-6 lg:p-8">
316
480
  {/* Scoped to `.mermaid-svg-container`, so it only needs to exist when a
317
481
  diagram is actually mounted. The engine used to emit this once per
318
482
  instance — i.e. once per chat segment, almost never with a diagram. */}
319
483
  <style dangerouslySetInnerHTML={{ __html: mermaidStyles }} />
320
- <div className="flex min-h-[200px] w-full items-center justify-center md:min-h-[250px] lg:min-h-[300px]">
484
+ {zoomable && (
321
485
  <div
322
- className="mermaid-svg-container flex w-full max-w-full justify-center"
323
- // The class is a styling hook for the injected SVG (see the <style>
324
- // block above); the test id is the stable handle for "which SVG is
325
- // mounted right now", which the stale-render guard has to assert on.
326
- data-testid="mermaid-svg-container"
327
- style={{ fontSize: '14px' }}
328
- dangerouslySetInnerHTML={{
329
- __html: svg.replace(/<svg[^>]*>/, match =>
330
- match.replace(/width="[^"]*"/, 'width="100%"').replace(/height="[^"]*"/, 'height="auto"'),
331
- ),
332
- }}
333
- />
486
+ className="absolute right-2 top-2 z-10 flex items-center gap-[var(--spacing-system-xxs)] rounded-md bg-ods-card"
487
+ role="group"
488
+ aria-label="Diagram zoom"
489
+ >
490
+ <Button
491
+ variant="outline"
492
+ size="icon-sm"
493
+ aria-label="Zoom out"
494
+ title="Zoom out (−, ⌘/Ctrl + wheel)"
495
+ disabled={!svg || zoom <= MERMAID_ZOOM_MIN}
496
+ onClick={() => zoomBy(1 / MERMAID_ZOOM_STEP)}
497
+ >
498
+ <ZoomOut />
499
+ </Button>
500
+ <Button
501
+ variant="outline"
502
+ size="compact"
503
+ aria-label="Reset zoom"
504
+ title="Back to 100% (0)"
505
+ disabled={!svg || zoom === 1}
506
+ onClick={() => applyZoom(1)}
507
+ >
508
+ {Math.round(zoom * 100)}%
509
+ </Button>
510
+ <Button
511
+ variant="outline"
512
+ size="icon-sm"
513
+ aria-label="Zoom in"
514
+ title="Zoom in (+, ⌘/Ctrl + wheel)"
515
+ disabled={!svg || zoom >= MERMAID_ZOOM_MAX}
516
+ onClick={() => zoomBy(MERMAID_ZOOM_STEP)}
517
+ >
518
+ <ZoomIn />
519
+ </Button>
520
+ <Button
521
+ variant="outline"
522
+ size="icon-sm"
523
+ aria-label="Fit to frame"
524
+ title="Fit the whole diagram in the frame (f)"
525
+ disabled={!svg}
526
+ onClick={fit}
527
+ >
528
+ <Maximize2 />
529
+ </Button>
530
+ </div>
531
+ )}
532
+ {/* The frame: the scroll region, the pan surface and the keyboard target. */}
533
+ <div
534
+ ref={scrollRef}
535
+ className={frameClass}
536
+ style={frameStyle}
537
+ data-testid="mermaid-frame"
538
+ data-frame={frame}
539
+ tabIndex={zoomable && svg ? 0 : -1}
540
+ role={zoomable && svg ? 'region' : undefined}
541
+ aria-label={
542
+ zoomable && svg
543
+ ? 'Diagram. Drag to pan; Ctrl or Cmd plus wheel, or + and -, to zoom; 0 resets; f fits.'
544
+ : undefined
545
+ }
546
+ title={zoomable && svg ? 'Drag to pan · ⌘/Ctrl + wheel to zoom' : undefined}
547
+ onPointerDown={onPointerDown}
548
+ onPointerMove={onPointerMove}
549
+ onPointerUp={endDrag}
550
+ onPointerCancel={endDrag}
551
+ onKeyDown={onKeyDown}
552
+ >
553
+ {body}
334
554
  </div>
335
555
  </div>
336
556
  );