pi-better-show 0.7.0 → 0.7.2
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 +31 -82
- package/README.zh-TW.md +67 -0
- package/package.json +1 -1
- package/src/elements/display.ts +47 -14
- package/src/elements/strings.ts +4 -0
- package/src/extension/client/diagram-map.ts +209 -90
- package/src/extension/client/feedback.ts +83 -11
- package/src/extension/client/markdown-page.ts +84 -0
- package/src/extension/client/page.ts +8 -47
- package/src/extension/server.ts +15 -11
package/README.md
CHANGED
|
@@ -1,37 +1,19 @@
|
|
|
1
1
|
# pi-better-show
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[繁體中文](README.zh-TW.md)
|
|
4
4
|
|
|
5
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
+

|
|
23
10
|
|
|
24
|
-
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
##
|
|
26
|
+
## Quick start
|
|
46
27
|
|
|
47
|
-
`show_doc({paths, reason, view})
|
|
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
|
|
50
|
-
|
|
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, 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
|
-
- 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
|
-
|
|
33
|
+
When you press **Send** on a form, the agent receives:
|
|
58
34
|
|
|
59
|
-
|
|
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
|
-
|
|
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` |
|
|
67
|
-
| `options` | choices
|
|
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
|
|
70
|
-
| `checklist` | items to tick | Send |
|
|
71
|
-
| `
|
|
72
|
-
| `
|
|
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
|
-

|
|
82
|
-
|
|
83
|
-
A structure review with `tree`, `mermaid`, and `diff`:
|
|
84
|
-
|
|
85
|
-

|
|
86
|
-
|
|
87
|
-
A design review with `review` and `suggest`:
|
|
88
|
-
|
|
89
|
-

|
|
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
|
-
|
|
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
|
-
##
|
|
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 #
|
|
113
|
-
|
|
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
|
package/README.zh-TW.md
ADDED
|
@@ -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
|
+

