pi-better-show 0.7.1 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.7.1",
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
+ }
@@ -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", { part: "image", src: url, alt: this.t("diagram"), loading: "lazy" });
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.
@@ -356,11 +391,21 @@ export class PbsDiagram extends PbsElement<MermaidData> {
356
391
  }
357
392
  });
358
393
  }
359
- // Later buttons sit above earlier ones: groups below edges below nodes, so a node inside a group is the node.
394
+ // Later buttons sit above earlier ones: groups below edges below nodes, so a node inside a group is the node. The
395
+ // DOM keeps that order, not the reading order; the description tells a screen reader to move with the arrow keys.
360
396
  const layers: DiagramTarget["kind"][] = ["group", "edge", "node"];
397
+ const keys = svg("desc", { id: "diagram-keys" });
398
+ keys.textContent = this.t("diagramKeys");
361
399
  return svg(
362
400
  "svg",
363
- { class: "targets", viewBox: map.viewBox, role: "group", "aria-label": this.t("diagram") },
401
+ {
402
+ class: "targets",
403
+ viewBox: map.viewBox,
404
+ role: "group",
405
+ "aria-label": this.#description(),
406
+ "aria-describedby": "diagram-keys",
407
+ },
408
+ keys,
364
409
  ...layers.flatMap((kind) => hits.filter((_, index) => map.targets[index]?.kind === kind)),
365
410
  );
366
411
  }
