@schlessera/brain-ui-react 0.8.0 → 0.10.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 (48) hide show
  1. package/dist/components/chat/chat-page.d.ts.map +1 -1
  2. package/dist/components/chat/chat-page.js +10 -1
  3. package/dist/components/chat/chat-page.js.map +1 -1
  4. package/dist/components/chat/copy-button.d.ts.map +1 -1
  5. package/dist/components/chat/copy-button.js +3 -1
  6. package/dist/components/chat/copy-button.js.map +1 -1
  7. package/dist/components/chat/mermaid-block.d.ts.map +1 -1
  8. package/dist/components/chat/mermaid-block.js +10 -2
  9. package/dist/components/chat/mermaid-block.js.map +1 -1
  10. package/dist/components/chat/mermaid-share.d.ts +5 -0
  11. package/dist/components/chat/mermaid-share.d.ts.map +1 -0
  12. package/dist/components/chat/mermaid-share.js +80 -0
  13. package/dist/components/chat/mermaid-share.js.map +1 -0
  14. package/dist/components/chat/mermaid-viewer.d.ts +6 -0
  15. package/dist/components/chat/mermaid-viewer.d.ts.map +1 -0
  16. package/dist/components/chat/mermaid-viewer.js +266 -0
  17. package/dist/components/chat/mermaid-viewer.js.map +1 -0
  18. package/dist/components/files/file-viewer.d.ts.map +1 -1
  19. package/dist/components/files/file-viewer.js +15 -0
  20. package/dist/components/files/file-viewer.js.map +1 -1
  21. package/dist/components/share/share-menu.d.ts +8 -1
  22. package/dist/components/share/share-menu.d.ts.map +1 -1
  23. package/dist/components/share/share-menu.js +10 -5
  24. package/dist/components/share/share-menu.js.map +1 -1
  25. package/dist/lib/client-environment.d.ts +29 -0
  26. package/dist/lib/client-environment.d.ts.map +1 -0
  27. package/dist/lib/client-environment.js +153 -0
  28. package/dist/lib/client-environment.js.map +1 -0
  29. package/dist/lib/mermaid-theme.d.ts +4 -0
  30. package/dist/lib/mermaid-theme.d.ts.map +1 -0
  31. package/dist/lib/mermaid-theme.js +221 -0
  32. package/dist/lib/mermaid-theme.js.map +1 -0
  33. package/dist/lib/mermaid.d.ts +15 -1
  34. package/dist/lib/mermaid.d.ts.map +1 -1
  35. package/dist/lib/mermaid.js +88 -38
  36. package/dist/lib/mermaid.js.map +1 -1
  37. package/dist/styles.css +1 -1
  38. package/package.json +2 -2
  39. package/src/components/chat/chat-page.tsx +20 -1
  40. package/src/components/chat/copy-button.tsx +3 -0
  41. package/src/components/chat/mermaid-block.tsx +38 -9
  42. package/src/components/chat/mermaid-share.ts +91 -0
  43. package/src/components/chat/mermaid-viewer.tsx +336 -0
  44. package/src/components/files/file-viewer.tsx +17 -0
  45. package/src/components/share/share-menu.tsx +20 -6
  46. package/src/lib/client-environment.ts +152 -0
  47. package/src/lib/mermaid-theme.ts +246 -0
  48. package/src/lib/mermaid.ts +90 -36
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Mermaid theme variables for the two surfaces a diagram can land on.
3
+ *
4
+ * Mermaid's stock "dark" theme is a blue-grey palette that reads as foreign
5
+ * next to the app's warm-neutral chrome, and its "neutral" theme is what the
6
+ * share renderer used to emit. Both are replaced by the "base" theme plus the
7
+ * variables below, so an in-app diagram and a shared PNG are recognisably the
8
+ * same product.
9
+ *
10
+ * Two rules kept the palette honest:
11
+ * - Surfaces follow the tokens in theme.css, not approximations of them. A
12
+ * chat diagram sits on `--color-surface` (#141619), not on the page
13
+ * background, because MermaidBlock draws it on a raised plate.
14
+ * - Multi-series colors reuse CATEGORICAL_SLOTS from the graph view, which
15
+ * is the repo's one CVD-validated categorical palette. Slot order is the
16
+ * CVD-safety mechanism there and is preserved here.
17
+ */
18
+ import { CATEGORICAL_SLOTS, OTHER_COLOR } from "../components/graph/lib/graph-helpers.js";
19
+
20
+ export type MermaidTheme = "dark" | "light";
21
+
22
+ // These variables reach mermaid through initialize(), NOT through a
23
+ // `%%{init: …}%%` directive: mermaid's directive path rewrites `'` to `"`
24
+ // before parsing the JSON and drops any themeVariable containing a hyphen, so
25
+ // a font stack cannot survive it. See the note in mermaid.ts.
26
+ const SANS = '"Plus Jakarta Sans", system-ui, -apple-system, sans-serif';
27
+
28
+ /** Ordered series colors, long enough for the 12-slot scales mermaid asks for. */
29
+ const SERIES = [...CATEGORICAL_SLOTS, OTHER_COLOR, "#67b8e3", "#eab354", "#b197d4"];
30
+
31
+ /** Expand a scale into the `${prefix}0..count-1` (or 1-based) shape mermaid wants. */
32
+ function scale(prefix: string, count: number, oneBased = false): Record<string, string> {
33
+ const out: Record<string, string> = {};
34
+ for (let i = 0; i < count; i++) {
35
+ out[`${prefix}${oneBased ? i + 1 : i}`] = SERIES[i % SERIES.length];
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /**
41
+ * Dark: the in-app palette. Node fills use `--color-surface-overlay` so nodes
42
+ * sit a step above the block's own `--color-surface` plate, and borders use
43
+ * #3d4150 rather than `--color-border` (#2a2d35) — a 1px border at the token
44
+ * value all but disappears against the plate at diagram scale.
45
+ */
46
+ const DARK: Record<string, string | boolean> = {
47
+ darkMode: true,
48
+ background: "#141619",
49
+ fontFamily: SANS,
50
+ fontSize: "14px",
51
+
52
+ primaryColor: "#1e2128",
53
+ primaryTextColor: "#e8e4df",
54
+ primaryBorderColor: "#3d4150",
55
+ secondaryColor: "#1a1d22",
56
+ secondaryTextColor: "#e8e4df",
57
+ secondaryBorderColor: "#3d4150",
58
+ tertiaryColor: "#0c0e12",
59
+ tertiaryTextColor: "#8a8691",
60
+ tertiaryBorderColor: "#2a2d35",
61
+
62
+ mainBkg: "#1e2128",
63
+ nodeBorder: "#3d4150",
64
+ nodeTextColor: "#e8e4df",
65
+ textColor: "#e8e4df",
66
+ lineColor: "#8a8691",
67
+ defaultLinkColor: "#8a8691",
68
+ titleColor: "#e09f3e",
69
+ edgeLabelBackground: "#141619",
70
+ clusterBkg: "#0c0e12",
71
+ clusterBorder: "#2a2d35",
72
+
73
+ noteBkgColor: "#1a1d22",
74
+ noteTextColor: "#e8e4df",
75
+ noteBorderColor: "#e09f3e",
76
+ errorBkgColor: "#2a1a1a",
77
+ errorTextColor: "#f87171",
78
+
79
+ // Sequence
80
+ actorBkg: "#1e2128",
81
+ actorBorder: "#3d4150",
82
+ actorTextColor: "#e8e4df",
83
+ actorLineColor: "#3d4150",
84
+ signalColor: "#8a8691",
85
+ signalTextColor: "#e8e4df",
86
+ labelBoxBkgColor: "#1a1d22",
87
+ labelBoxBorderColor: "#2a2d35",
88
+ labelTextColor: "#e8e4df",
89
+ loopTextColor: "#e8e4df",
90
+ activationBkgColor: "#1a1d22",
91
+ activationBorderColor: "#5bb5a2",
92
+ sequenceNumberColor: "#0c0e12",
93
+
94
+ // State / class / journey
95
+ labelColor: "#e8e4df",
96
+ altBackground: "#0c0e12",
97
+ classText: "#e8e4df",
98
+
99
+ // Gantt
100
+ sectionBkgColor: "#1a1d22",
101
+ altSectionBkgColor: "#141619",
102
+ sectionBkgColor2: "#1e2128",
103
+ gridColor: "#2a2d35",
104
+ taskBkgColor: "#2a2d35",
105
+ taskTextColor: "#e8e4df",
106
+ taskTextOutsideColor: "#e8e4df",
107
+ taskTextDarkColor: "#0c0e12",
108
+ taskBorderColor: "#3d4150",
109
+ doneTaskBkgColor: "#565b66",
110
+ doneTaskBorderColor: "#3d4150",
111
+ activeTaskBkgColor: "#e09f3e",
112
+ activeTaskBorderColor: "#e09f3e",
113
+ critBkgColor: "#d03b3b",
114
+ critBorderColor: "#d03b3b",
115
+ todayLineColor: "#5bb5a2",
116
+
117
+ // Pie
118
+ pieTitleTextColor: "#e8e4df",
119
+ pieSectionTextColor: "#0c0e12",
120
+ pieLegendTextColor: "#e8e4df",
121
+ pieStrokeColor: "#141619",
122
+ pieOuterStrokeColor: "#2a2d35",
123
+
124
+ // Quadrant / requirement / misc surfaces that don't inherit cleanly
125
+ quadrant1Fill: "#1e2128",
126
+ quadrant2Fill: "#1a1d22",
127
+ quadrant3Fill: "#141619",
128
+ quadrant4Fill: "#1e2128",
129
+ quadrantPointFill: "#e09f3e",
130
+ quadrantTitleFill: "#e8e4df",
131
+ quadrantInternalBorderStrokeFill: "#2a2d35",
132
+ quadrantExternalBorderStrokeFill: "#3d4150",
133
+ };
134
+
135
+ /**
136
+ * Light: what the share renderer emits. Tuned against the PNG/PDF template's
137
+ * own palette (`ui-server/src/render/template.ts`: #ffffff page, #f8fafc
138
+ * surface, #e5e7eb border, #1f2937 text) so a diagram doesn't look pasted in.
139
+ * The amber and teal are darkened from the app tokens — #e09f3e on white is a
140
+ * 1.9:1 line, unusable for edges or titles.
141
+ */
142
+ const LIGHT: Record<string, string | boolean> = {
143
+ darkMode: false,
144
+ background: "#ffffff",
145
+ fontFamily: SANS,
146
+ fontSize: "14px",
147
+
148
+ primaryColor: "#f8fafc",
149
+ primaryTextColor: "#1f2937",
150
+ primaryBorderColor: "#c3c9d2",
151
+ secondaryColor: "#f3f4f6",
152
+ secondaryTextColor: "#1f2937",
153
+ secondaryBorderColor: "#c3c9d2",
154
+ tertiaryColor: "#ffffff",
155
+ tertiaryTextColor: "#6b7280",
156
+ tertiaryBorderColor: "#e5e7eb",
157
+
158
+ mainBkg: "#f8fafc",
159
+ nodeBorder: "#c3c9d2",
160
+ nodeTextColor: "#1f2937",
161
+ textColor: "#1f2937",
162
+ lineColor: "#6b7280",
163
+ defaultLinkColor: "#6b7280",
164
+ titleColor: "#9a6516",
165
+ edgeLabelBackground: "#ffffff",
166
+ clusterBkg: "#f3f4f6",
167
+ clusterBorder: "#d7dbe0",
168
+
169
+ noteBkgColor: "#fdf6e8",
170
+ noteTextColor: "#1f2937",
171
+ noteBorderColor: "#9a6516",
172
+ errorBkgColor: "#fdecec",
173
+ errorTextColor: "#b42323",
174
+
175
+ // Sequence
176
+ actorBkg: "#f8fafc",
177
+ actorBorder: "#c3c9d2",
178
+ actorTextColor: "#1f2937",
179
+ actorLineColor: "#c3c9d2",
180
+ signalColor: "#6b7280",
181
+ signalTextColor: "#1f2937",
182
+ labelBoxBkgColor: "#f3f4f6",
183
+ labelBoxBorderColor: "#d7dbe0",
184
+ labelTextColor: "#1f2937",
185
+ loopTextColor: "#1f2937",
186
+ activationBkgColor: "#f3f4f6",
187
+ activationBorderColor: "#2f7d6b",
188
+ sequenceNumberColor: "#ffffff",
189
+
190
+ // State / class / journey
191
+ labelColor: "#1f2937",
192
+ altBackground: "#f3f4f6",
193
+ classText: "#1f2937",
194
+
195
+ // Gantt
196
+ sectionBkgColor: "#f8fafc",
197
+ altSectionBkgColor: "#ffffff",
198
+ sectionBkgColor2: "#f3f4f6",
199
+ gridColor: "#e5e7eb",
200
+ taskBkgColor: "#e5e7eb",
201
+ taskTextColor: "#1f2937",
202
+ taskTextOutsideColor: "#1f2937",
203
+ taskTextDarkColor: "#1f2937",
204
+ taskBorderColor: "#c3c9d2",
205
+ doneTaskBkgColor: "#d7dbe0",
206
+ doneTaskBorderColor: "#c3c9d2",
207
+ activeTaskBkgColor: "#e0a75a",
208
+ activeTaskBorderColor: "#9a6516",
209
+ critBkgColor: "#e08a8a",
210
+ critBorderColor: "#b42323",
211
+ todayLineColor: "#2f7d6b",
212
+
213
+ // Pie
214
+ pieTitleTextColor: "#1f2937",
215
+ pieSectionTextColor: "#ffffff",
216
+ pieLegendTextColor: "#1f2937",
217
+ pieStrokeColor: "#ffffff",
218
+ pieOuterStrokeColor: "#d7dbe0",
219
+
220
+ // Quadrant
221
+ quadrant1Fill: "#f8fafc",
222
+ quadrant2Fill: "#f3f4f6",
223
+ quadrant3Fill: "#ffffff",
224
+ quadrant4Fill: "#f8fafc",
225
+ quadrantPointFill: "#9a6516",
226
+ quadrantTitleFill: "#1f2937",
227
+ quadrantInternalBorderStrokeFill: "#e5e7eb",
228
+ quadrantExternalBorderStrokeFill: "#d7dbe0",
229
+ };
230
+
231
+ const SERIES_SCALES: Record<string, string> = {
232
+ ...scale("pie", 12, true), // pie1..pie12
233
+ ...scale("cScale", 12), // cScale0..11 (journey, timeline, xychart)
234
+ ...scale("fillType", 8), // fillType0..7 (class/state/journey sections)
235
+ ...scale("git", 8), // git0..git7 (gitgraph branches)
236
+ };
237
+
238
+ const THEME_VARIABLES: Record<MermaidTheme, Record<string, string | boolean>> = {
239
+ dark: { ...DARK, ...SERIES_SCALES },
240
+ light: { ...LIGHT, ...SERIES_SCALES },
241
+ };
242
+
243
+ /** Theme variables for a target surface, as mermaid's `themeVariables` object. */
244
+ export function mermaidThemeVariables(theme: MermaidTheme): Record<string, string | boolean> {
245
+ return THEME_VARIABLES[theme];
246
+ }
@@ -9,7 +9,9 @@
9
9
  * streaming message a cache hit.
10
10
  */
11
11
 
12
- export type MermaidTheme = "dark" | "neutral";
12
+ import { mermaidThemeVariables, type MermaidTheme } from "./mermaid-theme.js";
13
+
14
+ export type { MermaidTheme };
13
15
 
14
16
  type MermaidApi = typeof import("mermaid").default;
15
17
 
@@ -17,36 +19,50 @@ let mermaidPromise: Promise<MermaidApi> | null = null;
17
19
 
18
20
  function loadMermaid(): Promise<MermaidApi> {
19
21
  if (!mermaidPromise) {
20
- mermaidPromise = import("mermaid").then((mod) => {
21
- const mermaid = mod.default;
22
- mermaid.initialize({
23
- startOnLoad: false,
24
- // "strict" sanitizes label HTML and blocks script/click payloads —
25
- // diagram sources arrive from the model and from repo files.
26
- securityLevel: "strict",
27
- // Never inject mermaid's own error SVG into the document; failures
28
- // surface as a null render result and the caller shows the source.
29
- suppressErrorRendering: true,
30
- theme: "dark",
31
- fontFamily: "ui-sans-serif, system-ui, sans-serif",
32
- });
33
- return mermaid;
34
- });
22
+ mermaidPromise = import("mermaid").then((mod) => mod.default);
35
23
  }
36
24
  return mermaidPromise;
37
25
  }
38
26
 
39
- const INIT_DIRECTIVE_RE = /%%\{\s*init/;
27
+ /** Config shared by both themes; only `themeVariables` differs per render. */
28
+ function baseConfig(theme: MermaidTheme) {
29
+ return {
30
+ startOnLoad: false,
31
+ // "strict" sanitizes label HTML and blocks script/click payloads —
32
+ // diagram sources arrive from the model and from repo files.
33
+ securityLevel: "strict" as const,
34
+ // Never inject mermaid's own error SVG into the document; failures
35
+ // surface as a null render result and the caller shows the source.
36
+ suppressErrorRendering: true,
37
+ theme: "base" as const,
38
+ themeVariables: mermaidThemeVariables(theme),
39
+ };
40
+ }
40
41
 
41
42
  /**
42
- * Theme is applied per-diagram via an init directive rather than re-calling
43
- * mermaid.initialize(), so concurrent renders for different targets (dark
44
- * in-app, neutral for the light share template) can't race on global config.
45
- * A source that carries its own init directive is left alone.
43
+ * Renders are serialized through this chain because the theme is applied by
44
+ * re-calling mermaid.initialize(), which mutates GLOBAL config — a dark
45
+ * in-app render and a light share render would otherwise race and one would
46
+ * come out in the other's palette.
47
+ *
48
+ * The obvious alternative, a per-diagram `%%{init: …}%%` directive, does not
49
+ * work: mermaid rewrites every `'` to `"` before JSON.parse-ing a directive
50
+ * (chunk-NSK5VX7P), so a quoted font stack makes the whole directive
51
+ * unparseable and it is silently dropped; and its themeVariables sanitizer
52
+ * rejects any value outside /^[\\d "#%(),.;A-Za-z]+$/, which blanks every
53
+ * hyphenated CSS keyword (`system-ui`, `-apple-system`). A dropped directive
54
+ * fails SILENTLY — the diagram renders in whatever the last global config
55
+ * was — so this path is not worth the theming it appears to buy.
46
56
  */
47
- function withThemeDirective(source: string, theme: MermaidTheme): string {
48
- if (INIT_DIRECTIVE_RE.test(source)) return source;
49
- return `%%{init: {"theme": "${theme}"}}%%\n${source}`;
57
+ let renderChain: Promise<unknown> = Promise.resolve();
58
+
59
+ function serialized<T>(fn: () => Promise<T>): Promise<T> {
60
+ const run = renderChain.then(fn, fn);
61
+ renderChain = run.then(
62
+ () => undefined,
63
+ () => undefined
64
+ );
65
+ return run;
50
66
  }
51
67
 
52
68
  const svgCache = new Map<string, string>();
@@ -78,16 +94,22 @@ export async function renderMermaidSvg(
78
94
  if (hit !== undefined) return hit;
79
95
  try {
80
96
  const mermaid = await loadMermaid();
81
- const text = withThemeDirective(trimmed, theme);
82
- const ok = await mermaid.parse(text, { suppressErrors: true });
83
- if (!ok) return null;
84
- const { svg } = await mermaid.render(`brain-mermaid-${++renderSeq}`, text);
85
- if (svgCache.size >= CACHE_MAX) {
86
- const oldest = svgCache.keys().next().value;
87
- if (oldest !== undefined) svgCache.delete(oldest);
88
- }
89
- svgCache.set(key, svg);
90
- return svg;
97
+ return await serialized(async () => {
98
+ // Re-check inside the lock: an identical render may have been queued
99
+ // ahead of this one while both were waiting.
100
+ const queued = svgCache.get(key);
101
+ if (queued !== undefined) return queued;
102
+ mermaid.initialize(baseConfig(theme));
103
+ const ok = await mermaid.parse(trimmed, { suppressErrors: true });
104
+ if (!ok) return null;
105
+ const { svg } = await mermaid.render(`brain-mermaid-${++renderSeq}`, trimmed);
106
+ if (svgCache.size >= CACHE_MAX) {
107
+ const oldest = svgCache.keys().next().value;
108
+ if (oldest !== undefined) svgCache.delete(oldest);
109
+ }
110
+ svgCache.set(key, svg);
111
+ return svg;
112
+ });
91
113
  } catch {
92
114
  return null;
93
115
  }
@@ -184,7 +206,7 @@ export function replaceMermaidFences(
184
206
  * block. Used by the share pipeline: the PNG/PDF renderer runs the page with
185
207
  * JavaScript disabled and all network denied, so the diagram must already be
186
208
  * SVG by the time the markdown reaches the server. Defaults to the light
187
- * "neutral" theme to match the share template. Fences that fail to render are
209
+ * theme to match the share template. Fences that fail to render are
188
210
  * left as code fences — the pre-feature behavior.
189
211
  */
190
212
  /**
@@ -219,7 +241,7 @@ export function inlineRenderedFences(
219
241
 
220
242
  export async function inlineMermaidDiagrams(
221
243
  md: string,
222
- theme: MermaidTheme = "neutral"
244
+ theme: MermaidTheme = "light"
223
245
  ): Promise<string> {
224
246
  const fences = findMermaidFences(md);
225
247
  if (fences.length === 0) return md;
@@ -227,6 +249,38 @@ export async function inlineMermaidDiagrams(
227
249
  return inlineRenderedFences(md, rendered);
228
250
  }
229
251
 
252
+ const SVG_OPEN_TAG_RE = /<svg\b[^>]*>/i;
253
+ const VIEWBOX_RE = /\bviewBox\s*=\s*"\s*[\d.+-]+\s+[\d.+-]+\s+([\d.+-]+)\s+([\d.+-]+)\s*"/i;
254
+
255
+ /**
256
+ * Give a mermaid SVG an intrinsic pixel size taken from its viewBox.
257
+ *
258
+ * Mermaid ships its diagrams as `style="max-width: Npx"` with no width/height
259
+ * attribute, which is right for a responsive page and wrong for an export: a
260
+ * standalone .svg file then has no intrinsic size, and the PNG/PDF renderer
261
+ * lays it out at the full body width no matter how small the diagram is.
262
+ * Sizing it here is what lets the share page shrink-wrap the figure.
263
+ *
264
+ * Returns the input unchanged when there is no parseable viewBox — an
265
+ * un-sized export beats a corrupted one.
266
+ */
267
+ export function sizeSvgForExport(svg: string, maxWidth = 1200): string {
268
+ const open = SVG_OPEN_TAG_RE.exec(svg);
269
+ if (!open) return svg;
270
+ const tag = open[0];
271
+ const vb = VIEWBOX_RE.exec(tag);
272
+ if (!vb) return svg;
273
+ const vbW = Number(vb[1]);
274
+ const vbH = Number(vb[2]);
275
+ if (!Number.isFinite(vbW) || !Number.isFinite(vbH) || vbW <= 0 || vbH <= 0) return svg;
276
+ const width = Math.max(1, Math.min(maxWidth, Math.round(vbW)));
277
+ const height = Math.max(1, Math.round((width / vbW) * vbH));
278
+ const sized = tag
279
+ .replace(/\s(?:width|height|style)\s*=\s*"[^"]*"/gi, "")
280
+ .replace(/<svg\b/i, `<svg width="${width}" height="${height}"`);
281
+ return svg.slice(0, open.index) + sized + svg.slice(open.index + tag.length);
282
+ }
283
+
230
284
  /** Whether a repo path is a standalone mermaid source file (previewable as a diagram). */
231
285
  export function isMermaidPath(path: string): boolean {
232
286
  return /\.(mmd|mermaid)$/i.test(path);