pi-better-show 0.6.0 → 0.7.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/README.md CHANGED
@@ -50,8 +50,8 @@ If you use `pi-herdr-doc-review`, uninstall it first (`pi uninstall npm:pi-herdr
50
50
  Markdown renders with its blocks; `.html`, `.tsx`, and `.jsx` run in a sandboxed frame; images show as they are.
51
51
  - `view: "edit"` (the default) opens the file in your editor.
52
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.
53
+ - Select any passage on a page to comment on it, or click a node or an edge in a flowchart or state diagram.
54
+ The feedback panel sends your comments and an overall note in one message; a diagram comment names the diagram and the element, such as `[Diagram 2, stateDiagram-v2] edge: Paid → Refunded "money back"`.
55
55
  - Open pages reload when the agent edits the file.
56
56
 
57
57
  ![The feedback panel with a comment on a selected passage](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/feedback.png)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",
@@ -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,76 @@ 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 overlay arrives after the image; a diagram the host cannot read stays a plain image.
287
+ */
288
+ #addTargets(frame: HTMLElement, url: string): void {
289
+ const read = configuration().diagramMap;
290
+ if (!read) return;
291
+ // A host that throws, or answers without a promise, must not break the drawing.
292
+ Promise.resolve()
293
+ .then(() => read(url))
294
+ .then(
295
+ (map) => {
296
+ // A redraw replaced this frame while the map was loading.
297
+ if (map && frame.isConnected) frame.append(this.#overlay(map));
298
+ },
299
+ (error: unknown) => console.warn("pbs-diagram: the diagram's elements cannot be commented on:", error),
300
+ );
301
+ }
302
+
303
+ #overlay(map: DiagramMap): SVGElement {
304
+ const words: Record<DiagramTarget["kind"], string> = {
305
+ node: this.t("diagramNode"),
306
+ edge: this.t("diagramEdge"),
307
+ group: this.t("diagramGroup"),
308
+ };
309
+ const pick = (target: DiagramTarget): void => {
310
+ this.dispatchEvent(
311
+ new CustomEvent("pbs-diagram-target", {
312
+ bubbles: true,
313
+ composed: true,
314
+ detail: { kind: target.kind, text: target.text },
315
+ }),
316
+ );
317
+ };
318
+ const hits = map.targets.map((target) => {
319
+ const hit = svg(
320
+ "g",
321
+ {
322
+ class: "hit",
323
+ role: "button",
324
+ tabindex: 0,
325
+ "data-kind": target.kind,
326
+ "aria-label": this.t("diagramComment", { kind: words[target.kind], text: target.text }),
327
+ },
328
+ ...target.shapes.map((shape) => svg(shape.tag, shape.attrs)),
329
+ );
330
+ hit.addEventListener("click", () => pick(target));
331
+ hit.addEventListener("keydown", (event) => {
332
+ if (event.key !== "Enter" && event.key !== " ") return;
333
+ event.preventDefault();
334
+ pick(target);
335
+ });
336
+ return hit;
337
+ });
338
+ return svg(
339
+ "svg",
340
+ { class: "targets", viewBox: map.viewBox, role: "group", "aria-label": this.t("diagram") },
341
+ ...hits,
342
+ );
343
+ }
267
344
  }
268
345
 
269
346
  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,239 @@
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
+ /** The label a node is known by; a state diagram's `[*]` has none, and is `start` or `end` (`_start`, `_end2`, …). */
43
+ function labelOf(node: Element): string {
44
+ const label = words(node.getAttribute("data-label"));
45
+ if (label) return label;
46
+ const id = node.getAttribute("data-id") ?? "";
47
+ const mark = /_(start|end)\d*$/.exec(id);
48
+ return mark?.[1] ?? id;
49
+ }
50
+
51
+ /** The box a group draws, in the image's own coordinates. */
52
+ function boxOf(group: Element): { x: number; y: number; width: number; height: number } | undefined {
53
+ const box = [...group.children].find((child) => child.localName === "rect");
54
+ if (!box) return undefined;
55
+ const [x, y, width, height] = ["x", "y", "width", "height"].map((name) => Number(box.getAttribute(name)));
56
+ if (x === undefined || y === undefined || width === undefined || height === undefined) return undefined;
57
+ return [x, y, width, height].every(Number.isFinite) ? { x, y, width, height } : undefined;
58
+ }
59
+
60
+ /** Where a node is drawn: the centre of its first shape. */
61
+ function centreOf(node: Element): { x: number; y: number } | undefined {
62
+ const shape = node.children[0];
63
+ if (!shape) return undefined;
64
+ const at = (name: string): number | undefined => {
65
+ const value = shape.getAttribute(name);
66
+ return value === null || value === "" ? undefined : Number(value);
67
+ };
68
+ const [cx, cy, x, y, width, height] = ["cx", "cy", "x", "y", "width", "height"].map(at);
69
+ if (cx !== undefined && cy !== undefined) return { x: cx, y: cy };
70
+ if (x !== undefined && y !== undefined) return { x: x + (width ?? 0) / 2, y: y + (height ?? 0) / 2 };
71
+ return undefined;
72
+ }
73
+
74
+ /**
75
+ * The title of the innermost group that draws around `node`, if any. The drawing is flat (a state diagram's inner `[*]`
76
+ * is not nested in its composite state), so containment is read from the geometry.
77
+ */
78
+ function enclosingTitle(svg: Element, node: Element): string | undefined {
79
+ const at = centreOf(node);
80
+ if (!at) return undefined;
81
+ let best: { title: string; area: number } | undefined;
82
+ for (const group of svg.querySelectorAll("g.subgraph")) {
83
+ const box = boxOf(group);
84
+ if (!box || at.x < box.x || at.x > box.x + box.width || at.y < box.y || at.y > box.y + box.height) continue;
85
+ const area = box.width * box.height;
86
+ if (!best || area < best.area) best = { title: labelOf(group), area };
87
+ }
88
+ return best?.title;
89
+ }
90
+
91
+ /**
92
+ * The name of every node and group by id. Start and end marks are plain `start` and `end`; when a diagram has several of
93
+ * one, each inside a composite state is `start (in Active)`, scoped by the state around it.
94
+ */
95
+ function namesOf(svg: Element): Map<string, string> {
96
+ const names = new Map<string, string>();
97
+ const marks = new Map<string, Element[]>();
98
+ for (const node of svg.querySelectorAll("g.node, g.subgraph")) {
99
+ const id = node.getAttribute("data-id") ?? "";
100
+ const label = labelOf(node);
101
+ names.set(id, label);
102
+ if (node.localName === "g" && node.classList.contains("node") && (label === "start" || label === "end"))
103
+ if (!words(node.getAttribute("data-label"))) marks.set(label, [...(marks.get(label) ?? []), node]);
104
+ }
105
+ for (const [label, nodes] of marks) {
106
+ if (nodes.length < 2) continue;
107
+ for (const node of nodes) {
108
+ const title = enclosingTitle(svg, node);
109
+ if (title) names.set(node.getAttribute("data-id") ?? "", `${label} (in ${title})`);
110
+ }
111
+ }
112
+ return names;
113
+ }
114
+
115
+ /**
116
+ * Makes every target's text unique within the diagram, so one quote names one element. Only a text that more than one
117
+ * target has changes: nodes and groups add their id (`Check (B)`), edges their endpoint ids (`Check → Done (A → C)`),
118
+ * and what is still alike is numbered in drawing order (`#1`, `#2`), skipping a number whose text another target
119
+ * already has (a label written as `B #1`).
120
+ */
121
+ function disambiguated(targets: (DiagramTarget & { id?: string })[]): DiagramTarget[] {
122
+ const count = (list: DiagramTarget[]): Map<string, number> => {
123
+ const seen = new Map<string, number>();
124
+ for (const target of list)
125
+ seen.set(`${target.kind}:${target.text}`, (seen.get(`${target.kind}:${target.text}`) ?? 0) + 1);
126
+ return seen;
127
+ };
128
+ const first = count(targets);
129
+ // An id only helps where it differs between the targets that share a text.
130
+ const ids = new Map<string, Set<string | undefined>>();
131
+ for (const target of targets) {
132
+ const key = `${target.kind}:${target.text}`;
133
+ ids.set(key, (ids.get(key) ?? new Set()).add(target.id));
134
+ }
135
+ const named = targets.map(({ id, ...target }) => {
136
+ const key = `${target.kind}:${target.text}`;
137
+ return id && (first.get(key) ?? 0) > 1 && (ids.get(key)?.size ?? 0) > 1
138
+ ? { ...target, text: `${target.text} (${id})` }
139
+ : target;
140
+ });
141
+ const second = count(named);
142
+ const keyOf = (target: DiagramTarget): string => `${target.kind}:${target.text}`;
143
+ const taken = new Set(named.filter((target) => (second.get(keyOf(target)) ?? 0) < 2).map(keyOf));
144
+ const next = new Map<string, number>();
145
+ return named.map((target) => {
146
+ const key = keyOf(target);
147
+ if ((second.get(key) ?? 0) < 2) return target;
148
+ let ordinal = next.get(key) ?? 0;
149
+ do ordinal += 1;
150
+ while (taken.has(`${key} #${ordinal}`));
151
+ next.set(key, ordinal);
152
+ taken.add(`${key} #${ordinal}`);
153
+ return { ...target, text: `${target.text} #${ordinal}` };
154
+ });
155
+ }
156
+
157
+ export function diagramMap(svg: Element): DiagramMap | undefined {
158
+ const viewBox = svg.getAttribute("viewBox");
159
+ if (!viewBox) return undefined;
160
+ const labels = namesOf(svg);
161
+ const name = (id: string | null): string => labels.get(id ?? "") ?? words(id);
162
+
163
+ const groups: (DiagramTarget & { id?: string })[] = [...svg.querySelectorAll("g.subgraph")].map((group) => {
164
+ const [box, header] = shapesIn(group);
165
+ // The header strip only: the whole box would cover the nodes inside it.
166
+ return {
167
+ kind: "group",
168
+ text: labels.get(group.getAttribute("data-id") ?? "") ?? labelOf(group),
169
+ id: group.getAttribute("data-id") ?? undefined,
170
+ shapes: [header ?? box].filter((shape) => shape !== undefined),
171
+ };
172
+ });
173
+
174
+ const boxes = [...svg.querySelectorAll("g.edge-label")];
175
+ const edges: (DiagramTarget & { id?: string })[] = [];
176
+ for (const edge of svg.querySelectorAll(".edge")) {
177
+ const from = edge.getAttribute("data-from");
178
+ const to = edge.getAttribute("data-to");
179
+ const label = words(edge.getAttribute("data-label"));
180
+ const shapes = [shapeOf(edge)].filter((shape) => shape !== undefined);
181
+ if (label) {
182
+ // The box that carries the label belongs to the edge too; parallel edges each take their own.
183
+ const at = boxes.findIndex(
184
+ (box) =>
185
+ box.getAttribute("data-from") === from &&
186
+ box.getAttribute("data-to") === to &&
187
+ words(box.getAttribute("data-label")) === label,
188
+ );
189
+ const [box] = at === -1 ? [] : boxes.splice(at, 1);
190
+ if (box) shapes.push(...shapesIn(box).filter((shape) => shape.tag === "rect"));
191
+ }
192
+ if (shapes.length === 0) continue;
193
+ edges.push({
194
+ kind: "edge",
195
+ text: `${name(from)} → ${name(to)}${label ? ` "${label}"` : ""}`,
196
+ id: `${words(from)} → ${words(to)}`,
197
+ shapes,
198
+ });
199
+ }
200
+
201
+ const nodes: (DiagramTarget & { id?: string })[] = [...svg.querySelectorAll("g.node")].map((node) => ({
202
+ kind: "node",
203
+ text: labels.get(node.getAttribute("data-id") ?? "") ?? labelOf(node),
204
+ id: node.getAttribute("data-id") ?? undefined,
205
+ shapes: shapesIn(node),
206
+ }));
207
+
208
+ // Later targets sit above earlier ones: groups below edges below nodes.
209
+ const targets = disambiguated(
210
+ [...groups, ...edges, ...nodes].filter((target) => target.text && target.shapes.length > 0),
211
+ );
212
+ return targets.length > 0 ? { viewBox, targets } : undefined;
213
+ }
214
+
215
+ /** The map of the diagram image at `url`: fetched from the page's own server and read as SVG. */
216
+ export async function fetchDiagramMap(url: string): Promise<DiagramMap | undefined> {
217
+ const response = await fetch(url);
218
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
219
+ const doc = new DOMParser().parseFromString(await response.text(), "image/svg+xml");
220
+ return doc.querySelector("parsererror") ? undefined : diagramMap(doc.documentElement);
221
+ }
222
+
223
+ /** The first word of a diagram's source after front matter and comments: `flowchart`, `stateDiagram-v2`, … */
224
+ function diagramType(source: string): string {
225
+ const body = source.replace(/^\s*---[\s\S]*?\n---\s*\n/, "");
226
+ const line = body.split("\n").find((text) => text.trim() !== "" && !text.trim().startsWith("%%"));
227
+ return line?.trim().split(/\s+/)[0] ?? "diagram";
228
+ }
229
+
230
+ /**
231
+ * The quote a diagram element goes into the feedback panel under: which diagram on the page (its position among the
232
+ * page's diagrams, and its type), then the element: `[Diagram 2, stateDiagram-v2] edge: Paid → Refunded "money back"`.
233
+ * Part of the message the agent reads; keep it stable.
234
+ */
235
+ export function diagramQuote(diagram: Element, target: { kind: string; text: string }): string {
236
+ const position = [...document.querySelectorAll("pbs-diagram")].indexOf(diagram) + 1;
237
+ const source = (diagram as Element & { data?: { source?: string } }).data?.source ?? "";
238
+ return `[Diagram ${position}, ${diagramType(source)}] ${target.kind}: ${target.text}`;
239
+ }
@@ -10,6 +10,8 @@ export interface FeedbackWords {
10
10
  comment: string;
11
11
  heading: string;
12
12
  hint: string;
13
+ /** The hint on a page whose diagrams can be commented on. */
14
+ hintDiagram: string;
13
15
  overall: string;
14
16
  send: string;
15
17
  sending: string;
@@ -25,6 +27,7 @@ const ZH: FeedbackWords = {
25
27
  comment: "留言",
26
28
  heading: "給 agent 的回饋",
27
29
  hint: "選取頁面上的文字可以針對那段留言。",
30
+ hintDiagram: "選取頁面上的文字,或點圖表裡的節點與連線,可以針對它留言。",
28
31
  overall: "整體意見",
29
32
  send: "送給 agent",
30
33
  sending: "傳送中…",
@@ -39,6 +42,7 @@ const EN: FeedbackWords = {
39
42
  comment: "Comment",
40
43
  heading: "Feedback for the agent",
41
44
  hint: "Select text on the page to comment on it.",
45
+ hintDiagram: "Select text on the page, or click a node or edge in a diagram, to comment on it.",
42
46
  overall: "Overall",
43
47
  send: "Send to agent",
44
48
  sending: "Sending…",
@@ -71,6 +75,8 @@ export interface FeedbackOptions {
71
75
  * and passes the frame's selection to `offer` instead.
72
76
  */
73
77
  watchDocument?: boolean;
78
+ /** Whether the page's diagrams can be commented on (the hint says so); a host calls `comment` for them. */
79
+ diagrams?: boolean;
74
80
  }
75
81
 
76
82
  /** A passage to comment on, and where the Add button goes (viewport coordinates of the panel's document). */
@@ -98,6 +104,11 @@ const make = <K extends keyof HTMLElementTagNameMap>(
98
104
  export function mountFeedback(options: FeedbackOptions): {
99
105
  /** Offers a passage to comment on, or withdraws the offer with no text or `undefined`. */
100
106
  offer: (passage: Offered | undefined) => void;
107
+ /**
108
+ * Adds `quote` to the panel as a commented target at once and opens the panel on its comment box; for what cannot be
109
+ * selected as text (a diagram's node or edge). A target already in the panel is not added twice, only focused.
110
+ */
111
+ comment: (quote: string) => void;
101
112
  destroy: () => void;
102
113
  } {
103
114
  const { words, storage, storageKey } = options;
@@ -122,7 +133,7 @@ export function mountFeedback(options: FeedbackOptions): {
122
133
  const panel = make("section", { class: "pbs-fb-panel", hidden: true });
123
134
  panel.setAttribute("aria-label", words.heading);
124
135
  const heading = make("h2", { textContent: words.heading });
125
- const hint = make("p", { class: "pbs-fb-hint", textContent: words.hint });
136
+ const hint = make("p", { class: "pbs-fb-hint", textContent: options.diagrams ? words.hintDiagram : words.hint });
126
137
  const list = make("div", { class: "pbs-fb-list" });
127
138
  const overallBox = make("textarea", { class: "pbs-fb-overall", rows: 3, value: overall });
128
139
  overallBox.setAttribute("aria-label", words.overall);
@@ -192,18 +203,28 @@ export function mountFeedback(options: FeedbackOptions): {
192
203
  const onSelect = (): void => offer(selected());
193
204
  // The button is pressed before the click lands, which would collapse the selection; keep what was picked.
194
205
  add.addEventListener("mousedown", (event) => event.preventDefault());
206
+ const open = (index: number): void => {
207
+ panel.hidden = false;
208
+ list.querySelectorAll("textarea").item(index)?.focus();
209
+ };
210
+ const comment = (quote: string): void => {
211
+ const known = items.findIndex((item) => item.quote === quote);
212
+ if (known === -1) {
213
+ items.push({ quote, comment: "" });
214
+ save();
215
+ draw();
216
+ }
217
+ open(known === -1 ? items.length - 1 : known);
218
+ };
195
219
  add.addEventListener("click", () => {
196
- if (pending) items.push({ quote: pending, comment: "" });
220
+ const quote = pending;
197
221
  pending = "";
198
222
  add.hidden = true;
199
223
  getSelection()?.removeAllRanges();
224
+ if (quote) items.push({ quote, comment: "" });
200
225
  save();
201
226
  draw();
202
- panel.hidden = false;
203
- list
204
- .querySelectorAll("textarea")
205
- .item(items.length - 1)
206
- ?.focus();
227
+ open(items.length - 1);
207
228
  });
208
229
  sendButton.addEventListener("click", () => {
209
230
  if (items.length === 0 && !overall.trim()) {
@@ -237,6 +258,7 @@ export function mountFeedback(options: FeedbackOptions): {
237
258
  document.body.append(root);
238
259
  return {
239
260
  offer,
261
+ comment,
240
262
  destroy: () => {
241
263
  if (watch) document.removeEventListener("selectionchange", onSelect);
242
264
  root.remove();
@@ -1,5 +1,7 @@
1
1
  import type { Answer } from "../../core/types.ts";
2
2
  import "../../elements/index.ts";
3
+ import { configure } from "../../elements/index.ts";
4
+ import { diagramQuote, fetchDiagramMap } from "./diagram-map.ts";
3
5
  import { mountFeedback, wordsFor } from "./feedback.ts";
4
6
  import { type AnswerReply, configureElements, newAnswerId, postAnswerToServer, serverPrefix } from "./host-config.ts";
5
7
 
@@ -10,6 +12,8 @@ import { type AnswerReply, configureElements, newAnswerId, postAnswerToServer, s
10
12
 
11
13
  const prefix = serverPrefix();
12
14
  configureElements(prefix);
15
+ // A diagram's nodes and edges can be commented on, not only selected text.
16
+ configure({ diagramMap: fetchDiagramMap });
13
17
 
14
18
  const postAnswer = (answer: Answer): Promise<AnswerReply> =>
15
19
  postAnswerToServer(`${prefix}/answer`, { answerId: newAnswerId(), answer, page: location.pathname });
@@ -43,9 +47,10 @@ document.addEventListener("pbs-answer", (event) => {
43
47
  );
44
48
  });
45
49
 
46
- mountFeedback({
50
+ const feedback = mountFeedback({
47
51
  page: document.title || location.pathname.split("/").pop() || "",
48
52
  words,
53
+ diagrams: true,
49
54
  storage: sessionStorage,
50
55
  storageKey: `pbs-feedback:${location.pathname}`,
51
56
  send: async (answer) => {
@@ -54,6 +59,11 @@ mountFeedback({
54
59
  },
55
60
  });
56
61
 
62
+ document.addEventListener("pbs-diagram-target", (event) => {
63
+ const target = (event as CustomEvent<{ kind: string; text: string }>).detail;
64
+ if (event.target instanceof Element) feedback.comment(diagramQuote(event.target, target));
65
+ });
66
+
57
67
  new EventSource(`${prefix}/events?page=${encodeURIComponent(location.pathname)}`).addEventListener("reload", () =>
58
68
  location.reload(),
59
69
  );
@@ -38,6 +38,7 @@ import {
38
38
  } from "./edit.ts";
39
39
  import { createAllowList, HTML_FILE, IMAGE_FILE, MARKDOWN_FILE, REACT_FILE } from "./files.ts";
40
40
  import type { PageServer, PageServerOptions } from "./server.ts";
41
+ import { onPath, urlOpener } from "./system.ts";
41
42
 
42
43
  export const MESSAGE_TYPE = "better-show";
43
44
  export const MINI_SDD_FILE = /(^|\/)docs\/specs\/[^/]+\/(decision|spec|design|verification)\.md$/;
@@ -49,8 +50,8 @@ export const MAX_DOCUMENTS = 32;
49
50
  export const MAX_REMEMBERED_ANSWERS = 256;
50
51
  /** How long a page just sent to the browser counts as open before its tab connects. */
51
52
  export const PAGE_OPEN_WAIT_MS = 15_000;
52
- /** The command that opens a URL in the default browser. */
53
- export const OPENER = process.platform === "darwin" ? "open" : "xdg-open";
53
+ /** The command that opens a URL in the default browser (system.ts: `rundll32` on Windows, by absolute path). */
54
+ export const OPENER = urlOpener(process.platform)[0];
54
55
 
55
56
  export type View = "page" | "edit";
56
57
 
@@ -79,7 +80,14 @@ export const createPageServer = async (options: PageServerOptions): Promise<Page
79
80
 
80
81
  export const defaultDeps = (): Deps => ({
81
82
  editor: process.env[EDITOR_ENV],
82
- onPath: (command) => spawnSync("sh", ["-c", 'command -v "$1"', "sh", command], { stdio: "ignore" }).status === 0,
83
+ onPath: (command) =>
84
+ onPath(
85
+ command,
86
+ process.platform,
87
+ process.env,
88
+ undefined,
89
+ (name) => spawnSync("sh", ["-c", 'command -v "$1"', "sh", name], { stdio: "ignore" }).status === 0,
90
+ ),
83
91
  launch: defaultLaunch,
84
92
  run: defaultRun,
85
93
  platform: process.platform,
@@ -100,8 +108,9 @@ export const defaultDeps = (): Deps => ({
100
108
  },
101
109
  servePages: createPageServer,
102
110
  openUrl: (url) => {
103
- const opened = defaultRun(OPENER, [url]);
104
- if (opened.status !== 0) throw new Error(`${OPENER} failed: ${(opened.stderr || opened.stdout).trim()}`);
111
+ const [opener, args] = urlOpener(process.platform);
112
+ const opened = defaultRun(opener, args(url));
113
+ if (opened.status !== 0) throw new Error(`${opener} failed: ${(opened.stderr || opened.stdout).trim()}`);
105
114
  },
106
115
  realpath: (path) => (existsSync(path) ? realpathSync(path) : path),
107
116
  newId: randomUUID,
@@ -1,5 +1,6 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { join } from "node:path";
3
+ import { gitDiffHunks, windowsTextEditor } from "./system.ts";
3
4
 
4
5
  /** Edit mode (D7): the user's own editor, no terminal pane. Saves are noticed by watching the file. */
5
6
 
@@ -48,8 +49,11 @@ export const defaultLaunch = (command: string, args: string[]): Promise<void> =>
48
49
  });
49
50
  });
50
51
 
51
- /** Splits a command line into words, honouring single and double quotes and backslash escapes; no expansion happens. */
52
- export function shellWords(line: string): string[] {
52
+ /**
53
+ * Splits a command line into words, honouring single and double quotes and backslash escapes; no expansion happens. With `windows`, a
54
+ * backslash is an ordinary character, so `"C:\\Program Files\\Editor\\editor.exe" -w` keeps its path.
55
+ */
56
+ export function shellWords(line: string, windows = false): string[] {
53
57
  const words: string[] = [];
54
58
  let word = "";
55
59
  let quote: string | undefined;
@@ -58,12 +62,12 @@ export function shellWords(line: string): string[] {
58
62
  const char = line[index] as string;
59
63
  if (quote) {
60
64
  if (char === quote) quote = undefined;
61
- else if (char === "\\" && quote === '"' && index + 1 < line.length) word += line[++index];
65
+ else if (!windows && char === "\\" && quote === '"' && index + 1 < line.length) word += line[++index];
62
66
  else word += char;
63
67
  } else if (char === "'" || char === '"') {
64
68
  quote = char;
65
69
  started = true;
66
- } else if (char === "\\" && index + 1 < line.length) {
70
+ } else if (!windows && char === "\\" && index + 1 < line.length) {
67
71
  word += line[++index];
68
72
  started = true;
69
73
  } else if (/\s/.test(char)) {
@@ -135,7 +139,7 @@ export function createEditSession(deps: EditDeps, events: EditEvents) {
135
139
  /** Opens the paths in the user's editor: the chosen command, else VS Code, else the system's text editor. */
136
140
  async function open(paths: string[]): Promise<string> {
137
141
  if (deps.editor) {
138
- const [command, ...args] = shellWords(deps.editor);
142
+ const [command, ...args] = shellWords(deps.editor, deps.platform === "win32");
139
143
  if (!command) throw new Error(`${EDITOR_ENV} is empty`);
140
144
  if (!deps.onPath(command)) throw new Error(`${EDITOR_ENV}=${deps.editor}, but ${command} is not on PATH`);
141
145
  await deps.launch(command, [...args, ...paths]);
@@ -145,6 +149,12 @@ export function createEditSession(deps: EditDeps, events: EditEvents) {
145
149
  await deps.launch("code", paths);
146
150
  return "VS Code";
147
151
  }
152
+ if (deps.platform === "win32") {
153
+ // Notepad, by absolute path, is on every Windows machine; it opens one file per window.
154
+ const notepad = windowsTextEditor();
155
+ for (const path of paths) await deps.launch(notepad, [path]);
156
+ return "Notepad";
157
+ }
148
158
  const [command, args] =
149
159
  deps.platform === "darwin" ? (["open", ["-t", ...paths]] as const) : (["xdg-open", paths] as const);
150
160
  if (!deps.onPath(command)) throw new Error(`edit mode needs ${EDITOR_ENV}, VS Code (code), or ${command} on PATH`);
@@ -160,6 +170,35 @@ export function createEditSession(deps: EditDeps, events: EditEvents) {
160
170
  return "the system text editor";
161
171
  }
162
172
 
173
+ /**
174
+ * Zero-context hunks from `before` to `after`. `diff` when it is on PATH; on Windows without it (Git for Windows keeps `diff` out of the
175
+ * PATH it adds), `git diff --no-index`, whose header lines are taken out. Both exit 1 when the files differ.
176
+ */
177
+ function diffOf(before: string, after: string, display: string): string {
178
+ if (deps.platform === "win32" && !deps.onPath("diff")) {
179
+ const git = deps.run("git", [
180
+ "-c",
181
+ "core.autocrlf=false",
182
+ "-c",
183
+ "core.safecrlf=false",
184
+ "diff",
185
+ "--no-index",
186
+ "--no-color",
187
+ "--no-ext-diff",
188
+ "-U0",
189
+ "--",
190
+ before,
191
+ after,
192
+ ]);
193
+ if (git.status !== 0 && git.status !== 1)
194
+ throw new Error(`git diff failed: ${(git.stderr || git.stdout).trim()}`);
195
+ return gitDiffHunks(git.stdout);
196
+ }
197
+ const diff = deps.run("diff", ["-U0", "--label", `a/${display}`, "--label", `b/${display}`, before, after]);
198
+ if (diff.status !== 0 && diff.status !== 1) throw new Error(`diff failed: ${diff.stderr.trim()}`);
199
+ return diff.stdout;
200
+ }
201
+
163
202
  const paused = (path: string): boolean =>
164
203
  [...active.values()].some((call) => call.path === undefined || call.path === path);
165
204
 
@@ -171,9 +210,7 @@ export function createEditSession(deps: EditDeps, events: EditEvents) {
171
210
  deps.writeFile(before, doc.snapshot);
172
211
  // The content read, not the file: a save landing between the read and the diff waits for the next report.
173
212
  deps.writeFile(after, content);
174
- const diff = deps.run("diff", ["-U0", "--label", `a/${doc.display}`, "--label", `b/${doc.display}`, before, after]);
175
- if (diff.status !== 0 && diff.status !== 1) throw new Error(`diff failed: ${diff.stderr.trim()}`);
176
- const section = feedbackMessage(doc.display, diff.stdout, doc.duringShell);
213
+ const section = feedbackMessage(doc.display, diffOf(before, after, doc.display), doc.duringShell);
177
214
  doc.snapshot = content;
178
215
  doc.duringShell = false;
179
216
  return section;
@@ -0,0 +1,78 @@
1
+ import { statSync } from "node:fs";
2
+ import { win32 } from "node:path";
3
+
4
+ /** Platform details the extension needs from the operating system: the browser opener, the PATH lookup, the fallback text editor. */
5
+
6
+ type Env = Record<string, string | undefined>;
7
+
8
+ /** A Windows program under `%SystemRoot%`, by absolute path, so that a `rundll32` or `notepad` earlier on PATH (Git for Windows puts its own tools there) is never the one run. */
9
+ export const systemProgram = (env: Env, ...parts: string[]): string =>
10
+ win32.join(env.SystemRoot ?? env.SYSTEMROOT ?? "C:\\Windows", ...parts);
11
+
12
+ /**
13
+ * The command that opens a URL in the default browser. On Windows it is `rundll32 url.dll,FileProtocolHandler`, which takes the URL as one
14
+ * argument with no shell in between, so `&` and `%` in a query reach the browser as written (`cmd /c start` would parse them), and exits 0.
15
+ */
16
+ export function urlOpener(
17
+ platform: string,
18
+ env: Env = process.env,
19
+ ): [command: string, args: (url: string) => string[]] {
20
+ if (platform === "darwin") return ["open", (url) => [url]];
21
+ if (platform === "win32")
22
+ return [systemProgram(env, "System32", "rundll32.exe"), (url) => ["url.dll,FileProtocolHandler", url]];
23
+ return ["xdg-open", (url) => [url]];
24
+ }
25
+
26
+ const isFile = (path: string): boolean => {
27
+ try {
28
+ return statSync(path).isFile();
29
+ } catch {
30
+ return false;
31
+ }
32
+ };
33
+
34
+ /**
35
+ * Whether `command` names a program on PATH that can be started without a shell. On Windows the PATH is scanned, with no shell (a desk
36
+ * machine need not have `sh`), for `.exe` and `.com` only: Node spawns nothing else without `shell: true`, so a `code.cmd` shim counts as
37
+ * absent and the caller falls back instead of failing at launch. Elsewhere `sh -c 'command -v'` answers, as it did before.
38
+ */
39
+ export function onPath(
40
+ command: string,
41
+ platform: string,
42
+ env: Env = process.env,
43
+ exists: (path: string) => boolean = isFile,
44
+ shell: (command: string) => boolean = () => false,
45
+ ): boolean {
46
+ if (platform !== "win32") return shell(command);
47
+ const ext = /\.([^\\/.]+)$/.exec(command)?.[1]?.toLowerCase();
48
+ if (ext === "exe" || ext === "com") return checkNames([command], command, env, exists);
49
+ return checkNames([`${command}.exe`, `${command}.com`], command, env, exists);
50
+ }
51
+
52
+ function checkNames(names: string[], command: string, env: Env, exists: (path: string) => boolean): boolean {
53
+ const path = env.PATH ?? env.Path ?? "";
54
+ if (/[\\/]/.test(command)) return names.some((name) => exists(name));
55
+ const dirs = path
56
+ .split(";")
57
+ .map((dir) => dir.replace(/^"(.*)"$/, "$1"))
58
+ .filter((dir) => dir !== "");
59
+ return dirs.some((dir) => names.some((name) => exists(win32.join(dir, name))));
60
+ }
61
+
62
+ /** The text editor a Windows machine always has, for edit mode when neither PI_BETTER_SHOW_EDITOR nor VS Code is there; it opens one file per window. */
63
+ export const windowsTextEditor = (env: Env = process.env): string => systemProgram(env, "notepad.exe");
64
+
65
+ /**
66
+ * `git diff --no-index` output with git's own header lines taken out, so that what is left reads like `diff -U0` without `--label`: the
67
+ * `@@` hunks and their lines. The `---` and `+++` lines go too; the caller names the file itself. Git writes the line before a hunk after its
68
+ * header (`@@ -2 +2 @@ one`); that context is dropped, as `diff` has none. A binary change keeps git's `Binary files … differ` line.
69
+ */
70
+ export function gitDiffHunks(stdout: string): string {
71
+ const lines = stdout.split("\n");
72
+ const first = lines.findIndex((line) => line.startsWith("@@"));
73
+ if (first === -1) return lines.find((line) => line.startsWith("Binary files ")) ?? "";
74
+ return lines
75
+ .slice(first)
76
+ .map((line) => (line.startsWith("@@") ? line.replace(/^(@@ [^@]* @@).*$/, "$1") : line))
77
+ .join("\n");
78
+ }