@@ -41,6 +41,19 @@ export interface Strings {
41
41
  diagramNode: string;
42
42
  diagramEdge: string;
43
43
  diagramGroup: string;
44
+ /** How to move through a diagram's elements, for screen readers. */
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;
44
57
  diff: string;
45
58
  table: string;
46
59
  mindmap: string;
@@ -98,6 +111,16 @@ export const STRINGS: Record<Locale, Strings> = {
98
111
  diagramNode: "node",
99
112
  diagramEdge: "edge",
100
113
  diagramGroup: "group",
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}",
101
124
  diff: "Diff",
102
125
  table: "Table",
103
126
  mindmap: "Mind map",
@@ -152,6 +175,16 @@ export const STRINGS: Record<Locale, Strings> = {
152
175
  diagramNode: "節點",
153
176
  diagramEdge: "連線",
154
177
  diagramGroup: "群組",
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}",
155
188
  diff: "差異",
156
189
  table: "表格",
157
190
  mindmap: "心智圖",
@@ -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 mermaid = MERMAID_FENCE.test(markdown) ? (await import("../server/index.ts")).mermaidSvg : undefined;
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();
@@ -97,13 +97,26 @@ function enclosing(groups: Element[], node: Element): Element | undefined {
97
97
  */
98
98
  type Draft = DiagramTarget & { tag: string; id?: string };
99
99
 
100
+ /**
101
+ * What a number is written after: a run of `#` that no label or id of the drawing has, so a numbered quote never reads
102
+ * as another element's own words (`A → B ##1` beside a node labelled `B #1`). `#` unless a label has one.
103
+ */
104
+ function numberingOf(svg: Element): string {
105
+ const said = [...svg.querySelectorAll("[data-label], [data-id]")].flatMap((element) => [
106
+ words(element.getAttribute("data-label")),
107
+ words(element.getAttribute("data-id")),
108
+ ]);
109
+ let mark = "#";
110
+ while (said.some((text) => text.includes(mark))) mark += "#";
111
+ return mark;
112
+ }
113
+
100
114
  /**
101
115
  * Makes every target's text unique among `targets` (one kind), so one quote names one element. Only a text that more
102
116
  * than one target has changes: each adds its tag where the tags differ (`Check (B)`), and what is still alike is
103
- * numbered in drawing order (`#1`, `#2`), skipping a number whose text another target already has (a label written as
104
- * `B #1`).
117
+ * numbered in drawing order after `numbering` (`#1`, `#2`), which no label has, so a numbered text is no other's.
105
118
  */
106
- function disambiguated(targets: Draft[]): DiagramTarget[] {
119
+ function disambiguated(targets: Draft[], numbering: string): DiagramTarget[] {
107
120
  const count = (list: DiagramTarget[]): Map<string, number> => {
108
121
  const seen = new Map<string, number>();
109
122
  for (const target of list) seen.set(target.text, (seen.get(target.text) ?? 0) + 1);
@@ -119,16 +132,12 @@ function disambiguated(targets: Draft[]): DiagramTarget[] {
119
132
  : target,
120
133
  );
121
134
  const second = count(named);
122
- const taken = new Set(named.filter((target) => (second.get(target.text) ?? 0) < 2).map((target) => target.text));
123
135
  const next = new Map<string, number>();
124
136
  return named.map((target) => {
125
137
  if ((second.get(target.text) ?? 0) < 2) return target;
126
- let ordinal = next.get(target.text) ?? 0;
127
- do ordinal += 1;
128
- while (taken.has(`${target.text} #${ordinal}`));
138
+ const ordinal = (next.get(target.text) ?? 0) + 1;
129
139
  next.set(target.text, ordinal);
130
- taken.add(`${target.text} #${ordinal}`);
131
- return { ...target, text: `${target.text} #${ordinal}` };
140
+ return { ...target, text: `${target.text} ${numbering}${ordinal}` };
132
141
  });
133
142
  }
134
143
 
@@ -136,13 +145,18 @@ function disambiguated(targets: Draft[]): DiagramTarget[] {
136
145
  * Tells apart the nodes or the groups, and records each one's final name and tag by id: later targets (a `[*]`'s
137
146
  * composite state, an edge's ends) are named by them. A target with no text or shape is left out.
138
147
  */
139
- function settle(drafts: Draft[], names: Map<string, string>, tags: Map<string, string>): DiagramTarget[] {
148
+ function settle(
149
+ drafts: Draft[],
150
+ names: Map<string, string>,
151
+ tags: Map<string, string>,
152
+ numbering: string,
153
+ ): DiagramTarget[] {
140
154
  for (const draft of drafts) {
141
155
  names.set(draft.id ?? "", draft.text);
142
156
  tags.set(draft.id ?? "", draft.tag);
143
157
  }
144
158
  const kept = drafts.filter((draft) => draft.text && draft.shapes.length > 0);
145
- const targets = disambiguated(kept);
159
+ const targets = disambiguated(kept, numbering);
146
160
  for (const [index, draft] of kept.entries()) names.set(draft.id ?? "", targets[index]?.text ?? draft.text);
147
161
  return targets;
148
162
  }
@@ -214,6 +228,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
214
228
  /** Each node's and group's name, and the tag that tells it apart, by id: what an edge is named by. */
215
229
  const names = new Map<string, string>();
216
230
  const tags = new Map<string, string>();
231
+ const numbering = numberingOf(svg);
217
232
 
218
233
  const groupElements = [...svg.querySelectorAll("g.subgraph")];
219
234
  const groups = settle(
@@ -225,6 +240,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
225
240
  }),
226
241
  names,
227
242
  tags,
243
+ numbering,
228
244
  );
229
245
 
230
246
  const nodeElements = [...svg.querySelectorAll("g.node")];
@@ -250,6 +266,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
250
266
  }),
251
267
  names,
252
268
  tags,
269
+ numbering,
253
270
  );
254
271
 
255
272
  const name = (id: string | null): string => names.get(id ?? "") || words(id);
@@ -281,7 +298,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
281
298
  });
282
299
  }
283
300
 
284
- const targets = inReadingOrder([...groups, ...disambiguated(edges), ...nodes]);
301
+ const targets = inReadingOrder([...groups, ...disambiguated(edges, numbering), ...nodes]);
285
302
  return targets.length > 0 ? { viewBox, targets } : undefined;
286
303
  }
287
304
 
