pi-better-show 0.7.2 → 0.8.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.
- package/package.json +1 -1
- package/src/core/check.ts +8 -2
- package/src/elements/diagram-alt.ts +101 -0
- package/src/elements/display.ts +37 -2
- package/src/elements/strings.ts +29 -0
- package/src/extension/check.ts +9 -2
- package/src/extension/render.ts +2 -2
- package/src/server/index.ts +80 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/core/check.ts
CHANGED
|
@@ -22,6 +22,8 @@ export interface BlockProblem {
|
|
|
22
22
|
export interface CheckOptions {
|
|
23
23
|
/** Checks a Mermaid source and returns what is wrong with it; core carries no Mermaid parser, a host passes one. */
|
|
24
24
|
mermaid?: (source: string) => string | undefined;
|
|
25
|
+
/** Advice on a diagram that draws but will be hard to read, one sentence each; reported as warnings. */
|
|
26
|
+
mermaidNotes?: (source: string) => string[];
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
interface Shape {
|
|
@@ -318,8 +320,8 @@ export function checkBlocks(markdown: string, options: CheckOptions = {}): Block
|
|
|
318
320
|
});
|
|
319
321
|
} else if (isYamlKind(kind)) {
|
|
320
322
|
checkBody(context);
|
|
321
|
-
} else if (kind === "mermaid" && options.mermaid) {
|
|
322
|
-
const problem = options.mermaid(source);
|
|
323
|
+
} else if (kind === "mermaid" && (options.mermaid || options.mermaidNotes)) {
|
|
324
|
+
const problem = options.mermaid?.(source);
|
|
323
325
|
if (problem !== undefined) {
|
|
324
326
|
out.push({
|
|
325
327
|
kind,
|
|
@@ -328,6 +330,10 @@ export function checkBlocks(markdown: string, options: CheckOptions = {}): Block
|
|
|
328
330
|
message: `the diagram will not draw: ${problem}`,
|
|
329
331
|
severity: "error",
|
|
330
332
|
});
|
|
333
|
+
} else if (options.mermaidNotes) {
|
|
334
|
+
for (const note of options.mermaidNotes(source)) {
|
|
335
|
+
out.push({ kind, line: line + 1, path: kind, message: note, severity: "warning" });
|
|
336
|
+
}
|
|
331
337
|
}
|
|
332
338
|
}
|
|
333
339
|
if (!closed) {
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { format, type Strings } from "./strings.ts";
|
|
2
|
+
|
|
3
|
+
/** What a Mermaid diagram is and shows, in words: the image's alt text and the SVG's title and description. */
|
|
4
|
+
|
|
5
|
+
/** Chinese text sets the language, which the words (and the SVG's `xml:lang`) follow. */
|
|
6
|
+
export const langOf = (source: string): string | undefined => (/[\u3400-\u9fff]/.test(source) ? "zh-Hant" : undefined);
|
|
7
|
+
|
|
8
|
+
export interface DiagramDescription {
|
|
9
|
+
/** The type, with the diagram's own title when it has one: `Flowchart “Cache path”`. */
|
|
10
|
+
title: string;
|
|
11
|
+
/** The node count and the first edges, or empty when the type has no such reading. */
|
|
12
|
+
desc: string;
|
|
13
|
+
/** `title` and `desc` as one sentence. */
|
|
14
|
+
alt: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const KINDS: [RegExp, keyof Strings][] = [
|
|
18
|
+
[/^(?:graph|flowchart)\b/i, "diagramKindFlow"],
|
|
19
|
+
[/^stateDiagram/i, "diagramKindState"],
|
|
20
|
+
[/^sequenceDiagram\b/i, "diagramKindSequence"],
|
|
21
|
+
[/^classDiagram\b/i, "diagramKindClass"],
|
|
22
|
+
[/^erDiagram\b/i, "diagramKindEr"],
|
|
23
|
+
[/^xychart/i, "diagramKindChart"],
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
const MAX_PATH = 4;
|
|
27
|
+
const ARROW = /\s*(?:<?-{2,}>|<?={2,}>|-\.+->|-{3,})\s*(?:\|[^|]*\|\s*)?/;
|
|
28
|
+
const NODE = /^([^\s[\](){}"<>|:;&]+)(?::::\w+)?\s*(?:[[({]+\s*"?([^"\]})]*?)"?\s*[\])}]+)?/;
|
|
29
|
+
|
|
30
|
+
const unquote = (value: string): string => value.trim().replace(/^["']|["']$/g, "");
|
|
31
|
+
|
|
32
|
+
function titleOf(lines: string[], chart: boolean): string | undefined {
|
|
33
|
+
const plain = lines.filter((line) => !ARROW.test(line));
|
|
34
|
+
const front = /^title:\s*(.+)$/i.exec(plain.find((line) => /^title:/i.test(line)) ?? "");
|
|
35
|
+
if (front) return unquote(front[1] as string);
|
|
36
|
+
if (!chart) return undefined;
|
|
37
|
+
const named = /^title\s+(.+)$/i.exec(plain.find((line) => /^title\s/i.test(line)) ?? "");
|
|
38
|
+
return named ? unquote(named[1] as string) : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The nodes and edges a flowchart or state diagram names, in source order; the first label seen for an id wins. */
|
|
42
|
+
function readEdges(lines: string[]): { count: number; path: string[]; more: boolean } {
|
|
43
|
+
const labels = new Map<string, string>();
|
|
44
|
+
const edges: [string, string][] = [];
|
|
45
|
+
for (const line of lines) {
|
|
46
|
+
if (!ARROW.test(line)) continue;
|
|
47
|
+
const groups: string[][] = [];
|
|
48
|
+
for (const part of line.replace(/:[^>]*$/, "").split(ARROW)) {
|
|
49
|
+
const ids: string[] = [];
|
|
50
|
+
for (const piece of part.split(/\s+&\s+/)) {
|
|
51
|
+
const node = NODE.exec(piece.trim());
|
|
52
|
+
if (!node || node[1] === "[*]") continue;
|
|
53
|
+
const id = node[1] as string;
|
|
54
|
+
const label = node[2]?.trim();
|
|
55
|
+
if (!labels.has(id) || (label && labels.get(id) === id)) labels.set(id, label || id);
|
|
56
|
+
ids.push(id);
|
|
57
|
+
}
|
|
58
|
+
if (ids.length > 0) groups.push(ids);
|
|
59
|
+
}
|
|
60
|
+
for (let i = 1; i < groups.length; i++) {
|
|
61
|
+
for (const from of groups[i - 1] as string[]) for (const to of groups[i] as string[]) edges.push([from, to]);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const chains: string[][] = [];
|
|
65
|
+
let shown = 0;
|
|
66
|
+
let used = 0;
|
|
67
|
+
for (const [from, to] of edges) {
|
|
68
|
+
const last = chains.at(-1);
|
|
69
|
+
const extend = last?.at(-1) === from;
|
|
70
|
+
if (shown + (extend ? 1 : 2) > MAX_PATH) break;
|
|
71
|
+
if (extend) last?.push(to);
|
|
72
|
+
else chains.push([from, to]);
|
|
73
|
+
shown += extend ? 1 : 2;
|
|
74
|
+
used++;
|
|
75
|
+
}
|
|
76
|
+
const path = chains.map((chain) => chain.map((id) => labels.get(id) ?? id).join(" → "));
|
|
77
|
+
return { count: labels.size, path, more: used < edges.length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function describeDiagram(source: string, strings: Strings): DiagramDescription {
|
|
81
|
+
const lines = source
|
|
82
|
+
.replace(/^\s*---\n([\s\S]*?)\n---\s*\n/, (_, front: string) => `${front}\n`)
|
|
83
|
+
.split("\n")
|
|
84
|
+
.map((line) => line.trim())
|
|
85
|
+
.filter((line) => line !== "" && !line.startsWith("%%"));
|
|
86
|
+
const first = lines.find((line) => !/^\w+:/.test(line) || /^(?:graph|flowchart|stateDiagram)/i.test(line)) ?? "";
|
|
87
|
+
const kind = KINDS.find(([pattern]) => pattern.test(first))?.[1];
|
|
88
|
+
const base = kind ? strings[kind] : strings.diagram;
|
|
89
|
+
const name = titleOf(lines, kind === "diagramKindChart");
|
|
90
|
+
const title = name ? `${base} “${name}”` : base;
|
|
91
|
+
let desc = "";
|
|
92
|
+
if (kind === "diagramKindFlow" || kind === "diagramKindState") {
|
|
93
|
+
const { count, path, more } = readEdges(lines);
|
|
94
|
+
if (count > 0) {
|
|
95
|
+
const nodes = format(strings.diagramNodes, { n: count });
|
|
96
|
+
desc =
|
|
97
|
+
path.length > 0 ? format(strings.diagramDesc, { nodes, path: path.join("; ") + (more ? " …" : "") }) : nodes;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { title, desc, alt: desc ? format(strings.diagramAlt, { title, desc }) : title };
|
|
101
|
+
}
|
package/src/elements/display.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { AlertData, CardsData, DiffData, MermaidData, StatsData, StepStatus, StepsData } from "../core/types.ts";
|
|
2
2
|
import { define, PbsElement } from "./base.ts";
|
|
3
3
|
import { configuration, type DiagramMap, type DiagramTarget } from "./config.ts";
|
|
4
|
+
import { describeDiagram } from "./diagram-alt.ts";
|
|
4
5
|
import { h, inlineNodes, prose, svg } from "./dom.ts";
|
|
5
6
|
import type { Strings } from "./strings.ts";
|
|
6
7
|
|
|
@@ -45,6 +46,8 @@ const displayCss = `
|
|
|
45
46
|
|
|
46
47
|
.diagram { margin: 0; text-align: center; overflow: auto; }
|
|
47
48
|
.diagram img { display: block; max-width: 100%; height: auto; margin: 0 auto; }
|
|
49
|
+
.diagram[data-wide] img { max-width: none; }
|
|
50
|
+
.diagram[data-wide] .frame { max-width: none; }
|
|
48
51
|
.diagram .frame { position: relative; width: fit-content; max-width: 100%; margin: 0 auto; }
|
|
49
52
|
.diagram .targets { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
|
|
50
53
|
.targets .hit { cursor: pointer; outline: none; }
|
|
@@ -251,10 +254,20 @@ export class PbsDiff extends PbsElement<DiffData> {
|
|
|
251
254
|
}
|
|
252
255
|
}
|
|
253
256
|
|
|
257
|
+
/** A drawing wider than this many panel widths is shown at its own size, scrolled. */
|
|
258
|
+
const WIDE_RATIO = 1.25;
|
|
259
|
+
|
|
254
260
|
export class PbsDiagram extends PbsElement<MermaidData> {
|
|
255
261
|
static override css = displayCss;
|
|
256
262
|
/** A URL whose image failed to load; the source is shown instead. */
|
|
257
263
|
#failed: string | undefined;
|
|
264
|
+
#resize: ResizeObserver | undefined;
|
|
265
|
+
|
|
266
|
+
override disconnectedCallback(): void {
|
|
267
|
+
super.disconnectedCallback();
|
|
268
|
+
this.#resize?.disconnect();
|
|
269
|
+
this.#resize = undefined;
|
|
270
|
+
}
|
|
258
271
|
|
|
259
272
|
protected override reset(): void {
|
|
260
273
|
this.#failed = undefined;
|
|
@@ -266,7 +279,25 @@ export class PbsDiagram extends PbsElement<MermaidData> {
|
|
|
266
279
|
const source = h("pre", null, h("code", null, data.source));
|
|
267
280
|
const figure = h("figure", { part: "diagram", class: "panel diagram" });
|
|
268
281
|
if (shown) {
|
|
269
|
-
const image = h("img", {
|
|
282
|
+
const image = h("img", {
|
|
283
|
+
part: "image",
|
|
284
|
+
src: url,
|
|
285
|
+
alt: describeDiagram(data.source, this.strings).alt,
|
|
286
|
+
loading: "lazy",
|
|
287
|
+
});
|
|
288
|
+
// A drawing far wider than the panel would shrink to unreadable text: keep its size and let the panel scroll.
|
|
289
|
+
const judge = () => {
|
|
290
|
+
const wide = figure.clientWidth > 0 && image.naturalWidth > figure.clientWidth * WIDE_RATIO;
|
|
291
|
+
figure.toggleAttribute("data-wide", wide);
|
|
292
|
+
};
|
|
293
|
+
image.addEventListener("load", () => {
|
|
294
|
+
judge();
|
|
295
|
+
// A panel that was hidden at load, or later resized, is judged again.
|
|
296
|
+
if (typeof ResizeObserver === "undefined") return;
|
|
297
|
+
this.#resize?.disconnect();
|
|
298
|
+
this.#resize = new ResizeObserver(judge);
|
|
299
|
+
this.#resize.observe(figure);
|
|
300
|
+
});
|
|
270
301
|
image.addEventListener("error", () => {
|
|
271
302
|
this.#failed = url;
|
|
272
303
|
this.refresh();
|
|
@@ -280,6 +311,10 @@ export class PbsDiagram extends PbsElement<MermaidData> {
|
|
|
280
311
|
return figure;
|
|
281
312
|
}
|
|
282
313
|
|
|
314
|
+
#description(): string {
|
|
315
|
+
return describeDiagram(this.data?.source ?? "", this.strings).alt;
|
|
316
|
+
}
|
|
317
|
+
|
|
283
318
|
/**
|
|
284
319
|
* When the host can read the drawing (`diagramMap`), lays its nodes and edges over the image as buttons: a click, or
|
|
285
320
|
* Enter or Space on a focused one, dispatches `pbs-diagram-target` with the element in the diagram's own words.
|
|
@@ -367,7 +402,7 @@ export class PbsDiagram extends PbsElement<MermaidData> {
|
|
|
367
402
|
class: "targets",
|
|
368
403
|
viewBox: map.viewBox,
|
|
369
404
|
role: "group",
|
|
370
|
-
"aria-label": this
|
|
405
|
+
"aria-label": this.#description(),
|
|
371
406
|
"aria-describedby": "diagram-keys",
|
|
372
407
|
},
|
|
373
408
|
keys,
|
package/src/elements/strings.ts
CHANGED
|
@@ -43,6 +43,17 @@ export interface Strings {
|
|
|
43
43
|
diagramGroup: string;
|
|
44
44
|
/** How to move through a diagram's elements, for screen readers. */
|
|
45
45
|
diagramKeys: string;
|
|
46
|
+
diagramKindFlow: string;
|
|
47
|
+
diagramKindState: string;
|
|
48
|
+
diagramKindSequence: string;
|
|
49
|
+
diagramKindClass: string;
|
|
50
|
+
diagramKindEr: string;
|
|
51
|
+
diagramKindChart: string;
|
|
52
|
+
diagramNodes: string;
|
|
53
|
+
/** `{title}` then `{desc}`: what the image's alt text reads. */
|
|
54
|
+
diagramAlt: string;
|
|
55
|
+
/** `{nodes}` then `{path}`: what the diagram's description reads. */
|
|
56
|
+
diagramDesc: string;
|
|
46
57
|
diff: string;
|
|
47
58
|
table: string;
|
|
48
59
|
mindmap: string;
|
|
@@ -101,6 +112,15 @@ export const STRINGS: Record<Locale, Strings> = {
|
|
|
101
112
|
diagramEdge: "edge",
|
|
102
113
|
diagramGroup: "group",
|
|
103
114
|
diagramKeys: "Arrow keys move between its elements; Enter or Space comments on one.",
|
|
115
|
+
diagramKindFlow: "Flowchart",
|
|
116
|
+
diagramKindState: "State diagram",
|
|
117
|
+
diagramKindSequence: "Sequence diagram",
|
|
118
|
+
diagramKindClass: "Class diagram",
|
|
119
|
+
diagramKindEr: "Entity-relationship diagram",
|
|
120
|
+
diagramKindChart: "Chart",
|
|
121
|
+
diagramNodes: "{n} nodes",
|
|
122
|
+
diagramAlt: "{title}, {desc}",
|
|
123
|
+
diagramDesc: "{nodes}: {path}",
|
|
104
124
|
diff: "Diff",
|
|
105
125
|
table: "Table",
|
|
106
126
|
mindmap: "Mind map",
|
|
@@ -156,6 +176,15 @@ export const STRINGS: Record<Locale, Strings> = {
|
|
|
156
176
|
diagramEdge: "連線",
|
|
157
177
|
diagramGroup: "群組",
|
|
158
178
|
diagramKeys: "用方向鍵在元素之間移動,按 Enter 或空白鍵針對它留言。",
|
|
179
|
+
diagramKindFlow: "流程圖",
|
|
180
|
+
diagramKindState: "狀態圖",
|
|
181
|
+
diagramKindSequence: "循序圖",
|
|
182
|
+
diagramKindClass: "類別圖",
|
|
183
|
+
diagramKindEr: "實體關聯圖",
|
|
184
|
+
diagramKindChart: "XY 圖表",
|
|
185
|
+
diagramNodes: "{n} 個節點",
|
|
186
|
+
diagramAlt: "{title},{desc}",
|
|
187
|
+
diagramDesc: "{nodes}:{path}",
|
|
159
188
|
diff: "差異",
|
|
160
189
|
table: "表格",
|
|
161
190
|
mindmap: "心智圖",
|
package/src/extension/check.ts
CHANGED
|
@@ -16,13 +16,20 @@ export const hasBlockFence = (markdown: string): boolean => BLOCK_FENCE.test(mar
|
|
|
16
16
|
export async function checkText(name: string, markdown: string): Promise<string | undefined> {
|
|
17
17
|
if (!hasBlockFence(markdown)) return undefined;
|
|
18
18
|
const { checkBlocks, formatProblems } = await import("../core/check.ts");
|
|
19
|
-
const
|
|
19
|
+
const server = MERMAID_FENCE.test(markdown) ? await import("../server/index.ts") : undefined;
|
|
20
|
+
const mermaid = server?.mermaidSvg;
|
|
21
|
+
// The check asks for a diagram's error and then its notes: draw each source once.
|
|
22
|
+
const drawn = new Map<string, string>();
|
|
20
23
|
const problems = checkBlocks(markdown, {
|
|
21
24
|
...(mermaid
|
|
22
25
|
? {
|
|
26
|
+
mermaidNotes: (source: string) => {
|
|
27
|
+
const svg = drawn.get(source);
|
|
28
|
+
return svg === undefined ? [] : (server?.svgNotes(svg) ?? []);
|
|
29
|
+
},
|
|
23
30
|
mermaid: (source: string) => {
|
|
24
31
|
try {
|
|
25
|
-
mermaid(source);
|
|
32
|
+
drawn.set(source, mermaid(source));
|
|
26
33
|
return undefined;
|
|
27
34
|
} catch (error) {
|
|
28
35
|
return ((error instanceof Error ? error.message : String(error)).split("\n")[0] as string).trim();
|
package/src/extension/render.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import MarkdownIt from "markdown-it";
|
|
2
2
|
import { parse } from "../core/index.ts";
|
|
3
3
|
import type { Segment } from "../core/types.ts";
|
|
4
|
+
import { langOf } from "../elements/diagram-alt.ts";
|
|
4
5
|
import { TAGS } from "../elements/index.ts";
|
|
5
6
|
|
|
6
7
|
/** Prose is Markdown with raw HTML left as text; blocks become `pbs-*` elements that read their data from an attribute. */
|
|
@@ -52,8 +53,7 @@ export function renderBody(markdown: string, options: RenderOptions): string {
|
|
|
52
53
|
.join("");
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
|
|
56
|
-
export const langOf = (source: string): string | undefined => (/[\u3400-\u9fff]/.test(source) ? "zh-Hant" : undefined);
|
|
56
|
+
export { langOf };
|
|
57
57
|
|
|
58
58
|
export interface PageOptions {
|
|
59
59
|
title: string;
|
package/src/server/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { type DiagramColors, renderMermaidASCII, renderMermaidSVG } from "beautiful-mermaid";
|
|
2
2
|
import { displayWidth } from "../core/index.ts";
|
|
3
|
+
import { describeDiagram, langOf } from "../elements/diagram-alt.ts";
|
|
4
|
+
import { STRINGS } from "../elements/strings.ts";
|
|
3
5
|
|
|
4
6
|
/** Node side of pi-better-show: Mermaid diagrams drawn as SVG for the web and as Unicode text for chat. */
|
|
5
7
|
|
|
@@ -16,11 +18,30 @@ export interface SvgOptions {
|
|
|
16
18
|
transparent?: boolean;
|
|
17
19
|
}
|
|
18
20
|
|
|
21
|
+
/** The default element tokens (`--pbs-*` in elements/styles.ts), so a diagram matches the panel around it. */
|
|
19
22
|
const SCHEMES: Record<"light" | "dark", DiagramColors> = {
|
|
20
|
-
light:
|
|
21
|
-
|
|
23
|
+
light: {
|
|
24
|
+
bg: "#ffffff",
|
|
25
|
+
fg: "#1f2328",
|
|
26
|
+
accent: "#0969da",
|
|
27
|
+
muted: "#59636e",
|
|
28
|
+
surface: "#f6f8fa",
|
|
29
|
+
border: "#d1d9e0",
|
|
30
|
+
},
|
|
31
|
+
dark: {
|
|
32
|
+
bg: "#151b23",
|
|
33
|
+
fg: "#e6edf3",
|
|
34
|
+
accent: "#4493f8",
|
|
35
|
+
muted: "#9ba3ad",
|
|
36
|
+
surface: "#1d252f",
|
|
37
|
+
border: "#3d444d",
|
|
38
|
+
},
|
|
22
39
|
};
|
|
23
40
|
|
|
41
|
+
const PADDING = 20;
|
|
42
|
+
const CJK_FONTS = "'PingFang TC', 'Noto Sans TC', 'Microsoft JhengHei'";
|
|
43
|
+
const escapeXml = (text: string): string => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
44
|
+
|
|
24
45
|
/** Columns a text diagram may take unless the caller says otherwise; matches core's `toText` default. */
|
|
25
46
|
export const DEFAULT_DIAGRAM_WIDTH = 60;
|
|
26
47
|
|
|
@@ -36,9 +57,64 @@ export function mermaidSvg(source: string, options: SvgOptions = {}): string {
|
|
|
36
57
|
...colors,
|
|
37
58
|
font: options.font ?? "system-ui",
|
|
38
59
|
transparent: options.transparent ?? false,
|
|
60
|
+
padding: PADDING,
|
|
39
61
|
});
|
|
40
62
|
// The library imports a web font; hosts serve diagrams from their own origin, and a CSP may forbid more.
|
|
41
|
-
|
|
63
|
+
let out = svg
|
|
64
|
+
.replace(/@import\s+url\([^)]*\)\s*;?/g, "")
|
|
65
|
+
// The `font` option takes one quoted family, so the Traditional Chinese faces are added after the fact.
|
|
66
|
+
.replace(
|
|
67
|
+
/font-family:\s*[^;}]*;/,
|
|
68
|
+
(rule) => `${rule.slice(0, -1).replace(/,\s*sans-serif$/, "")}, ${CJK_FONTS}, sans-serif;`,
|
|
69
|
+
);
|
|
70
|
+
const han = langOf(source) !== undefined;
|
|
71
|
+
const { title, desc } = describeDiagram(source, STRINGS[han ? "zh-Hant" : "en"]);
|
|
72
|
+
const notes = `\n<title>${escapeXml(title)}</title>${desc ? `\n<desc>${escapeXml(desc)}</desc>` : ""}`;
|
|
73
|
+
out = out.replace(
|
|
74
|
+
/^<svg ([^>]*)>/,
|
|
75
|
+
(_, attributes: string) => `<svg ${han ? 'xml:lang="zh-Hant" ' : ""}${attributes} role="img">${notes}`,
|
|
76
|
+
);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The widest a drawing may be before a 52rem page shrinks its text too small to read. */
|
|
81
|
+
const WIDE = 900;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Advice on a diagram that will be hard to read: too many nodes, edges, lifelines or entities for its type, or a
|
|
85
|
+
* drawing so wide that the page shrinks it. Each note is one sentence for the author. Advice only: the diagram still
|
|
86
|
+
* draws, and a source that does not draw has no notes.
|
|
87
|
+
*/
|
|
88
|
+
export function diagramNotes(source: string): string[] {
|
|
89
|
+
try {
|
|
90
|
+
return svgNotes(mermaidSvg(source));
|
|
91
|
+
} catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** `diagramNotes` for a drawing already made by `mermaidSvg`, so a host that has the SVG need not draw again. */
|
|
97
|
+
export function svgNotes(svg: string): string[] {
|
|
98
|
+
const count = (pattern: RegExp): number => svg.match(pattern)?.length ?? 0;
|
|
99
|
+
const notes: string[] = [];
|
|
100
|
+
const over = (n: number, limit: number, thing: string) => {
|
|
101
|
+
if (n > limit)
|
|
102
|
+
notes.push(
|
|
103
|
+
`the diagram has ${n} ${thing} (more than ${limit} is hard to read); split it into an overview and detail diagrams`,
|
|
104
|
+
);
|
|
105
|
+
};
|
|
106
|
+
over(count(/<g class="node"/g), 9, "nodes");
|
|
107
|
+
over(count(/class="edge"/g), 12, "edges");
|
|
108
|
+
over(count(/class="actor"/g), 5, "lifelines");
|
|
109
|
+
over(count(/class="entity"/g), 8, "entities");
|
|
110
|
+
over(count(/class="class-node"/g), 8, "classes");
|
|
111
|
+
const width = Number(/viewBox="0 0 ([\d.]+) /.exec(svg)?.[1]);
|
|
112
|
+
if (width > WIDE) {
|
|
113
|
+
notes.push(
|
|
114
|
+
`the diagram is ${Math.round(width)}px wide, too wide for the page; shorten the labels, use TD, or split it`,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
return notes;
|
|
42
118
|
}
|
|
43
119
|
|
|
44
120
|
/**
|