@cerebriline/ui 0.0.0-stage → 4.100.313
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.
- package/ADOPTION.md +833 -0
- package/LICENSE +201 -0
- package/RADIX-COLORS-LICENSE +21 -0
- package/README.md +427 -2
- package/components/agent-approval-card.css +70 -0
- package/components/agent-approval-card.tsx +109 -0
- package/components/agent-ask-question.css +103 -0
- package/components/agent-ask-question.tsx +276 -0
- package/components/agent-aurora.css +228 -0
- package/components/agent-aurora.tsx +96 -0
- package/components/agent-changes.css +13 -0
- package/components/agent-changes.tsx +167 -0
- package/components/agent-chat/agent-chat.css +556 -0
- package/components/agent-chat/index.tsx +1037 -0
- package/components/agent-chat/tool-diff.tsx +165 -0
- package/components/agent-chat/tool-summary/agents.ts +114 -0
- package/components/agent-chat/tool-summary/diff.ts +152 -0
- package/components/agent-chat/tool-summary/index.ts +928 -0
- package/components/agent-chat/tool-summary/parsers.ts +611 -0
- package/components/agent-chat/tool-summary/paths.ts +84 -0
- package/components/agent-chat/tool-summary/team.ts +401 -0
- package/components/agent-command-output.tsx +63 -0
- package/components/agent-composer.tsx +263 -0
- package/components/agent-context-usage.tsx +181 -0
- package/components/agent-conversation-layout.tsx +139 -0
- package/components/agent-hero-heading.css +53 -0
- package/components/agent-hero-heading.tsx +45 -0
- package/components/agent-image-lightbox.tsx +48 -0
- package/components/agent-prompt-queue.css +20 -0
- package/components/agent-prompt-queue.tsx +350 -0
- package/components/agent-pull-request-bar.css +13 -0
- package/components/agent-pull-request-bar.tsx +346 -0
- package/components/agent-quick-actions.css +19 -0
- package/components/agent-quick-actions.tsx +70 -0
- package/components/agent-session-row.tsx +183 -0
- package/components/agent-welcome-hero-pointer.ts +199 -0
- package/components/agent-welcome-hero.css +205 -0
- package/components/agent-welcome-hero.tsx +68 -0
- package/components/attachment-drop-zone.tsx +154 -0
- package/components/badge.tsx +21 -0
- package/components/button.tsx +324 -0
- package/components/generated-media.tsx +173 -0
- package/components/github-icon.tsx +19 -0
- package/components/index.ts +133 -0
- package/components/markdown.css +490 -0
- package/components/markdown.ts +365 -0
- package/components/mermaid-block.tsx +722 -0
- package/components/mermaid-diagram.ts +1260 -0
- package/components/mermaid-dom.ts +301 -0
- package/components/message-scroller.css +118 -0
- package/components/message-scroller.tsx +114 -0
- package/components/search-combobox.css +67 -0
- package/components/search-combobox.tsx +433 -0
- package/components/session-status.css +19 -0
- package/components/session-status.tsx +39 -0
- package/components/switch.css +221 -0
- package/components/switch.tsx +48 -0
- package/components.css +16 -0
- package/dist/components/agent-approval-card.d.ts +14 -0
- package/dist/components/agent-approval-card.d.ts.map +1 -0
- package/dist/components/agent-approval-card.js +12 -0
- package/dist/components/agent-approval-card.js.map +1 -0
- package/dist/components/agent-ask-question.d.ts +18 -0
- package/dist/components/agent-ask-question.d.ts.map +1 -0
- package/dist/components/agent-ask-question.js +101 -0
- package/dist/components/agent-ask-question.js.map +1 -0
- package/dist/components/agent-aurora.d.ts +3 -0
- package/dist/components/agent-aurora.d.ts.map +1 -0
- package/dist/components/agent-aurora.js +60 -0
- package/dist/components/agent-aurora.js.map +1 -0
- package/dist/components/agent-changes.d.ts +26 -0
- package/dist/components/agent-changes.d.ts.map +1 -0
- package/dist/components/agent-changes.js +19 -0
- package/dist/components/agent-changes.js.map +1 -0
- package/dist/components/agent-chat/disclosure.d.ts +25 -0
- package/dist/components/agent-chat/disclosure.d.ts.map +1 -0
- package/dist/components/agent-chat/disclosure.js +39 -0
- package/dist/components/agent-chat/disclosure.js.map +1 -0
- package/dist/components/agent-chat/index.d.ts +140 -0
- package/dist/components/agent-chat/index.d.ts.map +1 -0
- package/dist/components/agent-chat/index.js +379 -0
- package/dist/components/agent-chat/index.js.map +1 -0
- package/dist/components/agent-chat/tool-diff.d.ts +32 -0
- package/dist/components/agent-chat/tool-diff.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-diff.js +97 -0
- package/dist/components/agent-chat/tool-diff.js.map +1 -0
- package/dist/components/agent-chat/tool-summary/agents.d.ts +10 -0
- package/dist/components/agent-chat/tool-summary/agents.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-summary/agents.js +100 -0
- package/dist/components/agent-chat/tool-summary/agents.js.map +1 -0
- package/dist/components/agent-chat/tool-summary/diff.d.ts +22 -0
- package/dist/components/agent-chat/tool-summary/diff.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-summary/diff.js +127 -0
- package/dist/components/agent-chat/tool-summary/diff.js.map +1 -0
- package/dist/components/agent-chat/tool-summary/index.d.ts +145 -0
- package/dist/components/agent-chat/tool-summary/index.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-summary/index.js +663 -0
- package/dist/components/agent-chat/tool-summary/index.js.map +1 -0
- package/dist/components/agent-chat/tool-summary/parsers.d.ts +114 -0
- package/dist/components/agent-chat/tool-summary/parsers.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-summary/parsers.js +502 -0
- package/dist/components/agent-chat/tool-summary/parsers.js.map +1 -0
- package/dist/components/agent-chat/tool-summary/paths.d.ts +10 -0
- package/dist/components/agent-chat/tool-summary/paths.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-summary/paths.js +88 -0
- package/dist/components/agent-chat/tool-summary/paths.js.map +1 -0
- package/dist/components/agent-chat/tool-summary/team.d.ts +16 -0
- package/dist/components/agent-chat/tool-summary/team.d.ts.map +1 -0
- package/dist/components/agent-chat/tool-summary/team.js +283 -0
- package/dist/components/agent-chat/tool-summary/team.js.map +1 -0
- package/dist/components/agent-command-output.d.ts +14 -0
- package/dist/components/agent-command-output.d.ts.map +1 -0
- package/dist/components/agent-command-output.js +22 -0
- package/dist/components/agent-command-output.js.map +1 -0
- package/dist/components/agent-composer.d.ts +34 -0
- package/dist/components/agent-composer.d.ts.map +1 -0
- package/dist/components/agent-composer.js +65 -0
- package/dist/components/agent-composer.js.map +1 -0
- package/dist/components/agent-context-usage.d.ts +28 -0
- package/dist/components/agent-context-usage.d.ts.map +1 -0
- package/dist/components/agent-context-usage.js +51 -0
- package/dist/components/agent-context-usage.js.map +1 -0
- package/dist/components/agent-conversation-layout.d.ts +30 -0
- package/dist/components/agent-conversation-layout.d.ts.map +1 -0
- package/dist/components/agent-conversation-layout.js +24 -0
- package/dist/components/agent-conversation-layout.js.map +1 -0
- package/dist/components/agent-hero-heading.d.ts +2 -0
- package/dist/components/agent-hero-heading.d.ts.map +1 -0
- package/dist/components/agent-hero-heading.js +20 -0
- package/dist/components/agent-hero-heading.js.map +1 -0
- package/dist/components/agent-image-lightbox.d.ts +11 -0
- package/dist/components/agent-image-lightbox.d.ts.map +1 -0
- package/dist/components/agent-image-lightbox.js +8 -0
- package/dist/components/agent-image-lightbox.js.map +1 -0
- package/dist/components/agent-prompt-queue.d.ts +14 -0
- package/dist/components/agent-prompt-queue.d.ts.map +1 -0
- package/dist/components/agent-prompt-queue.js +114 -0
- package/dist/components/agent-prompt-queue.js.map +1 -0
- package/dist/components/agent-pull-request-bar.d.ts +72 -0
- package/dist/components/agent-pull-request-bar.d.ts.map +1 -0
- package/dist/components/agent-pull-request-bar.js +90 -0
- package/dist/components/agent-pull-request-bar.js.map +1 -0
- package/dist/components/agent-quick-actions.d.ts +14 -0
- package/dist/components/agent-quick-actions.d.ts.map +1 -0
- package/dist/components/agent-quick-actions.js +12 -0
- package/dist/components/agent-quick-actions.js.map +1 -0
- package/dist/components/agent-session-row.d.ts +45 -0
- package/dist/components/agent-session-row.d.ts.map +1 -0
- package/dist/components/agent-session-row.js +34 -0
- package/dist/components/agent-session-row.js.map +1 -0
- package/dist/components/agent-welcome-hero-pointer.d.ts +3 -0
- package/dist/components/agent-welcome-hero-pointer.d.ts.map +1 -0
- package/dist/components/agent-welcome-hero-pointer.js +169 -0
- package/dist/components/agent-welcome-hero-pointer.js.map +1 -0
- package/dist/components/agent-welcome-hero.d.ts +9 -0
- package/dist/components/agent-welcome-hero.d.ts.map +1 -0
- package/dist/components/agent-welcome-hero.js +14 -0
- package/dist/components/agent-welcome-hero.js.map +1 -0
- package/dist/components/attachment-drop-zone.d.ts +15 -0
- package/dist/components/attachment-drop-zone.d.ts.map +1 -0
- package/dist/components/attachment-drop-zone.js +64 -0
- package/dist/components/attachment-drop-zone.js.map +1 -0
- package/dist/components/badge.d.ts +5 -0
- package/dist/components/badge.d.ts.map +1 -0
- package/dist/components/badge.js +7 -0
- package/dist/components/badge.js.map +1 -0
- package/dist/components/button.d.ts +27 -0
- package/dist/components/button.d.ts.map +1 -0
- package/dist/components/button.js +209 -0
- package/dist/components/button.js.map +1 -0
- package/dist/components/generated-media.d.ts +12 -0
- package/dist/components/generated-media.d.ts.map +1 -0
- package/dist/components/generated-media.js +105 -0
- package/dist/components/generated-media.js.map +1 -0
- package/dist/components/github-icon.d.ts +3 -0
- package/dist/components/github-icon.d.ts.map +1 -0
- package/dist/components/github-icon.js +6 -0
- package/dist/components/github-icon.js.map +1 -0
- package/dist/components/index.d.ts +24 -0
- package/dist/components/index.d.ts.map +1 -0
- package/dist/components/index.js +25 -0
- package/dist/components/index.js.map +1 -0
- package/dist/components/markdown.d.ts +48 -0
- package/dist/components/markdown.d.ts.map +1 -0
- package/dist/components/markdown.js +264 -0
- package/dist/components/markdown.js.map +1 -0
- package/dist/components/mermaid-block.d.ts +14 -0
- package/dist/components/mermaid-block.d.ts.map +1 -0
- package/dist/components/mermaid-block.js +339 -0
- package/dist/components/mermaid-block.js.map +1 -0
- package/dist/components/mermaid-diagram.d.ts +264 -0
- package/dist/components/mermaid-diagram.d.ts.map +1 -0
- package/dist/components/mermaid-diagram.js +999 -0
- package/dist/components/mermaid-diagram.js.map +1 -0
- package/dist/components/mermaid-dom.d.ts +51 -0
- package/dist/components/mermaid-dom.d.ts.map +1 -0
- package/dist/components/mermaid-dom.js +246 -0
- package/dist/components/mermaid-dom.js.map +1 -0
- package/dist/components/message-scroller.d.ts +23 -0
- package/dist/components/message-scroller.d.ts.map +1 -0
- package/dist/components/message-scroller.js +31 -0
- package/dist/components/message-scroller.js.map +1 -0
- package/dist/components/search-combobox.d.ts +44 -0
- package/dist/components/search-combobox.d.ts.map +1 -0
- package/dist/components/search-combobox.js +191 -0
- package/dist/components/search-combobox.js.map +1 -0
- package/dist/components/session-status.d.ts +9 -0
- package/dist/components/session-status.d.ts.map +1 -0
- package/dist/components/session-status.js +11 -0
- package/dist/components/session-status.js.map +1 -0
- package/dist/components/switch.d.ts +7 -0
- package/dist/components/switch.d.ts.map +1 -0
- package/dist/components/switch.js +14 -0
- package/dist/components/switch.js.map +1 -0
- package/package.json +177 -5
- package/theme/base.css +83 -0
- package/theme/component-theme.css +126 -0
- package/theme/index.css +3 -0
- package/theme/palette.css +347 -0
- package/theme/scoped-tokens.css +503 -0
- package/theme/theme.css +90 -0
- package/theme/tokens.css +165 -0
|
@@ -0,0 +1,1260 @@
|
|
|
1
|
+
import type { MermaidConfig } from "mermaid";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pure (DOM-free) logic behind the owned Mermaid diagram block: fence/diagram
|
|
5
|
+
* naming, CSS color parsing, theme-variable construction, zoom math, PNG export
|
|
6
|
+
* sizing and the serialized (queued) lazy renderer. Everything here runs in Node so it
|
|
7
|
+
* can be unit-tested without a DOM; the browser glue lives in `mermaid-dom.ts`
|
|
8
|
+
* and the React block in `mermaid-block.tsx`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Lazy Mermaid module
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
export interface LazyMermaidInstance {
|
|
16
|
+
initialize: (config: MermaidConfig) => void;
|
|
17
|
+
render: (id: string, source: string) => Promise<{ svg: string }>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type MermaidModule = {
|
|
21
|
+
default: LazyMermaidInstance;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type MermaidModuleLoader = () => Promise<MermaidModule>;
|
|
25
|
+
|
|
26
|
+
/** Dynamic import so Mermaid only loads when a diagram first appears. */
|
|
27
|
+
export const defaultMermaidLoader: MermaidModuleLoader = () =>
|
|
28
|
+
import("mermaid");
|
|
29
|
+
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
// Naming
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_DIAGRAM_NAME = "diagram";
|
|
35
|
+
export const MAX_DIAGRAM_SLUG_LENGTH = 64;
|
|
36
|
+
const MAX_DERIVED_SLUG_LENGTH = 48;
|
|
37
|
+
|
|
38
|
+
/** Lowercase, alphanumerics and single hyphens, trimmed, length-capped. */
|
|
39
|
+
export function slugifyDiagramName(
|
|
40
|
+
value: string,
|
|
41
|
+
maxLength: number = MAX_DIAGRAM_SLUG_LENGTH,
|
|
42
|
+
): string {
|
|
43
|
+
const slug = value
|
|
44
|
+
.normalize("NFKD")
|
|
45
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
46
|
+
.toLowerCase()
|
|
47
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
48
|
+
.replace(/^-+|-+$/g, "");
|
|
49
|
+
if (slug.length <= maxLength) return slug;
|
|
50
|
+
return slug.slice(0, maxLength).replace(/-+$/g, "");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Reads `title="..."` from a code-fence metastring. Tolerates single quotes,
|
|
55
|
+
* curly quotes, an unquoted value, `title:` instead of `title=`, and a missing
|
|
56
|
+
* closing quote. `meta` is often undefined or empty (including while
|
|
57
|
+
* streaming), which yields `undefined`.
|
|
58
|
+
*/
|
|
59
|
+
export function parseFenceTitle(
|
|
60
|
+
meta: string | null | undefined,
|
|
61
|
+
): string | undefined {
|
|
62
|
+
if (!meta) return undefined;
|
|
63
|
+
const closingQuotes: Record<string, string> = {
|
|
64
|
+
'"': '"',
|
|
65
|
+
"'": "'",
|
|
66
|
+
"“": "”",
|
|
67
|
+
};
|
|
68
|
+
const lastQuotes: Record<string, number> = {
|
|
69
|
+
'"': meta.lastIndexOf('"'),
|
|
70
|
+
"'": meta.lastIndexOf("'"),
|
|
71
|
+
"”": meta.lastIndexOf("”"),
|
|
72
|
+
};
|
|
73
|
+
const lastTerminator = Math.max(...Object.values(lastQuotes));
|
|
74
|
+
let unquoted: string | undefined;
|
|
75
|
+
let unterminated: string | undefined;
|
|
76
|
+
const unquotedValue = /[^\s"'“{},]+/y;
|
|
77
|
+
for (const match of meta.matchAll(/(?:^|[\s{,])title\s*[=:]/gi)) {
|
|
78
|
+
let start = match.index + match[0].length;
|
|
79
|
+
while (start < meta.length && /\s/.test(meta[start] ?? "")) start++;
|
|
80
|
+
const closing = closingQuotes[meta[start] ?? ""];
|
|
81
|
+
if (closing) {
|
|
82
|
+
// A missing closing quote must not rescan the suffix for every title.
|
|
83
|
+
if ((lastQuotes[closing] ?? -1) > start) {
|
|
84
|
+
return (
|
|
85
|
+
meta.slice(start + 1, meta.indexOf(closing, start + 1)).trim() ||
|
|
86
|
+
undefined
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
if (start >= lastTerminator && unterminated === undefined) {
|
|
90
|
+
unterminated = meta.slice(start + 1);
|
|
91
|
+
}
|
|
92
|
+
} else if (unquoted === undefined) {
|
|
93
|
+
unquotedValue.lastIndex = start;
|
|
94
|
+
unquoted = unquotedValue.exec(meta)?.[0];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return (unquoted ?? unterminated)?.trim() || undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const FRONTMATTER =
|
|
101
|
+
/^\uFEFF?\s*---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
|
|
102
|
+
|
|
103
|
+
/** Splits a leading `---` YAML frontmatter block off a diagram source. */
|
|
104
|
+
export function splitFrontmatter(source: string): {
|
|
105
|
+
body: string;
|
|
106
|
+
frontmatter: string | undefined;
|
|
107
|
+
} {
|
|
108
|
+
const match = FRONTMATTER.exec(source);
|
|
109
|
+
if (!match) return { body: source, frontmatter: undefined };
|
|
110
|
+
return { body: source.slice(match[0].length), frontmatter: match[1] };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function unquote(value: string): string {
|
|
114
|
+
const trimmed = value.trim();
|
|
115
|
+
const quote = trimmed[0];
|
|
116
|
+
if (
|
|
117
|
+
trimmed.length >= 2 &&
|
|
118
|
+
(quote === '"' || quote === "'") &&
|
|
119
|
+
trimmed.endsWith(quote)
|
|
120
|
+
) {
|
|
121
|
+
return trimmed.slice(1, -1).trim();
|
|
122
|
+
}
|
|
123
|
+
return trimmed;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** `title:` from the diagram's own frontmatter (top-level key only). */
|
|
127
|
+
export function parseFrontmatterTitle(source: string): string | undefined {
|
|
128
|
+
const { frontmatter } = splitFrontmatter(source);
|
|
129
|
+
if (!frontmatter) return undefined;
|
|
130
|
+
const match = /^title[ \t]*:(.+)$/m.exec(frontmatter);
|
|
131
|
+
const title = match ? unquote(match[1] ?? "") : "";
|
|
132
|
+
return title || undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const DIAGRAM_TYPE_NAMES: Record<string, string> = {
|
|
136
|
+
"architecture-beta": "architecture",
|
|
137
|
+
"block-beta": "block",
|
|
138
|
+
c4component: "c4",
|
|
139
|
+
c4container: "c4",
|
|
140
|
+
c4context: "c4",
|
|
141
|
+
c4deployment: "c4",
|
|
142
|
+
c4dynamic: "c4",
|
|
143
|
+
classdiagram: "class",
|
|
144
|
+
"classdiagram-v2": "class",
|
|
145
|
+
erdiagram: "er",
|
|
146
|
+
flowchart: "flowchart",
|
|
147
|
+
"flowchart-elk": "flowchart",
|
|
148
|
+
gantt: "gantt",
|
|
149
|
+
gitgraph: "git",
|
|
150
|
+
graph: "flowchart",
|
|
151
|
+
journey: "journey",
|
|
152
|
+
kanban: "kanban",
|
|
153
|
+
mindmap: "mindmap",
|
|
154
|
+
"packet-beta": "packet",
|
|
155
|
+
pie: "pie",
|
|
156
|
+
quadrantchart: "quadrant",
|
|
157
|
+
requirementdiagram: "requirement",
|
|
158
|
+
sankey: "sankey",
|
|
159
|
+
"sankey-beta": "sankey",
|
|
160
|
+
sequencediagram: "sequence",
|
|
161
|
+
statediagram: "state",
|
|
162
|
+
"statediagram-v2": "state",
|
|
163
|
+
timeline: "timeline",
|
|
164
|
+
"xychart-beta": "xychart",
|
|
165
|
+
xychart: "xychart",
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const FLOWCHART_SKIP_LINE =
|
|
169
|
+
/^\s*(?:subgraph|end|classDef|class|style|linkStyle|click|direction|accTitle|accDescr)\b/;
|
|
170
|
+
|
|
171
|
+
const BRACKET_CLOSERS: Record<string, string> = {
|
|
172
|
+
"(": ")",
|
|
173
|
+
"[": "]",
|
|
174
|
+
"{": "}",
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
function isIdentifierCharacter(char: string | undefined): boolean {
|
|
178
|
+
return char !== undefined && /[A-Za-z0-9_]/.test(char);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* First `identifier [Label]`-style label at/after `from`, where the bracket may
|
|
183
|
+
* be doubled (`[[...]]`). Scans once, left to right, so adversarial input stays
|
|
184
|
+
* linear-time where the equivalent backtracking regex did not.
|
|
185
|
+
*/
|
|
186
|
+
function nextNodeLabel(
|
|
187
|
+
line: string,
|
|
188
|
+
from: number,
|
|
189
|
+
): { label: string; next: number } | undefined {
|
|
190
|
+
let index = from;
|
|
191
|
+
while (index < line.length) {
|
|
192
|
+
// An identifier run starting with a digit (e.g. `9ab`) cannot begin a
|
|
193
|
+
// label, and no label can start inside it; skip the whole run.
|
|
194
|
+
if (/[0-9]/.test(line[index])) {
|
|
195
|
+
while (isIdentifierCharacter(line[index])) index += 1;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (!/[A-Za-z_]/.test(line[index])) {
|
|
199
|
+
index += 1;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
let cursor = index + 1;
|
|
203
|
+
while (isIdentifierCharacter(line[cursor])) cursor += 1;
|
|
204
|
+
while (cursor < line.length && /\s/.test(line[cursor])) cursor += 1;
|
|
205
|
+
const opener = line[cursor];
|
|
206
|
+
const closer = opener ? BRACKET_CLOSERS[opener] : undefined;
|
|
207
|
+
if (!closer) {
|
|
208
|
+
index = cursor;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const openEnd = line[cursor + 1] === opener ? cursor + 2 : cursor + 1;
|
|
212
|
+
const close = line.indexOf(closer, openEnd);
|
|
213
|
+
if (close === -1) return undefined;
|
|
214
|
+
return { label: unquote(line.slice(openEnd, close)), next: close + 1 };
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function stripMarkup(value: string): string {
|
|
220
|
+
let withoutTags = "";
|
|
221
|
+
let cursor = 0;
|
|
222
|
+
while (cursor < value.length) {
|
|
223
|
+
const open = value.indexOf("<", cursor);
|
|
224
|
+
if (open === -1) {
|
|
225
|
+
withoutTags += value.slice(cursor);
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
withoutTags += value.slice(cursor, open);
|
|
229
|
+
const close = value.indexOf(">", open + 1);
|
|
230
|
+
// An unterminated `<` is literal text, not a tag.
|
|
231
|
+
if (close === -1) {
|
|
232
|
+
withoutTags += value.slice(open);
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
withoutTags += " ";
|
|
236
|
+
cursor = close + 1;
|
|
237
|
+
}
|
|
238
|
+
return withoutTags
|
|
239
|
+
.replaceAll(/[*_`]+/g, "")
|
|
240
|
+
.replaceAll(/\s+/g, " ")
|
|
241
|
+
.trim();
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function pushUnique(labels: string[], label: string | undefined): void {
|
|
245
|
+
if (!label) return;
|
|
246
|
+
const clean = stripMarkup(label);
|
|
247
|
+
if (!clean) return;
|
|
248
|
+
const slug = slugifyDiagramName(clean);
|
|
249
|
+
if (
|
|
250
|
+
!slug ||
|
|
251
|
+
labels.some((existing) => slugifyDiagramName(existing) === slug)
|
|
252
|
+
) {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
labels.push(clean);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function stripDirectivesAndComments(body: string): string {
|
|
259
|
+
const parts: string[] = [];
|
|
260
|
+
let cursor = 0;
|
|
261
|
+
while (cursor < body.length) {
|
|
262
|
+
const start = body.indexOf("%%{", cursor);
|
|
263
|
+
if (start === -1) break;
|
|
264
|
+
const end = body.indexOf("}%%", start + 3);
|
|
265
|
+
if (end === -1) break;
|
|
266
|
+
parts.push(body.slice(cursor, start));
|
|
267
|
+
cursor = end + 3;
|
|
268
|
+
}
|
|
269
|
+
parts.push(body.slice(cursor));
|
|
270
|
+
return parts
|
|
271
|
+
.join("")
|
|
272
|
+
.split(/\r?\n/)
|
|
273
|
+
.filter((line) => !/^\s*%%/.test(line))
|
|
274
|
+
.join("\n");
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Label of a `subgraph` line: `subgraph id [Label]`, or the bare text. */
|
|
278
|
+
function subgraphLabel(rest: string): string | undefined {
|
|
279
|
+
const text = rest.trim();
|
|
280
|
+
let index = 0;
|
|
281
|
+
while (index < text.length && /[\w-]/.test(text[index])) index += 1;
|
|
282
|
+
// Without an `id [` prefix the whole text is the label.
|
|
283
|
+
if (index === 0) return unquote(text) || undefined;
|
|
284
|
+
while (index < text.length && /\s/.test(text[index])) index += 1;
|
|
285
|
+
if (text[index] !== "[") return unquote(text) || undefined;
|
|
286
|
+
const close = text.indexOf("]", index + 1);
|
|
287
|
+
if (close === -1) return undefined;
|
|
288
|
+
return unquote(text.slice(index + 1, close)) || undefined;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function subgraphTitle(lines: string[]): string | undefined {
|
|
292
|
+
for (const line of lines) {
|
|
293
|
+
const trimmed = line.trim();
|
|
294
|
+
if (!trimmed.startsWith("subgraph")) continue;
|
|
295
|
+
const rest = trimmed.slice("subgraph".length);
|
|
296
|
+
if (!/\s/.test(rest[0] ?? "")) continue;
|
|
297
|
+
return subgraphLabel(rest);
|
|
298
|
+
}
|
|
299
|
+
return undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function addNodeLabels(line: string, labels: string[]): void {
|
|
303
|
+
let index = 0;
|
|
304
|
+
while (labels.length < 2) {
|
|
305
|
+
const found = nextNodeLabel(line, index);
|
|
306
|
+
if (!found) return;
|
|
307
|
+
pushUnique(labels, found.label);
|
|
308
|
+
index = found.next;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function flowchartLabels(lines: string[]): string[] {
|
|
313
|
+
const labels: string[] = [];
|
|
314
|
+
pushUnique(labels, subgraphTitle(lines));
|
|
315
|
+
for (const line of lines.slice(1)) {
|
|
316
|
+
if (FLOWCHART_SKIP_LINE.test(line)) continue;
|
|
317
|
+
addNodeLabels(line, labels);
|
|
318
|
+
if (labels.length >= 2) break;
|
|
319
|
+
}
|
|
320
|
+
return labels;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** A `title` or `keyword title` line, with the words after the keyword. */
|
|
324
|
+
function titleLine(lines: string[]): string | undefined {
|
|
325
|
+
for (const line of lines) {
|
|
326
|
+
const columns = line.trim().split(/\s+/);
|
|
327
|
+
const titleIndex =
|
|
328
|
+
columns[0] === "title" ? 1 : columns[1] === "title" ? 2 : 0;
|
|
329
|
+
if (titleIndex === 0) continue;
|
|
330
|
+
const title = columns.slice(titleIndex).join(" ").trim();
|
|
331
|
+
if (title) return title;
|
|
332
|
+
}
|
|
333
|
+
return undefined;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** A `participant id` or `actor id as Alias` line. */
|
|
337
|
+
function participantLabel(line: string): string | undefined {
|
|
338
|
+
const columns = line.trim().split(/\s+/);
|
|
339
|
+
if (columns[0] !== "participant" && columns[0] !== "actor") return undefined;
|
|
340
|
+
if (columns.length === 2) return columns[1];
|
|
341
|
+
if (columns[2] !== "as" || columns.length < 4) return undefined;
|
|
342
|
+
return columns.slice(3).join(" ");
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function genericLabels(lines: string[]): string[] {
|
|
346
|
+
const labels: string[] = [];
|
|
347
|
+
pushUnique(labels, titleLine(lines));
|
|
348
|
+
if (labels.length === 0) {
|
|
349
|
+
for (const line of lines.slice(1)) addNodeLabels(line, labels);
|
|
350
|
+
}
|
|
351
|
+
return labels;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Best-effort diagram type + first labels for naming, e.g. `flowchart` +
|
|
356
|
+
* `["VPC", "API Gateway"]`. Never throws on malformed input.
|
|
357
|
+
*/
|
|
358
|
+
export function deriveDiagramLabels(source: string): {
|
|
359
|
+
labels: string[];
|
|
360
|
+
type: string;
|
|
361
|
+
} {
|
|
362
|
+
const body = stripDirectivesAndComments(splitFrontmatter(source).body).trim();
|
|
363
|
+
const lines = body.split("\n");
|
|
364
|
+
const firstLine = lines[0] ?? "";
|
|
365
|
+
const keyword = /^[A-Za-z0-9-]+/.exec(firstLine.trim())?.[0] ?? "";
|
|
366
|
+
const type =
|
|
367
|
+
DIAGRAM_TYPE_NAMES[keyword.toLowerCase()] ?? slugifyDiagramName(keyword);
|
|
368
|
+
|
|
369
|
+
let labels: string[] = [];
|
|
370
|
+
if (type === "flowchart") {
|
|
371
|
+
labels = flowchartLabels(lines);
|
|
372
|
+
} else if (type === "sequence") {
|
|
373
|
+
for (const line of lines) {
|
|
374
|
+
pushUnique(labels, participantLabel(line));
|
|
375
|
+
}
|
|
376
|
+
} else if (type === "class") {
|
|
377
|
+
for (const match of body.matchAll(/^\s*class\s+([\w.-]+)/gm)) {
|
|
378
|
+
pushUnique(labels, match[1]);
|
|
379
|
+
}
|
|
380
|
+
} else if (type === "er") {
|
|
381
|
+
const relation =
|
|
382
|
+
/^\s*([A-Za-z_][\w-]*)\s+[|}][|o](?:--|\.\.)[o|][|{]\s+([A-Za-z_][\w-]*)/m.exec(
|
|
383
|
+
body,
|
|
384
|
+
);
|
|
385
|
+
pushUnique(labels, relation?.[1]);
|
|
386
|
+
pushUnique(labels, relation?.[2]);
|
|
387
|
+
} else if (type) {
|
|
388
|
+
labels = genericLabels(lines);
|
|
389
|
+
}
|
|
390
|
+
return { labels: labels.slice(0, 2), type };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export interface ResolveDiagramSlugInput {
|
|
394
|
+
/** Raw fence metastring (`title="..."`), possibly undefined/empty. */
|
|
395
|
+
meta?: string | null;
|
|
396
|
+
/** Diagram source (may include frontmatter). */
|
|
397
|
+
source: string;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Filename stem for a diagram. Order: fence `title="..."`, diagram frontmatter
|
|
402
|
+
* `title:`, diagram type + first subgraph/node labels, then `diagram`.
|
|
403
|
+
*/
|
|
404
|
+
export function resolveDiagramSlug({
|
|
405
|
+
meta,
|
|
406
|
+
source,
|
|
407
|
+
}: ResolveDiagramSlugInput): string {
|
|
408
|
+
const fromMeta = slugifyDiagramName(parseFenceTitle(meta) ?? "");
|
|
409
|
+
if (fromMeta) return fromMeta;
|
|
410
|
+
|
|
411
|
+
const fromFrontmatter = slugifyDiagramName(
|
|
412
|
+
parseFrontmatterTitle(source) ?? "",
|
|
413
|
+
);
|
|
414
|
+
if (fromFrontmatter) return fromFrontmatter;
|
|
415
|
+
|
|
416
|
+
const { labels, type } = deriveDiagramLabels(source);
|
|
417
|
+
const derived = slugifyDiagramName(
|
|
418
|
+
[type, ...labels].filter(Boolean).join(" "),
|
|
419
|
+
MAX_DERIVED_SLUG_LENGTH,
|
|
420
|
+
);
|
|
421
|
+
return derived || DEFAULT_DIAGRAM_NAME;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export type DiagramFileExtension = "mmd" | "png";
|
|
425
|
+
|
|
426
|
+
export function diagramFileName(
|
|
427
|
+
slug: string,
|
|
428
|
+
extension: DiagramFileExtension,
|
|
429
|
+
): string {
|
|
430
|
+
return `${slug || DEFAULT_DIAGRAM_NAME}.${extension}`;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** Source text as copied / saved to `.mmd`: trailing whitespace collapsed to one newline. */
|
|
434
|
+
export function normalizeDiagramSource(source: string): string {
|
|
435
|
+
return `${source.trimEnd()}\n`;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ---------------------------------------------------------------------------
|
|
439
|
+
// Color parsing / conversion
|
|
440
|
+
// ---------------------------------------------------------------------------
|
|
441
|
+
|
|
442
|
+
/** sRGB channels in 0-255 (may be fractional) plus alpha in 0-1. */
|
|
443
|
+
export interface RgbaColor {
|
|
444
|
+
a: number;
|
|
445
|
+
b: number;
|
|
446
|
+
g: number;
|
|
447
|
+
r: number;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function clamp(value: number, min: number, max: number): number {
|
|
451
|
+
return Math.min(max, Math.max(min, value));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function parseAlpha(token: string | undefined): number {
|
|
455
|
+
const trimmed = token?.trim();
|
|
456
|
+
if (!trimmed || trimmed === "none") return 1;
|
|
457
|
+
const value = trimmed.endsWith("%")
|
|
458
|
+
? Number.parseFloat(trimmed) / 100
|
|
459
|
+
: Number.parseFloat(trimmed);
|
|
460
|
+
return Number.isFinite(value) ? clamp(value, 0, 1) : 1;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function parseChannel(token: string, percentScale: number): number | null {
|
|
464
|
+
if (token === "none") return 0;
|
|
465
|
+
const value = Number.parseFloat(token);
|
|
466
|
+
if (!Number.isFinite(value)) return null;
|
|
467
|
+
return token.endsWith("%") ? (value / 100) * percentScale : value;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function parseHue(token: string): number | null {
|
|
471
|
+
if (token === "none") return 0;
|
|
472
|
+
const value = Number.parseFloat(token);
|
|
473
|
+
if (!Number.isFinite(value)) return null;
|
|
474
|
+
if (token.endsWith("turn")) return value * 360;
|
|
475
|
+
if (token.endsWith("grad")) return value * 0.9;
|
|
476
|
+
if (token.endsWith("rad")) return (value * 180) / Math.PI;
|
|
477
|
+
return value;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function encodeSrgb(linear: number): number {
|
|
481
|
+
const value = clamp(linear, 0, 1);
|
|
482
|
+
const encoded =
|
|
483
|
+
value <= 0.0031308 ? 12.92 * value : 1.055 * value ** (1 / 2.4) - 0.055;
|
|
484
|
+
return clamp(encoded, 0, 1) * 255;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function oklabToRgb(
|
|
488
|
+
lightness: number,
|
|
489
|
+
a: number,
|
|
490
|
+
b: number,
|
|
491
|
+
): [number, number, number] {
|
|
492
|
+
const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
493
|
+
const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
494
|
+
const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
495
|
+
return [
|
|
496
|
+
encodeSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
|
|
497
|
+
encodeSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
|
|
498
|
+
encodeSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
|
|
499
|
+
];
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function parseHex(value: string): RgbaColor | null {
|
|
503
|
+
const match = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.exec(value);
|
|
504
|
+
if (!match) return null;
|
|
505
|
+
let hex = match[1] ?? "";
|
|
506
|
+
if (hex.length <= 4) hex = [...hex].map((char) => char + char).join("");
|
|
507
|
+
const channel = (offset: number) =>
|
|
508
|
+
Number.parseInt(hex.slice(offset, offset + 2), 16);
|
|
509
|
+
return {
|
|
510
|
+
a: hex.length === 8 ? channel(6) / 255 : 1,
|
|
511
|
+
b: channel(4),
|
|
512
|
+
g: channel(2),
|
|
513
|
+
r: channel(0),
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function splitFunctionArgs(inner: string): {
|
|
518
|
+
alpha: string | undefined;
|
|
519
|
+
tokens: string[];
|
|
520
|
+
} {
|
|
521
|
+
const [main = "", alpha] = inner.replace(/,/g, " ").split("/");
|
|
522
|
+
return { alpha, tokens: main.trim().split(/\s+/).filter(Boolean) };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function parseRgbFunction(tokens: string[], a: number): RgbaColor | null {
|
|
526
|
+
if (tokens.length < 3) return null;
|
|
527
|
+
const channels = tokens.slice(0, 3).map((token) => parseChannel(token, 255));
|
|
528
|
+
const [r, g, b] = channels;
|
|
529
|
+
if (r === null || g === null || b === null) return null;
|
|
530
|
+
if (r === undefined || g === undefined || b === undefined) return null;
|
|
531
|
+
return {
|
|
532
|
+
a,
|
|
533
|
+
b: clamp(b, 0, 255),
|
|
534
|
+
g: clamp(g, 0, 255),
|
|
535
|
+
r: clamp(r, 0, 255),
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function parseOklabFamily(
|
|
540
|
+
name: "oklab" | "oklch",
|
|
541
|
+
tokens: string[],
|
|
542
|
+
a: number,
|
|
543
|
+
): RgbaColor | null {
|
|
544
|
+
if (tokens.length < 3) return null;
|
|
545
|
+
const lightness = parseChannel(tokens[0] ?? "", 1);
|
|
546
|
+
if (lightness === null) return null;
|
|
547
|
+
let opponentA: number | null;
|
|
548
|
+
let opponentB: number | null;
|
|
549
|
+
if (name === "oklch") {
|
|
550
|
+
const chroma = parseChannel(tokens[1] ?? "", 0.4);
|
|
551
|
+
const hue = parseHue(tokens[2] ?? "");
|
|
552
|
+
if (chroma === null || hue === null) return null;
|
|
553
|
+
const radians = (hue * Math.PI) / 180;
|
|
554
|
+
opponentA = chroma * Math.cos(radians);
|
|
555
|
+
opponentB = chroma * Math.sin(radians);
|
|
556
|
+
} else {
|
|
557
|
+
opponentA = parseChannel(tokens[1] ?? "", 0.4);
|
|
558
|
+
opponentB = parseChannel(tokens[2] ?? "", 0.4);
|
|
559
|
+
}
|
|
560
|
+
if (opponentA === null || opponentB === null) return null;
|
|
561
|
+
const [r, g, b] = oklabToRgb(clamp(lightness, 0, 1), opponentA, opponentB);
|
|
562
|
+
return { a, b, g, r };
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function parseColorSrgb(tokens: string[], a: number): RgbaColor | null {
|
|
566
|
+
if ((tokens[0] ?? "").toLowerCase() !== "srgb") return null;
|
|
567
|
+
const channels = tokens.slice(1, 4).map((token) => parseChannel(token, 1));
|
|
568
|
+
const [r, g, b] = channels;
|
|
569
|
+
if (r == null || g == null || b == null) return null;
|
|
570
|
+
return {
|
|
571
|
+
a,
|
|
572
|
+
b: clamp(b, 0, 1) * 255,
|
|
573
|
+
g: clamp(g, 0, 1) * 255,
|
|
574
|
+
r: clamp(r, 0, 1) * 255,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Parses the color syntaxes `getComputedStyle` and our tokens produce:
|
|
580
|
+
* `#rgb[a]`/`#rrggbb[aa]`, `rgb()/rgba()`, `oklch()`, `oklab()` and
|
|
581
|
+
* `color(srgb ...)`. Returns `null` for anything else so callers can fall back
|
|
582
|
+
* to a canvas-based conversion or a palette default.
|
|
583
|
+
*/
|
|
584
|
+
export function parseCssColor(input: string): RgbaColor | null {
|
|
585
|
+
const value = input.trim();
|
|
586
|
+
if (!value) return null;
|
|
587
|
+
const hex = parseHex(value);
|
|
588
|
+
if (hex) return hex;
|
|
589
|
+
|
|
590
|
+
const fn = /^([a-z-]+)\(([^)]*)\)$/i.exec(value);
|
|
591
|
+
if (!fn) return null;
|
|
592
|
+
const name = (fn[1] ?? "").toLowerCase();
|
|
593
|
+
const { alpha, tokens } = splitFunctionArgs(fn[2] ?? "");
|
|
594
|
+
const a = parseAlpha(alpha);
|
|
595
|
+
|
|
596
|
+
if (name === "rgb" || name === "rgba") {
|
|
597
|
+
// Legacy comma syntax carries alpha as a 4th positional argument.
|
|
598
|
+
const legacyAlpha = alpha === undefined ? tokens[3] : undefined;
|
|
599
|
+
return parseRgbFunction(tokens, legacyAlpha ? parseAlpha(legacyAlpha) : a);
|
|
600
|
+
}
|
|
601
|
+
if (name === "oklch" || name === "oklab") {
|
|
602
|
+
return parseOklabFamily(name, tokens, a);
|
|
603
|
+
}
|
|
604
|
+
if (name === "color") return parseColorSrgb(tokens, a);
|
|
605
|
+
return null;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function toChannelHex(value: number): string {
|
|
609
|
+
return Math.round(clamp(value, 0, 255))
|
|
610
|
+
.toString(16)
|
|
611
|
+
.padStart(2, "0");
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
export function rgbToHex(color: Pick<RgbaColor, "b" | "g" | "r">): string {
|
|
615
|
+
return `#${toChannelHex(color.r)}${toChannelHex(color.g)}${toChannelHex(color.b)}`;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** Any supported CSS color to `#rrggbb`, or `null` when unparseable. */
|
|
619
|
+
export function cssColorToHex(input: string): string | null {
|
|
620
|
+
const parsed = parseCssColor(input);
|
|
621
|
+
return parsed ? rgbToHex(parsed) : null;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Mixes `top` over `base` by `amount` (0 = base, 1 = top) in sRGB. Falls back
|
|
626
|
+
* to `base` when either color is unparseable.
|
|
627
|
+
*/
|
|
628
|
+
export function mixColors(base: string, top: string, amount: number): string {
|
|
629
|
+
const a = parseCssColor(base);
|
|
630
|
+
const b = parseCssColor(top);
|
|
631
|
+
if (!a) return base;
|
|
632
|
+
if (!b) return rgbToHex(a);
|
|
633
|
+
const t = clamp(amount, 0, 1);
|
|
634
|
+
return rgbToHex({
|
|
635
|
+
b: a.b + (b.b - a.b) * t,
|
|
636
|
+
g: a.g + (b.g - a.g) * t,
|
|
637
|
+
r: a.r + (b.r - a.r) * t,
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// ---------------------------------------------------------------------------
|
|
642
|
+
// Mermaid theme
|
|
643
|
+
// ---------------------------------------------------------------------------
|
|
644
|
+
|
|
645
|
+
export type MermaidColorMode = "dark" | "light";
|
|
646
|
+
|
|
647
|
+
/** Resolved Cline design tokens the diagram theme is derived from. */
|
|
648
|
+
export interface MermaidThemeTokens {
|
|
649
|
+
/** Diagram surface (`--card`); also the PNG background fill. */
|
|
650
|
+
background: string;
|
|
651
|
+
border: string;
|
|
652
|
+
/** Destructive/error role color (`--destructive`). */
|
|
653
|
+
error: string;
|
|
654
|
+
foreground: string;
|
|
655
|
+
muted: string;
|
|
656
|
+
mutedForeground: string;
|
|
657
|
+
/** Accent (`--primary`); follows the user's accent palette. */
|
|
658
|
+
primary: string;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Palette values from `theme/palette.css`, used when tokens can't be read. */
|
|
662
|
+
export const FALLBACK_MERMAID_TOKENS: Record<
|
|
663
|
+
MermaidColorMode,
|
|
664
|
+
MermaidThemeTokens
|
|
665
|
+
> = {
|
|
666
|
+
dark: {
|
|
667
|
+
background: "#18191b",
|
|
668
|
+
border: "#2f2f37",
|
|
669
|
+
error: "#e54666",
|
|
670
|
+
foreground: "#fcfcfd",
|
|
671
|
+
muted: "#212225",
|
|
672
|
+
mutedForeground: "#b0b4ba",
|
|
673
|
+
primary: "#6e56cf",
|
|
674
|
+
},
|
|
675
|
+
light: {
|
|
676
|
+
background: "#f9f9fb",
|
|
677
|
+
border: "#e8e8ec",
|
|
678
|
+
error: "#e54666",
|
|
679
|
+
foreground: "#1c2024",
|
|
680
|
+
muted: "#f0f0f3",
|
|
681
|
+
mutedForeground: "#60646c",
|
|
682
|
+
primary: "#6e56cf",
|
|
683
|
+
},
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
/** Inter-first, matching `--font-sans`; never monospace. */
|
|
687
|
+
export const MERMAID_FONT_FAMILY =
|
|
688
|
+
"'Inter Variable', Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
|
|
689
|
+
export const MERMAID_FONT_SIZE = "14px";
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Font stack for a raw `--font-sans` value (`"Inter Variable", sans-serif`).
|
|
693
|
+
* Double quotes become single quotes so the stack survives Mermaid's inline
|
|
694
|
+
* `style="..."` attributes, and the Inter-first system stack is appended so
|
|
695
|
+
* text still measures sensibly before the web font loads. An empty or
|
|
696
|
+
* monospace value falls back to `MERMAID_FONT_FAMILY`.
|
|
697
|
+
*/
|
|
698
|
+
export function resolveMermaidFontFamily(
|
|
699
|
+
cssFontValue: string | null | undefined,
|
|
700
|
+
): string {
|
|
701
|
+
const value = cssFontValue?.trim().replace(/"/g, "'") ?? "";
|
|
702
|
+
if (!value || /\bmonospace\b/i.test(value)) return MERMAID_FONT_FAMILY;
|
|
703
|
+
return `${value}, ${MERMAID_FONT_FAMILY}`;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export type MermaidThemeVariables = Record<string, string | boolean>;
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Resolves a CSS color (`oklch(...)`, `var(--x)`, named, ...) to `#rrggbb`, or
|
|
710
|
+
* returns null when it can't. Hosts with a DOM can pass a canvas/computed-style
|
|
711
|
+
* backed resolver; tests can pass a stub. Consulted before the built-in parser.
|
|
712
|
+
*/
|
|
713
|
+
export type MermaidColorResolver = (cssValue: string) => string | null;
|
|
714
|
+
|
|
715
|
+
export interface MermaidThemeOptions {
|
|
716
|
+
/** Overrides the UI font stack; defaults to `MERMAID_FONT_FAMILY`. */
|
|
717
|
+
fontFamily?: string;
|
|
718
|
+
/** Optional host resolver for colors the pure parser can't read. */
|
|
719
|
+
resolveColor?: MermaidColorResolver;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function hexOr(
|
|
723
|
+
value: string,
|
|
724
|
+
fallback: string,
|
|
725
|
+
resolveColor: MermaidColorResolver | undefined,
|
|
726
|
+
): string {
|
|
727
|
+
const resolved = resolveColor?.(value);
|
|
728
|
+
const hex = resolved ? cssColorToHex(resolved) : null;
|
|
729
|
+
return hex ?? cssColorToHex(value) ?? fallback;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** Normalizes every token to `#rrggbb`, substituting palette fallbacks. */
|
|
733
|
+
export function normalizeMermaidTokens(
|
|
734
|
+
tokens: MermaidThemeTokens,
|
|
735
|
+
mode: MermaidColorMode,
|
|
736
|
+
resolveColor?: MermaidColorResolver,
|
|
737
|
+
): MermaidThemeTokens {
|
|
738
|
+
const fallback = FALLBACK_MERMAID_TOKENS[mode];
|
|
739
|
+
return {
|
|
740
|
+
background: hexOr(tokens.background, fallback.background, resolveColor),
|
|
741
|
+
border: hexOr(tokens.border, fallback.border, resolveColor),
|
|
742
|
+
error: hexOr(tokens.error, fallback.error, resolveColor),
|
|
743
|
+
foreground: hexOr(tokens.foreground, fallback.foreground, resolveColor),
|
|
744
|
+
muted: hexOr(tokens.muted, fallback.muted, resolveColor),
|
|
745
|
+
mutedForeground: hexOr(
|
|
746
|
+
tokens.mutedForeground,
|
|
747
|
+
fallback.mutedForeground,
|
|
748
|
+
resolveColor,
|
|
749
|
+
),
|
|
750
|
+
primary: hexOr(tokens.primary, fallback.primary, resolveColor),
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Mermaid `base`-theme variables from concrete sRGB colors. Mermaid derives the
|
|
756
|
+
* rest (git/pie/state colors, ...) from these. Concrete hex is required:
|
|
757
|
+
* Mermaid tints colors with khroma, and the exported SVG is rasterized in an
|
|
758
|
+
* `<img>` that can't resolve `var(--x)`.
|
|
759
|
+
*/
|
|
760
|
+
export function buildMermaidThemeVariables(
|
|
761
|
+
tokens: MermaidThemeTokens,
|
|
762
|
+
mode: MermaidColorMode,
|
|
763
|
+
{ fontFamily = MERMAID_FONT_FAMILY, resolveColor }: MermaidThemeOptions = {},
|
|
764
|
+
): MermaidThemeVariables {
|
|
765
|
+
const t = normalizeMermaidTokens(tokens, mode, resolveColor);
|
|
766
|
+
const dark = mode === "dark";
|
|
767
|
+
const nodeFill = mixColors(t.background, t.primary, dark ? 0.18 : 0.1);
|
|
768
|
+
const nodeBorder = mixColors(t.background, t.primary, dark ? 0.6 : 0.5);
|
|
769
|
+
const neutralFill = mixColors(t.background, t.foreground, dark ? 0.08 : 0.05);
|
|
770
|
+
const clusterFill = mixColors(t.background, t.foreground, dark ? 0.05 : 0.03);
|
|
771
|
+
const tertiaryFill = mixColors(t.background, t.primary, dark ? 0.07 : 0.04);
|
|
772
|
+
const errorFill = mixColors(t.background, t.error, dark ? 0.2 : 0.12);
|
|
773
|
+
|
|
774
|
+
return {
|
|
775
|
+
activationBkgColor: neutralFill,
|
|
776
|
+
activationBorderColor: t.border,
|
|
777
|
+
actorBkg: nodeFill,
|
|
778
|
+
actorBorder: nodeBorder,
|
|
779
|
+
actorLineColor: t.mutedForeground,
|
|
780
|
+
actorTextColor: t.foreground,
|
|
781
|
+
background: t.background,
|
|
782
|
+
clusterBkg: clusterFill,
|
|
783
|
+
clusterBorder: t.border,
|
|
784
|
+
darkMode: dark,
|
|
785
|
+
edgeLabelBackground: t.background,
|
|
786
|
+
errorBkgColor: errorFill,
|
|
787
|
+
errorTextColor: t.error,
|
|
788
|
+
fontFamily,
|
|
789
|
+
fontSize: MERMAID_FONT_SIZE,
|
|
790
|
+
labelBoxBkgColor: neutralFill,
|
|
791
|
+
labelBoxBorderColor: t.border,
|
|
792
|
+
labelTextColor: t.foreground,
|
|
793
|
+
lineColor: t.mutedForeground,
|
|
794
|
+
loopTextColor: t.foreground,
|
|
795
|
+
mainBkg: nodeFill,
|
|
796
|
+
nodeBorder,
|
|
797
|
+
noteBkgColor: t.muted,
|
|
798
|
+
noteBorderColor: t.border,
|
|
799
|
+
noteTextColor: t.foreground,
|
|
800
|
+
primaryBorderColor: nodeBorder,
|
|
801
|
+
primaryColor: nodeFill,
|
|
802
|
+
primaryTextColor: t.foreground,
|
|
803
|
+
secondaryBorderColor: t.border,
|
|
804
|
+
secondaryColor: neutralFill,
|
|
805
|
+
secondaryTextColor: t.foreground,
|
|
806
|
+
sequenceNumberColor: t.background,
|
|
807
|
+
signalColor: t.mutedForeground,
|
|
808
|
+
signalTextColor: t.foreground,
|
|
809
|
+
tertiaryBorderColor: t.border,
|
|
810
|
+
tertiaryColor: tertiaryFill,
|
|
811
|
+
tertiaryTextColor: t.foreground,
|
|
812
|
+
textColor: t.foreground,
|
|
813
|
+
titleColor: t.foreground,
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* Site-level Mermaid config for the Cline theme. User `%%{init}%%`, frontmatter
|
|
819
|
+
* `config:`, `classDef` and `style` layer on top of this inside Mermaid, so
|
|
820
|
+
* nothing here is forced per node. `htmlLabels: false` keeps labels as SVG
|
|
821
|
+
* `<text>` instead of `<foreignObject>`, which taints canvases in WebKit and
|
|
822
|
+
* would make PNG export fail in the Tauri webview.
|
|
823
|
+
*/
|
|
824
|
+
export function buildMermaidConfig(
|
|
825
|
+
tokens: MermaidThemeTokens,
|
|
826
|
+
mode: MermaidColorMode,
|
|
827
|
+
options: MermaidThemeOptions = {},
|
|
828
|
+
): MermaidConfig {
|
|
829
|
+
return {
|
|
830
|
+
fontFamily: options.fontFamily ?? MERMAID_FONT_FAMILY,
|
|
831
|
+
htmlLabels: false,
|
|
832
|
+
securityLevel: "strict",
|
|
833
|
+
startOnLoad: false,
|
|
834
|
+
suppressErrorRendering: true,
|
|
835
|
+
theme: "base",
|
|
836
|
+
themeVariables: buildMermaidThemeVariables(tokens, mode, options),
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/** Base-theme defaults from the palette, for hosts with no DOM to sample. */
|
|
841
|
+
export function createDefaultMermaidConfig(
|
|
842
|
+
mode: MermaidColorMode = "light",
|
|
843
|
+
): MermaidConfig {
|
|
844
|
+
return buildMermaidConfig(FALLBACK_MERMAID_TOKENS[mode], mode);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// ---------------------------------------------------------------------------
|
|
848
|
+
// Zoom
|
|
849
|
+
// ---------------------------------------------------------------------------
|
|
850
|
+
|
|
851
|
+
export const MIN_DIAGRAM_ZOOM = 0.25;
|
|
852
|
+
export const MAX_DIAGRAM_ZOOM = 4;
|
|
853
|
+
export const DIAGRAM_ZOOM_STEP = 1.25;
|
|
854
|
+
|
|
855
|
+
export function clampDiagramZoom(scale: number): number {
|
|
856
|
+
if (!Number.isFinite(scale)) return 1;
|
|
857
|
+
return clamp(scale, MIN_DIAGRAM_ZOOM, MAX_DIAGRAM_ZOOM);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
export function stepDiagramZoom(
|
|
861
|
+
scale: number,
|
|
862
|
+
direction: "in" | "out",
|
|
863
|
+
): number {
|
|
864
|
+
const next =
|
|
865
|
+
direction === "in" ? scale * DIAGRAM_ZOOM_STEP : scale / DIAGRAM_ZOOM_STEP;
|
|
866
|
+
// Round so repeated in/out returns to 1 instead of drifting.
|
|
867
|
+
return clampDiagramZoom(Math.round(next * 1000) / 1000);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
export interface DiagramView {
|
|
871
|
+
scale: number;
|
|
872
|
+
x: number;
|
|
873
|
+
y: number;
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
export const INITIAL_DIAGRAM_VIEW: DiagramView = { scale: 1, x: 0, y: 0 };
|
|
877
|
+
|
|
878
|
+
/**
|
|
879
|
+
* Zooms to `nextScale` keeping the content under `point` (viewport-relative)
|
|
880
|
+
* fixed, for a `translate(x, y) scale(s)` transform with a top-left origin.
|
|
881
|
+
*/
|
|
882
|
+
export function zoomViewAtPoint(
|
|
883
|
+
view: DiagramView,
|
|
884
|
+
nextScale: number,
|
|
885
|
+
point: { x: number; y: number },
|
|
886
|
+
): DiagramView {
|
|
887
|
+
const scale = clampDiagramZoom(nextScale);
|
|
888
|
+
const ratio = scale / view.scale;
|
|
889
|
+
return {
|
|
890
|
+
scale,
|
|
891
|
+
x: point.x - (point.x - view.x) * ratio,
|
|
892
|
+
y: point.y - (point.y - view.y) * ratio,
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/** Exponential wheel zoom; `deltaY` is clamped so a notched wheel isn't jumpy. */
|
|
897
|
+
export function wheelZoomScale(scale: number, deltaY: number): number {
|
|
898
|
+
return scale * Math.exp(-clamp(deltaY, -100, 100) * 0.0025);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// ---------------------------------------------------------------------------
|
|
902
|
+
// PNG export
|
|
903
|
+
// ---------------------------------------------------------------------------
|
|
904
|
+
|
|
905
|
+
/** Longest allowed PNG edge; keeps encoded output well under ~5 MiB. */
|
|
906
|
+
export const PNG_MAX_EDGE = 4096;
|
|
907
|
+
/** Crisp-but-modest baseline; Streamdown's fixed 5x is needlessly large. */
|
|
908
|
+
export const PNG_BASE_SCALE = 2;
|
|
909
|
+
export const PNG_MAX_DESIRED_SCALE = 3;
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* Preferred export scale for a display: at least `PNG_BASE_SCALE`, following
|
|
913
|
+
* the device pixel ratio up to `PNG_MAX_DESIRED_SCALE`. Non-finite or missing
|
|
914
|
+
* ratios (SSR, odd embeds) yield the base scale.
|
|
915
|
+
*/
|
|
916
|
+
export function resolvePngDesiredScale(
|
|
917
|
+
devicePixelRatio?: number | null,
|
|
918
|
+
): number {
|
|
919
|
+
const ratio =
|
|
920
|
+
typeof devicePixelRatio === "number" && Number.isFinite(devicePixelRatio)
|
|
921
|
+
? Math.ceil(devicePixelRatio)
|
|
922
|
+
: PNG_BASE_SCALE;
|
|
923
|
+
return clamp(ratio, PNG_BASE_SCALE, PNG_MAX_DESIRED_SCALE);
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* Attached images are validated on their base64 length, capped at 5 MiB
|
|
927
|
+
* (`DEFAULT_MAX_IMAGE_ENCODED_BYTES` in `@cerebriline/shared`'s `llms/media.ts`).
|
|
928
|
+
*/
|
|
929
|
+
export const PNG_MAX_ENCODED_BYTES = 5 * 1024 * 1024;
|
|
930
|
+
/** Each retry re-encodes at this fraction of the previous scale. */
|
|
931
|
+
export const PNG_RETRY_SCALE_FACTOR = 0.7;
|
|
932
|
+
export const PNG_MAX_ATTEMPTS = 4;
|
|
933
|
+
const FALLBACK_SVG_SIZE = { height: 600, width: 800 };
|
|
934
|
+
|
|
935
|
+
/** Whether a PNG of `byteLength` bytes stays attachable once base64-encoded. */
|
|
936
|
+
export function pngFitsAttachmentLimit(byteLength: number): boolean {
|
|
937
|
+
return 4 * Math.ceil(byteLength / 3) <= PNG_MAX_ENCODED_BYTES;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
export interface PngExportSize {
|
|
941
|
+
height: number;
|
|
942
|
+
scale: number;
|
|
943
|
+
width: number;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* `scale = min(desiredScale, maxEdge / longestEdge)`. Small diagrams get the
|
|
948
|
+
* desired (crisp) scale; larger ones are scaled down so the longest edge never
|
|
949
|
+
* exceeds `maxEdge`, which is what keeps the encoded PNG attachable. A diagram
|
|
950
|
+
* whose natural size already passes the cap is therefore shrunk (scale < 1)
|
|
951
|
+
* rather than exported oversize. Non-finite or non-positive dimensions are
|
|
952
|
+
* treated as 1px so the result is always a finite, positive number.
|
|
953
|
+
*/
|
|
954
|
+
export function computeExportScale(
|
|
955
|
+
size: { height: number; width: number },
|
|
956
|
+
desiredScale: number = PNG_BASE_SCALE,
|
|
957
|
+
maxEdge: number = PNG_MAX_EDGE,
|
|
958
|
+
): number {
|
|
959
|
+
const width = Number.isFinite(size.width) && size.width > 0 ? size.width : 1;
|
|
960
|
+
const height =
|
|
961
|
+
Number.isFinite(size.height) && size.height > 0 ? size.height : 1;
|
|
962
|
+
return Math.min(desiredScale, maxEdge / Math.max(width, height));
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** Canvas dimensions for `computeExportScale`, rounded to whole pixels. */
|
|
966
|
+
export function computePngExportSize(
|
|
967
|
+
size: { height: number; width: number },
|
|
968
|
+
desiredScale: number = PNG_BASE_SCALE,
|
|
969
|
+
maxEdge: number = PNG_MAX_EDGE,
|
|
970
|
+
): PngExportSize {
|
|
971
|
+
const width = Number.isFinite(size.width) && size.width > 0 ? size.width : 1;
|
|
972
|
+
const height =
|
|
973
|
+
Number.isFinite(size.height) && size.height > 0 ? size.height : 1;
|
|
974
|
+
const scale = computeExportScale(size, desiredScale, maxEdge);
|
|
975
|
+
return {
|
|
976
|
+
height: Math.max(1, Math.round(height * scale)),
|
|
977
|
+
scale,
|
|
978
|
+
width: Math.max(1, Math.round(width * scale)),
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/**
|
|
983
|
+
* Encodes at the desired scale and, while the result is too large to attach
|
|
984
|
+
* (see `pngFitsAttachmentLimit`), retries at `PNG_RETRY_SCALE_FACTOR` of the
|
|
985
|
+
* previous scale. Retries stop at scale 1 (or earlier if the edge cap already
|
|
986
|
+
* forced a smaller scale), after `PNG_MAX_ATTEMPTS`, or when a retry would not
|
|
987
|
+
* shrink the image. The smallest attempt is returned even if it is still
|
|
988
|
+
* oversize: it is still a valid PNG for a plain file download.
|
|
989
|
+
*/
|
|
990
|
+
export async function encodePngWithinLimit<T extends { size: number }>(
|
|
991
|
+
natural: { height: number; width: number },
|
|
992
|
+
encode: (size: PngExportSize) => Promise<T>,
|
|
993
|
+
initialScale: number = PNG_BASE_SCALE,
|
|
994
|
+
): Promise<T> {
|
|
995
|
+
let desired = initialScale;
|
|
996
|
+
let previousScale = Number.POSITIVE_INFINITY;
|
|
997
|
+
let result: T | undefined;
|
|
998
|
+
for (let attempt = 0; attempt < PNG_MAX_ATTEMPTS; attempt += 1) {
|
|
999
|
+
const size = computePngExportSize(natural, desired);
|
|
1000
|
+
if (result && size.scale >= previousScale) break;
|
|
1001
|
+
result = await encode(size);
|
|
1002
|
+
if (pngFitsAttachmentLimit(result.size)) return result;
|
|
1003
|
+
previousScale = size.scale;
|
|
1004
|
+
// The last attempt always drops to the 1x floor, so a geometric decay that
|
|
1005
|
+
// never quite reaches it can't leave a smaller export untried.
|
|
1006
|
+
desired =
|
|
1007
|
+
attempt + 2 >= PNG_MAX_ATTEMPTS
|
|
1008
|
+
? 1
|
|
1009
|
+
: Math.max(1, size.scale * PNG_RETRY_SCALE_FACTOR);
|
|
1010
|
+
}
|
|
1011
|
+
if (!result) throw new Error("Failed to encode PNG");
|
|
1012
|
+
return result;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
export interface PreparedSvg {
|
|
1016
|
+
height: number;
|
|
1017
|
+
svg: string;
|
|
1018
|
+
width: number;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
function readAttribute(tag: string, name: string): string | undefined {
|
|
1022
|
+
return new RegExp(`\\s${name}\\s*=\\s*"([^"]*)"`, "i").exec(tag)?.[1];
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
function setAttribute(tag: string, name: string, value: string): string {
|
|
1026
|
+
const pattern = new RegExp(`(\\s${name}\\s*=\\s*)"[^"]*"`, "i");
|
|
1027
|
+
if (pattern.test(tag)) return tag.replace(pattern, `$1"${value}"`);
|
|
1028
|
+
return tag.replace(/^<svg/i, `<svg ${name}="${value}"`);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
function parseLength(value: string | undefined): number | undefined {
|
|
1032
|
+
if (!value || value.includes("%")) return undefined;
|
|
1033
|
+
const parsed = Number.parseFloat(value);
|
|
1034
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
function viewBoxSize(
|
|
1038
|
+
tag: string,
|
|
1039
|
+
): { height: number; width: number } | undefined {
|
|
1040
|
+
const parts = readAttribute(tag, "viewBox")
|
|
1041
|
+
?.trim()
|
|
1042
|
+
.split(/[\s,]+/)
|
|
1043
|
+
.map(Number.parseFloat);
|
|
1044
|
+
const width = parts?.[2];
|
|
1045
|
+
const height = parts?.[3];
|
|
1046
|
+
if (width && height && width > 0 && height > 0) return { height, width };
|
|
1047
|
+
return undefined;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* Makes Mermaid's SVG safe to load as a standalone image. Mermaid emits
|
|
1052
|
+
* `width="100%"` (no intrinsic size for `<img>`/canvas), so the root gets the
|
|
1053
|
+
* viewBox size; HTML-only entities/void tags are made XML-valid.
|
|
1054
|
+
*/
|
|
1055
|
+
export function prepareSvgForRaster(svg: string): PreparedSvg {
|
|
1056
|
+
const tagMatch = /<svg\b[^>]*>/i.exec(svg);
|
|
1057
|
+
if (!tagMatch) return { ...FALLBACK_SVG_SIZE, svg };
|
|
1058
|
+
let tag = tagMatch[0];
|
|
1059
|
+
const box = viewBoxSize(tag);
|
|
1060
|
+
const width =
|
|
1061
|
+
box?.width ??
|
|
1062
|
+
parseLength(readAttribute(tag, "width")) ??
|
|
1063
|
+
FALLBACK_SVG_SIZE.width;
|
|
1064
|
+
const height =
|
|
1065
|
+
box?.height ??
|
|
1066
|
+
parseLength(readAttribute(tag, "height")) ??
|
|
1067
|
+
FALLBACK_SVG_SIZE.height;
|
|
1068
|
+
|
|
1069
|
+
tag = setAttribute(tag, "width", String(width));
|
|
1070
|
+
tag = setAttribute(tag, "height", String(height));
|
|
1071
|
+
tag = tag.replace(/\sstyle\s*=\s*"([^"]*)"/i, (attribute, value: string) =>
|
|
1072
|
+
value.toLowerCase().includes("max-width") ? "" : attribute,
|
|
1073
|
+
);
|
|
1074
|
+
if (!/\sxmlns\s*=/i.test(tag)) {
|
|
1075
|
+
tag = tag.replace(/^<svg/i, '<svg xmlns="http://www.w3.org/2000/svg"');
|
|
1076
|
+
}
|
|
1077
|
+
if (/xlink:/i.test(svg) && !/\sxmlns:xlink\s*=/i.test(tag)) {
|
|
1078
|
+
tag = tag.replace(
|
|
1079
|
+
/^<svg/i,
|
|
1080
|
+
'<svg xmlns:xlink="http://www.w3.org/1999/xlink"',
|
|
1081
|
+
);
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
const sanitized = svg
|
|
1085
|
+
.replace(tagMatch[0], tag)
|
|
1086
|
+
.replace(/ /g, " ")
|
|
1087
|
+
.replace(/<(br|hr)\s*>/gi, "<$1/>");
|
|
1088
|
+
return { height, svg: sanitized, width };
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// ---------------------------------------------------------------------------
|
|
1092
|
+
// Diagram links
|
|
1093
|
+
// ---------------------------------------------------------------------------
|
|
1094
|
+
|
|
1095
|
+
/**
|
|
1096
|
+
* Carries a diagram link's original destination once the navigable href has
|
|
1097
|
+
* been removed, so hosts can offer their own vetted way to open it.
|
|
1098
|
+
*/
|
|
1099
|
+
export const DIAGRAM_LINK_HREF_ATTRIBUTE = "data-cline-diagram-href";
|
|
1100
|
+
|
|
1101
|
+
/** Attributes that would let an anchor navigate on its own. */
|
|
1102
|
+
const NAVIGABLE_LINK_ATTRIBUTES = ["href", "xlink:href"] as const;
|
|
1103
|
+
|
|
1104
|
+
function openableHref(value: string): string | null {
|
|
1105
|
+
try {
|
|
1106
|
+
const parsed = new URL(value.trim());
|
|
1107
|
+
return parsed.protocol === "http:" || parsed.protocol === "https:"
|
|
1108
|
+
? parsed.href
|
|
1109
|
+
: null;
|
|
1110
|
+
} catch {
|
|
1111
|
+
return null;
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
function neutralizeWithDom(svg: string): string | null {
|
|
1116
|
+
if (
|
|
1117
|
+
typeof DOMParser === "undefined" ||
|
|
1118
|
+
typeof XMLSerializer === "undefined"
|
|
1119
|
+
) {
|
|
1120
|
+
return null;
|
|
1121
|
+
}
|
|
1122
|
+
try {
|
|
1123
|
+
const document = new DOMParser().parseFromString(svg, "image/svg+xml");
|
|
1124
|
+
if (document.getElementsByTagName("parsererror").length > 0) return null;
|
|
1125
|
+
|
|
1126
|
+
for (const anchor of Array.from(document.getElementsByTagName("a"))) {
|
|
1127
|
+
const destination = NAVIGABLE_LINK_ATTRIBUTES.map((attribute) =>
|
|
1128
|
+
anchor.getAttribute(attribute),
|
|
1129
|
+
).find((value): value is string => Boolean(value));
|
|
1130
|
+
|
|
1131
|
+
for (const attribute of NAVIGABLE_LINK_ATTRIBUTES) {
|
|
1132
|
+
anchor.removeAttribute(attribute);
|
|
1133
|
+
}
|
|
1134
|
+
// `target` alone cannot navigate, but leaving it invites a future
|
|
1135
|
+
// re-add of href to open in a new context without host review.
|
|
1136
|
+
anchor.removeAttribute("target");
|
|
1137
|
+
|
|
1138
|
+
const openable = destination ? openableHref(destination) : null;
|
|
1139
|
+
if (openable) anchor.setAttribute(DIAGRAM_LINK_HREF_ATTRIBUTE, openable);
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
return new XMLSerializer().serializeToString(document.documentElement);
|
|
1143
|
+
} catch {
|
|
1144
|
+
return null;
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
const ANCHOR_OPEN_TAG_PATTERN = /<a\b[^>]*>/gi;
|
|
1149
|
+
const LINK_ATTRIBUTE_PATTERN =
|
|
1150
|
+
/\s(?:xlink:href|href|target)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
1151
|
+
|
|
1152
|
+
function neutralizeWithPatterns(svg: string): string {
|
|
1153
|
+
return svg.replace(ANCHOR_OPEN_TAG_PATTERN, (openTag) => {
|
|
1154
|
+
let destination: string | null = null;
|
|
1155
|
+
const stripped = openTag.replace(
|
|
1156
|
+
LINK_ATTRIBUTE_PATTERN,
|
|
1157
|
+
(match, doubleQuoted?: string, singleQuoted?: string) => {
|
|
1158
|
+
if (!/\starget\s*=/i.test(match)) {
|
|
1159
|
+
destination ??= doubleQuoted ?? singleQuoted ?? null;
|
|
1160
|
+
}
|
|
1161
|
+
return "";
|
|
1162
|
+
},
|
|
1163
|
+
);
|
|
1164
|
+
const openable = destination ? openableHref(destination) : null;
|
|
1165
|
+
if (!openable) return stripped;
|
|
1166
|
+
return stripped.replace(
|
|
1167
|
+
/\s*\/?>$/,
|
|
1168
|
+
(tail) =>
|
|
1169
|
+
` ${DIAGRAM_LINK_HREF_ATTRIBUTE}="${openable.replace(/"/g, """)}"${tail}`,
|
|
1170
|
+
);
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Mermaid's `securityLevel: "strict"` blocks script execution and dangerous URL
|
|
1176
|
+
* schemes, but still renders `click <node> "https://…"` directives as live
|
|
1177
|
+
* `<a xlink:href>` anchors inside the SVG. Streamdown injects that SVG with
|
|
1178
|
+
* `dangerouslySetInnerHTML`, so those anchors never pass through a product's
|
|
1179
|
+
* React link component — bypassing whatever link policy the host applies to
|
|
1180
|
+
* ordinary Markdown links (confirmation prompts, external-open routing), and in
|
|
1181
|
+
* a desktop webview letting a click navigate the app away from itself.
|
|
1182
|
+
*
|
|
1183
|
+
* A diagram label is authored independently of its destination, so these links
|
|
1184
|
+
* are deceptive by construction. Strip the navigable attributes so a diagram
|
|
1185
|
+
* link cannot navigate on its own, and preserve an http(s) destination in
|
|
1186
|
+
* `DIAGRAM_LINK_HREF_ATTRIBUTE` so hosts can opt into opening it deliberately.
|
|
1187
|
+
*/
|
|
1188
|
+
export function neutralizeDiagramLinks(svg: string): string {
|
|
1189
|
+
if (!svg.includes("<a")) return svg;
|
|
1190
|
+
return neutralizeWithDom(svg) ?? neutralizeWithPatterns(svg);
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
// ---------------------------------------------------------------------------
|
|
1194
|
+
// Render service
|
|
1195
|
+
// ---------------------------------------------------------------------------
|
|
1196
|
+
|
|
1197
|
+
export interface MermaidService {
|
|
1198
|
+
/**
|
|
1199
|
+
* Renders `source` with `config`. The Mermaid module is imported on first
|
|
1200
|
+
* use (and re-attempted after a failed chunk load); `initialize` only runs
|
|
1201
|
+
* when the config object changes.
|
|
1202
|
+
*/
|
|
1203
|
+
render: (
|
|
1204
|
+
id: string,
|
|
1205
|
+
source: string,
|
|
1206
|
+
config: MermaidConfig,
|
|
1207
|
+
) => Promise<{ svg: string }>;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/**
|
|
1211
|
+
* Mermaid is a process-wide singleton whose `render` is not safe to run
|
|
1212
|
+
* concurrently (it mutates shared config and a temporary DOM container), and a
|
|
1213
|
+
* render must see the config it was requested with. `initialize` + `render`
|
|
1214
|
+
* therefore run as one queued unit, shared by every service so blocks from
|
|
1215
|
+
* different renderers never interleave. A failed render never blocks the queue.
|
|
1216
|
+
*/
|
|
1217
|
+
let renderQueue: Promise<unknown> = Promise.resolve();
|
|
1218
|
+
|
|
1219
|
+
function enqueueRender<T>(task: () => Promise<T>): Promise<T> {
|
|
1220
|
+
const run = renderQueue.then(task, task);
|
|
1221
|
+
renderQueue = run.catch(() => undefined);
|
|
1222
|
+
return run;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
// The config each Mermaid instance was last initialized with, tracked per
|
|
1226
|
+
// instance so services sharing one singleton don't skip a needed re-init.
|
|
1227
|
+
const appliedConfigs = new WeakMap<LazyMermaidInstance, MermaidConfig>();
|
|
1228
|
+
|
|
1229
|
+
export function createMermaidService(
|
|
1230
|
+
loader: MermaidModuleLoader = defaultMermaidLoader,
|
|
1231
|
+
): MermaidService {
|
|
1232
|
+
let modulePromise: Promise<MermaidModule> | undefined;
|
|
1233
|
+
const getModule = () => {
|
|
1234
|
+
modulePromise ??= loader().catch((error: unknown) => {
|
|
1235
|
+
modulePromise = undefined;
|
|
1236
|
+
throw error;
|
|
1237
|
+
});
|
|
1238
|
+
return modulePromise;
|
|
1239
|
+
};
|
|
1240
|
+
|
|
1241
|
+
return {
|
|
1242
|
+
async render(id, source, config) {
|
|
1243
|
+
const mermaid = (await getModule()).default;
|
|
1244
|
+
return enqueueRender(async () => {
|
|
1245
|
+
if (appliedConfigs.get(mermaid) !== config) {
|
|
1246
|
+
mermaid.initialize(config);
|
|
1247
|
+
appliedConfigs.set(mermaid, config);
|
|
1248
|
+
}
|
|
1249
|
+
const result = await mermaid.render(id, source);
|
|
1250
|
+
return { ...result, svg: neutralizeDiagramLinks(result.svg) };
|
|
1251
|
+
});
|
|
1252
|
+
},
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
export function describeMermaidError(error: unknown): string {
|
|
1257
|
+
if (error instanceof Error && error.message) return error.message;
|
|
1258
|
+
if (typeof error === "string" && error) return error;
|
|
1259
|
+
return "Failed to render diagram";
|
|
1260
|
+
}
|