@@ -324,18 +341,18 @@ export function diagramRef(diagram: Element): string {
324
341
 
325
342
  /**
326
343
  * A `diagramQuote` made on an earlier load, with the position its diagram (found by `diagramRef`) has on the page now.
327
- * A diagram whose source changed is not found, and the quote keeps the position it has.
344
+ * A diagram whose source changed is not found: `undefined`, and the panel keeps the quote's position.
328
345
  */
329
- export function requoteDiagram(quote: string, ref: string): string {
346
+ export function requoteDiagram(quote: string, ref: string): string | undefined {
330
347
  let found: Element | undefined;
331
348
  try {
332
349
  const [source, nth] = JSON.parse(ref) as [unknown, unknown];
333
350
  const alike = [...document.querySelectorAll("pbs-diagram")].filter((other) => sourceOf(other) === source);
334
351
  found = typeof nth === "number" ? alike[nth] : undefined;
335
352
  } catch {
336
- // A ref that cannot be read leaves the quote as it is.
353
+ // A ref that cannot be read finds nothing.
337
354
  }
338
- if (!found) return quote;
355
+ if (!found) return undefined;
339
356
  const position = [...document.querySelectorAll("pbs-diagram")].indexOf(found) + 1;
340
357
  return quote.replace(/^\[Diagram \d+,/, `[Diagram ${position},`);
341
358
  }
@@ -81,9 +81,22 @@ export interface FeedbackOptions {
81
81
  diagrams?: boolean;
82
82
  /**
83
83
  * Rewrites a restored draft's quote that came with a `ref` for the page as it is now: the reload an agent's edit causes
84
- * may have moved what the quote names.
84
+ * may have moved what the quote names. `undefined` when what the ref names is no longer on the page: the quote keeps
85
+ * its text, marked (`STALE`) while another draft's quote reads the same.
85
86
  */
86
- requote?: (quote: string, ref: string) => string;
87
+ requote?: (quote: string, ref: string) => string | undefined;
88
+ }
89
+
90
+ /**
91
+ * What a draft's quote adds when what it named is no longer on the page and another draft's quote reads the same, so
92
+ * two drafts never share a quote. Part of the message the agent reads; keep it stable.
93
+ */
94
+ export const STALE = " (from an earlier version of the page)";
95
+
96
+ /** A quote without the `STALE` mark (and its number) it was saved with. */
97
+ function unmarked(quote: string): string {
98
+ const at = quote.lastIndexOf(STALE);
99
+ return at !== -1 && /^(?: #\d+)?$/.test(quote.slice(at + STALE.length)) ? quote.slice(0, at) : quote;
87
100
  }
88
101
 
89
102
  /** A passage to comment on, and where the Add button goes (viewport coordinates of the panel's document). */
@@ -122,19 +135,48 @@ export function mountFeedback(options: FeedbackOptions): {
122
135
  const { words, storage, storageKey } = options;
123
136
  let items: FeedbackItem[] = [];
124
137
  let overall = "";
138
+ /** The restored drafts whose `ref` names nothing on the page now, with their quote as it was made (unmarked). */
139
+ const stale = new Map<FeedbackItem, string>();
125
140
  try {
126
141
  const saved = JSON.parse(storage.getItem(storageKey) ?? "null") as {
127
142
  items?: FeedbackItem[];
128
143
  overall?: string;
129
144
  } | null;
130
145
  const { requote } = options;
131
- items = (saved?.items ?? []).map((item) =>
132
- item.ref && requote ? { ...item, quote: requote(item.quote, item.ref) } : item,
133
- );
146
+ items = (saved?.items ?? []).map((item) => {
147
+ if (!item.ref || !requote) return item;
148
+ const made = unmarked(item.quote);
149
+ const quote = requote(made, item.ref);
150
+ if (quote !== undefined) return { ...item, quote };
151
+ const kept = { ...item, quote: made };
152
+ stale.set(kept, made);
153
+ return kept;
154
+ });
134
155
  overall = saved?.overall ?? "";
135
156
  } catch {
136
157
  // A draft that cannot be read is dropped.
137
158
  }
159
+ /**
160
+ * Marks each stale quote that reads like another draft's, current or stale, and numbers marks that would still be
161
+ * alike; a stale quote that reads like no other is left as it was made.
162
+ */
163
+ const settle = (): void => {
164
+ const used = new Set(items.filter((item) => !stale.has(item)).map((item) => item.quote));
165
+ const made = [...stale.values()];
166
+ for (const item of items) {
167
+ const quote = stale.get(item);
168
+ if (quote === undefined) continue;
169
+ if (!used.has(quote) && made.filter((other) => other === quote).length < 2) {
170
+ item.quote = quote;
171
+ continue;
172
+ }
173
+ let marked = `${quote}${STALE}`;
174
+ for (let n = 2; used.has(marked); n += 1) marked = `${quote}${STALE} #${n}`;
175
+ item.quote = marked;
176
+ used.add(marked);
177
+ }
178
+ };
179
+ settle();
138
180
  const save = (): void => {
139
181
  if (items.length === 0 && !overall) storage.removeItem(storageKey);
140
182
  else storage.setItem(storageKey, JSON.stringify({ items, overall }));
@@ -171,8 +213,8 @@ export function mountFeedback(options: FeedbackOptions): {
171
213
  const remove = make("button", { type: "button", textContent: words.remove });
172
214
  remove.addEventListener("click", () => {
173
215
  items.splice(index, 1);
174
- save();
175
- draw();
216
+ stale.delete(item);
217
+ changed();
176
218
  });
177
219
  entry.append(quote, box, remove);
178
220
  return entry;
@@ -180,6 +222,12 @@ export function mountFeedback(options: FeedbackOptions): {
180
222
  );
181
223
  toggle.textContent = items.length > 0 ? `${words.feedback} (${items.length})` : words.feedback;
182
224
  };
225
+ /** After a draft is added or removed: marks the quotes that now read alike, keeps, and redraws. */
226
+ const changed = (): void => {
227
+ settle();
228
+ save();
229
+ draw();
230
+ };
183
231
  overallBox.addEventListener("input", () => {
184
232
  overall = overallBox.value;
185
233
  save();
@@ -191,6 +239,8 @@ export function mountFeedback(options: FeedbackOptions): {
191
239
  panel.hidden = !panel.hidden;
192
240
  });
193
241
  panel.addEventListener("keydown", (event) => {
242
+ // An Escape that ends an input method's composition belongs to the input method.
243
+ if (event.isComposing || event.keyCode === 229) return;
194
244
  if (event.key !== "Escape" || !back?.isConnected) return;
195
245
  event.preventDefault();
196
246
  back.focus();
@@ -229,11 +279,11 @@ export function mountFeedback(options: FeedbackOptions): {
229
279
  const comment = (quote: string, from: { ref?: string; back?: HTMLElement | SVGElement } = {}): void => {
230
280
  const { ref } = from;
231
281
  back = from.back;
232
- const known = items.findIndex((item) => item.quote === quote);
282
+ // A stale draft names something the page no longer has, even when its quote reads the same.
283
+ const known = items.findIndex((item) => item.quote === quote && !stale.has(item));
233
284
  if (known === -1) {
234
285
  items.push(ref ? { quote, comment: "", ref } : { quote, comment: "" });
235
- save();
236
- draw();
286
+ changed();
237
287
  }
238
288
  open(known === -1 ? items.length - 1 : known);
239
289
  };
@@ -244,8 +294,7 @@ export function mountFeedback(options: FeedbackOptions): {
244
294
  add.hidden = true;
245
295
  getSelection()?.removeAllRanges();
246
296
  if (quote) items.push({ quote, comment: "" });
247
- save();
248
- draw();
297
+ changed();
249
298
  open(items.length - 1);
250
299
  });
251
300
  sendButton.addEventListener("click", () => {
@@ -260,6 +309,7 @@ export function mountFeedback(options: FeedbackOptions): {
260
309
  .then(
261
310
  () => {
262
311
  items = [];
312
+ stale.clear();
263
313
  overall = "";
264
314
  overallBox.value = "";
265
315
  save();
@@ -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
- /** Chinese text sets the page's language, which the elements' words follow. */
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;
@@ -1,5 +1,7 @@
1
- import { DEFAULTS, type DiagramColors, renderMermaidASCII, renderMermaidSVG, THEMES } from "beautiful-mermaid";
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: THEMES["zinc-light"] ?? DEFAULTS,
21
- dark: THEMES["zinc-dark"] ?? DEFAULTS,
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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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
- return svg.replace(/@import\s+url\([^)]*\)\s*;?/g, "");
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
  /**