|
|
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.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/elements/display.ts
CHANGED
|
@@ -283,6 +283,7 @@ export class PbsDiagram extends PbsElement<MermaidData> {
|
|
|
283
283
|
/**
|
|
284
284
|
* When the host can read the drawing (`diagramMap`), lays its nodes and edges over the image as buttons: a click, or
|
|
285
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).
|
|
286
287
|
* The overlay arrives after the image; a diagram the host cannot read stays a plain image.
|
|
287
288
|
*/
|
|
288
289
|
#addTargets(frame: HTMLElement, url: string): void {
|
|
@@ -306,8 +307,9 @@ export class PbsDiagram extends PbsElement<MermaidData> {
|
|
|
306
307
|
edge: this.t("diagramEdge"),
|
|
307
308
|
group: this.t("diagramGroup"),
|
|
308
309
|
};
|
|
309
|
-
|
|
310
|
-
|
|
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(
|
|
311
313
|
new CustomEvent("pbs-diagram-target", {
|
|
312
314
|
bubbles: true,
|
|
313
315
|
composed: true,
|
|
@@ -315,30 +317,61 @@ export class PbsDiagram extends PbsElement<MermaidData> {
|
|
|
315
317
|
}),
|
|
316
318
|
);
|
|
317
319
|
};
|
|
318
|
-
const hits = map.targets.map((target) =>
|
|
319
|
-
|
|
320
|
+
const hits = map.targets.map((target, index) =>
|
|
321
|
+
svg(
|
|
320
322
|
"g",
|
|
321
323
|
{
|
|
322
324
|
class: "hit",
|
|
323
325
|
role: "button",
|
|
324
|
-
tabindex: 0,
|
|
326
|
+
tabindex: index === 0 ? 0 : -1,
|
|
325
327
|
"data-kind": target.kind,
|
|
326
328
|
"aria-label": this.t("diagramComment", { kind: words[target.kind], text: target.text }),
|
|
327
329
|
},
|
|
328
330
|
...target.shapes.map((shape) => svg(shape.tag, shape.attrs)),
|
|
329
|
-
)
|
|
330
|
-
|
|
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));
|
|
331
348
|
hit.addEventListener("keydown", (event) => {
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
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
|
+
}
|
|
335
357
|
});
|
|
336
|
-
|
|
337
|
-
|
|
358
|
+
}
|
|
359
|
+
// Later buttons sit above earlier ones: groups below edges below nodes, so a node inside a group is the node. The
|
|
360
|
+
// DOM keeps that order, not the reading order; the description tells a screen reader to move with the arrow keys.
|
|
361
|
+
const layers: DiagramTarget["kind"][] = ["group", "edge", "node"];
|
|
362
|
+
const keys = svg("desc", { id: "diagram-keys" });
|
|
363
|
+
keys.textContent = this.t("diagramKeys");
|
|
338
364
|
return svg(
|
|
339
365
|
"svg",
|
|
340
|
-
{
|
|
341
|
-
|
|
366
|
+
{
|
|
367
|
+
class: "targets",
|
|
368
|
+
viewBox: map.viewBox,
|
|
369
|
+
role: "group",
|
|
370
|
+
"aria-label": this.t("diagram"),
|
|
371
|
+
"aria-describedby": "diagram-keys",
|
|
372
|
+
},
|
|
373
|
+
keys,
|
|
374
|
+
...layers.flatMap((kind) => hits.filter((_, index) => map.targets[index]?.kind === kind)),
|
|
342
375
|
);
|
|
343
376
|
}
|
|
344
377
|
}
|
package/src/elements/strings.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface Strings {
|
|
|
41
41
|
diagramNode: string;
|
|
42
42
|
diagramEdge: string;
|
|
43
43
|
diagramGroup: string;
|
|
44
|
+
/** How to move through a diagram's elements, for screen readers. */
|
|
45
|
+
diagramKeys: string;
|
|
44
46
|
diff: string;
|
|
45
47
|
table: string;
|
|
46
48
|
mindmap: string;
|
|
@@ -98,6 +100,7 @@ export const STRINGS: Record<Locale, Strings> = {
|
|
|
98
100
|
diagramNode: "node",
|
|
99
101
|
diagramEdge: "edge",
|
|
100
102
|
diagramGroup: "group",
|
|
103
|
+
diagramKeys: "Arrow keys move between its elements; Enter or Space comments on one.",
|
|
101
104
|
diff: "Diff",
|
|
102
105
|
table: "Table",
|
|
103
106
|
mindmap: "Mind map",
|
|
@@ -152,6 +155,7 @@ export const STRINGS: Record<Locale, Strings> = {
|
|
|
152
155
|
diagramNode: "節點",
|
|
153
156
|
diagramEdge: "連線",
|
|
154
157
|
diagramGroup: "群組",
|
|
158
|
+
diagramKeys: "用方向鍵在元素之間移動,按 Enter 或空白鍵針對它留言。",
|
|
155
159
|
diff: "差異",
|
|
156
160
|
table: "表格",
|
|
157
161
|
mindmap: "心智圖",
|
|
@@ -39,15 +39,18 @@ function shapeOf(element: Element): DiagramShape | undefined {
|
|
|
39
39
|
const shapesIn = (group: Element): DiagramShape[] =>
|
|
40
40
|
[...group.children].map(shapeOf).filter((shape) => shape !== undefined);
|
|
41
41
|
|
|
42
|
-
/**
|
|
43
|
-
function
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
const id = node.getAttribute("data-id") ?? "";
|
|
47
|
-
const mark = /_(start|end)\d*$/.exec(id);
|
|
48
|
-
return mark?.[1] ?? id;
|
|
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;
|
|
49
46
|
}
|
|
50
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
|
+
|
|
51
54
|
/** The box a group draws, in the image's own coordinates. */
|
|
52
55
|
function boxOf(group: Element): { x: number; y: number; width: number; height: number } | undefined {
|
|
53
56
|
const box = [...group.children].find((child) => child.localName === "rect");
|
|
@@ -72,107 +75,204 @@ function centreOf(node: Element): { x: number; y: number } | undefined {
|
|
|
72
75
|
}
|
|
73
76
|
|
|
74
77
|
/**
|
|
75
|
-
* The
|
|
76
|
-
*
|
|
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.
|
|
77
80
|
*/
|
|
78
|
-
function
|
|
81
|
+
function enclosing(groups: Element[], node: Element): Element | undefined {
|
|
79
82
|
const at = centreOf(node);
|
|
80
83
|
if (!at) return undefined;
|
|
81
|
-
let best: {
|
|
82
|
-
for (const group of
|
|
84
|
+
let best: { group: Element; area: number } | undefined;
|
|
85
|
+
for (const group of groups) {
|
|
83
86
|
const box = boxOf(group);
|
|
84
87
|
if (!box || at.x < box.x || at.x > box.x + box.width || at.y < box.y || at.y > box.y + box.height) continue;
|
|
85
88
|
const area = box.width * box.height;
|
|
86
|
-
if (!best || area < best.area) best = {
|
|
89
|
+
if (!best || area < best.area) best = { group, area };
|
|
87
90
|
}
|
|
88
|
-
return best?.
|
|
91
|
+
return best?.group;
|
|
89
92
|
}
|
|
90
93
|
|
|
91
94
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
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.
|
|
94
97
|
*/
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
if (title) names.set(node.getAttribute("data-id") ?? "", `${label} (in ${title})`);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return names;
|
|
98
|
+
type Draft = DiagramTarget & { tag: string; id?: string };
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* What a number is written after: a run of `#` that no label or id of the drawing has, so a numbered quote never reads
|
|
102
|
+
* as another element's own words (`A → B ##1` beside a node labelled `B #1`). `#` unless a label has one.
|
|
103
|
+
*/
|
|
104
|
+
function numberingOf(svg: Element): string {
|
|
105
|
+
const said = [...svg.querySelectorAll("[data-label], [data-id]")].flatMap((element) => [
|
|
106
|
+
words(element.getAttribute("data-label")),
|
|
107
|
+
words(element.getAttribute("data-id")),
|
|
108
|
+
]);
|
|
109
|
+
let mark = "#";
|
|
110
|
+
while (said.some((text) => text.includes(mark))) mark += "#";
|
|
111
|
+
return mark;
|
|
113
112
|
}
|
|
114
113
|
|
|
115
114
|
/**
|
|
116
|
-
* Makes every target's text unique
|
|
117
|
-
* target has changes:
|
|
118
|
-
*
|
|
119
|
-
* already has (a label written as `B #1`).
|
|
115
|
+
* Makes every target's text unique among `targets` (one kind), so one quote names one element. Only a text that more
|
|
116
|
+
* than one target has changes: each adds its tag where the tags differ (`Check (B)`), and what is still alike is
|
|
117
|
+
* numbered in drawing order after `numbering` (`#1`, `#2`), which no label has, so a numbered text is no other's.
|
|
120
118
|
*/
|
|
121
|
-
function disambiguated(targets:
|
|
119
|
+
function disambiguated(targets: Draft[], numbering: string): DiagramTarget[] {
|
|
122
120
|
const count = (list: DiagramTarget[]): Map<string, number> => {
|
|
123
121
|
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);
|
|
122
|
+
for (const target of list) seen.set(target.text, (seen.get(target.text) ?? 0) + 1);
|
|
126
123
|
return seen;
|
|
127
124
|
};
|
|
128
125
|
const first = count(targets);
|
|
129
|
-
//
|
|
130
|
-
const
|
|
131
|
-
for (const target of targets)
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
return id && (first.get(key) ?? 0) > 1 && (ids.get(key)?.size ?? 0) > 1
|
|
138
|
-
? { ...target, text: `${target.text} (${id})` }
|
|
139
|
-
: target;
|
|
140
|
-
});
|
|
126
|
+
// A tag only helps where it differs between the targets that share a text.
|
|
127
|
+
const tags = new Map<string, Set<string>>();
|
|
128
|
+
for (const target of targets) tags.set(target.text, (tags.get(target.text) ?? new Set()).add(target.tag));
|
|
129
|
+
const named = targets.map(({ tag, id: _id, ...target }) =>
|
|
130
|
+
tag && (first.get(target.text) ?? 0) > 1 && (tags.get(target.text)?.size ?? 0) > 1
|
|
131
|
+
? { ...target, text: `${target.text} (${tag})` }
|
|
132
|
+
: target,
|
|
133
|
+
);
|
|
141
134
|
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
135
|
const next = new Map<string, number>();
|
|
145
136
|
return named.map((target) => {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
137
|
+
if ((second.get(target.text) ?? 0) < 2) return target;
|
|
138
|
+
const ordinal = (next.get(target.text) ?? 0) + 1;
|
|
139
|
+
next.set(target.text, ordinal);
|
|
140
|
+
return { ...target, text: `${target.text} ${numbering}${ordinal}` };
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Tells apart the nodes or the groups, and records each one's final name and tag by id: later targets (a `[*]`'s
|
|
146
|
+
* composite state, an edge's ends) are named by them. A target with no text or shape is left out.
|
|
147
|
+
*/
|
|
148
|
+
function settle(
|
|
149
|
+
drafts: Draft[],
|
|
150
|
+
names: Map<string, string>,
|
|
151
|
+
tags: Map<string, string>,
|
|
152
|
+
numbering: string,
|
|
153
|
+
): DiagramTarget[] {
|
|
154
|
+
for (const draft of drafts) {
|
|
155
|
+
names.set(draft.id ?? "", draft.text);
|
|
156
|
+
tags.set(draft.id ?? "", draft.tag);
|
|
157
|
+
}
|
|
158
|
+
const kept = drafts.filter((draft) => draft.text && draft.shapes.length > 0);
|
|
159
|
+
const targets = disambiguated(kept, numbering);
|
|
160
|
+
for (const [index, draft] of kept.entries()) names.set(draft.id ?? "", targets[index]?.text ?? draft.text);
|
|
161
|
+
return targets;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The points a shape's geometry spans, in the image's coordinates. */
|
|
165
|
+
function pointsOf({ tag, attrs }: DiagramShape): [number, number][] {
|
|
166
|
+
const at = (name: string): number => Number(attrs[name]);
|
|
167
|
+
const box = (x: number, y: number, rx: number, ry: number): [number, number][] => [
|
|
168
|
+
[x - rx, y - ry],
|
|
169
|
+
[x + rx, y + ry],
|
|
170
|
+
];
|
|
171
|
+
if (tag === "rect")
|
|
172
|
+
return [
|
|
173
|
+
[at("x"), at("y")],
|
|
174
|
+
[at("x") + at("width"), at("y") + at("height")],
|
|
175
|
+
];
|
|
176
|
+
if (tag === "circle") return box(at("cx"), at("cy"), at("r"), at("r"));
|
|
177
|
+
if (tag === "ellipse") return box(at("cx"), at("cy"), at("rx"), at("ry"));
|
|
178
|
+
// A polygon's or polyline's points; a path's coordinates, near enough to place it.
|
|
179
|
+
const values = (attrs.points ?? attrs.d ?? "").match(/-?\d*\.?\d+(?:e-?\d+)?/gi)?.map(Number) ?? [];
|
|
180
|
+
return values.flatMap((x, index) =>
|
|
181
|
+
index % 2 === 0 ? [[x, values[index + 1] ?? Number.NaN] as [number, number]] : [],
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The targets in reading order, the order arrow keys move through them: along the flow (down, or across in a chart
|
|
187
|
+
* whose edges run more across than down), then across it, so an edge comes between the elements it joins.
|
|
188
|
+
*/
|
|
189
|
+
function inReadingOrder(targets: DiagramTarget[]): DiagramTarget[] {
|
|
190
|
+
let across = 0;
|
|
191
|
+
let down = 0;
|
|
192
|
+
for (const target of targets) {
|
|
193
|
+
const line = target.kind === "edge" && target.shapes[0] ? pointsOf(target.shapes[0]) : [];
|
|
194
|
+
const [first, last] = [line[0], line.at(-1)];
|
|
195
|
+
if (!first || !last) continue;
|
|
196
|
+
across += Math.abs(last[0] - first[0]);
|
|
197
|
+
down += Math.abs(last[1] - first[1]);
|
|
198
|
+
}
|
|
199
|
+
const [along, side] = across > down ? [0, 1] : [1, 0];
|
|
200
|
+
const placed = targets.map((target, index) => {
|
|
201
|
+
const points = target.shapes.flatMap(pointsOf).filter((point) => point.every(Number.isFinite));
|
|
202
|
+
const centre = [0, 1].map((axis) => {
|
|
203
|
+
const values = points.map((point) => point[axis] ?? 0);
|
|
204
|
+
return (Math.min(...values) + Math.max(...values)) / 2;
|
|
205
|
+
});
|
|
206
|
+
return { target, index, centre: points.length > 0 ? centre : undefined };
|
|
154
207
|
});
|
|
208
|
+
// Within half a unit is the same rank: the layout's own arithmetic leaves crumbs.
|
|
209
|
+
const compare = (a: number[], b: number[], axis: number): number =>
|
|
210
|
+
Math.abs((a[axis] ?? 0) - (b[axis] ?? 0)) < 0.5 ? 0 : (a[axis] ?? 0) - (b[axis] ?? 0);
|
|
211
|
+
return placed
|
|
212
|
+
.sort((a, b) => {
|
|
213
|
+
if (!a.centre || !b.centre) return (a.centre ? -1 : b.centre ? 1 : 0) || a.index - b.index;
|
|
214
|
+
return compare(a.centre, b.centre, along) || compare(a.centre, b.centre, side) || a.index - b.index;
|
|
215
|
+
})
|
|
216
|
+
.map(({ target }) => target);
|
|
155
217
|
}
|
|
156
218
|
|
|
219
|
+
/**
|
|
220
|
+
* What a reader can point at in the drawing, each named in the diagram's own words and unique within its kind. Groups
|
|
221
|
+
* are named first, then nodes (a `[*]` among several is scoped by the composite state around it: `start (in Active)`),
|
|
222
|
+
* then edges by the names of their ends, so an edge says which `Check` it starts from. Renderer ids never show: a `[*]`
|
|
223
|
+
* that reads like another node adds `([*])`.
|
|
224
|
+
*/
|
|
157
225
|
export function diagramMap(svg: Element): DiagramMap | undefined {
|
|
158
226
|
const viewBox = svg.getAttribute("viewBox");
|
|
159
227
|
if (!viewBox) return undefined;
|
|
160
|
-
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
shapes
|
|
171
|
-
|
|
228
|
+
/** Each node's and group's name, and the tag that tells it apart, by id: what an edge is named by. */
|
|
229
|
+
const names = new Map<string, string>();
|
|
230
|
+
const tags = new Map<string, string>();
|
|
231
|
+
const numbering = numberingOf(svg);
|
|
232
|
+
|
|
233
|
+
const groupElements = [...svg.querySelectorAll("g.subgraph")];
|
|
234
|
+
const groups = settle(
|
|
235
|
+
groupElements.map((group) => {
|
|
236
|
+
const [box, header] = shapesIn(group);
|
|
237
|
+
// The header strip only: the whole box would cover the nodes inside it.
|
|
238
|
+
const shapes = [header ?? box].filter((shape) => shape !== undefined);
|
|
239
|
+
return { kind: "group", text: labelOf(group), tag: idOf(group), id: idOf(group), shapes };
|
|
240
|
+
}),
|
|
241
|
+
names,
|
|
242
|
+
tags,
|
|
243
|
+
numbering,
|
|
244
|
+
);
|
|
245
|
+
|
|
246
|
+
const nodeElements = [...svg.querySelectorAll("g.node")];
|
|
247
|
+
const several = (mark: string): boolean => nodeElements.filter((node) => markOf(node) === mark).length > 1;
|
|
248
|
+
const scoped = nodeElements.map((node) => {
|
|
249
|
+
const mark = markOf(node);
|
|
250
|
+
if (!mark) return labelOf(node);
|
|
251
|
+
const around = several(mark) ? enclosing(groupElements, node) : undefined;
|
|
252
|
+
return around ? `${mark} (in ${names.get(idOf(around))})` : mark;
|
|
172
253
|
});
|
|
254
|
+
const labels = new Set(nodeElements.filter((node) => !markOf(node)).map(labelOf));
|
|
255
|
+
const nodes = settle(
|
|
256
|
+
nodeElements.map((node, index) => {
|
|
257
|
+
const text = scoped[index] ?? "";
|
|
258
|
+
const mark = markOf(node) !== undefined;
|
|
259
|
+
return {
|
|
260
|
+
kind: "node",
|
|
261
|
+
text: mark && labels.has(text) ? `${text} ([*])` : text,
|
|
262
|
+
tag: mark ? "[*]" : idOf(node),
|
|
263
|
+
id: idOf(node),
|
|
264
|
+
shapes: shapesIn(node),
|
|
265
|
+
};
|
|
266
|
+
}),
|
|
267
|
+
names,
|
|
268
|
+
tags,
|
|
269
|
+
numbering,
|
|
270
|
+
);
|
|
173
271
|
|
|
272
|
+
const name = (id: string | null): string => names.get(id ?? "") || words(id);
|
|
273
|
+
const tag = (id: string | null): string => tags.get(id ?? "") || words(id);
|
|
174
274
|
const boxes = [...svg.querySelectorAll("g.edge-label")];
|
|
175
|
-
const edges:
|
|
275
|
+
const edges: Draft[] = [];
|
|
176
276
|
for (const edge of svg.querySelectorAll(".edge")) {
|
|
177
277
|
const from = edge.getAttribute("data-from");
|
|
178
278
|
const to = edge.getAttribute("data-to");
|
|
@@ -193,22 +293,12 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
|
|
|
193
293
|
edges.push({
|
|
194
294
|
kind: "edge",
|
|
195
295
|
text: `${name(from)} → ${name(to)}${label ? ` "${label}"` : ""}`,
|
|
196
|
-
|
|
296
|
+
tag: `${tag(from)} → ${tag(to)}`,
|
|
197
297
|
shapes,
|
|
198
298
|
});
|
|
199
299
|
}
|
|
200
300
|
|
|
201
|
-
const
|
|
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
|
-
);
|
|
301
|
+
const targets = inReadingOrder([...groups, ...disambiguated(edges, numbering), ...nodes]);
|
|
212
302
|
return targets.length > 0 ? { viewBox, targets } : undefined;
|
|
213
303
|
}
|
|
214
304
|
|
|
@@ -234,6 +324,35 @@ function diagramType(source: string): string {
|
|
|
234
324
|
*/
|
|
235
325
|
export function diagramQuote(diagram: Element, target: { kind: string; text: string }): string {
|
|
236
326
|
const position = [...document.querySelectorAll("pbs-diagram")].indexOf(diagram) + 1;
|
|
237
|
-
|
|
238
|
-
|
|
327
|
+
return `[Diagram ${position}, ${diagramType(sourceOf(diagram))}] ${target.kind}: ${target.text}`;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const sourceOf = (diagram: Element): string => (diagram as Element & { data?: { source?: string } }).data?.source ?? "";
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* What finds a diagram again when the page reloads after an agent's edit, which may add or remove diagrams before it:
|
|
334
|
+
* its source, and which of the page's diagrams drawn from that source it is.
|
|
335
|
+
*/
|
|
336
|
+
export function diagramRef(diagram: Element): string {
|
|
337
|
+
const source = sourceOf(diagram);
|
|
338
|
+
const alike = [...document.querySelectorAll("pbs-diagram")].filter((other) => sourceOf(other) === source);
|
|
339
|
+
return JSON.stringify([source, alike.indexOf(diagram)]);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* A `diagramQuote` made on an earlier load, with the position its diagram (found by `diagramRef`) has on the page now.
|
|
344
|
+
* A diagram whose source changed is not found: `undefined`, and the panel keeps the quote's position.
|
|
345
|
+
*/
|
|
346
|
+
export function requoteDiagram(quote: string, ref: string): string | undefined {
|
|
347
|
+
let found: Element | undefined;
|
|
348
|
+
try {
|
|
349
|
+
const [source, nth] = JSON.parse(ref) as [unknown, unknown];
|
|
350
|
+
const alike = [...document.querySelectorAll("pbs-diagram")].filter((other) => sourceOf(other) === source);
|
|
351
|
+
found = typeof nth === "number" ? alike[nth] : undefined;
|
|
352
|
+
} catch {
|
|
353
|
+
// A ref that cannot be read finds nothing.
|
|
354
|
+
}
|
|
355
|
+
if (!found) return undefined;
|
|
356
|
+
const position = [...document.querySelectorAll("pbs-diagram")].indexOf(found) + 1;
|
|
357
|
+
return quote.replace(/^\[Diagram \d+,/, `[Diagram ${position},`);
|
|
239
358
|
}
|
|
@@ -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 {
|
|
@@ -77,6 +79,24 @@ export interface FeedbackOptions {
|
|
|
77
79
|
watchDocument?: boolean;
|
|
78
80
|
/** Whether the page's diagrams can be commented on (the hint says so); a host calls `comment` for them. */
|
|
79
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. `undefined` when what the ref names is no longer on the page: the quote keeps
|
|
85
|
+
* its text, marked (`STALE`) while another draft's quote reads the same.
|
|
86
|
+
*/
|
|
87
|
+
requote?: (quote: string, ref: string) => string | undefined;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* What a draft's quote adds when what it named is no longer on the page and another draft's quote reads the same, so
|
|
92
|
+
* two drafts never share a quote. Part of the message the agent reads; keep it stable.
|
|
93
|
+
*/
|
|
94
|
+
export const STALE = " (from an earlier version of the page)";
|
|
95
|
+
|
|
96
|
+
/** A quote without the `STALE` mark (and its number) it was saved with. */
|
|
97
|
+
function unmarked(quote: string): string {
|
|
98
|
+
const at = quote.lastIndexOf(STALE);
|
|
99
|
+
return at !== -1 && /^(?: #\d+)?$/.test(quote.slice(at + STALE.length)) ? quote.slice(0, at) : quote;
|
|
80
100
|
}
|
|
81
101
|
|
|
82
102
|
/** A passage to comment on, and where the Add button goes (viewport coordinates of the panel's document). */
|
|
@@ -107,23 +127,56 @@ export function mountFeedback(options: FeedbackOptions): {
|
|
|
107
127
|
/**
|
|
108
128
|
* Adds `quote` to the panel as a commented target at once and opens the panel on its comment box; for what cannot be
|
|
109
129
|
* selected as text (a diagram's node or edge). A target already in the panel is not added twice, only focused.
|
|
130
|
+
* `ref` is kept with the draft for `requote`; Escape in the panel returns focus to `back`, the control it came from.
|
|
110
131
|
*/
|
|
111
|
-
comment: (quote: string) => void;
|
|
132
|
+
comment: (quote: string, from?: { ref?: string; back?: HTMLElement | SVGElement }) => void;
|
|
112
133
|
destroy: () => void;
|
|
113
134
|
} {
|
|
114
135
|
const { words, storage, storageKey } = options;
|
|
115
136
|
let items: FeedbackItem[] = [];
|
|
116
137
|
let overall = "";
|
|
138
|
+
/** The restored drafts whose `ref` names nothing on the page now, with their quote as it was made (unmarked). */
|
|
139
|
+
const stale = new Map<FeedbackItem, string>();
|
|
117
140
|
try {
|
|
118
141
|
const saved = JSON.parse(storage.getItem(storageKey) ?? "null") as {
|
|
119
142
|
items?: FeedbackItem[];
|
|
120
143
|
overall?: string;
|
|
121
144
|
} | null;
|
|
122
|
-
|
|
145
|
+
const { requote } = options;
|
|
146
|
+
items = (saved?.items ?? []).map((item) => {
|
|
147
|
+
if (!item.ref || !requote) return item;
|
|
148
|
+
const made = unmarked(item.quote);
|
|
149
|
+
const quote = requote(made, item.ref);
|
|
150
|
+
if (quote !== undefined) return { ...item, quote };
|
|
151
|
+
const kept = { ...item, quote: made };
|
|
152
|
+
stale.set(kept, made);
|
|
153
|
+
return kept;
|
|
154
|
+
});
|
|
123
155
|
overall = saved?.overall ?? "";
|
|
124
156
|
} catch {
|
|
125
157
|
// A draft that cannot be read is dropped.
|
|
126
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Marks each stale quote that reads like another draft's, current or stale, and numbers marks that would still be
|
|
161
|
+
* alike; a stale quote that reads like no other is left as it was made.
|
|
162
|
+
*/
|
|
163
|
+
const settle = (): void => {
|
|
164
|
+
const used = new Set(items.filter((item) => !stale.has(item)).map((item) => item.quote));
|
|
165
|
+
const made = [...stale.values()];
|
|
166
|
+
for (const item of items) {
|
|
167
|
+
const quote = stale.get(item);
|
|
168
|
+
if (quote === undefined) continue;
|
|
169
|
+
if (!used.has(quote) && made.filter((other) => other === quote).length < 2) {
|
|
170
|
+
item.quote = quote;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
let marked = `${quote}${STALE}`;
|
|
174
|
+
for (let n = 2; used.has(marked); n += 1) marked = `${quote}${STALE} #${n}`;
|
|
175
|
+
item.quote = marked;
|
|
176
|
+
used.add(marked);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
settle();
|
|
127
180
|
const save = (): void => {
|
|
128
181
|
if (items.length === 0 && !overall) storage.removeItem(storageKey);
|
|
129
182
|
else storage.setItem(storageKey, JSON.stringify({ items, overall }));
|
|
@@ -160,8 +213,8 @@ export function mountFeedback(options: FeedbackOptions): {
|
|
|
160
213
|
const remove = make("button", { type: "button", textContent: words.remove });
|
|
161
214
|
remove.addEventListener("click", () => {
|
|
162
215
|
items.splice(index, 1);
|
|
163
|
-
|
|
164
|
-
|
|
216
|
+
stale.delete(item);
|
|
217
|
+
changed();
|
|
165
218
|
});
|
|
166
219
|
entry.append(quote, box, remove);
|
|
167
220
|
return entry;
|
|
@@ -169,13 +222,29 @@ export function mountFeedback(options: FeedbackOptions): {
|
|
|
169
222
|
);
|
|
170
223
|
toggle.textContent = items.length > 0 ? `${words.feedback} (${items.length})` : words.feedback;
|
|
171
224
|
};
|
|
225
|
+
/** After a draft is added or removed: marks the quotes that now read alike, keeps, and redraws. */
|
|
226
|
+
const changed = (): void => {
|
|
227
|
+
settle();
|
|
228
|
+
save();
|
|
229
|
+
draw();
|
|
230
|
+
};
|
|
172
231
|
overallBox.addEventListener("input", () => {
|
|
173
232
|
overall = overallBox.value;
|
|
174
233
|
save();
|
|
175
234
|
});
|
|
235
|
+
/** Where Escape in the panel returns focus: the diagram element a comment was opened from. */
|
|
236
|
+
let back: HTMLElement | SVGElement | undefined;
|
|
176
237
|
toggle.addEventListener("click", () => {
|
|
238
|
+
back = undefined;
|
|
177
239
|
panel.hidden = !panel.hidden;
|
|
178
240
|
});
|
|
241
|
+
panel.addEventListener("keydown", (event) => {
|
|
242
|
+
// An Escape that ends an input method's composition belongs to the input method.
|
|
243
|
+
if (event.isComposing || event.keyCode === 229) return;
|
|
244
|
+
if (event.key !== "Escape" || !back?.isConnected) return;
|
|
245
|
+
event.preventDefault();
|
|
246
|
+
back.focus();
|
|
247
|
+
});
|
|
179
248
|
|
|
180
249
|
let pending = "";
|
|
181
250
|
const offer = (passage: Offered | undefined): void => {
|
|
@@ -207,23 +276,25 @@ export function mountFeedback(options: FeedbackOptions): {
|
|
|
207
276
|
panel.hidden = false;
|
|
208
277
|
list.querySelectorAll("textarea").item(index)?.focus();
|
|
209
278
|
};
|
|
210
|
-
const comment = (quote: string): void => {
|
|
211
|
-
const
|
|
279
|
+
const comment = (quote: string, from: { ref?: string; back?: HTMLElement | SVGElement } = {}): void => {
|
|
280
|
+
const { ref } = from;
|
|
281
|
+
back = from.back;
|
|
282
|
+
// A stale draft names something the page no longer has, even when its quote reads the same.
|
|
283
|
+
const known = items.findIndex((item) => item.quote === quote && !stale.has(item));
|
|
212
284
|
if (known === -1) {
|
|
213
|
-
items.push({ quote, comment: "" });
|
|
214
|
-
|
|
215
|
-
draw();
|
|
285
|
+
items.push(ref ? { quote, comment: "", ref } : { quote, comment: "" });
|
|
286
|
+
changed();
|
|
216
287
|
}
|
|
217
288
|
open(known === -1 ? items.length - 1 : known);
|
|
218
289
|
};
|
|
219
290
|
add.addEventListener("click", () => {
|
|
291
|
+
back = undefined;
|
|
220
292
|
const quote = pending;
|
|
221
293
|
pending = "";
|
|
222
294
|
add.hidden = true;
|
|
223
295
|
getSelection()?.removeAllRanges();
|
|
224
296
|
if (quote) items.push({ quote, comment: "" });
|
|
225
|
-
|
|
226
|
-
draw();
|
|
297
|
+
changed();
|
|
227
298
|
open(items.length - 1);
|
|
228
299
|
});
|
|
229
300
|
sendButton.addEventListener("click", () => {
|
|
@@ -238,6 +309,7 @@ export function mountFeedback(options: FeedbackOptions): {
|
|
|
238
309
|
.then(
|
|
239
310
|
() => {
|
|
240
311
|
items = [];
|
|
312
|
+
stale.clear();
|
|
241
313
|
overall = "";
|
|
242
314
|
overallBox.value = "";
|
|
243
315
|
save();
|
|
@@ -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,9 +1,10 @@
|
|
|
1
1
|
import type { Answer } from "../../core/types.ts";
|
|
2
2
|
import "../../elements/index.ts";
|
|
3
3
|
import { configure } from "../../elements/index.ts";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
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";
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* The script of a rendered Markdown page: wires the elements to the page server (diagrams, images, answers),
|
|
@@ -15,53 +16,13 @@ configureElements(prefix);
|
|
|
15
16
|
// A diagram's nodes and edges can be commented on, not only selected text.
|
|
16
17
|
configure({ diagramMap: fetchDiagramMap });
|
|
17
18
|
|
|
18
|
-
|
|
19
|
-
postAnswerToServer(`${prefix}/answer`, { answerId: newAnswerId(), answer, page: location.pathname });
|
|
20
|
-
|
|
21
|
-
const toast = (text: string): void => {
|
|
22
|
-
const box = document.createElement("div");
|
|
23
|
-
box.className = "pbs-toast";
|
|
24
|
-
box.setAttribute("role", "status");
|
|
25
|
-
box.textContent = text;
|
|
26
|
-
document.body.append(box);
|
|
27
|
-
setTimeout(() => box.remove(), 5000);
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
const lang = document.documentElement.lang || navigator.language;
|
|
31
|
-
const words = wordsFor(lang);
|
|
32
|
-
|
|
33
|
-
document.addEventListener("pbs-answer", (event) => {
|
|
34
|
-
const answer = (event as CustomEvent<Answer>).detail;
|
|
35
|
-
const element = event.target as (HTMLElement & { answered?: unknown }) | null;
|
|
36
|
-
postAnswer(answer).then(
|
|
37
|
-
(reply) => {
|
|
38
|
-
if (reply.accepted) return;
|
|
39
|
-
// A pick locks itself once taken; clearing `answered` reopens it so the user can try again.
|
|
40
|
-
if (element) element.answered = undefined;
|
|
41
|
-
toast(`${words.notSent}${reply.reason ?? "refused"}`);
|
|
42
|
-
},
|
|
43
|
-
(error: unknown) => {
|
|
44
|
-
if (element) element.answered = undefined;
|
|
45
|
-
toast(`${words.notSent}${error instanceof Error ? error.message : String(error)}`);
|
|
46
|
-
},
|
|
47
|
-
);
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
const feedback = mountFeedback({
|
|
19
|
+
mountPage({
|
|
51
20
|
page: document.title || location.pathname.split("/").pop() || "",
|
|
52
|
-
words,
|
|
53
|
-
diagrams: true,
|
|
21
|
+
words: wordsFor(document.documentElement.lang || navigator.language),
|
|
54
22
|
storage: sessionStorage,
|
|
55
23
|
storageKey: `pbs-feedback:${location.pathname}`,
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if (!reply.accepted) throw new Error(reply.reason ?? "refused");
|
|
59
|
-
},
|
|
60
|
-
});
|
|
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));
|
|
24
|
+
post: (answer: Answer) =>
|
|
25
|
+
postAnswerToServer(`${prefix}/answer`, { answerId: newAnswerId(), answer, page: location.pathname }),
|
|
65
26
|
});
|
|
66
27
|
|
|
67
28
|
new EventSource(`${prefix}/events?page=${encodeURIComponent(location.pathname)}`).addEventListener("reload", () =>
|
package/src/extension/server.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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);
|