pi-better-show 0.6.1 → 0.7.1

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/README.md CHANGED
@@ -1,37 +1,19 @@
1
1
  # pi-better-show
2
2
 
3
- Let your pi agent show you a page instead of a wall of text, and answer it by clicking.
3
+ [繁體中文](README.zh-TW.md)
4
4
 
5
- The agent writes Markdown with fenced blocks (`` ```options ``, `` ```form ``, `` ```table ``, ...).
6
- `show_doc` opens it in your browser, and every pick, form, or comment you send comes back to the agent as a message.
5
+ **Let your [pi](https://github.com/earendil-works/pi) agent show you a page instead of a wall of text, and answer it by clicking.**
7
6
 
8
- ![A decision page: an alert, two options, and a form](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/decide.png)
9
-
10
- When you press **Send** on the form above, the agent receives:
11
-
12
- ```text
13
- User submitted a form in the HTML review pane:
14
- - ttl: week
15
- - extras: WAL mode, Nightly backup
16
- - note: The API runs on two hosts next month.
17
- ```
18
-
19
- ## Fewer tokens
7
+ **[Documentation](https://wayne930242.github.io/pi-better-show/)** in English and [Traditional Chinese](https://wayne930242.github.io/pi-better-show/zh-tw/): concepts, every block kind, agent pages, and the library.
20
8
 
21
- The agent writes data, not a web page: the package owns the layout, styles, controls, and the code that sends answers back.
22
- For the four example pages in this README, writing the blocks took **1,253 output tokens**; asking the same model for one self-contained HTML page with the same content and working controls took **12,364**, about **10 times as many** (90% saved).
9
+ ![A decision page: an alert, two options, and a form](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/decide.png)
23
10
 
24
- | Page | Blocks | HTML page (median) | HTML runs | Saved |
25
- |---|---:|---:|---|---:|
26
- | [Decision](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-decide.md): alert, options, form | 347 | 2,770 | 1,651 – 2,917 | 87% |
27
- | [Status](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-status.md): stats, steps, table | 412 | 3,726 | 2,145 – 3,895 | 89% |
28
- | [Structure](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-structure.md): tree, mermaid, diff | 338 | 3,719 | 3,514 – 4,064 | 91% |
29
- | [Review](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-review.md): review, suggest | 156 | 2,149 | 2,008 – 2,478 | 93% |
30
- | Total | 1,253 | 12,364 | | 90% |
11
+ ## Why
31
12
 
32
- Counts are Claude output tokens from `claude -p --model claude-sonnet-5-5` (3 to 5 HTML runs per page; the block count is the file echoed back verbatim), measured on 2026-11-10 with `scripts/token-bench.sh`.
33
- None of the HTML pages had the feedback panel for commenting on a selected passage, which `show_doc` adds to every page.
34
- The saving repeats on every revision, since the agent changes a few YAML lines instead of rewriting markup and script.
13
+ - **Blocks, not markup.** The agent writes a few YAML lines per block; the package owns the layout, the controls, and the code that sends answers back.
14
+ - **Answers come back as a message.** A pick, a form, a comment on a passage or on a diagram node: one message, in a fixed shape.
15
+ - **About 10 times fewer tokens** than the same pages written as HTML (1,253 against 12,364 output tokens, measured).
16
+ - **One vocabulary for every host.** Core, custom elements, and React wrappers share one parser, one text fallback, and one answer encoding.
35
17
 
36
18
  ## Install
37
19
 
@@ -39,78 +21,45 @@ The saving repeats on every revision, since the agent changes a few YAML lines i
39
21
  pi install npm:pi-better-show
40
22
  ```
41
23
 
42
- Then `/reload` in a running session.
43
- If you use `pi-herdr-doc-review`, uninstall it first (`pi uninstall npm:pi-herdr-doc-review`): both register `show_doc`.
24
+ Then `/reload` in a running session. If you use `pi-herdr-doc-review`, uninstall it first (`pi uninstall npm:pi-herdr-doc-review`): both register `show_doc`.
44
25
 
45
- ## What `show_doc` does
26
+ ## Quick start
46
27
 
47
- `show_doc({paths, reason, view})` returns at once; the agent does not wait for you.
28
+ Ask the agent to show you something. It writes a Markdown file with blocks and calls `show_doc({paths, reason, view})`, which returns at once:
48
29
 
49
- - `view: "page"` opens the file in your default browser.
50
- Markdown renders with its blocks; `.html`, `.tsx`, and `.jsx` run in a sandboxed frame; images show as they are.
51
- - `view: "edit"` (the default) opens the file in your editor.
52
- Your saves reach the agent as one net diff per file, without starting a turn.
53
- - Select any passage on a page to comment on it.
54
- The feedback panel sends your comments and an overall note in one message.
55
- - Open pages reload when the agent edits the file.
30
+ - `view: "page"` opens the file in your browser; select a passage, or click a diagram node, to comment on it.
31
+ - `view: "edit"` (the default) opens it in your editor; your saves reach the agent as one net diff per file.
56
32
 
57
- ![The feedback panel with a comment on a selected passage](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/feedback.png)
33
+ When you press **Send** on a form, the agent receives:
58
34
 
59
- ## Blocks
35
+ ```text
36
+ User submitted a form in the HTML review pane:
37
+ - ttl: week
38
+ - extras: WAL mode, Nightly backup
39
+ ```
60
40
 
61
- A block is a fenced code block whose first word is its kind, or a GitHub alert (`> [!NOTE]`).
62
- Most take YAML; text fields take bold, italic, code, and `http(s)` links, never raw HTML.
41
+ ## Blocks
63
42
 
64
43
  | Kind | Shows | You answer by |
65
44
  |---|---|---|
66
- | `alert` | a callout (`NOTE`, `TIP`, `IMPORTANT`, `WARNING`, `CAUTION`) | |
67
- | `options` | choices side by side, with pros and cons | picking one |
45
+ | `alert`, `cards`, `stats` | callouts and tiles with a tone | |
46
+ | `options` | choices with pros and cons | picking one |
68
47
  | `form` | single, multi, and text questions | Send |
69
- | `review` | designs, screenshots, or prototypes to compare | commenting and picking |
70
- | `checklist` | items to tick | Send |
71
- | `suggest` | quick-reply chips | clicking one |
72
- | `cards`, `stats` | tiles with a tone | |
73
- | `steps` | a timeline with status | |
74
- | `table` | sortable, filterable rows | |
75
- | `tree` | a directory tree with tags and notes (`npx pbs-tree` prints one) | |
76
- | `mindmap` | a collapsible outline | |
77
- | `mermaid`, `diff` | a diagram, a coloured diff | |
78
-
79
- A status page with `stats`, `steps`, and `table`:
80
-
81
- ![Stats tiles, a steps timeline, and a sortable table](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/status.png)
82
-
83
- A structure review with `tree`, `mermaid`, and `diff`:
84
-
85
- ![A directory tree with tags, a flowchart, and a diff](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/structure.png)
86
-
87
- A design review with `review` and `suggest`:
88
-
89
- ![Two header designs to compare, with quick-reply chips below](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/review.png)
90
-
91
- A block that does not parse shows its source and the reason on the page, and the agent's `write` and `edit` results list the problem with its line number.
92
-
93
- ## Outside pi
94
-
95
- The block vocabulary is a library too, so other hosts (a GUI, a chat bridge) draw the same blocks and send the same answers:
96
-
97
- | Entry | For |
98
- |---|---|
99
- | `pi-better-show` | `parse`, `toText` (a plain-text or Discord fallback), `encodeAnswer`, `validateAnswer`, `checkBlocks` |
100
- | `pi-better-show/elements` | framework-free custom elements, one per block kind |
101
- | `pi-better-show/react` | React wrappers over the elements |
102
- | `pi-better-show/server` | Mermaid to SVG and to Unicode text |
48
+ | `review` | designs or prototypes to compare | commenting, picking |
49
+ | `checklist`, `suggest` | items to tick, quick-reply chips | Send, clicking |
50
+ | `table`, `steps`, `tree`, `mindmap` | sortable rows, a timeline, a directory tree, an outline | |
51
+ | `mermaid`, `diff` | a diagram you can comment on, a coloured diff | |
103
52
 
104
- The [reference](https://github.com/wayne930242/pi-better-show/blob/main/docs/reference.md) covers every block's schema, these APIs, theming tokens, and the extension's event bus.
53
+ HTML and TSX pages, the `pbs-tree` CLI, the library entries, and every schema are in the [documentation](https://wayne930242.github.io/pi-better-show/reference/blocks/).
105
54
 
106
- ## Development
55
+ ## Develop
107
56
 
108
57
  ```bash
109
58
  bun install
110
59
  bun test
111
60
  bun run check # tsc, tsc for core without node types, biome
112
- bun run demo # examples/elements.html on http://127.0.0.1:4177/
113
- bun run show # the show_doc page server on examples/, with a fake pi that prints each message
61
+ bun run demo # every element, on http://127.0.0.1:4177/
62
+ cd site && npm ci && npm run check && npm run build # the documentation site
114
63
  ```
115
64
 
116
65
  ## License
@@ -0,0 +1,67 @@
1
+ # pi-better-show
2
+
3
+ [English](README.md)
4
+
5
+ **讓你的 [pi](https://github.com/earendil-works/pi) agent 給你一個頁面,而不是一大堆文字,你點一點就能回答。**
6
+
7
+ **[文件](https://wayne930242.github.io/pi-better-show/zh-tw/)** 有繁體中文與 [English](https://wayne930242.github.io/pi-better-show/) 兩種版本:概念、每一種區塊、agent 頁面與函式庫。
8
+
9
+ ![決策頁:一個 alert、兩個選項與一份表單](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/decide.png)
10
+
11
+ ## 為什麼
12
+
13
+ - **寫區塊,不寫標記。** agent 每個區塊只寫幾行 YAML;版面、控制項,以及把答案送回去的程式碼,都由套件負責。
14
+ - **答案以訊息送回。** 一次挑選、一份表單、對段落或圖上節點的留言:一則固定格式的訊息。
15
+ - **省下約 10 倍 token**,相較於把同樣的頁面寫成 HTML(實測 1,253 對 12,364 個輸出 token)。
16
+ - **每個宿主共用一套詞彙。** Core、自訂元素與 React 包裝共用同一個剖析器、同一套純文字備援與同一種答案編碼。
17
+
18
+ ## 安裝
19
+
20
+ ```bash
21
+ pi install npm:pi-better-show
22
+ ```
23
+
24
+ 接著在執行中的 session 裡 `/reload`。如果你用 `pi-herdr-doc-review`,請先移除它(`pi uninstall npm:pi-herdr-doc-review`):兩者都註冊 `show_doc`。
25
+
26
+ ## 快速開始
27
+
28
+ 請 agent 給你看點東西。它會寫一個帶區塊的 Markdown 檔並呼叫 `show_doc({paths, reason, view})`,呼叫會立刻回傳:
29
+
30
+ - `view: "page"` 在瀏覽器開啟檔案;選取一段文字,或點圖上的節點,就能留言。
31
+ - `view: "edit"`(預設)在你的編輯器開啟;你的儲存會以每個檔案一份淨 diff 送到 agent。
32
+
33
+ 你在表單按下 **Send**,agent 收到:
34
+
35
+ ```text
36
+ User submitted a form in the HTML review pane:
37
+ - ttl: week
38
+ - extras: WAL mode, Nightly backup
39
+ ```
40
+
41
+ ## 區塊
42
+
43
+ | 種類 | 顯示 | 你的回答方式 |
44
+ |---|---|---|
45
+ | `alert`、`cards`、`stats` | 帶語氣的提示與方塊 | |
46
+ | `options` | 附優缺點的選項 | 挑一個 |
47
+ | `form` | 單選、多選與文字問題 | Send |
48
+ | `review` | 要比較的設計或原型 | 留言、挑選 |
49
+ | `checklist`、`suggest` | 要勾選的項目、快速回覆 chip | Send、點擊 |
50
+ | `table`、`steps`、`tree`、`mindmap` | 可排序的列、時間軸、目錄樹、大綱 | |
51
+ | `mermaid`、`diff` | 可以留言的圖、上色的 diff | |
52
+
53
+ HTML 與 TSX 頁面、`pbs-tree` CLI、函式庫進入點與每個 schema 都在[文件](https://wayne930242.github.io/pi-better-show/zh-tw/reference/blocks/)裡。
54
+
55
+ ## 開發
56
+
57
+ ```bash
58
+ bun install
59
+ bun test
60
+ bun run check # tsc, tsc for core without node types, biome
61
+ bun run demo # every element, on http://127.0.0.1:4177/
62
+ cd site && npm ci && npm run check && npm run build # the documentation site
63
+ ```
64
+
65
+ ## 授權
66
+
67
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
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",
@@ -3,11 +3,36 @@ import type { Locale, Strings } from "./strings.ts";
3
3
  /** Which colour scheme a diagram is drawn for. */
4
4
  export type Scheme = "light" | "dark";
5
5
 
6
+ /** A shape of a diagram element's hit area, in the diagram's own coordinates; only geometry attributes are carried. */
7
+ export interface DiagramShape {
8
+ tag: "rect" | "circle" | "ellipse" | "polygon" | "polyline" | "path";
9
+ attrs: Record<string, string>;
10
+ }
11
+
12
+ /** Something in a diagram a reader can point at, in the diagram's own words (`text`: a label, or `from → to "label"`). */
13
+ export interface DiagramTarget {
14
+ kind: "node" | "edge" | "group";
15
+ text: string;
16
+ shapes: DiagramShape[];
17
+ }
18
+
19
+ /** The pointable parts of one drawn diagram; `viewBox` is the drawing's, so shapes overlay the image exactly. */
20
+ export interface DiagramMap {
21
+ viewBox: string;
22
+ targets: DiagramTarget[];
23
+ }
24
+
6
25
  export interface Configuration {
7
26
  /** Overrides for single words, per locale. */
8
27
  strings: Partial<Record<Locale, Partial<Strings>>>;
9
28
  /** The image URL of a diagram, which the host serves (`mermaidSvg` from `pi-better-show/server`); `undefined` shows the source. */
10
29
  diagramUrl: ((source: string, scheme: Scheme) => string | undefined) | undefined;
30
+ /**
31
+ * Reads the pointable nodes and edges of the diagram image at the URL `diagramUrl` gave (the host fetches and parses
32
+ * it: elements never parse markup). When set, a diagram's elements become buttons over the image that dispatch
33
+ * `pbs-diagram-target` with `{kind, text}`. `undefined` leaves the diagram a plain image.
34
+ */
35
+ diagramMap: ((url: string) => Promise<DiagramMap | undefined>) | undefined;
11
36
  /** Turns a review item's `image` into a URL the page may load; `undefined` shows a placeholder. */
12
37
  imageUrl: (ref: string) => string | undefined;
13
38
  /** Turns a review item's `page` into a URL for a sandboxed frame; `undefined` shows the reference as text. */
@@ -22,7 +47,7 @@ let current: Configuration = initial();
22
47
  const listeners = new Set<() => void>();
23
48
 
24
49
  function initial(): Configuration {
25
- return { strings: {}, diagramUrl: undefined, imageUrl: defaultImageUrl, pageUrl: undefined };
50
+ return { strings: {}, diagramUrl: undefined, diagramMap: undefined, imageUrl: defaultImageUrl, pageUrl: undefined };
26
51
  }
27
52
 
28
53
  export const configuration = (): Configuration => current;
@@ -45,6 +70,7 @@ export function configure(options: Partial<Configuration>): void {
45
70
  current = {
46
71
  strings,
47
72
  diagramUrl: "diagramUrl" in options ? options.diagramUrl : current.diagramUrl,
73
+ diagramMap: "diagramMap" in options ? options.diagramMap : current.diagramMap,
48
74
  imageUrl: "imageUrl" in options ? (options.imageUrl ?? defaultImageUrl) : current.imageUrl,
49
75
  pageUrl: "pageUrl" in options ? options.pageUrl : current.pageUrl,
50
76
  };
@@ -1,7 +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
- import { configuration } from "./config.ts";
4
- import { h, inlineNodes, prose } from "./dom.ts";
3
+ import { configuration, type DiagramMap, type DiagramTarget } from "./config.ts";
4
+ import { h, inlineNodes, prose, svg } from "./dom.ts";
5
5
  import type { Strings } from "./strings.ts";
6
6
 
7
7
  /** The blocks that only show: callout, cards, steps, stats, diff, diagram. */
@@ -45,6 +45,19 @@ const displayCss = `
45
45
 
46
46
  .diagram { margin: 0; text-align: center; overflow: auto; }
47
47
  .diagram img { display: block; max-width: 100%; height: auto; margin: 0 auto; }
48
+ .diagram .frame { position: relative; width: fit-content; max-width: 100%; margin: 0 auto; }
49
+ .diagram .targets { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
50
+ .targets .hit { cursor: pointer; outline: none; }
51
+ .targets .hit > * {
52
+ fill: transparent; stroke: transparent; stroke-width: 1px; vector-effect: non-scaling-stroke; pointer-events: all;
53
+ }
54
+ .targets .hit > polyline { fill: none; stroke-width: 8px; stroke-linecap: round; stroke-linejoin: round; }
55
+ .targets .hit:hover > *, .targets .hit:focus-visible > * {
56
+ fill: color-mix(in srgb, var(--_accent) 14%, transparent);
57
+ stroke: color-mix(in srgb, var(--_accent) 60%, transparent);
58
+ stroke-width: 2px;
59
+ }
60
+ .targets .hit:hover > polyline, .targets .hit:focus-visible > polyline { fill: none; stroke-width: 8px; }
48
61
  .diagram details { margin-top: 0.6rem; text-align: left; }
49
62
  .diagram summary { cursor: pointer; color: var(--_muted); font-size: 0.9em; }
50
63
  .diagram pre { margin-top: 0.4rem; padding: var(--_pad); background: var(--_surface); border-radius: var(--_radius); }
@@ -258,12 +271,99 @@ export class PbsDiagram extends PbsElement<MermaidData> {
258
271
  this.#failed = url;
259
272
  this.refresh();
260
273
  });
261
- figure.append(image, h("details", { part: "source" }, h("summary", null, this.t("diagramSource")), source));
274
+ const frame = h("div", { class: "frame" }, image);
275
+ this.#addTargets(frame, url);
276
+ figure.append(frame, h("details", { part: "source" }, h("summary", null, this.t("diagramSource")), source));
262
277
  } else {
263
278
  figure.append(h("p", { part: "note", class: "muted note" }, this.t("diagramFallback")), source);
264
279
  }
265
280
  return figure;
266
281
  }
282
+
283
+ /**
284
+ * When the host can read the drawing (`diagramMap`), lays its nodes and edges over the image as buttons: a click, or
285
+ * Enter or Space on a focused one, dispatches `pbs-diagram-target` with the element in the diagram's own words.
286
+ * The diagram is one tab stop; arrow keys move through its elements in the map's order (Home and End jump).
287
+ * The overlay arrives after the image; a diagram the host cannot read stays a plain image.
288
+ */
289
+ #addTargets(frame: HTMLElement, url: string): void {
290
+ const read = configuration().diagramMap;
291
+ if (!read) return;
292
+ // A host that throws, or answers without a promise, must not break the drawing.
293
+ Promise.resolve()
294
+ .then(() => read(url))
295
+ .then(
296
+ (map) => {
297
+ // A redraw replaced this frame while the map was loading.
298
+ if (map && frame.isConnected) frame.append(this.#overlay(map));
299
+ },
300
+ (error: unknown) => console.warn("pbs-diagram: the diagram's elements cannot be commented on:", error),
301
+ );
302
+ }
303
+
304
+ #overlay(map: DiagramMap): SVGElement {
305
+ const words: Record<DiagramTarget["kind"], string> = {
306
+ node: this.t("diagramNode"),
307
+ edge: this.t("diagramEdge"),
308
+ group: this.t("diagramGroup"),
309
+ };
310
+ // Dispatched from the button itself, so a host that moves focus away can find its way back (`composedPath()[0]`).
311
+ const pick = (hit: Element, target: DiagramTarget): void => {
312
+ hit.dispatchEvent(
313
+ new CustomEvent("pbs-diagram-target", {
314
+ bubbles: true,
315
+ composed: true,
316
+ detail: { kind: target.kind, text: target.text },
317
+ }),
318
+ );
319
+ };
320
+ const hits = map.targets.map((target, index) =>
321
+ svg(
322
+ "g",
323
+ {
324
+ class: "hit",
325
+ role: "button",
326
+ tabindex: index === 0 ? 0 : -1,
327
+ "data-kind": target.kind,
328
+ "aria-label": this.t("diagramComment", { kind: words[target.kind], text: target.text }),
329
+ },
330
+ ...target.shapes.map((shape) => svg(shape.tag, shape.attrs)),
331
+ ),
332
+ );
333
+ const moves: Record<string, (at: number) => number> = {
334
+ ArrowDown: (at) => at + 1,
335
+ ArrowRight: (at) => at + 1,
336
+ ArrowUp: (at) => at - 1,
337
+ ArrowLeft: (at) => at - 1,
338
+ Home: () => 0,
339
+ End: () => hits.length - 1,
340
+ };
341
+ for (const [index, hit] of hits.entries()) {
342
+ const target = map.targets[index] as DiagramTarget;
343
+ // The one tab stop is where the reader last was.
344
+ hit.addEventListener("focus", () => {
345
+ for (const other of hits) other.setAttribute("tabindex", other === hit ? "0" : "-1");
346
+ });
347
+ hit.addEventListener("click", () => pick(hit, target));
348
+ hit.addEventListener("keydown", (event) => {
349
+ const move = moves[event.key];
350
+ if (move) {
351
+ event.preventDefault();
352
+ (hits[Math.min(hits.length - 1, Math.max(0, move(index)))] as SVGElement | undefined)?.focus();
353
+ } else if (event.key === "Enter" || event.key === " ") {
354
+ event.preventDefault();
355
+ pick(hit, target);
356
+ }
357
+ });
358
+ }
359
+ // Later buttons sit above earlier ones: groups below edges below nodes, so a node inside a group is the node.
360
+ const layers: DiagramTarget["kind"][] = ["group", "edge", "node"];
361
+ return svg(
362
+ "svg",
363
+ { class: "targets", viewBox: map.viewBox, role: "group", "aria-label": this.t("diagram") },
364
+ ...layers.flatMap((kind) => hits.filter((_, index) => map.targets[index]?.kind === kind)),
365
+ );
366
+ }
267
367
  }
268
368
 
269
369
  export function defineDisplay(): void {
@@ -29,6 +29,19 @@ export function h(tag: string, props?: Props | null, ...children: Child[]): HTML
29
29
  return node;
30
30
  }
31
31
 
32
+ const SVG_NS = "http://www.w3.org/2000/svg";
33
+
34
+ /** An SVG element built from attribute values only (geometry, classes, labels), never from markup. */
35
+ export function svg(tag: string, props?: Props | null, ...children: (SVGElement | null)[]): SVGElement {
36
+ const node = document.createElementNS(SVG_NS, tag);
37
+ for (const [name, value] of Object.entries(props ?? {})) {
38
+ if (value === undefined || value === null || value === false) continue;
39
+ node.setAttribute(name, value === true ? "" : String(value));
40
+ }
41
+ for (const child of children) if (child) node.append(child);
42
+ return node;
43
+ }
44
+
32
45
  export function append(parent: ParentNode, children: Child[]): void {
33
46
  for (const child of children) {
34
47
  if (child === null || child === undefined || child === false) continue;
@@ -16,7 +16,7 @@ import { defineTree } from "./tree.ts";
16
16
  export type { AnsweredFields, BlockRef, Density } from "./base.ts";
17
17
  export { PbsElement } from "./base.ts";
18
18
  export { PbsChecklist, PbsOptions, PbsSuggest } from "./choice.ts";
19
- export type { Configuration, Scheme } from "./config.ts";
19
+ export type { Configuration, DiagramMap, DiagramShape, DiagramTarget, Scheme } from "./config.ts";
20
20
  export { configure, resetConfiguration } from "./config.ts";
21
21
  export { PbsCallout, PbsCards, PbsDiagram, PbsDiff, PbsStats, PbsSteps } from "./display.ts";
22
22
  export { PbsForm } from "./form.ts";
@@ -37,6 +37,10 @@ export interface Strings {
37
37
  diagram: string;
38
38
  diagramSource: string;
39
39
  diagramFallback: string;
40
+ diagramComment: string;
41
+ diagramNode: string;
42
+ diagramEdge: string;
43
+ diagramGroup: string;
40
44
  diff: string;
41
45
  table: string;
42
46
  mindmap: string;
@@ -90,6 +94,10 @@ export const STRINGS: Record<Locale, Strings> = {
90
94
  diagram: "Diagram",
91
95
  diagramSource: "Source",
92
96
  diagramFallback: "The diagram is not available here; its source is shown instead.",
97
+ diagramComment: "Comment on {kind}: {text}",
98
+ diagramNode: "node",
99
+ diagramEdge: "edge",
100
+ diagramGroup: "group",
93
101
  diff: "Diff",
94
102
  table: "Table",
95
103
  mindmap: "Mind map",
@@ -140,6 +148,10 @@ export const STRINGS: Record<Locale, Strings> = {
140
148
  diagram: "圖表",
141
149
  diagramSource: "原始碼",
142
150
  diagramFallback: "這裡無法顯示圖表,改為顯示原始碼。",
151
+ diagramComment: "針對{kind}留言:{text}",
152
+ diagramNode: "節點",
153
+ diagramEdge: "連線",
154
+ diagramGroup: "群組",
143
155
  diff: "差異",
144
156
  table: "表格",
145
157
  mindmap: "心智圖",
@@ -0,0 +1,341 @@
1
+ import type { DiagramMap, DiagramShape, DiagramTarget } from "../../elements/index.ts";
2
+
3
+ /**
4
+ * Reads what a reader can point at in a diagram drawn by `mermaidSvg` (beautiful-mermaid): flowchart and state
5
+ * diagram nodes, edges, and subgraphs, each named in the diagram's own words. The drawing carries them as
6
+ * `data-id`, `data-label`, `data-from`, and `data-to` on `g.node`, `.edge`, `g.edge-label`, and `g.subgraph`; a diagram
7
+ * type without them yields no targets and stays a plain image.
8
+ */
9
+
10
+ const SHAPES = new Set<DiagramShape["tag"]>(["rect", "circle", "ellipse", "polygon", "polyline", "path"]);
11
+ /** Only geometry is carried over; paint, classes, and anything else from the drawing stay behind. */
12
+ const GEOMETRY = new Set(["x", "y", "width", "height", "rx", "ry", "cx", "cy", "r", "points", "d"]);
13
+
14
+ const ENTITIES: Record<string, string> = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'", nbsp: " " };
15
+
16
+ /** Mermaid writes a character as `#quot;` or `#35;` in a label; the drawing keeps the code, a reader means the character. */
17
+ function decoded(text: string): string {
18
+ return text.replace(/#(\w+);/g, (code, name: string) => {
19
+ const point = /^\d+$/.test(name) ? Number(name) : undefined;
20
+ if (point === undefined) return ENTITIES[name] ?? code;
21
+ return point > 0 && point <= 0x10ffff ? String.fromCodePoint(point) : code;
22
+ });
23
+ }
24
+
25
+ const words = (value: string | null): string => decoded((value ?? "").replace(/\s+/g, " ").trim());
26
+
27
+ function shapeOf(element: Element): DiagramShape | undefined {
28
+ const tag = element.localName as DiagramShape["tag"];
29
+ if (!SHAPES.has(tag)) return undefined;
30
+ const attrs: Record<string, string> = {};
31
+ for (const name of GEOMETRY) {
32
+ const value = element.getAttribute(name);
33
+ if (value !== null) attrs[name] = value;
34
+ }
35
+ return { tag, attrs };
36
+ }
37
+
38
+ /** The shapes drawn directly inside a `g`. */
39
+ const shapesIn = (group: Element): DiagramShape[] =>
40
+ [...group.children].map(shapeOf).filter((shape) => shape !== undefined);
41
+
42
+ /** A state diagram's `[*]`: the renderer draws it unlabelled, as a `state-start` or `state-end` shape. */
43
+ function markOf(node: Element): "start" | "end" | undefined {
44
+ const shape = node.getAttribute("data-shape");
45
+ return shape === "state-start" ? "start" : shape === "state-end" ? "end" : undefined;
46
+ }
47
+
48
+ /** The label a node or group is known by: its own, `start` or `end` for a `[*]`, or else its id. */
49
+ const labelOf = (node: Element): string =>
50
+ words(node.getAttribute("data-label")) || markOf(node) || words(node.getAttribute("data-id"));
51
+
52
+ const idOf = (element: Element): string => element.getAttribute("data-id") ?? "";
53
+
54
+ /** The box a group draws, in the image's own coordinates. */
55
+ function boxOf(group: Element): { x: number; y: number; width: number; height: number } | undefined {
56
+ const box = [...group.children].find((child) => child.localName === "rect");
57
+ if (!box) return undefined;
58
+ const [x, y, width, height] = ["x", "y", "width", "height"].map((name) => Number(box.getAttribute(name)));
59
+ if (x === undefined || y === undefined || width === undefined || height === undefined) return undefined;
60
+ return [x, y, width, height].every(Number.isFinite) ? { x, y, width, height } : undefined;
61
+ }
62
+
63
+ /** Where a node is drawn: the centre of its first shape. */
64
+ function centreOf(node: Element): { x: number; y: number } | undefined {
65
+ const shape = node.children[0];
66
+ if (!shape) return undefined;
67
+ const at = (name: string): number | undefined => {
68
+ const value = shape.getAttribute(name);
69
+ return value === null || value === "" ? undefined : Number(value);
70
+ };
71
+ const [cx, cy, x, y, width, height] = ["cx", "cy", "x", "y", "width", "height"].map(at);
72
+ if (cx !== undefined && cy !== undefined) return { x: cx, y: cy };
73
+ if (x !== undefined && y !== undefined) return { x: x + (width ?? 0) / 2, y: y + (height ?? 0) / 2 };
74
+ return undefined;
75
+ }
76
+
77
+ /**
78
+ * The innermost group that draws around `node`, if any. The drawing is flat (a state diagram's inner `[*]` is not
79
+ * nested in its composite state), so containment is read from the geometry.
80
+ */
81
+ function enclosing(groups: Element[], node: Element): Element | undefined {
82
+ const at = centreOf(node);
83
+ if (!at) return undefined;
84
+ let best: { group: Element; area: number } | undefined;
85
+ for (const group of groups) {
86
+ const box = boxOf(group);
87
+ if (!box || at.x < box.x || at.x > box.x + box.width || at.y < box.y || at.y > box.y + box.height) continue;
88
+ const area = box.width * box.height;
89
+ if (!best || area < best.area) best = { group, area };
90
+ }
91
+ return best?.group;
92
+ }
93
+
94
+ /**
95
+ * A target before it is told apart: `tag` is what it adds when another target reads alike (`Check (B)`), `id` the
96
+ * drawing's id of the node or group it is.
97
+ */
98
+ type Draft = DiagramTarget & { tag: string; id?: string };
99
+
100
+ /**
101
+ * Makes every target's text unique among `targets` (one kind), so one quote names one element. Only a text that more
102
+ * 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`).
105
+ */
106
+ function disambiguated(targets: Draft[]): DiagramTarget[] {
107
+ const count = (list: DiagramTarget[]): Map<string, number> => {
108
+ const seen = new Map<string, number>();
109
+ for (const target of list) seen.set(target.text, (seen.get(target.text) ?? 0) + 1);
110
+ return seen;
111
+ };
112
+ const first = count(targets);
113
+ // A tag only helps where it differs between the targets that share a text.
114
+ const tags = new Map<string, Set<string>>();
115
+ for (const target of targets) tags.set(target.text, (tags.get(target.text) ?? new Set()).add(target.tag));
116
+ const named = targets.map(({ tag, id: _id, ...target }) =>
117
+ tag && (first.get(target.text) ?? 0) > 1 && (tags.get(target.text)?.size ?? 0) > 1
118
+ ? { ...target, text: `${target.text} (${tag})` }
119
+ : target,
120
+ );
121
+ const second = count(named);
122
+ const taken = new Set(named.filter((target) => (second.get(target.text) ?? 0) < 2).map((target) => target.text));
123
+ const next = new Map<string, number>();
124
+ return named.map((target) => {
125
+ 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}`));
129
+ next.set(target.text, ordinal);
130
+ taken.add(`${target.text} #${ordinal}`);
131
+ return { ...target, text: `${target.text} #${ordinal}` };
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Tells apart the nodes or the groups, and records each one's final name and tag by id: later targets (a `[*]`'s
137
+ * composite state, an edge's ends) are named by them. A target with no text or shape is left out.
138
+ */
139
+ function settle(drafts: Draft[], names: Map<string, string>, tags: Map<string, string>): DiagramTarget[] {
140
+ for (const draft of drafts) {
141
+ names.set(draft.id ?? "", draft.text);
142
+ tags.set(draft.id ?? "", draft.tag);
143
+ }
144
+ const kept = drafts.filter((draft) => draft.text && draft.shapes.length > 0);
145
+ const targets = disambiguated(kept);
146
+ for (const [index, draft] of kept.entries()) names.set(draft.id ?? "", targets[index]?.text ?? draft.text);
147
+ return targets;
148
+ }
149
+
150
+ /** The points a shape's geometry spans, in the image's coordinates. */
151
+ function pointsOf({ tag, attrs }: DiagramShape): [number, number][] {
152
+ const at = (name: string): number => Number(attrs[name]);
153
+ const box = (x: number, y: number, rx: number, ry: number): [number, number][] => [
154
+ [x - rx, y - ry],
155
+ [x + rx, y + ry],
156
+ ];
157
+ if (tag === "rect")
158
+ return [
159
+ [at("x"), at("y")],
160
+ [at("x") + at("width"), at("y") + at("height")],
161
+ ];
162
+ if (tag === "circle") return box(at("cx"), at("cy"), at("r"), at("r"));
163
+ if (tag === "ellipse") return box(at("cx"), at("cy"), at("rx"), at("ry"));
164
+ // A polygon's or polyline's points; a path's coordinates, near enough to place it.
165
+ const values = (attrs.points ?? attrs.d ?? "").match(/-?\d*\.?\d+(?:e-?\d+)?/gi)?.map(Number) ?? [];
166
+ return values.flatMap((x, index) =>
167
+ index % 2 === 0 ? [[x, values[index + 1] ?? Number.NaN] as [number, number]] : [],
168
+ );
169
+ }
170
+
171
+ /**
172
+ * The targets in reading order, the order arrow keys move through them: along the flow (down, or across in a chart
173
+ * whose edges run more across than down), then across it, so an edge comes between the elements it joins.
174
+ */
175
+ function inReadingOrder(targets: DiagramTarget[]): DiagramTarget[] {
176
+ let across = 0;
177
+ let down = 0;
178
+ for (const target of targets) {
179
+ const line = target.kind === "edge" && target.shapes[0] ? pointsOf(target.shapes[0]) : [];
180
+ const [first, last] = [line[0], line.at(-1)];
181
+ if (!first || !last) continue;
182
+ across += Math.abs(last[0] - first[0]);
183
+ down += Math.abs(last[1] - first[1]);
184
+ }
185
+ const [along, side] = across > down ? [0, 1] : [1, 0];
186
+ const placed = targets.map((target, index) => {
187
+ const points = target.shapes.flatMap(pointsOf).filter((point) => point.every(Number.isFinite));
188
+ const centre = [0, 1].map((axis) => {
189
+ const values = points.map((point) => point[axis] ?? 0);
190
+ return (Math.min(...values) + Math.max(...values)) / 2;
191
+ });
192
+ return { target, index, centre: points.length > 0 ? centre : undefined };
193
+ });
194
+ // Within half a unit is the same rank: the layout's own arithmetic leaves crumbs.
195
+ const compare = (a: number[], b: number[], axis: number): number =>
196
+ Math.abs((a[axis] ?? 0) - (b[axis] ?? 0)) < 0.5 ? 0 : (a[axis] ?? 0) - (b[axis] ?? 0);
197
+ return placed
198
+ .sort((a, b) => {
199
+ if (!a.centre || !b.centre) return (a.centre ? -1 : b.centre ? 1 : 0) || a.index - b.index;
200
+ return compare(a.centre, b.centre, along) || compare(a.centre, b.centre, side) || a.index - b.index;
201
+ })
202
+ .map(({ target }) => target);
203
+ }
204
+
205
+ /**
206
+ * What a reader can point at in the drawing, each named in the diagram's own words and unique within its kind. Groups
207
+ * are named first, then nodes (a `[*]` among several is scoped by the composite state around it: `start (in Active)`),
208
+ * then edges by the names of their ends, so an edge says which `Check` it starts from. Renderer ids never show: a `[*]`
209
+ * that reads like another node adds `([*])`.
210
+ */
211
+ export function diagramMap(svg: Element): DiagramMap | undefined {
212
+ const viewBox = svg.getAttribute("viewBox");
213
+ if (!viewBox) return undefined;
214
+ /** Each node's and group's name, and the tag that tells it apart, by id: what an edge is named by. */
215
+ const names = new Map<string, string>();
216
+ const tags = new Map<string, string>();
217
+
218
+ const groupElements = [...svg.querySelectorAll("g.subgraph")];
219
+ const groups = settle(
220
+ groupElements.map((group) => {
221
+ const [box, header] = shapesIn(group);
222
+ // The header strip only: the whole box would cover the nodes inside it.
223
+ const shapes = [header ?? box].filter((shape) => shape !== undefined);
224
+ return { kind: "group", text: labelOf(group), tag: idOf(group), id: idOf(group), shapes };
225
+ }),
226
+ names,
227
+ tags,
228
+ );
229
+
230
+ const nodeElements = [...svg.querySelectorAll("g.node")];
231
+ const several = (mark: string): boolean => nodeElements.filter((node) => markOf(node) === mark).length > 1;
232
+ const scoped = nodeElements.map((node) => {
233
+ const mark = markOf(node);
234
+ if (!mark) return labelOf(node);
235
+ const around = several(mark) ? enclosing(groupElements, node) : undefined;
236
+ return around ? `${mark} (in ${names.get(idOf(around))})` : mark;
237
+ });
238
+ const labels = new Set(nodeElements.filter((node) => !markOf(node)).map(labelOf));
239
+ const nodes = settle(
240
+ nodeElements.map((node, index) => {
241
+ const text = scoped[index] ?? "";
242
+ const mark = markOf(node) !== undefined;
243
+ return {
244
+ kind: "node",
245
+ text: mark && labels.has(text) ? `${text} ([*])` : text,
246
+ tag: mark ? "[*]" : idOf(node),
247
+ id: idOf(node),
248
+ shapes: shapesIn(node),
249
+ };
250
+ }),
251
+ names,
252
+ tags,
253
+ );
254
+
255
+ const name = (id: string | null): string => names.get(id ?? "") || words(id);
256
+ const tag = (id: string | null): string => tags.get(id ?? "") || words(id);
257
+ const boxes = [...svg.querySelectorAll("g.edge-label")];
258
+ const edges: Draft[] = [];
259
+ for (const edge of svg.querySelectorAll(".edge")) {
260
+ const from = edge.getAttribute("data-from");
261
+ const to = edge.getAttribute("data-to");
262
+ const label = words(edge.getAttribute("data-label"));
263
+ const shapes = [shapeOf(edge)].filter((shape) => shape !== undefined);
264
+ if (label) {
265
+ // The box that carries the label belongs to the edge too; parallel edges each take their own.
266
+ const at = boxes.findIndex(
267
+ (box) =>
268
+ box.getAttribute("data-from") === from &&
269
+ box.getAttribute("data-to") === to &&
270
+ words(box.getAttribute("data-label")) === label,
271
+ );
272
+ const [box] = at === -1 ? [] : boxes.splice(at, 1);
273
+ if (box) shapes.push(...shapesIn(box).filter((shape) => shape.tag === "rect"));
274
+ }
275
+ if (shapes.length === 0) continue;
276
+ edges.push({
277
+ kind: "edge",
278
+ text: `${name(from)} → ${name(to)}${label ? ` "${label}"` : ""}`,
279
+ tag: `${tag(from)} → ${tag(to)}`,
280
+ shapes,
281
+ });
282
+ }
283
+
284
+ const targets = inReadingOrder([...groups, ...disambiguated(edges), ...nodes]);
285
+ return targets.length > 0 ? { viewBox, targets } : undefined;
286
+ }
287
+
288
+ /** The map of the diagram image at `url`: fetched from the page's own server and read as SVG. */
289
+ export async function fetchDiagramMap(url: string): Promise<DiagramMap | undefined> {
290
+ const response = await fetch(url);
291
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
292
+ const doc = new DOMParser().parseFromString(await response.text(), "image/svg+xml");
293
+ return doc.querySelector("parsererror") ? undefined : diagramMap(doc.documentElement);
294
+ }
295
+
296
+ /** The first word of a diagram's source after front matter and comments: `flowchart`, `stateDiagram-v2`, … */
297
+ function diagramType(source: string): string {
298
+ const body = source.replace(/^\s*---[\s\S]*?\n---\s*\n/, "");
299
+ const line = body.split("\n").find((text) => text.trim() !== "" && !text.trim().startsWith("%%"));
300
+ return line?.trim().split(/\s+/)[0] ?? "diagram";
301
+ }
302
+
303
+ /**
304
+ * The quote a diagram element goes into the feedback panel under: which diagram on the page (its position among the
305
+ * page's diagrams, and its type), then the element: `[Diagram 2, stateDiagram-v2] edge: Paid → Refunded "money back"`.
306
+ * Part of the message the agent reads; keep it stable.
307
+ */
308
+ export function diagramQuote(diagram: Element, target: { kind: string; text: string }): string {
309
+ const position = [...document.querySelectorAll("pbs-diagram")].indexOf(diagram) + 1;
310
+ return `[Diagram ${position}, ${diagramType(sourceOf(diagram))}] ${target.kind}: ${target.text}`;
311
+ }
312
+
313
+ const sourceOf = (diagram: Element): string => (diagram as Element & { data?: { source?: string } }).data?.source ?? "";
314
+
315
+ /**
316
+ * What finds a diagram again when the page reloads after an agent's edit, which may add or remove diagrams before it:
317
+ * its source, and which of the page's diagrams drawn from that source it is.
318
+ */
319
+ export function diagramRef(diagram: Element): string {
320
+ const source = sourceOf(diagram);
321
+ const alike = [...document.querySelectorAll("pbs-diagram")].filter((other) => sourceOf(other) === source);
322
+ return JSON.stringify([source, alike.indexOf(diagram)]);
323
+ }
324
+
325
+ /**
326
+ * 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.
328
+ */
329
+ export function requoteDiagram(quote: string, ref: string): string {
330
+ let found: Element | undefined;
331
+ try {
332
+ const [source, nth] = JSON.parse(ref) as [unknown, unknown];
333
+ const alike = [...document.querySelectorAll("pbs-diagram")].filter((other) => sourceOf(other) === source);
334
+ found = typeof nth === "number" ? alike[nth] : undefined;
335
+ } catch {
336
+ // A ref that cannot be read leaves the quote as it is.
337
+ }
338
+ if (!found) return quote;
339
+ const position = [...document.querySelectorAll("pbs-diagram")].indexOf(found) + 1;
340
+ return quote.replace(/^\[Diagram \d+,/, `[Diagram ${position},`);
341
+ }
@@ -3,6 +3,8 @@ import type { Answer } from "../../core/types.ts";
3
3
  export interface FeedbackItem {
4
4
  quote: string;
5
5
  comment: string;
6
+ /** Where a quote that is not selected text came from, for `requote`; kept with the draft, never sent. */
7
+ ref?: string;
6
8
  }
7
9
 
8
10
  export interface FeedbackWords {
@@ -10,6 +12,8 @@ export interface FeedbackWords {
10
12
  comment: string;
11
13
  heading: string;
12
14
  hint: string;
15
+ /** The hint on a page whose diagrams can be commented on. */
16
+ hintDiagram: string;
13
17
  overall: string;
14
18
  send: string;
15
19
  sending: string;
@@ -25,6 +29,7 @@ const ZH: FeedbackWords = {
25
29
  comment: "留言",
26
30
  heading: "給 agent 的回饋",
27
31
  hint: "選取頁面上的文字可以針對那段留言。",
32
+ hintDiagram: "選取頁面上的文字,或點圖表裡的節點與連線,可以針對它留言。",
28
33
  overall: "整體意見",
29
34
  send: "送給 agent",
30
35
  sending: "傳送中…",
@@ -39,6 +44,7 @@ const EN: FeedbackWords = {
39
44
  comment: "Comment",
40
45
  heading: "Feedback for the agent",
41
46
  hint: "Select text on the page to comment on it.",
47
+ hintDiagram: "Select text on the page, or click a node or edge in a diagram, to comment on it.",
42
48
  overall: "Overall",
43
49
  send: "Send to agent",
44
50
  sending: "Sending…",
@@ -71,6 +77,13 @@ export interface FeedbackOptions {
71
77
  * and passes the frame's selection to `offer` instead.
72
78
  */
73
79
  watchDocument?: boolean;
80
+ /** Whether the page's diagrams can be commented on (the hint says so); a host calls `comment` for them. */
81
+ diagrams?: boolean;
82
+ /**
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.
85
+ */
86
+ requote?: (quote: string, ref: string) => string;
74
87
  }
75
88
 
76
89
  /** A passage to comment on, and where the Add button goes (viewport coordinates of the panel's document). */
@@ -98,6 +111,12 @@ const make = <K extends keyof HTMLElementTagNameMap>(
98
111
  export function mountFeedback(options: FeedbackOptions): {
99
112
  /** Offers a passage to comment on, or withdraws the offer with no text or `undefined`. */
100
113
  offer: (passage: Offered | undefined) => void;
114
+ /**
115
+ * Adds `quote` to the panel as a commented target at once and opens the panel on its comment box; for what cannot be
116
+ * selected as text (a diagram's node or edge). A target already in the panel is not added twice, only focused.
117
+ * `ref` is kept with the draft for `requote`; Escape in the panel returns focus to `back`, the control it came from.
118
+ */
119
+ comment: (quote: string, from?: { ref?: string; back?: HTMLElement | SVGElement }) => void;
101
120
  destroy: () => void;
102
121
  } {
103
122
  const { words, storage, storageKey } = options;
@@ -108,7 +127,10 @@ export function mountFeedback(options: FeedbackOptions): {
108
127
  items?: FeedbackItem[];
109
128
  overall?: string;
110
129
  } | null;
111
- items = saved?.items ?? [];
130
+ const { requote } = options;
131
+ items = (saved?.items ?? []).map((item) =>
132
+ item.ref && requote ? { ...item, quote: requote(item.quote, item.ref) } : item,
133
+ );
112
134
  overall = saved?.overall ?? "";
113
135
  } catch {
114
136
  // A draft that cannot be read is dropped.
@@ -122,7 +144,7 @@ export function mountFeedback(options: FeedbackOptions): {
122
144
  const panel = make("section", { class: "pbs-fb-panel", hidden: true });
123
145
  panel.setAttribute("aria-label", words.heading);
124
146
  const heading = make("h2", { textContent: words.heading });
125
- const hint = make("p", { class: "pbs-fb-hint", textContent: words.hint });
147
+ const hint = make("p", { class: "pbs-fb-hint", textContent: options.diagrams ? words.hintDiagram : words.hint });
126
148
  const list = make("div", { class: "pbs-fb-list" });
127
149
  const overallBox = make("textarea", { class: "pbs-fb-overall", rows: 3, value: overall });
128
150
  overallBox.setAttribute("aria-label", words.overall);
@@ -162,9 +184,17 @@ export function mountFeedback(options: FeedbackOptions): {
162
184
  overall = overallBox.value;
163
185
  save();
164
186
  });
187
+ /** Where Escape in the panel returns focus: the diagram element a comment was opened from. */
188
+ let back: HTMLElement | SVGElement | undefined;
165
189
  toggle.addEventListener("click", () => {
190
+ back = undefined;
166
191
  panel.hidden = !panel.hidden;
167
192
  });
193
+ panel.addEventListener("keydown", (event) => {
194
+ if (event.key !== "Escape" || !back?.isConnected) return;
195
+ event.preventDefault();
196
+ back.focus();
197
+ });
168
198
 
169
199
  let pending = "";
170
200
  const offer = (passage: Offered | undefined): void => {
@@ -192,18 +222,31 @@ export function mountFeedback(options: FeedbackOptions): {
192
222
  const onSelect = (): void => offer(selected());
193
223
  // The button is pressed before the click lands, which would collapse the selection; keep what was picked.
194
224
  add.addEventListener("mousedown", (event) => event.preventDefault());
225
+ const open = (index: number): void => {
226
+ panel.hidden = false;
227
+ list.querySelectorAll("textarea").item(index)?.focus();
228
+ };
229
+ const comment = (quote: string, from: { ref?: string; back?: HTMLElement | SVGElement } = {}): void => {
230
+ const { ref } = from;
231
+ back = from.back;
232
+ const known = items.findIndex((item) => item.quote === quote);
233
+ if (known === -1) {
234
+ items.push(ref ? { quote, comment: "", ref } : { quote, comment: "" });
235
+ save();
236
+ draw();
237
+ }
238
+ open(known === -1 ? items.length - 1 : known);
239
+ };
195
240
  add.addEventListener("click", () => {
196
- if (pending) items.push({ quote: pending, comment: "" });
241
+ back = undefined;
242
+ const quote = pending;
197
243
  pending = "";
198
244
  add.hidden = true;
199
245
  getSelection()?.removeAllRanges();
246
+ if (quote) items.push({ quote, comment: "" });
200
247
  save();
201
248
  draw();
202
- panel.hidden = false;
203
- list
204
- .querySelectorAll("textarea")
205
- .item(items.length - 1)
206
- ?.focus();
249
+ open(items.length - 1);
207
250
  });
208
251
  sendButton.addEventListener("click", () => {
209
252
  if (items.length === 0 && !overall.trim()) {
@@ -237,6 +280,7 @@ export function mountFeedback(options: FeedbackOptions): {
237
280
  document.body.append(root);
238
281
  return {
239
282
  offer,
283
+ comment,
240
284
  destroy: () => {
241
285
  if (watch) document.removeEventListener("selectionchange", onSelect);
242
286
  root.remove();
@@ -0,0 +1,84 @@
1
+ import type { Answer } from "../../core/types.ts";
2
+ import { diagramQuote, diagramRef, requoteDiagram } from "./diagram-map.ts";
3
+ import { type FeedbackWords, mountFeedback } from "./feedback.ts";
4
+ import type { AnswerReply } from "./host-config.ts";
5
+
6
+ export interface PageOptions {
7
+ /** The name the agent knows the page by: its title, else the file name. */
8
+ page: string;
9
+ words: FeedbackWords;
10
+ storage: Pick<Storage, "getItem" | "setItem" | "removeItem">;
11
+ storageKey: string;
12
+ /** Delivers one answer to the page server, and tells whether it was taken. */
13
+ post: (answer: Answer) => Promise<AnswerReply>;
14
+ }
15
+
16
+ /**
17
+ * The wiring of a rendered Markdown page: each block's answer goes to the page server (a refused one reopens its
18
+ * block), and the feedback panel takes selected text and the diagrams' elements.
19
+ */
20
+ export function mountPage(options: PageOptions): { destroy: () => void } {
21
+ const { words, post } = options;
22
+ const toast = (text: string): void => {
23
+ const box = document.createElement("div");
24
+ box.className = "pbs-toast";
25
+ box.setAttribute("role", "status");
26
+ box.textContent = text;
27
+ document.body.append(box);
28
+ setTimeout(() => box.remove(), 5000);
29
+ };
30
+
31
+ const onAnswer = (event: Event): void => {
32
+ const answer = (event as CustomEvent<Answer>).detail;
33
+ const element = event.target as (HTMLElement & { answered?: unknown }) | null;
34
+ post(answer).then(
35
+ (reply) => {
36
+ if (reply.accepted) return;
37
+ // A pick locks itself once taken; clearing `answered` reopens it so the user can try again.
38
+ if (element) element.answered = undefined;
39
+ toast(`${words.notSent}${reply.reason ?? "refused"}`);
40
+ },
41
+ (error: unknown) => {
42
+ if (element) element.answered = undefined;
43
+ toast(`${words.notSent}${error instanceof Error ? error.message : String(error)}`);
44
+ },
45
+ );
46
+ };
47
+
48
+ const feedback = mountFeedback({
49
+ page: options.page,
50
+ words,
51
+ diagrams: true,
52
+ requote: requoteDiagram,
53
+ storage: options.storage,
54
+ storageKey: options.storageKey,
55
+ send: async (answer) => {
56
+ const reply = await post(answer);
57
+ if (!reply.accepted) throw new Error(reply.reason ?? "refused");
58
+ },
59
+ });
60
+
61
+ const onDiagramTarget = (event: Event): void => {
62
+ const target = (event as CustomEvent<{ kind: string; text: string }>).detail;
63
+ // The path runs from the element's own button, inside the diagram's shadow tree, out through the diagram.
64
+ const path = event.composedPath();
65
+ const diagram = path.find((node) => node instanceof Element && node.localName === "pbs-diagram");
66
+ if (!(diagram instanceof Element)) return;
67
+ const [button] = path;
68
+ feedback.comment(diagramQuote(diagram, target), {
69
+ ref: diagramRef(diagram),
70
+ // Escape in the panel returns there.
71
+ back: button instanceof HTMLElement || button instanceof SVGElement ? button : undefined,
72
+ });
73
+ };
74
+
75
+ document.addEventListener("pbs-answer", onAnswer);
76
+ document.addEventListener("pbs-diagram-target", onDiagramTarget);
77
+ return {
78
+ destroy: () => {
79
+ document.removeEventListener("pbs-answer", onAnswer);
80
+ document.removeEventListener("pbs-diagram-target", onDiagramTarget);
81
+ feedback.destroy();
82
+ },
83
+ };
84
+ }
@@ -1,7 +1,10 @@
1
1
  import type { Answer } from "../../core/types.ts";
2
2
  import "../../elements/index.ts";
3
- import { mountFeedback, wordsFor } from "./feedback.ts";
4
- import { type AnswerReply, configureElements, newAnswerId, postAnswerToServer, serverPrefix } from "./host-config.ts";
3
+ import { configure } from "../../elements/index.ts";
4
+ import { fetchDiagramMap } from "./diagram-map.ts";
5
+ import { wordsFor } from "./feedback.ts";
6
+ import { configureElements, newAnswerId, postAnswerToServer, serverPrefix } from "./host-config.ts";
7
+ import { mountPage } from "./markdown-page.ts";
5
8
 
6
9
  /**
7
10
  * The script of a rendered Markdown page: wires the elements to the page server (diagrams, images, answers),
@@ -10,48 +13,16 @@ import { type AnswerReply, configureElements, newAnswerId, postAnswerToServer, s
10
13
 
11
14
  const prefix = serverPrefix();
12
15
  configureElements(prefix);
16
+ // A diagram's nodes and edges can be commented on, not only selected text.
17
+ configure({ diagramMap: fetchDiagramMap });
13
18
 
14
- const postAnswer = (answer: Answer): Promise<AnswerReply> =>
15
- postAnswerToServer(`${prefix}/answer`, { answerId: newAnswerId(), answer, page: location.pathname });
16
-
17
- const toast = (text: string): void => {
18
- const box = document.createElement("div");
19
- box.className = "pbs-toast";
20
- box.setAttribute("role", "status");
21
- box.textContent = text;
22
- document.body.append(box);
23
- setTimeout(() => box.remove(), 5000);
24
- };
25
-
26
- const lang = document.documentElement.lang || navigator.language;
27
- const words = wordsFor(lang);
28
-
29
- document.addEventListener("pbs-answer", (event) => {
30
- const answer = (event as CustomEvent<Answer>).detail;
31
- const element = event.target as (HTMLElement & { answered?: unknown }) | null;
32
- postAnswer(answer).then(
33
- (reply) => {
34
- if (reply.accepted) return;
35
- // A pick locks itself once taken; clearing `answered` reopens it so the user can try again.
36
- if (element) element.answered = undefined;
37
- toast(`${words.notSent}${reply.reason ?? "refused"}`);
38
- },
39
- (error: unknown) => {
40
- if (element) element.answered = undefined;
41
- toast(`${words.notSent}${error instanceof Error ? error.message : String(error)}`);
42
- },
43
- );
44
- });
45
-
46
- mountFeedback({
19
+ mountPage({
47
20
  page: document.title || location.pathname.split("/").pop() || "",
48
- words,
21
+ words: wordsFor(document.documentElement.lang || navigator.language),
49
22
  storage: sessionStorage,
50
23
  storageKey: `pbs-feedback:${location.pathname}`,
51
- send: async (answer) => {
52
- const reply = await postAnswer(answer);
53
- if (!reply.accepted) throw new Error(reply.reason ?? "refused");
54
- },
24
+ post: (answer: Answer) =>
25
+ postAnswerToServer(`${prefix}/answer`, { answerId: newAnswerId(), answer, page: location.pathname }),
55
26
  });
56
27
 
57
28
  new EventSource(`${prefix}/events?page=${encodeURIComponent(location.pathname)}`).addEventListener("reload", () =>
@@ -16,6 +16,8 @@ import { escapeHtml, langOf, pageShell, renderBody } from "./render.ts";
16
16
  export const PAGE_IDLE_MS = 30_000;
17
17
  /** The largest answer the page server reads. */
18
18
  export const MAX_ANSWER_BYTES = 1_000_000;
19
+ /** How much of a refused answer the server reads and drops before it answers 413; a longer one is cut off with no reply. */
20
+ const MAX_REFUSED_BYTES = 16 * MAX_ANSWER_BYTES;
19
21
  /** The longest Mermaid source the diagram route draws: it travels in the image URL, which node limits to 16 KB. */
20
22
  const MAX_DIAGRAM_SOURCE = 6000;
21
23
 
@@ -182,26 +184,28 @@ export function createPageServer(options: PageServerOptions): Promise<PageServer
182
184
  }
183
185
  };
184
186
 
187
+ /**
188
+ * Reads a request body of at most `MAX_ANSWER_BYTES`. A longer one is refused with 413 once the client has sent it:
189
+ * closing while the client still sends resets the connection, and the reset loses the 413 (RFC 9112, 9.6). What comes
190
+ * past the cap is dropped, not kept; past `MAX_REFUSED_BYTES` the connection is cut.
191
+ */
185
192
  const body = (request: IncomingMessage, response: ServerResponse, then: (text: string) => void) => {
186
- if (Number(request.headers["content-length"] ?? 0) > MAX_ANSWER_BYTES) {
187
- response.writeHead(413, { connection: "close", "content-security-policy": RAW_POLICY });
188
- response.end();
189
- return;
190
- }
193
+ let refused = Number(request.headers["content-length"] ?? 0) > MAX_ANSWER_BYTES;
191
194
  let text = "";
192
195
  let bytes = 0;
193
196
  request.setEncoding("utf8");
194
197
  request.on("data", (chunk: string) => {
195
- text += chunk;
196
198
  bytes += Buffer.byteLength(chunk);
197
- if (bytes > MAX_ANSWER_BYTES) {
199
+ if (bytes > MAX_ANSWER_BYTES) refused = true;
200
+ if (bytes > MAX_REFUSED_BYTES) request.destroy();
201
+ text = refused ? "" : text + chunk;
202
+ });
203
+ request.on("end", () => {
204
+ if (refused) {
198
205
  response.writeHead(413, { connection: "close", "content-security-policy": RAW_POLICY });
199
206
  response.end();
200
- request.destroy();
207
+ return;
201
208
  }
202
- });
203
- request.on("end", () => {
204
- if (bytes > MAX_ANSWER_BYTES) return;
205
209
  // This runs outside `handle`'s catch: a throw here would be an uncaught exception in pi.
206
210
  try {
207
211
  then(text);