@flamingo-stack/openframe-frontend-core 0.0.646 → 0.0.647-snapshot.20260917173248

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 (139) hide show
  1. package/dist/chat-protocol/index.cjs.map +1 -1
  2. package/dist/chat-protocol/index.js.map +1 -1
  3. package/dist/{chunk-ETEM2ZD4.js → chunk-2A4RLR7R.js} +3 -3
  4. package/dist/{chunk-JFBUXYDK.cjs → chunk-2ENDIKKP.cjs} +15 -15
  5. package/dist/{chunk-JFBUXYDK.cjs.map → chunk-2ENDIKKP.cjs.map} +1 -1
  6. package/dist/{chunk-QS55P2TA.js → chunk-2ULLNHL3.js} +6 -6
  7. package/dist/chunk-2ULLNHL3.js.map +1 -0
  8. package/dist/{chunk-DULSS7R6.js → chunk-3ORBE27K.js} +832 -547
  9. package/dist/chunk-3ORBE27K.js.map +1 -0
  10. package/dist/{chunk-ZW2BEEX2.cjs → chunk-4JRBRMKO.cjs} +25 -25
  11. package/dist/{chunk-ZW2BEEX2.cjs.map → chunk-4JRBRMKO.cjs.map} +1 -1
  12. package/dist/{chunk-7UWJMWDH.cjs → chunk-EFPAKLT5.cjs} +784 -499
  13. package/dist/chunk-EFPAKLT5.cjs.map +1 -0
  14. package/dist/{chunk-5C7GMRJU.js → chunk-EKLOXVG2.js} +5 -5
  15. package/dist/{chunk-AYAZU3BO.cjs → chunk-EW3EIPT5.cjs} +5 -5
  16. package/dist/{chunk-AYAZU3BO.cjs.map → chunk-EW3EIPT5.cjs.map} +1 -1
  17. package/dist/{chunk-NKMXFBV5.js → chunk-FQ4TZP6K.js} +4 -4
  18. package/dist/{chunk-5JVN3EVT.cjs → chunk-HN4DLGKP.cjs} +71 -71
  19. package/dist/{chunk-5JVN3EVT.cjs.map → chunk-HN4DLGKP.cjs.map} +1 -1
  20. package/dist/{chunk-WJ7PDBPK.cjs → chunk-HXQWGZYG.cjs} +4 -4
  21. package/dist/{chunk-WJ7PDBPK.cjs.map → chunk-HXQWGZYG.cjs.map} +1 -1
  22. package/dist/{chunk-5MZZFTME.js → chunk-IUHU5BC2.js} +5 -5
  23. package/dist/{chunk-ZGWXD2S3.js → chunk-IWEJCDCB.js} +3 -3
  24. package/dist/{chunk-N2E26OD6.cjs → chunk-LFCMKMHR.cjs} +45 -45
  25. package/dist/{chunk-N2E26OD6.cjs.map → chunk-LFCMKMHR.cjs.map} +1 -1
  26. package/dist/{chunk-XJH5M2B7.js → chunk-M6QCADAT.js} +6 -6
  27. package/dist/{chunk-NWYSHZG7.cjs → chunk-N7AJUG4C.cjs} +22 -22
  28. package/dist/{chunk-NWYSHZG7.cjs.map → chunk-N7AJUG4C.cjs.map} +1 -1
  29. package/dist/{chunk-LDJ4TIDC.cjs → chunk-ODXVLFAQ.cjs} +13 -24
  30. package/dist/chunk-ODXVLFAQ.cjs.map +1 -0
  31. package/dist/{chunk-4GOJFHJY.js → chunk-OLPU5IVF.js} +2 -2
  32. package/dist/{chunk-PD47DDHS.js → chunk-PYAFHT6B.js} +7 -18
  33. package/dist/chunk-PYAFHT6B.js.map +1 -0
  34. package/dist/{chunk-H4FQRA5O.cjs → chunk-RM5MF2N3.cjs} +3 -3
  35. package/dist/{chunk-H4FQRA5O.cjs.map → chunk-RM5MF2N3.cjs.map} +1 -1
  36. package/dist/{chunk-ZDIDA4QG.js → chunk-SBKNMSQR.js} +2 -2
  37. package/dist/{chunk-GBZ3IR3S.js → chunk-SNQ5KWLP.js} +2 -2
  38. package/dist/{chunk-LLT5XMP2.js → chunk-UW7XUQFP.js} +3 -3
  39. package/dist/{chunk-RRSR2XHJ.cjs → chunk-VPEETTUS.cjs} +167 -167
  40. package/dist/chunk-VPEETTUS.cjs.map +1 -0
  41. package/dist/{chunk-UR7BC74V.js → chunk-VTLDEZ5D.js} +3 -3
  42. package/dist/{chunk-XPPGI7SD.js → chunk-WBRO3MX2.js} +2 -2
  43. package/dist/{chunk-NZ66W56D.cjs → chunk-WMKXHOOD.cjs} +10 -10
  44. package/dist/{chunk-NZ66W56D.cjs.map → chunk-WMKXHOOD.cjs.map} +1 -1
  45. package/dist/{chunk-TZO743LD.cjs → chunk-WPNY4XEL.cjs} +3 -3
  46. package/dist/{chunk-TZO743LD.cjs.map → chunk-WPNY4XEL.cjs.map} +1 -1
  47. package/dist/{chunk-XATBOM3X.js → chunk-XE5DNWOR.js} +5 -5
  48. package/dist/{chunk-C6QUB6IS.cjs → chunk-XI3QJD3N.cjs} +22 -22
  49. package/dist/{chunk-C6QUB6IS.cjs.map → chunk-XI3QJD3N.cjs.map} +1 -1
  50. package/dist/{chunk-2V7SCIOG.cjs → chunk-YTOUGDPY.cjs} +33 -33
  51. package/dist/{chunk-2V7SCIOG.cjs.map → chunk-YTOUGDPY.cjs.map} +1 -1
  52. package/dist/{chunk-X2VTQ3TL.cjs → chunk-YUXFHVC2.cjs} +10 -10
  53. package/dist/{chunk-X2VTQ3TL.cjs.map → chunk-YUXFHVC2.cjs.map} +1 -1
  54. package/dist/components/case-studies/index.cjs +14 -14
  55. package/dist/components/case-studies/index.js +3 -3
  56. package/dist/components/chat/embeddable-chat.d.ts.map +1 -1
  57. package/dist/components/chat/index.cjs +2 -2
  58. package/dist/components/chat/index.js +1 -1
  59. package/dist/components/chat/types/message.types.d.ts +5 -0
  60. package/dist/components/chat/types/message.types.d.ts.map +1 -1
  61. package/dist/components/chat/utils/cited-sources.d.ts +5 -0
  62. package/dist/components/chat/utils/cited-sources.d.ts.map +1 -1
  63. package/dist/components/chat/utils/source-row-cta.d.ts +2 -7
  64. package/dist/components/chat/utils/source-row-cta.d.ts.map +1 -1
  65. package/dist/components/contact/index.cjs +4 -4
  66. package/dist/components/contact/index.js +3 -3
  67. package/dist/components/docs/index.cjs +7 -7
  68. package/dist/components/docs/index.js +6 -6
  69. package/dist/components/embeds/index.cjs +4 -4
  70. package/dist/components/embeds/index.js +3 -3
  71. package/dist/components/faq/index.cjs +4 -4
  72. package/dist/components/faq/index.js +3 -3
  73. package/dist/components/features/index.cjs +3 -3
  74. package/dist/components/features/index.js +2 -2
  75. package/dist/components/help-center-pages/index.cjs +23 -23
  76. package/dist/components/help-center-pages/index.js +14 -14
  77. package/dist/components/index.cjs +39 -39
  78. package/dist/components/index.js +13 -13
  79. package/dist/components/meeting-scheduler/index.cjs +24 -24
  80. package/dist/components/meeting-scheduler/index.js +2 -2
  81. package/dist/components/navigation/index.cjs +6 -6
  82. package/dist/components/navigation/index.js +5 -5
  83. package/dist/components/onboarding-guides/index.cjs +6 -6
  84. package/dist/components/onboarding-guides/index.js +5 -5
  85. package/dist/components/shared/doc-search/map-doc-search-results.d.ts.map +1 -1
  86. package/dist/components/tickets/index.cjs +7 -7
  87. package/dist/components/tickets/index.js +6 -6
  88. package/dist/components/ui/data-table/data-table-skeleton.d.ts.map +1 -1
  89. package/dist/components/ui/index.cjs +3 -3
  90. package/dist/components/ui/index.js +2 -2
  91. package/dist/components/ui/markdown/mermaid-diagram.d.ts +31 -9
  92. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +1 -1
  93. package/dist/index.cjs +19 -7
  94. package/dist/index.cjs.map +1 -1
  95. package/dist/index.js +18 -6
  96. package/dist/index.js.map +1 -1
  97. package/dist/utils/index.cjs +163 -0
  98. package/dist/utils/index.cjs.map +1 -1
  99. package/dist/utils/index.d.ts +1 -0
  100. package/dist/utils/index.d.ts.map +1 -1
  101. package/dist/utils/index.js +158 -1
  102. package/dist/utils/index.js.map +1 -1
  103. package/dist/utils/source-grouping.d.ts +86 -0
  104. package/dist/utils/source-grouping.d.ts.map +1 -0
  105. package/dist/utils/source-icons.d.ts +7 -0
  106. package/dist/utils/source-icons.d.ts.map +1 -1
  107. package/package.json +1 -1
  108. package/src/components/chat/embeddable-chat.tsx +10 -2
  109. package/src/components/chat/types/message.types.ts +5 -0
  110. package/src/components/chat/utils/cited-sources.ts +7 -1
  111. package/src/components/chat/utils/source-row-cta.ts +4 -7
  112. package/src/components/shared/doc-search/__tests__/map-doc-search-results.test.ts +48 -0
  113. package/src/components/shared/doc-search/map-doc-search-results.ts +6 -16
  114. package/src/components/ui/data-table/data-table-skeleton.tsx +15 -7
  115. package/src/components/ui/markdown/__tests__/mermaid-zoom.test.tsx +117 -0
  116. package/src/components/ui/markdown/mermaid-diagram.tsx +279 -59
  117. package/src/utils/__tests__/source-grouping.test.ts +240 -0
  118. package/src/utils/index.ts +11 -0
  119. package/src/utils/source-grouping.ts +215 -0
  120. package/src/utils/source-icons.ts +13 -0
  121. package/dist/chunk-7UWJMWDH.cjs.map +0 -1
  122. package/dist/chunk-DULSS7R6.js.map +0 -1
  123. package/dist/chunk-LDJ4TIDC.cjs.map +0 -1
  124. package/dist/chunk-PD47DDHS.js.map +0 -1
  125. package/dist/chunk-QS55P2TA.js.map +0 -1
  126. package/dist/chunk-RRSR2XHJ.cjs.map +0 -1
  127. /package/dist/{chunk-ETEM2ZD4.js.map → chunk-2A4RLR7R.js.map} +0 -0
  128. /package/dist/{chunk-5C7GMRJU.js.map → chunk-EKLOXVG2.js.map} +0 -0
  129. /package/dist/{chunk-NKMXFBV5.js.map → chunk-FQ4TZP6K.js.map} +0 -0
  130. /package/dist/{chunk-5MZZFTME.js.map → chunk-IUHU5BC2.js.map} +0 -0
  131. /package/dist/{chunk-ZGWXD2S3.js.map → chunk-IWEJCDCB.js.map} +0 -0
  132. /package/dist/{chunk-XJH5M2B7.js.map → chunk-M6QCADAT.js.map} +0 -0
  133. /package/dist/{chunk-4GOJFHJY.js.map → chunk-OLPU5IVF.js.map} +0 -0
  134. /package/dist/{chunk-ZDIDA4QG.js.map → chunk-SBKNMSQR.js.map} +0 -0
  135. /package/dist/{chunk-GBZ3IR3S.js.map → chunk-SNQ5KWLP.js.map} +0 -0
  136. /package/dist/{chunk-LLT5XMP2.js.map → chunk-UW7XUQFP.js.map} +0 -0
  137. /package/dist/{chunk-UR7BC74V.js.map → chunk-VTLDEZ5D.js.map} +0 -0
  138. /package/dist/{chunk-XPPGI7SD.js.map → chunk-WBRO3MX2.js.map} +0 -0
  139. /package/dist/{chunk-XATBOM3X.js.map → chunk-XE5DNWOR.js.map} +0 -0
