pi-better-show 0.3.0 → 0.4.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 +39 -5
- package/bin/pbs-tree.js +424 -0
- package/package.json +5 -1
- package/src/core/parse.ts +2 -0
- package/src/core/text.ts +24 -0
- package/src/core/tree.ts +84 -0
- package/src/core/types.ts +34 -1
- package/src/core/validate.ts +10 -0
- package/src/elements/index.ts +4 -0
- package/src/elements/strings.ts +13 -0
- package/src/elements/tree.ts +261 -0
- package/src/extension/client/bridge.ts +29 -0
- package/src/extension/client/feedback.ts +38 -16
- package/src/extension/client/frame.ts +27 -1
- package/src/extension/client/host-config.ts +20 -0
- package/src/extension/client/host-page.ts +73 -0
- package/src/extension/client/host.ts +12 -24
- package/src/extension/client/page.ts +3 -12
- package/src/extension/controller.ts +34 -16
- package/src/extension/index.ts +1 -2
- package/src/extension/server.ts +20 -2
- package/src/extension/tool.ts +7 -3
- package/src/react/index.ts +3 -0
package/src/core/tree.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { TREE_LIMITS, TREE_TAGS, type TreeData, type TreeNode, type TreeTag } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
const MORE = /^… (\d+) more$/;
|
|
4
|
+
const NOTE = " # ";
|
|
5
|
+
const TAGS = /^(?:(.*?) )?\{([^{}]*)\}$/;
|
|
6
|
+
const KNOWN = new Set<string>(TREE_TAGS);
|
|
7
|
+
|
|
8
|
+
/** Trims spaces and tabs only: a no-break space at an edge belongs to a name. */
|
|
9
|
+
const strip = (text: string): string => text.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
10
|
+
|
|
11
|
+
/** The tags written between braces: names separated by commas or spaces, each once, all known. */
|
|
12
|
+
function tagsOf(list: string, line: number): TreeTag[] {
|
|
13
|
+
const tags: TreeTag[] = [];
|
|
14
|
+
for (const word of list.split(/[\s,]+/).filter(Boolean)) {
|
|
15
|
+
if (!KNOWN.has(word)) throw new Error(`line ${line}: unknown tag "${word}" (use ${TREE_TAGS.join(", ")})`);
|
|
16
|
+
if (!tags.includes(word as TreeTag)) tags.push(word as TreeTag);
|
|
17
|
+
}
|
|
18
|
+
return tags;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One line's content (indentation already removed): `name[/] [{tags}] [# note]`. */
|
|
22
|
+
function nodeOf(content: string, line: number): TreeNode {
|
|
23
|
+
const cut = content.indexOf(NOTE);
|
|
24
|
+
const head = strip(cut < 0 ? content : content.slice(0, cut));
|
|
25
|
+
const note = cut < 0 ? "" : strip(content.slice(cut + NOTE.length));
|
|
26
|
+
const tagged = TAGS.exec(head);
|
|
27
|
+
const text = tagged ? (tagged[1] ?? "") : head;
|
|
28
|
+
const dir = text.endsWith("/");
|
|
29
|
+
const name = strip(dir ? text.slice(0, -1) : text);
|
|
30
|
+
if (name === "") throw new Error(`line ${line}: a line has no name`);
|
|
31
|
+
// Tags are read last, so a bad name is reported before a bad tag.
|
|
32
|
+
const tags = tagged ? tagsOf(tagged[2] as string, line) : [];
|
|
33
|
+
const more = dir ? null : MORE.exec(name);
|
|
34
|
+
return {
|
|
35
|
+
name,
|
|
36
|
+
dir,
|
|
37
|
+
tags,
|
|
38
|
+
...(note === "" ? {} : { note }),
|
|
39
|
+
children: [],
|
|
40
|
+
...(more ? { more: Number(more[1]) } : {}),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* An indented tree, two spaces per level: the first line is the root, a folder's name ends with `/`, then optional
|
|
46
|
+
* `{tags}` and a note after ` # `. A `… N more` line stands for entries a limit cut. At most 2,000 lines and 32 levels.
|
|
47
|
+
*/
|
|
48
|
+
export function tree(source: string): TreeData {
|
|
49
|
+
const stack: TreeNode[] = [];
|
|
50
|
+
let root: TreeNode | undefined;
|
|
51
|
+
let count = 0;
|
|
52
|
+
for (const [at, raw] of source.split("\n").entries()) {
|
|
53
|
+
const line = raw.replace(/[ \t]+$/, "");
|
|
54
|
+
if (line === "") continue;
|
|
55
|
+
const number = at + 1;
|
|
56
|
+
const space = /^[ \t]*/.exec(line)?.[0] as string;
|
|
57
|
+
if (space.includes("\t")) throw new Error(`line ${number}: indent with two spaces, not tabs`);
|
|
58
|
+
if (space.length % 2 !== 0) throw new Error(`line ${number}: indent by two spaces per level`);
|
|
59
|
+
const level = space.length / 2;
|
|
60
|
+
if (root === undefined && level > 0) throw new Error(`line ${number}: the root line is not indented`);
|
|
61
|
+
if (level > stack.length) throw new Error(`line ${number}: indented more than one level below the line above`);
|
|
62
|
+
if (++count > TREE_LIMITS.nodes) throw new Error(`a tree holds at most ${TREE_LIMITS.nodes} nodes`);
|
|
63
|
+
if (level + 1 > TREE_LIMITS.depth) throw new Error(`a tree is at most ${TREE_LIMITS.depth} levels deep`);
|
|
64
|
+
if (level === 0 && root !== undefined) {
|
|
65
|
+
throw new Error("a tree has one root: indent the other top-level lines under it");
|
|
66
|
+
}
|
|
67
|
+
const node = nodeOf(line.slice(space.length), number);
|
|
68
|
+
stack.length = level;
|
|
69
|
+
const parent = stack[level - 1];
|
|
70
|
+
if (parent) {
|
|
71
|
+
if (!parent.dir) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`line ${number}: "${parent.name}" is a file and cannot hold entries (end a folder's name with /)`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
parent.children.push(node);
|
|
77
|
+
} else {
|
|
78
|
+
root = node;
|
|
79
|
+
}
|
|
80
|
+
stack.push(node);
|
|
81
|
+
}
|
|
82
|
+
if (root === undefined) throw new Error("a tree needs a root line");
|
|
83
|
+
return { root };
|
|
84
|
+
}
|
package/src/core/types.ts
CHANGED
|
@@ -14,6 +14,7 @@ export const BLOCK_KINDS = [
|
|
|
14
14
|
"table",
|
|
15
15
|
"steps",
|
|
16
16
|
"stats",
|
|
17
|
+
"tree",
|
|
17
18
|
] as const;
|
|
18
19
|
export type BlockKind = (typeof BLOCK_KINDS)[number];
|
|
19
20
|
|
|
@@ -166,6 +167,27 @@ export interface StatsData {
|
|
|
166
167
|
items: StatItem[];
|
|
167
168
|
}
|
|
168
169
|
|
|
170
|
+
/** What a tree line can be marked with; the host draws each in its tone. */
|
|
171
|
+
export const TREE_TAGS = ["new", "changed", "removed", "focus", "risk"] as const;
|
|
172
|
+
export type TreeTag = (typeof TREE_TAGS)[number];
|
|
173
|
+
/** A tree beyond these is invalid: nodes counts every line, depth counts the root as level 1. */
|
|
174
|
+
export const TREE_LIMITS = { nodes: 2000, depth: 32 } as const;
|
|
175
|
+
|
|
176
|
+
export interface TreeNode {
|
|
177
|
+
/** The file or folder name, without the folder's trailing `/` and without tags or note. Plain text. */
|
|
178
|
+
name: string;
|
|
179
|
+
dir: boolean;
|
|
180
|
+
tags: TreeTag[];
|
|
181
|
+
/** Restricted inline Markdown. */
|
|
182
|
+
note?: string;
|
|
183
|
+
children: TreeNode[];
|
|
184
|
+
/** On a `… N more` line: the number of entries a limit cut. */
|
|
185
|
+
more?: number;
|
|
186
|
+
}
|
|
187
|
+
export interface TreeData {
|
|
188
|
+
root: TreeNode;
|
|
189
|
+
}
|
|
190
|
+
|
|
169
191
|
export interface BlockDataMap {
|
|
170
192
|
alert: AlertData;
|
|
171
193
|
mermaid: MermaidData;
|
|
@@ -180,6 +202,7 @@ export interface BlockDataMap {
|
|
|
180
202
|
table: TableData;
|
|
181
203
|
steps: StepsData;
|
|
182
204
|
stats: StatsData;
|
|
205
|
+
tree: TreeData;
|
|
183
206
|
}
|
|
184
207
|
|
|
185
208
|
export interface MarkdownSegment {
|
|
@@ -240,7 +263,17 @@ export interface TextProfile {
|
|
|
240
263
|
export type TextLang = "en" | "zh-TW";
|
|
241
264
|
|
|
242
265
|
/** The kinds a display surface (a chat UI that draws blocks itself) typically keeps through `toText`. */
|
|
243
|
-
export const DISPLAY_KINDS = [
|
|
266
|
+
export const DISPLAY_KINDS = [
|
|
267
|
+
"alert",
|
|
268
|
+
"cards",
|
|
269
|
+
"mermaid",
|
|
270
|
+
"mindmap",
|
|
271
|
+
"diff",
|
|
272
|
+
"table",
|
|
273
|
+
"steps",
|
|
274
|
+
"stats",
|
|
275
|
+
"tree",
|
|
276
|
+
] as const;
|
|
244
277
|
|
|
245
278
|
/** The kinds a reader answers; a surface that cannot draw them gets their reply instructions from `toText`. */
|
|
246
279
|
export const INTERACTIVE_KINDS = ["options", "suggest", "form", "checklist", "review"] as const;
|
package/src/core/validate.ts
CHANGED
|
@@ -122,6 +122,16 @@ function problem(block: BlockSegment, answer: Answer): string | undefined {
|
|
|
122
122
|
* are at most 64 fields of 1,024 characters each.
|
|
123
123
|
*/
|
|
124
124
|
export function validateAnswer(block: BlockSegment, answer: Answer): Validation {
|
|
125
|
+
// The answer comes from outside: check its shape before reading it.
|
|
126
|
+
const shaped = answer as { kind?: unknown; fields?: unknown };
|
|
127
|
+
if (typeof shaped.kind !== "string") return fail("answer kind is not a string");
|
|
128
|
+
if (
|
|
129
|
+
!Array.isArray(shaped.fields) ||
|
|
130
|
+
!shaped.fields.every(
|
|
131
|
+
(pair) => Array.isArray(pair) && pair.length === 2 && typeof pair[0] === "string" && typeof pair[1] === "string",
|
|
132
|
+
)
|
|
133
|
+
)
|
|
134
|
+
return fail("answer fields are not pairs of strings");
|
|
125
135
|
const expected = KINDS[block.kind];
|
|
126
136
|
if (expected === undefined) return fail(`a ${block.kind} block takes no answer`);
|
|
127
137
|
if (answer.kind !== expected) return fail(`answer kind ${quoted(answer.kind)} does not fit a ${block.kind} block`);
|
package/src/elements/index.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { defineForm } from "./form.ts";
|
|
|
11
11
|
import { defineMindmap } from "./mindmap.ts";
|
|
12
12
|
import { defineReview } from "./review.ts";
|
|
13
13
|
import { defineTable } from "./table.ts";
|
|
14
|
+
import { defineTree } from "./tree.ts";
|
|
14
15
|
|
|
15
16
|
export type { AnsweredFields, BlockRef, Density } from "./base.ts";
|
|
16
17
|
export { PbsElement } from "./base.ts";
|
|
@@ -23,6 +24,7 @@ export { PbsMindmap } from "./mindmap.ts";
|
|
|
23
24
|
export { PbsReview } from "./review.ts";
|
|
24
25
|
export type { Locale, Strings } from "./strings.ts";
|
|
25
26
|
export { PbsTable } from "./table.ts";
|
|
27
|
+
export { PbsTree } from "./tree.ts";
|
|
26
28
|
|
|
27
29
|
/** The tag of every element, by the block kind it draws. `alert` is drawn by `pbs-callout`, `mermaid` by `pbs-diagram`. */
|
|
28
30
|
export const TAGS = {
|
|
@@ -39,6 +41,7 @@ export const TAGS = {
|
|
|
39
41
|
stats: "pbs-stats",
|
|
40
42
|
diff: "pbs-diff",
|
|
41
43
|
mermaid: "pbs-diagram",
|
|
44
|
+
tree: "pbs-tree",
|
|
42
45
|
} as const;
|
|
43
46
|
|
|
44
47
|
/** Defines every element that is not defined yet. Importing the module already calls it. */
|
|
@@ -49,6 +52,7 @@ export function defineAll(): void {
|
|
|
49
52
|
defineReview();
|
|
50
53
|
defineMindmap();
|
|
51
54
|
defineTable();
|
|
55
|
+
defineTree();
|
|
52
56
|
}
|
|
53
57
|
|
|
54
58
|
defineAll();
|
package/src/elements/strings.ts
CHANGED
|
@@ -39,6 +39,11 @@ export interface Strings {
|
|
|
39
39
|
diff: string;
|
|
40
40
|
table: string;
|
|
41
41
|
mindmap: string;
|
|
42
|
+
tree: string;
|
|
43
|
+
treeExpandAll: string;
|
|
44
|
+
treeCollapseAll: string;
|
|
45
|
+
/** A folder's count of entries; `{n}` is the number. */
|
|
46
|
+
treeEntries: string;
|
|
42
47
|
suggestions: string;
|
|
43
48
|
checklistProgress: string;
|
|
44
49
|
stats: string;
|
|
@@ -86,6 +91,10 @@ export const STRINGS: Record<Locale, Strings> = {
|
|
|
86
91
|
diff: "Diff",
|
|
87
92
|
table: "Table",
|
|
88
93
|
mindmap: "Mind map",
|
|
94
|
+
tree: "Directory tree",
|
|
95
|
+
treeExpandAll: "Expand all",
|
|
96
|
+
treeCollapseAll: "Collapse all",
|
|
97
|
+
treeEntries: "entries: {n}",
|
|
89
98
|
suggestions: "Suggested replies",
|
|
90
99
|
checklistProgress: "{done} of {total} done",
|
|
91
100
|
stats: "Metrics",
|
|
@@ -131,6 +140,10 @@ export const STRINGS: Record<Locale, Strings> = {
|
|
|
131
140
|
diff: "差異",
|
|
132
141
|
table: "表格",
|
|
133
142
|
mindmap: "心智圖",
|
|
143
|
+
tree: "目錄樹",
|
|
144
|
+
treeExpandAll: "全部展開",
|
|
145
|
+
treeCollapseAll: "全部收合",
|
|
146
|
+
treeEntries: "{n} 項",
|
|
134
147
|
suggestions: "建議回覆",
|
|
135
148
|
checklistProgress: "已完成 {done} / {total}",
|
|
136
149
|
stats: "指標",
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import type { TreeData, TreeNode } from "../core/types.ts";
|
|
2
|
+
import { define, PbsElement } from "./base.ts";
|
|
3
|
+
import { h, inlineNodes, uid } from "./dom.ts";
|
|
4
|
+
|
|
5
|
+
const treeCss = `
|
|
6
|
+
.treeview { padding: 0; overflow: hidden; }
|
|
7
|
+
.treeview .bar { display: flex; flex-wrap: wrap; gap: 0.25rem 0.5rem; padding: var(--_pad-s) var(--_pad); border-bottom: 1px solid var(--_line); background: var(--_surface); }
|
|
8
|
+
.treeview .bar .btn { padding: 0.15em 0.7em; font-size: 0.9em; }
|
|
9
|
+
.treeview .body { padding: var(--_pad-s) var(--_pad); overflow: auto; max-width: 100%; }
|
|
10
|
+
.treeview ul { list-style: none; margin: 0; padding: 0; }
|
|
11
|
+
.treeview ul ul { padding-left: 1.2rem; }
|
|
12
|
+
.treeview li { margin: 0; }
|
|
13
|
+
.treeview li:focus { outline: none; }
|
|
14
|
+
.treeview .node { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 0.45rem; padding: 0.1rem 0.4rem; border-radius: 6px; cursor: default; }
|
|
15
|
+
.treeview li[aria-expanded] > .node { cursor: pointer; }
|
|
16
|
+
.treeview li:focus-visible > .node { outline: 2px solid var(--_accent); outline-offset: 1px; }
|
|
17
|
+
.treeview .node:hover { background: var(--_surface); }
|
|
18
|
+
.treeview .toggle { flex: none; width: 1em; color: var(--_muted); text-align: center; font-size: 0.85em; }
|
|
19
|
+
.treeview .name { font-family: var(--_mono); font-size: 0.92em; overflow-wrap: anywhere; }
|
|
20
|
+
.treeview .count { color: var(--_muted); font-size: 0.8em; }
|
|
21
|
+
.treeview .tags { display: inline-flex; flex-wrap: wrap; gap: 0.25rem; }
|
|
22
|
+
.treeview .note { min-width: 0; flex: 1 1 12rem; color: var(--_muted); font-size: 0.9em; }
|
|
23
|
+
.treeview .more { color: var(--_muted); font-size: 0.9em; font-style: italic; }
|
|
24
|
+
.treeview [data-tag="new"] { --_t: var(--_ok); }
|
|
25
|
+
.treeview [data-tag="changed"] { --_t: var(--_note); }
|
|
26
|
+
.treeview [data-tag="removed"] { --_t: var(--_muted); }
|
|
27
|
+
.treeview [data-tag="focus"] { --_t: var(--_accent); }
|
|
28
|
+
.treeview [data-tag="risk"] { --_t: var(--_risk); }
|
|
29
|
+
.treeview li[data-tags~="removed"] > .node .name { color: var(--_muted); text-decoration: line-through; }
|
|
30
|
+
.treeview li[data-tags~="focus"] > .node { background: color-mix(in srgb, var(--_accent) 10%, transparent); }
|
|
31
|
+
.treeview li[data-tags~="risk"] > .node .name { color: var(--_risk); }
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
/** Folders deeper than this start closed, unless something under them is tagged. */
|
|
35
|
+
const OPEN_TO_LEVEL = 2;
|
|
36
|
+
|
|
37
|
+
interface Item {
|
|
38
|
+
node: TreeNode;
|
|
39
|
+
/** The item's address in the tree (`0.2.1`), which keeps its open state across a redraw. */
|
|
40
|
+
path: string;
|
|
41
|
+
element: HTMLElement;
|
|
42
|
+
group: HTMLElement | undefined;
|
|
43
|
+
toggle: HTMLElement;
|
|
44
|
+
parent: Item | undefined;
|
|
45
|
+
children: Item[];
|
|
46
|
+
expanded: boolean;
|
|
47
|
+
/** The node or something below it carries a tag. */
|
|
48
|
+
tagged: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Entries a folder holds, counting the ones a `… N more` line stands for. */
|
|
52
|
+
const entries = (node: TreeNode): number => node.children.reduce((sum, child) => sum + (child.more ?? 1), 0);
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A directory tree (WAI-ARIA tree pattern): folders open and close by click, arrows, Enter and Space; Home and End jump.
|
|
56
|
+
* Tags show as badges, notes beside the name, and the folders that hold a tagged node start open.
|
|
57
|
+
*/
|
|
58
|
+
export class PbsTree extends PbsElement<TreeData> {
|
|
59
|
+
static override css = treeCss;
|
|
60
|
+
/** Open state the user chose, by item path. */
|
|
61
|
+
#open = new Map<string, boolean>();
|
|
62
|
+
|
|
63
|
+
protected override reset(): void {
|
|
64
|
+
this.#open = new Map();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
protected view(data: TreeData): Node {
|
|
68
|
+
const items: Item[] = [];
|
|
69
|
+
let current: Item | undefined;
|
|
70
|
+
|
|
71
|
+
const build = (node: TreeNode, path: string, level: number, parent: Item | undefined, at: number, of: number) => {
|
|
72
|
+
const ids = { name: uid("pbs-tree"), note: uid("pbs-tree") };
|
|
73
|
+
const toggle = h("span", { part: "toggle", class: "toggle", "aria-hidden": "true" });
|
|
74
|
+
const tagIds: string[] = [];
|
|
75
|
+
const row: (Node | null)[] = [toggle];
|
|
76
|
+
if (node.more === undefined) {
|
|
77
|
+
row.push(h("span", { part: "name", class: "name", id: ids.name }, node.name + (node.dir ? "/" : "")));
|
|
78
|
+
if (node.children.length > 0) {
|
|
79
|
+
row.push(h("span", { part: "count", class: "count" }, this.t("treeEntries", { n: entries(node) })));
|
|
80
|
+
}
|
|
81
|
+
if (node.tags.length > 0) {
|
|
82
|
+
row.push(
|
|
83
|
+
h(
|
|
84
|
+
"span",
|
|
85
|
+
{ part: "tags", class: "tags" },
|
|
86
|
+
node.tags.map((tag) => {
|
|
87
|
+
const id = uid("pbs-tree");
|
|
88
|
+
tagIds.push(id);
|
|
89
|
+
return h("span", { part: "tag", class: "badge tag", id, "data-tag": tag }, tag);
|
|
90
|
+
}),
|
|
91
|
+
),
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
if (node.note !== undefined) {
|
|
95
|
+
row.push(h("span", { part: "note", class: "note", id: ids.note }, inlineNodes(node.note)));
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
row.push(h("span", { part: "more", class: "more", id: ids.name }, node.name));
|
|
99
|
+
}
|
|
100
|
+
const labelled = [ids.name, ...tagIds, ...(node.note !== undefined && node.more === undefined ? [ids.note] : [])];
|
|
101
|
+
const element = h(
|
|
102
|
+
"li",
|
|
103
|
+
{
|
|
104
|
+
role: "treeitem",
|
|
105
|
+
part: "item",
|
|
106
|
+
tabindex: "-1",
|
|
107
|
+
"aria-labelledby": labelled.join(" "),
|
|
108
|
+
"aria-level": level + 1,
|
|
109
|
+
"aria-setsize": of,
|
|
110
|
+
"aria-posinset": at + 1,
|
|
111
|
+
"data-tags": node.tags.length > 0 ? node.tags.join(" ") : null,
|
|
112
|
+
},
|
|
113
|
+
h("div", { part: "node", class: "node" }, row),
|
|
114
|
+
);
|
|
115
|
+
const item: Item = {
|
|
116
|
+
node,
|
|
117
|
+
path,
|
|
118
|
+
element,
|
|
119
|
+
group: undefined,
|
|
120
|
+
toggle,
|
|
121
|
+
parent,
|
|
122
|
+
children: [],
|
|
123
|
+
expanded: false,
|
|
124
|
+
tagged: node.tags.length > 0,
|
|
125
|
+
};
|
|
126
|
+
items.push(item);
|
|
127
|
+
if (node.children.length > 0) {
|
|
128
|
+
item.children = node.children.map((child, index) =>
|
|
129
|
+
build(child, `${path}.${index}`, level + 1, item, index, node.children.length),
|
|
130
|
+
);
|
|
131
|
+
item.group = h(
|
|
132
|
+
"ul",
|
|
133
|
+
{ role: "group", part: "group" },
|
|
134
|
+
item.children.map((child) => child.element),
|
|
135
|
+
);
|
|
136
|
+
element.append(item.group);
|
|
137
|
+
const holdsTag = item.children.some((child) => child.tagged);
|
|
138
|
+
item.tagged ||= holdsTag;
|
|
139
|
+
item.expanded = this.#open.get(path) ?? (level <= OPEN_TO_LEVEL || holdsTag);
|
|
140
|
+
}
|
|
141
|
+
sync(item);
|
|
142
|
+
(element.firstElementChild as Element).addEventListener("click", () => {
|
|
143
|
+
toggleItem(item);
|
|
144
|
+
focus(item);
|
|
145
|
+
});
|
|
146
|
+
return item;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** Brings an item's markers in line with its open state. */
|
|
150
|
+
const sync = (item: Item) => {
|
|
151
|
+
const branch = item.children.length > 0;
|
|
152
|
+
if (branch) item.element.setAttribute("aria-expanded", String(item.expanded));
|
|
153
|
+
if (item.group) item.group.hidden = !item.expanded;
|
|
154
|
+
item.toggle.textContent = branch ? (item.expanded ? "▾" : "▸") : "";
|
|
155
|
+
};
|
|
156
|
+
const setOpen = (item: Item, open: boolean) => {
|
|
157
|
+
if (item.children.length === 0 || item.expanded === open) return;
|
|
158
|
+
item.expanded = open;
|
|
159
|
+
this.#open.set(item.path, open);
|
|
160
|
+
sync(item);
|
|
161
|
+
};
|
|
162
|
+
const toggleItem = (item: Item) => setOpen(item, !item.expanded);
|
|
163
|
+
|
|
164
|
+
const visible = (): Item[] => {
|
|
165
|
+
const out: Item[] = [];
|
|
166
|
+
const walk = (item: Item) => {
|
|
167
|
+
out.push(item);
|
|
168
|
+
if (item.expanded) item.children.forEach(walk);
|
|
169
|
+
};
|
|
170
|
+
walk(root);
|
|
171
|
+
return out;
|
|
172
|
+
};
|
|
173
|
+
const stop = (item: Item) => {
|
|
174
|
+
for (const each of items) each.element.tabIndex = each === item ? 0 : -1;
|
|
175
|
+
current = item;
|
|
176
|
+
};
|
|
177
|
+
const focus = (item: Item) => {
|
|
178
|
+
stop(item);
|
|
179
|
+
item.element.focus();
|
|
180
|
+
};
|
|
181
|
+
/** After folders closed: the single tab stop goes to the nearest item still shown. */
|
|
182
|
+
const keepStop = () => {
|
|
183
|
+
const shown = new Set(visible());
|
|
184
|
+
let at = current;
|
|
185
|
+
while (at && !shown.has(at)) at = at.parent;
|
|
186
|
+
stop(at ?? root);
|
|
187
|
+
};
|
|
188
|
+
const all = (open: boolean) => {
|
|
189
|
+
for (const item of items) {
|
|
190
|
+
// Closing everything leaves the root open: a closed root would hide the whole tree.
|
|
191
|
+
setOpen(item, item === root ? true : open);
|
|
192
|
+
}
|
|
193
|
+
keepStop();
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const root = build(data.root, "0", 0, undefined, 0, 1);
|
|
197
|
+
stop(root);
|
|
198
|
+
|
|
199
|
+
const tree = h("ul", { role: "tree", part: "tree", "aria-label": this.t("tree") }, root.element);
|
|
200
|
+
tree.addEventListener("focusin", (event) => {
|
|
201
|
+
const found = items.find((item) => item.element === event.target);
|
|
202
|
+
if (found) stop(found);
|
|
203
|
+
});
|
|
204
|
+
tree.addEventListener("keydown", (event) => {
|
|
205
|
+
const item = items.find((each) => each.element === event.target);
|
|
206
|
+
if (!item || event.altKey || event.ctrlKey || event.metaKey) return;
|
|
207
|
+
const list = visible();
|
|
208
|
+
const at = list.indexOf(item);
|
|
209
|
+
let handled = true;
|
|
210
|
+
switch (event.key) {
|
|
211
|
+
case "ArrowDown":
|
|
212
|
+
focus(list[Math.min(list.length - 1, at + 1)] as Item);
|
|
213
|
+
break;
|
|
214
|
+
case "ArrowUp":
|
|
215
|
+
focus(list[Math.max(0, at - 1)] as Item);
|
|
216
|
+
break;
|
|
217
|
+
case "Home":
|
|
218
|
+
focus(list[0] as Item);
|
|
219
|
+
break;
|
|
220
|
+
case "End":
|
|
221
|
+
focus(list[list.length - 1] as Item);
|
|
222
|
+
break;
|
|
223
|
+
case "ArrowRight":
|
|
224
|
+
if (item.children.length > 0 && !item.expanded) setOpen(item, true);
|
|
225
|
+
else if (item.children.length > 0) focus(item.children[0] as Item);
|
|
226
|
+
break;
|
|
227
|
+
case "ArrowLeft":
|
|
228
|
+
if (item.children.length > 0 && item.expanded) setOpen(item, false);
|
|
229
|
+
else if (item.parent) focus(item.parent);
|
|
230
|
+
break;
|
|
231
|
+
case "Enter":
|
|
232
|
+
case " ":
|
|
233
|
+
toggleItem(item);
|
|
234
|
+
break;
|
|
235
|
+
default:
|
|
236
|
+
handled = false;
|
|
237
|
+
}
|
|
238
|
+
if (handled) event.preventDefault();
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const button = (part: string, label: string, onClick: () => void) => {
|
|
242
|
+
const control = h("button", { type: "button", part, class: "btn quiet" }, label);
|
|
243
|
+
control.addEventListener("click", onClick);
|
|
244
|
+
return control;
|
|
245
|
+
};
|
|
246
|
+
const bar =
|
|
247
|
+
data.root.children.length > 0
|
|
248
|
+
? h(
|
|
249
|
+
"div",
|
|
250
|
+
{ part: "bar", class: "bar" },
|
|
251
|
+
button("expand-all", this.t("treeExpandAll"), () => all(true)),
|
|
252
|
+
button("collapse-all", this.t("treeCollapseAll"), () => all(false)),
|
|
253
|
+
)
|
|
254
|
+
: null;
|
|
255
|
+
return h("div", { part: "treeview", class: "panel treeview" }, bar, h("div", { class: "body" }, tree));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function defineTree(): void {
|
|
260
|
+
define("pbs-tree", PbsTree);
|
|
261
|
+
}
|
|
@@ -3,6 +3,9 @@ import type { Answer } from "../../core/types.ts";
|
|
|
3
3
|
/** The origin of a sandboxed frame without `allow-same-origin`. */
|
|
4
4
|
export const OPAQUE_ORIGIN = "null";
|
|
5
5
|
|
|
6
|
+
/** The longest passage a frame may quote; the frame cuts to it and the host cuts again, since the frame is not trusted. */
|
|
7
|
+
export const MAX_SELECTION = 2000;
|
|
8
|
+
|
|
6
9
|
export interface FrameAnswer {
|
|
7
10
|
answerId: string;
|
|
8
11
|
answer: Answer;
|
|
@@ -24,3 +27,29 @@ export function frameAnswer(
|
|
|
24
27
|
if (typeof data.answer !== "object" || data.answer === null) return undefined;
|
|
25
28
|
return { answerId: data.answerId, answer: data.answer as Answer };
|
|
26
29
|
}
|
|
30
|
+
|
|
31
|
+
export interface FrameSelection {
|
|
32
|
+
/** The selected text; empty when the selection was cleared. */
|
|
33
|
+
text: string;
|
|
34
|
+
/** Where the selection starts, in the frame's own viewport. */
|
|
35
|
+
top?: number;
|
|
36
|
+
left?: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The selection a message reports, when the host page should take it: it came from the page's own frame, from that
|
|
41
|
+
* frame's opaque origin, and has the shape the frame hook sends. The text is cut to `MAX_SELECTION`; a position that
|
|
42
|
+
* is not a finite number is dropped.
|
|
43
|
+
*/
|
|
44
|
+
export function frameSelection(
|
|
45
|
+
event: { source: unknown; origin: string; data: unknown },
|
|
46
|
+
frameWindow: unknown,
|
|
47
|
+
): FrameSelection | undefined {
|
|
48
|
+
if (!frameWindow || event.source !== frameWindow || event.origin !== OPAQUE_ORIGIN) return undefined;
|
|
49
|
+
const data = event.data as { source?: unknown; type?: unknown; text?: unknown; top?: unknown; left?: unknown } | null;
|
|
50
|
+
if (data?.source !== "pbs-frame" || data.type !== "selection" || typeof data.text !== "string") return undefined;
|
|
51
|
+
const selection: FrameSelection = { text: data.text.slice(0, MAX_SELECTION) };
|
|
52
|
+
if (typeof data.top === "number" && Number.isFinite(data.top)) selection.top = data.top;
|
|
53
|
+
if (typeof data.left === "number" && Number.isFinite(data.left)) selection.left = data.left;
|
|
54
|
+
return selection;
|
|
55
|
+
}
|
|
@@ -66,6 +66,18 @@ export interface FeedbackOptions {
|
|
|
66
66
|
storageKey: string;
|
|
67
67
|
/** Delivers the answer; rejects with the reason it was not taken. */
|
|
68
68
|
send: (answer: Answer) => Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Whether the panel follows the selection in its own document (default). A host page around a frame turns this off
|
|
71
|
+
* and passes the frame's selection to `offer` instead.
|
|
72
|
+
*/
|
|
73
|
+
watchDocument?: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A passage to comment on, and where the Add button goes (viewport coordinates of the panel's document). */
|
|
77
|
+
export interface Offered {
|
|
78
|
+
text: string;
|
|
79
|
+
top?: number;
|
|
80
|
+
left?: number;
|
|
69
81
|
}
|
|
70
82
|
|
|
71
83
|
const make = <K extends keyof HTMLElementTagNameMap>(
|
|
@@ -83,7 +95,11 @@ const make = <K extends keyof HTMLElementTagNameMap>(
|
|
|
83
95
|
* The feedback panel: select a passage, comment on it, and send the comments with an overall note in one message.
|
|
84
96
|
* Drafts live in the tab's session storage, so they survive the reload an agent's edit causes.
|
|
85
97
|
*/
|
|
86
|
-
export function mountFeedback(options: FeedbackOptions): {
|
|
98
|
+
export function mountFeedback(options: FeedbackOptions): {
|
|
99
|
+
/** Offers a passage to comment on, or withdraws the offer with no text or `undefined`. */
|
|
100
|
+
offer: (passage: Offered | undefined) => void;
|
|
101
|
+
destroy: () => void;
|
|
102
|
+
} {
|
|
87
103
|
const { words, storage, storageKey } = options;
|
|
88
104
|
let items: FeedbackItem[] = [];
|
|
89
105
|
let overall = "";
|
|
@@ -151,25 +167,29 @@ export function mountFeedback(options: FeedbackOptions): { destroy: () => void }
|
|
|
151
167
|
});
|
|
152
168
|
|
|
153
169
|
let pending = "";
|
|
154
|
-
const
|
|
170
|
+
const offer = (passage: Offered | undefined): void => {
|
|
171
|
+
const text = passage?.text.trim();
|
|
172
|
+
if (!passage || !text) {
|
|
173
|
+
pending = "";
|
|
174
|
+
add.hidden = true;
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
pending = text;
|
|
178
|
+
add.hidden = false;
|
|
179
|
+
add.style.top = `${Math.max(8, (passage.top ?? 44) - 36)}px`;
|
|
180
|
+
add.style.left = `${Math.max(8, Math.min(passage.left ?? 8, innerWidth - 120))}px`;
|
|
181
|
+
};
|
|
182
|
+
const selected = (): Offered | undefined => {
|
|
155
183
|
const selection = getSelection();
|
|
156
184
|
if (!selection || selection.isCollapsed || selection.rangeCount === 0) return undefined;
|
|
157
185
|
const anchor = selection.anchorNode instanceof Element ? selection.anchorNode : selection.anchorNode?.parentElement;
|
|
158
186
|
if (anchor?.closest(".pbs-fb, input, textarea")) return undefined;
|
|
159
187
|
const text = selection.toString().trim();
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const found = selected();
|
|
164
|
-
if (!found) {
|
|
165
|
-
add.hidden = true;
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
pending = found.text;
|
|
169
|
-
add.hidden = false;
|
|
170
|
-
add.style.top = `${Math.max(8, found.rect.top - 36)}px`;
|
|
171
|
-
add.style.left = `${Math.max(8, Math.min(found.rect.left, innerWidth - 120))}px`;
|
|
188
|
+
if (!text) return undefined;
|
|
189
|
+
const rect = selection.getRangeAt(0).getBoundingClientRect();
|
|
190
|
+
return { text, top: rect.top, left: rect.left };
|
|
172
191
|
};
|
|
192
|
+
const onSelect = (): void => offer(selected());
|
|
173
193
|
// The button is pressed before the click lands, which would collapse the selection; keep what was picked.
|
|
174
194
|
add.addEventListener("mousedown", (event) => event.preventDefault());
|
|
175
195
|
add.addEventListener("click", () => {
|
|
@@ -211,12 +231,14 @@ export function mountFeedback(options: FeedbackOptions): { destroy: () => void }
|
|
|
211
231
|
sendButton.disabled = false;
|
|
212
232
|
});
|
|
213
233
|
});
|
|
214
|
-
|
|
234
|
+
const watch = options.watchDocument !== false;
|
|
235
|
+
if (watch) document.addEventListener("selectionchange", onSelect);
|
|
215
236
|
draw();
|
|
216
237
|
document.body.append(root);
|
|
217
238
|
return {
|
|
239
|
+
offer,
|
|
218
240
|
destroy: () => {
|
|
219
|
-
document.removeEventListener("selectionchange", onSelect);
|
|
241
|
+
if (watch) document.removeEventListener("selectionchange", onSelect);
|
|
220
242
|
root.remove();
|
|
221
243
|
},
|
|
222
244
|
};
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import type { Answer } from "../../core/types.ts";
|
|
2
|
+
import { MAX_SELECTION } from "./bridge.ts";
|
|
2
3
|
import { newAnswerId } from "./host-config.ts";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Injected into every HTML page that runs in the sandboxed frame. A form whose action is `cgi-bin:pi-answer`
|
|
6
7
|
* sends its fields to the agent, and `piBetterShow.send(fields | answer)` does the same for a page's own script.
|
|
7
|
-
* Both go through the parent page (see host.ts), which is the only party that talks to the server.
|
|
8
|
+
* Both go through the parent page (see host-page.ts), which is the only party that talks to the server.
|
|
9
|
+
* The text the user selects is reported to the parent too, for its feedback panel: the frame cannot show the panel
|
|
10
|
+
* itself, and the parent cannot read the frame.
|
|
8
11
|
*/
|
|
9
12
|
|
|
10
13
|
const ACTION = "cgi-bin:pi-answer";
|
|
@@ -95,3 +98,26 @@ document.addEventListener(
|
|
|
95
98
|
},
|
|
96
99
|
true,
|
|
97
100
|
);
|
|
101
|
+
|
|
102
|
+
/** The text the user has selected on the page, with where it starts; none when it is empty or inside a field. */
|
|
103
|
+
function selectedText(): { text: string; top: number; left: number } {
|
|
104
|
+
const none = { text: "", top: 0, left: 0 };
|
|
105
|
+
const selection = getSelection();
|
|
106
|
+
if (!selection || selection.isCollapsed || selection.rangeCount === 0) return none;
|
|
107
|
+
const active = document.activeElement;
|
|
108
|
+
if (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) return none;
|
|
109
|
+
const text = selection.toString().trim().slice(0, MAX_SELECTION);
|
|
110
|
+
if (!text) return none;
|
|
111
|
+
const rect = selection.getRangeAt(0).getBoundingClientRect();
|
|
112
|
+
return { text, top: rect.top, left: rect.left };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
let reported = "";
|
|
116
|
+
document.addEventListener("selectionchange", () => {
|
|
117
|
+
const { text, top, left } = selectedText();
|
|
118
|
+
// The parent already has what it is told; only a change is worth a message.
|
|
119
|
+
const key = text === "" ? "" : `${top}:${left}:${text}`;
|
|
120
|
+
if (key === reported) return;
|
|
121
|
+
reported = key;
|
|
122
|
+
parent.postMessage({ source: "pbs-frame", type: "selection", text, top, left }, "*");
|
|
123
|
+
});
|