@@ -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
  );
@@ -0,0 +1,240 @@
1
+ /**
2
+ * One rule and one constructor draw every grouped source chip: the hub's web
3
+ * chat, its side-channel chips, and this chat's strip over flat MCP sources.
4
+ * These pin the rule, the chip's shape, and what grouping must leave alone.
5
+ */
6
+
7
+ import { describe, expect, it } from 'vitest';
8
+
9
+ import type { ChatSource } from '../../components/chat/types/message.types';
10
+ import { splitCitedSources } from '../../components/chat/utils/cited-sources';
11
+ import {
12
+ buildGroupedSource,
13
+ formatCitationIndices,
14
+ groupSourcesByTable,
15
+ groupsByTable,
16
+ recordCountLabel,
17
+ } from '../source-grouping';
18
+
19
+ const row = (table: string, documentType: string, index: number): ChatSource => ({
20
+ index,
21
+ name: `${table} ${index}`,
22
+ path: `${table}/${index}`,
23
+ documentType,
24
+ externalUrl: `/${table}?search=${index}`,
25
+ targetPlatform: 'product-hub',
26
+ id: `${index}`,
27
+ sourceRepo: table,
28
+ });
29
+
30
+ const task = (index: number) => row('clickup-tasks-internal', 'internal_task', index);
31
+ const blog = (index: number) => row('blog-posts', 'blog_post', index);
32
+ const webinar = (index: number) => row('webinars', 'webinar', index);
33
+
34
+ const doc = (index: number): ChatSource => ({
35
+ index,
36
+ name: `Doc ${index}`,
37
+ path: `guides/doc-${index}`,
38
+ documentType: 'markdown',
39
+ id: `doc-${index}`,
40
+ sourceRepo: 'openframe-docs',
41
+ });
42
+
43
+ describe('groupsByTable', () => {
44
+ it('groups every table except whole documents', () => {
45
+ expect(groupsByTable('internal_task')).toBe(true);
46
+ expect(groupsByTable(undefined)).toBe(true);
47
+ expect(groupsByTable('markdown')).toBe(false);
48
+ expect(groupsByTable('data_room_doc')).toBe(false);
49
+ });
50
+ });
51
+
52
+ describe('buildGroupedSource', () => {
53
+ it('names the chip by table and count, and heads it with its first row', () => {
54
+ const chip = buildGroupedSource({
55
+ index: 4,
56
+ sourceRepo: 'clickup-tasks-internal',
57
+ rows: [
58
+ {
59
+ id: 'a',
60
+ documentType: 'internal_task',
61
+ name: 'A',
62
+ externalUrl: '/a',
63
+ targetPlatform: 'product-hub',
64
+ path: 'p/a',
65
+ },
66
+ { id: 'b', documentType: 'internal_task', name: 'B', path: null },
67
+ ],
68
+ });
69
+
70
+ expect(chip).toMatchObject({
71
+ index: 4,
72
+ name: 'ClickUp Tasks (2 records)',
73
+ path: 'p/a',
74
+ documentType: 'internal_task',
75
+ externalUrl: '/a',
76
+ targetPlatform: 'product-hub',
77
+ sourceRepo: 'clickup-tasks-internal',
78
+ });
79
+ // A row with no public URL still gets its dropdown row (Ask needs only id + type).
80
+ expect(chip.items?.map(item => item.id)).toEqual(['a', 'b']);
81
+ });
82
+
83
+ it('lets a producer set the chip-level link', () => {
84
+ const chip = buildGroupedSource({
85
+ index: 1,
86
+ sourceRepo: 'hubspot-tickets-self',
87
+ rows: [{ id: '1', documentType: 'hubspot_ticket_self', name: 'T', externalUrl: '/t/1' }],
88
+ externalUrl: '/my-tickets',
89
+ targetPlatform: 'openframe',
90
+ });
91
+ expect(chip.externalUrl).toBe('/my-tickets');
92
+ expect(chip.targetPlatform).toBe('openframe');
93
+ expect(recordCountLabel(1)).toBe('(1 record)');
94
+ expect(chip.name.endsWith('(1 record)')).toBe(true);
95
+ });
96
+ });
97
+
98
+ describe('groupSourcesByTable', () => {
99
+ it('collapses rows of one table into a single chip that keeps every citation number', () => {
100
+ const [group, ...rest] = groupSourcesByTable([task(1), task(2), task(4)]);
101
+
102
+ expect(rest).toEqual([]);
103
+ expect(group.name).toBe('ClickUp Tasks (3 records)');
104
+ expect(group.index).toBe(1);
105
+ expect(group.items?.map(item => item.index)).toEqual([1, 2, 4]);
106
+ expect(group.items?.[1]).toEqual({
107
+ index: 2,
108
+ id: '2',
109
+ documentType: 'internal_task',
110
+ name: 'clickup-tasks-internal 2',
111
+ externalUrl: '/clickup-tasks-internal?search=2',
112
+ targetPlatform: 'product-hub',
113
+ path: 'clickup-tasks-internal/2',
114
+ });
115
+ });
116
+
117
+ it('groups a lone record too, exactly as the hub web chat draws it', () => {
118
+ const [chip] = groupSourcesByTable([blog(1)]);
119
+ expect(chip.name).toBe('Blog Posts (1 record)');
120
+ expect(chip.items).toHaveLength(1);
121
+ });
122
+
123
+ it('keeps one deterministic order when three tables interleave: each chip at its first row', () => {
124
+ const chips = groupSourcesByTable([task(1), blog(2), webinar(3), task(4), doc(5), blog(6), webinar(7), task(8)]);
125
+
126
+ expect(chips.map(chip => chip.sourceRepo)).toEqual([
127
+ 'clickup-tasks-internal',
128
+ 'blog-posts',
129
+ 'webinars',
130
+ 'openframe-docs',
131
+ ]);
132
+ // Every row lands in exactly one chip, in the order it arrived.
133
+ expect(chips.map(chip => chip.items?.map(item => item.index) ?? [chip.index])).toEqual([
134
+ [1, 4, 8],
135
+ [2, 6],
136
+ [3, 7],
137
+ [5],
138
+ ]);
139
+ });
140
+
141
+ it('never groups doc-table rows: each document is its own chip', () => {
142
+ const docs = [doc(1), doc(2), doc(3)];
143
+ expect(groupSourcesByTable(docs)).toEqual(docs);
144
+ });
145
+
146
+ it('passes a server-grouped chip through untouched', () => {
147
+ const serverGroup = buildGroupedSource({
148
+ index: 1,
149
+ sourceRepo: 'clickup-tasks-internal',
150
+ rows: [{ id: '9', documentType: 'internal_task', name: 'Task 9' }],
151
+ });
152
+ const [first] = groupSourcesByTable([serverGroup, doc(2)]);
153
+ expect(first).toBe(serverGroup);
154
+ });
155
+
156
+ it('merges flat rows into a server-grouped chip of the same table: one chip, never two', () => {
157
+ const serverChip = buildGroupedSource({
158
+ index: 1,
159
+ sourceRepo: 'clickup-tasks-internal',
160
+ rows: [{ id: '9', documentType: 'internal_task', name: 'Task 9' }],
161
+ externalUrl: '/admin/tasks',
162
+ targetPlatform: 'product-hub',
163
+ });
164
+ // task(9) is the record already inside the chip; task(2) is new.
165
+ const chips = groupSourcesByTable([serverChip, blog(5), task(2), task(9)]);
166
+
167
+ expect(chips.map(chip => chip.sourceRepo)).toEqual(['clickup-tasks-internal', 'blog-posts']);
168
+ expect(chips[0].name).toBe('ClickUp Tasks (2 records)');
169
+ expect(chips[0].index).toBe(1);
170
+ expect(chips[0].externalUrl).toBe('/admin/tasks');
171
+ expect(chips[0].items?.map(item => item.id)).toEqual(['9', '2']);
172
+ // The server's row keeps the group's number; the flat row keeps its own.
173
+ expect(chips[0].items?.map(item => item.index)).toEqual([undefined, 2]);
174
+ });
175
+
176
+ it('keeps a table in ONE chip when a row has no id: it joins as an Open-only row', () => {
177
+ const { id: _id, ...noId } = task(2);
178
+ const chips = groupSourcesByTable([task(1), noId, task(3)]);
179
+
180
+ expect(chips).toHaveLength(1);
181
+ expect(chips[0].name).toBe('ClickUp Tasks (3 records)');
182
+ expect(chips[0].items?.map(item => item.id)).toEqual(['1', '', '3']);
183
+ expect(chips[0].items?.[1].externalUrl).toBe('/clickup-tasks-internal?search=2');
184
+ });
185
+
186
+ it('keeps a table in ONE chip when a row has no documentType: the table supplies the type', () => {
187
+ const typeless = { ...task(2), documentType: '' };
188
+ const chips = groupSourcesByTable([task(1), typeless]);
189
+
190
+ expect(chips).toHaveLength(1);
191
+ expect(chips[0].name).toBe('ClickUp Tasks (2 records)');
192
+ // The row gets its table's canonical type, so Ask still works on it.
193
+ expect(chips[0].items?.map(item => item.documentType)).toEqual(['internal_task', 'internal_task']);
194
+ });
195
+
196
+ it('still treats a typeless row of a doc table as a whole document', () => {
197
+ const typelessDoc = { ...doc(1), documentType: '' };
198
+ expect(groupSourcesByTable([typelessDoc, doc(2)])).toEqual([typelessDoc, doc(2)]);
199
+ });
200
+
201
+ it('leaves a row that names no table as its own chip', () => {
202
+ const { sourceRepo: _repo, ...noTable } = task(2);
203
+ expect(groupSourcesByTable([noTable])).toEqual([noTable]);
204
+ });
205
+ });
206
+
207
+ describe('splitCitedSources with grouping', () => {
208
+ it('groups the cited and the uncited rows of one table separately', () => {
209
+ const { cited, uncited } = splitCitedSources([task(1), task(2), task(3), task(4)], 'See [3] and [1].');
210
+
211
+ expect(cited).toHaveLength(1);
212
+ expect(cited[0].items?.map(item => item.index)).toEqual([3, 1]);
213
+ expect(uncited).toHaveLength(1);
214
+ expect(uncited[0].items?.map(item => item.index)).toEqual([2, 4]);
215
+ });
216
+ });
217
+
218
+ describe('grouping is per message', () => {
219
+ it('groups each answer from its own sources only: the same table in two answers is two chips', () => {
220
+ // The strip calls this once per message with THAT message's sources. There
221
+ // is no shared state to carry a table's rows from one answer into the next.
222
+ const first = splitCitedSources([task(1), task(2)], 'See [1] and [2].');
223
+ const second = splitCitedSources([task(1), blog(2)], 'See [1].');
224
+
225
+ expect(first.cited.map(chip => chip.name)).toEqual(['ClickUp Tasks (2 records)']);
226
+ expect(second.cited.map(chip => chip.name)).toEqual(['ClickUp Tasks (1 record)']);
227
+ expect(second.uncited.map(chip => chip.name)).toEqual(['Blog Posts (1 record)']);
228
+ // The inputs are never mutated, so a re-render regroups from the same flat list.
229
+ const flat = [task(1), task(2)];
230
+ groupSourcesByTable(flat);
231
+ expect(flat.every(source => source.items === undefined)).toBe(true);
232
+ });
233
+ });
234
+
235
+ describe('formatCitationIndices', () => {
236
+ it('folds consecutive numbers into ranges', () => {
237
+ expect(formatCitationIndices([3, 1, 2, 7, 9, 10])).toBe('1-3, 7, 9-10');
238
+ expect(formatCitationIndices([5])).toBe('5');
239
+ });
240
+ });
@@ -196,6 +196,17 @@ export {
196
196
  // instead of src/components/chat/utils/ so server-side hub callers like
197
197
  // doc-chat-utils can use them without tripping the 'use client' boundary)
198
198
  export { SOURCE_ICON_NAMES, getSourceIconName, SOURCE_LABELS_BY_TABLE, getSourceLabel } from './source-icons';
199
+ // Grouped source chips: the one rule + the one constructor, for the hub
200
+ // (server) and the chat strip (client) alike.
201
+ export {
202
+ DOC_TABLE_TYPES,
203
+ groupsByTable,
204
+ recordCountLabel,
205
+ buildGroupedSource,
206
+ groupSourcesByTable,
207
+ formatCitationIndices,
208
+ type GroupedSourceRow,
209
+ } from './source-grouping';
199
210
 
200
211
  // Embed-surface auth — generic across chat AND ticket center (and any
201
212
  // future embedded React component that needs to identify as the proxied