pi-better-show 0.3.1 → 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 +37 -3
- 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/controller.ts +34 -16
- package/src/extension/index.ts +1 -2
- package/src/extension/tool.ts +6 -2
- package/src/react/index.ts +3 -0
package/README.md
CHANGED
|
@@ -33,6 +33,39 @@ A block is a fenced code block whose first word is the kind, or a GitHub alert.
|
|
|
33
33
|
| `table` | YAML `{columns, rows, sort, filter}` | |
|
|
34
34
|
| `steps` | YAML `{items: [{title, status: done\|doing\|todo\|blocked, when, body}]}` | |
|
|
35
35
|
| `stats` | YAML list of `{label, value, delta, tone, note}` | |
|
|
36
|
+
| `tree` | indented lines (two spaces per level, first line the root): `name/` for a folder, then `{tags}` and ` # note` | |
|
|
37
|
+
|
|
38
|
+
**The `tree` block** shows a directory tree for structure reviews:
|
|
39
|
+
|
|
40
|
+
```tree
|
|
41
|
+
pi-better-show/
|
|
42
|
+
src/ # one package, four entries
|
|
43
|
+
core/ {focus} # parser and text, no DOM
|
|
44
|
+
parse.ts
|
|
45
|
+
validate.ts {new} # checks answers
|
|
46
|
+
elements/ # web components
|
|
47
|
+
tests/
|
|
48
|
+
README.md {changed}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A folder's name ends with `/`; tags are `new`, `changed`, `removed`, `focus`, `risk` (an unknown tag makes the block invalid); the note after ` # ` takes inline Markdown; a `… N more` line stands for entries a limit cut. A tree has at most 2,000 nodes and 32 levels (the root is level 1). The block carries a snapshot, so every host draws it; `toText` writes it in `tree` style (`├──`, `└──`, tags as `[new]`, notes after ` — `), in a fence on Discord.
|
|
52
|
+
|
|
53
|
+
**`pbs-tree`** prints the fence for a folder: `npx pbs-tree [dir]` or `bunx pbs-tree [dir]` (plain JavaScript on node built-ins; runs under node and bun). Output is sorted by name in byte order, so a snapshot is reproducible; symlinks are not followed. Flags follow Linux `tree` where they exist:
|
|
54
|
+
|
|
55
|
+
| Flag | Meaning |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `-L n` | depth |
|
|
58
|
+
| `-d` | folders only |
|
|
59
|
+
| `-a` | include dot files (default skips them; `.git` is always skipped) |
|
|
60
|
+
| `-I pattern` | leave out names matching the glob (`*` `?` `[..]`); `\|` separates several; repeatable |
|
|
61
|
+
| `-P pattern` | list only files matching; a folder is kept when it holds a match (even below the `-L` cut); ignored with `-d` |
|
|
62
|
+
| `--gitignore` | honour `.gitignore` files, those of the folder and of the folders above it up to the repository's top |
|
|
63
|
+
| `--dirsfirst` | folders before files |
|
|
64
|
+
| `--filelimit n` | do not open a folder holding more than n entries; writes `… N more` in its place |
|
|
65
|
+
| `--prune` | drop folders that hold nothing (what `-L` hides still counts); ignored with `-d` |
|
|
66
|
+
| `--changed-since <rev>` | tag `new`, `changed`, `removed` from `git diff --name-status <rev>` against the working tree; removed files are listed though absent, untracked files are `new`, a rename is a removed and a new file |
|
|
67
|
+
|
|
68
|
+
A tree over the block's limits is refused (exit 1) with the node count; narrow it with `-L`, `-I`, `--gitignore`. Names that would read as a note or tags get a no-break space, and a newline in a name becomes `?`. Exit codes: 0, 1 for a failure (not a folder, git failed, too large), 2 for a bad flag.
|
|
36
69
|
|
|
37
70
|
A block whose body is not valid YAML, or does not fit its schema, becomes an `invalid` segment that keeps its source and the reason; nothing throws.
|
|
38
71
|
|
|
@@ -60,7 +93,7 @@ interface TextProfile {
|
|
|
60
93
|
|
|
61
94
|
The interactive kinds end with a reply instruction (`options`, `form`, `review`, `suggest`, and `checklist`): "Reply with a number.", "Reply in text, one line per question, like `1: b`.", and so on. `lang: "zh-TW"` writes them in Traditional Chinese; pass the conversation's language when you know it. Block content is never translated.
|
|
62
95
|
|
|
63
|
-
Every `BlockSegment` and `InvalidSegment` carries `raw`: the block's exact original text, fences (or an alert's whole `>` quote) included, byte for byte. Kinds listed in `keep` are emitted as `raw` verbatim, valid or invalid, for a surface that draws them itself; other kinds convert as usual. `DISPLAY_KINDS` (`alert`, `cards`, `mermaid`, `mindmap`, `diff`, `table`, `steps`, `stats`) is the usual `keep` list for such a surface; `INTERACTIVE_KINDS` (`options`, `suggest`, `form`, `checklist`, `review`) are the kinds a reader answers, the ones a surface that cannot draw them gets as reply instructions. Without `keep`, output is unchanged.
|
|
96
|
+
Every `BlockSegment` and `InvalidSegment` carries `raw`: the block's exact original text, fences (or an alert's whole `>` quote) included, byte for byte. Kinds listed in `keep` are emitted as `raw` verbatim, valid or invalid, for a surface that draws them itself; other kinds convert as usual. `DISPLAY_KINDS` (`alert`, `cards`, `mermaid`, `mindmap`, `diff`, `table`, `steps`, `stats`, `tree`) is the usual `keep` list for such a surface; `INTERACTIVE_KINDS` (`options`, `suggest`, `form`, `checklist`, `review`) are the kinds a reader answers, the ones a surface that cannot draw them gets as reply instructions. Without `keep`, output is unchanged.
|
|
64
97
|
|
|
65
98
|
Renders a document for a surface that cannot draw blocks. A diagram goes through the `mermaid` hook; when there is no hook, or it returns `undefined` or a drawing wider than `width`, the output is the Mermaid source in a code block plus a pointer to the web view. No block-kind fence is left in the output, except Discord's native `diff`.
|
|
66
99
|
|
|
@@ -141,6 +174,7 @@ A host gives an element the block's parsed `data` and listens for `pbs-answer` (
|
|
|
141
174
|
| `pbs-stats` | `stats` | `StatsData` | | `grid` `stat` `label` `value` `delta` `note` |
|
|
142
175
|
| `pbs-diff` | `diff` | `DiffData` | | `diff` `scroll` `line` |
|
|
143
176
|
| `pbs-diagram` | `mermaid` | `MermaidData` | | `diagram` `image` `source` `note` |
|
|
177
|
+
| `pbs-tree` | `tree` | `TreeData` | | `treeview` `bar` `expand-all` `collapse-all` `tree` `item` `node` `toggle` `name` `count` `tags` `tag` `note` `more` `group` |
|
|
144
178
|
|
|
145
179
|
`TAGS` maps a block kind to its tag. There is no whole-document element: the extension renders Markdown on its page server, and other hosts use their own renderer.
|
|
146
180
|
|
|
@@ -186,7 +220,7 @@ Serve diagram images from `pi-better-show/server` (`mermaidSvg(source, { scheme,
|
|
|
186
220
|
|
|
187
221
|
Structure carries `part` names for `::part()` restyling. A panel has the same border on all four sides, or none; a tone shows as a tint, a badge, an icon, and the heading colour, never a coloured or thicker one-sided border. `examples/demo.css` maps the Roundtable and Straw boss tokens as examples.
|
|
188
222
|
|
|
189
|
-
**Keyboard.** Every control is a native control, labelled. `pbs-mindmap` follows the ARIA tree pattern (arrows move, Right and Left open and close, Enter and Space toggle, Home and End jump); `pbs-table` sorts from header buttons (`aria-sort`) and filters from a labelled search box.
|
|
223
|
+
**Keyboard.** Every control is a native control, labelled. `pbs-mindmap` follows the ARIA tree pattern (arrows move, Right and Left open and close, Enter and Space toggle, Home and End jump); `pbs-tree` follows it too, and opens folders to depth 2 (deeper folders that hold a tagged node open their path) with "expand all" and "collapse all" buttons; `pbs-table` sorts from header buttons (`aria-sort`) and filters from a labelled search box.
|
|
190
224
|
|
|
191
225
|
## React
|
|
192
226
|
|
|
@@ -197,7 +231,7 @@ import { PbsBlock, PbsForm } from "pi-better-show/react";
|
|
|
197
231
|
<PbsForm data={formData} answered={fields} density="compact" onAnswer={...} />
|
|
198
232
|
```
|
|
199
233
|
|
|
200
|
-
One component per element (`PbsCallout` ... `
|
|
234
|
+
One component per element (`PbsCallout` ... `PbsTree`) plus `PbsBlock`, which draws a `parse` segment with the element for its kind and addresses it by its `index`. Props: `data`, `answered`, `onAnswer(answer, event)` (return `false` to refuse), `blockRef`, `density`, `scheme`, `lang`, `className`, `id`, `ref`. A parent render with equal `data` does not redraw the element or clear what the user typed. React 19 or later, as an optional peer dependency.
|
|
201
235
|
|
|
202
236
|
## The pi extension: `show_doc`
|
|
203
237
|
|
package/bin/pbs-tree.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// pbs-tree: prints a folder as a ```tree block for pi-better-show. Flags follow Linux `tree` where they exist.
|
|
3
|
+
// Plain JavaScript on node built-ins only: it runs from node_modules, where node does not strip types, under node and bun.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
6
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
|
|
9
|
+
// The limits of the tree block (TREE_LIMITS in src/core/types.ts; a test keeps the two in step).
|
|
10
|
+
const MAX_NODES = 2000;
|
|
11
|
+
const MAX_DEPTH = 32;
|
|
12
|
+
|
|
13
|
+
const USAGE = `Usage: pbs-tree [options] [dir]
|
|
14
|
+
|
|
15
|
+
Prints dir (default .) as a \`\`\`tree block, sorted by name in byte order.
|
|
16
|
+
|
|
17
|
+
-L n list n levels
|
|
18
|
+
-d folders only
|
|
19
|
+
-a include dot files (.git is always skipped)
|
|
20
|
+
-I pattern leave out names matching the glob (* ? [..]); | separates several; repeatable
|
|
21
|
+
-P pattern list only files matching the glob; folders are kept when they hold a match
|
|
22
|
+
--gitignore honour .gitignore files
|
|
23
|
+
--dirsfirst folders before files
|
|
24
|
+
--filelimit n do not open a folder holding more than n entries; write "… N more" instead
|
|
25
|
+
--prune leave out folders that hold nothing
|
|
26
|
+
--changed-since rev tag files new, changed or removed since rev (git diff --name-status rev; removed files are listed)
|
|
27
|
+
-h, --help this text
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
class Usage extends Error {}
|
|
31
|
+
class Failure extends Error {}
|
|
32
|
+
|
|
33
|
+
/** @param {string} message */
|
|
34
|
+
const usage = (message) => new Usage(message);
|
|
35
|
+
|
|
36
|
+
function options(argv) {
|
|
37
|
+
let parsed;
|
|
38
|
+
try {
|
|
39
|
+
parsed = parseArgs({
|
|
40
|
+
args: argv,
|
|
41
|
+
allowPositionals: true,
|
|
42
|
+
options: {
|
|
43
|
+
L: { type: "string", short: "L" },
|
|
44
|
+
d: { type: "boolean", short: "d" },
|
|
45
|
+
a: { type: "boolean", short: "a" },
|
|
46
|
+
I: { type: "string", short: "I", multiple: true },
|
|
47
|
+
P: { type: "string", short: "P", multiple: true },
|
|
48
|
+
gitignore: { type: "boolean" },
|
|
49
|
+
dirsfirst: { type: "boolean" },
|
|
50
|
+
filelimit: { type: "string" },
|
|
51
|
+
prune: { type: "boolean" },
|
|
52
|
+
"changed-since": { type: "string" },
|
|
53
|
+
help: { type: "boolean", short: "h" },
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
} catch (error) {
|
|
57
|
+
throw usage(error instanceof Error ? error.message : String(error));
|
|
58
|
+
}
|
|
59
|
+
const { values, positionals } = parsed;
|
|
60
|
+
if (values.help) return { help: true };
|
|
61
|
+
if (positionals.length > 1) throw usage(`one folder at most, got ${positionals.length}`);
|
|
62
|
+
const count = (name, text, least) => {
|
|
63
|
+
if (text === undefined) return undefined;
|
|
64
|
+
if (!/^\d+$/.test(text) || Number(text) < least)
|
|
65
|
+
throw usage(`${name} needs a whole number of at least ${least}, got "${text}"`);
|
|
66
|
+
return Number(text);
|
|
67
|
+
};
|
|
68
|
+
const since = values["changed-since"];
|
|
69
|
+
if (since !== undefined && (since === "" || since.startsWith("-")))
|
|
70
|
+
throw usage(`--changed-since needs a revision, got "${since}"`);
|
|
71
|
+
return {
|
|
72
|
+
help: false,
|
|
73
|
+
dir: positionals[0] ?? ".",
|
|
74
|
+
depth: count("-L", values.L, 1),
|
|
75
|
+
dirsOnly: values.d === true,
|
|
76
|
+
dotFiles: values.a === true,
|
|
77
|
+
exclude: (values.I ?? []).flatMap(globs),
|
|
78
|
+
include: (values.P ?? []).flatMap(globs),
|
|
79
|
+
gitignore: values.gitignore === true,
|
|
80
|
+
dirsFirst: values.dirsfirst === true,
|
|
81
|
+
fileLimit: count("--filelimit", values.filelimit, 1),
|
|
82
|
+
prune: values.prune === true,
|
|
83
|
+
since,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---- globs ---------------------------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
/** A bracket expression at `glob[at]` (`[abc]`, `[a-z]`, `[!abc]`) as a regex class and the index after it; undefined when it is not closed. */
|
|
90
|
+
function bracket(glob, at) {
|
|
91
|
+
const end = glob.indexOf("]", at + 2);
|
|
92
|
+
if (end < 0) return undefined;
|
|
93
|
+
let set = glob.slice(at + 1, end);
|
|
94
|
+
const negate = set.startsWith("!") || set.startsWith("^");
|
|
95
|
+
if (negate) set = set.slice(1);
|
|
96
|
+
return { source: `[${negate ? "^" : ""}${set.replace(/[\\\]^]/g, "\\$&")}]`, end };
|
|
97
|
+
}
|
|
98
|
+
const literal = (char) => char.replace(/[\\^$.|+(){}[\]*?/]/g, "\\$&");
|
|
99
|
+
|
|
100
|
+
/** A shell glob (`*`, `?`, `[..]`, `[!..]`) as a regex over a whole name. */
|
|
101
|
+
function globRegex(glob) {
|
|
102
|
+
let source = "";
|
|
103
|
+
for (let i = 0; i < glob.length; i++) {
|
|
104
|
+
const char = glob[i];
|
|
105
|
+
if (char === "*") source += ".*";
|
|
106
|
+
else if (char === "?") source += ".";
|
|
107
|
+
else if (char === "[") {
|
|
108
|
+
const set = bracket(glob, i);
|
|
109
|
+
if (set) {
|
|
110
|
+
source += set.source;
|
|
111
|
+
i = set.end;
|
|
112
|
+
} else source += "\\[";
|
|
113
|
+
} else source += literal(char);
|
|
114
|
+
}
|
|
115
|
+
return new RegExp(`^${source}$`, "s");
|
|
116
|
+
}
|
|
117
|
+
/** `a|b` as two regexes. */
|
|
118
|
+
const globs = (list) => list.split("|").filter(Boolean).map(globRegex);
|
|
119
|
+
const matches = (list, name) => list.some((regex) => regex.test(name));
|
|
120
|
+
|
|
121
|
+
// ---- .gitignore ------------------------------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/** A gitignore pattern's glob as a regex over a `/`-separated path (`*` and `?` stop at `/`, `**` does not). */
|
|
124
|
+
function ignoreRegex(glob) {
|
|
125
|
+
let source = "";
|
|
126
|
+
for (let i = 0; i < glob.length; i++) {
|
|
127
|
+
const char = glob[i];
|
|
128
|
+
if (char === "*" && glob[i + 1] === "*") {
|
|
129
|
+
const whole = (i === 0 || glob[i - 1] === "/") && (glob[i + 2] === "/" || glob[i + 2] === undefined);
|
|
130
|
+
if (whole && glob[i + 2] === "/") {
|
|
131
|
+
source += "(?:.*/)?";
|
|
132
|
+
i += 2;
|
|
133
|
+
} else {
|
|
134
|
+
source += whole ? ".*" : "[^/]*";
|
|
135
|
+
i += 1;
|
|
136
|
+
}
|
|
137
|
+
} else if (char === "*") source += "[^/]*";
|
|
138
|
+
else if (char === "?") source += "[^/]";
|
|
139
|
+
else if (char === "[") {
|
|
140
|
+
const set = bracket(glob, i);
|
|
141
|
+
if (set) {
|
|
142
|
+
source += set.source;
|
|
143
|
+
i = set.end;
|
|
144
|
+
} else source += "\\[";
|
|
145
|
+
} else if (char === "\\" && i + 1 < glob.length) {
|
|
146
|
+
i++;
|
|
147
|
+
source += literal(glob[i] ?? "");
|
|
148
|
+
} else source += literal(char);
|
|
149
|
+
}
|
|
150
|
+
return new RegExp(`^${source}$`, "s");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The rules of one .gitignore file. */
|
|
154
|
+
function ignoreRules(text) {
|
|
155
|
+
const rules = [];
|
|
156
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
157
|
+
let line = raw.replace(/(?<!\\)[ \t]+$/, "");
|
|
158
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
159
|
+
const negate = line.startsWith("!");
|
|
160
|
+
if (negate) line = line.slice(1);
|
|
161
|
+
const dirOnly = line.endsWith("/");
|
|
162
|
+
if (dirOnly) line = line.slice(0, -1);
|
|
163
|
+
if (line === "") continue;
|
|
164
|
+
// A pattern with a slash inside it (or in front) is relative to the .gitignore's folder; the others match a name at any depth.
|
|
165
|
+
const anchored = line.includes("/");
|
|
166
|
+
if (line.startsWith("/")) line = line.slice(1);
|
|
167
|
+
rules.push({ negate, dirOnly, anchored, regex: ignoreRegex(line) });
|
|
168
|
+
}
|
|
169
|
+
return rules;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Whether the .gitignore files in `files` (outermost first) ignore `path`; the last rule that matches decides. */
|
|
173
|
+
function ignored(files, path, isDir) {
|
|
174
|
+
let verdict = false;
|
|
175
|
+
for (const file of files) {
|
|
176
|
+
if (!path.startsWith(file.base + sep)) continue;
|
|
177
|
+
const relative = path
|
|
178
|
+
.slice(file.base.length + 1)
|
|
179
|
+
.split(sep)
|
|
180
|
+
.join("/");
|
|
181
|
+
const name = relative.slice(relative.lastIndexOf("/") + 1);
|
|
182
|
+
for (const rule of file.rules) {
|
|
183
|
+
if (rule.dirOnly && !isDir) continue;
|
|
184
|
+
if (rule.regex.test(rule.anchored ? relative : name)) verdict = !rule.negate;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return verdict;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The .gitignore files from the repository's top (the first folder above with a .git) down to `dir`. */
|
|
191
|
+
function ancestorIgnores(dir) {
|
|
192
|
+
const chain = [];
|
|
193
|
+
for (let at = dir; ; at = dirname(at)) {
|
|
194
|
+
chain.unshift(at);
|
|
195
|
+
if (existsSync(join(at, ".git")) || dirname(at) === at) break;
|
|
196
|
+
}
|
|
197
|
+
// Without a repository above, only the folder itself counts.
|
|
198
|
+
if (!existsSync(join(chain[0], ".git"))) return ignoreFiles([dir]);
|
|
199
|
+
return ignoreFiles(chain);
|
|
200
|
+
}
|
|
201
|
+
function ignoreFiles(folders) {
|
|
202
|
+
const files = [];
|
|
203
|
+
for (const base of folders) files.push(...ignoreFile(base));
|
|
204
|
+
return files;
|
|
205
|
+
}
|
|
206
|
+
function ignoreFile(base) {
|
|
207
|
+
try {
|
|
208
|
+
return [{ base, rules: ignoreRules(readFileSync(join(base, ".gitignore"), "utf8")) }];
|
|
209
|
+
} catch {
|
|
210
|
+
return [];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---- git ---------------------------------------------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
function git(dir, args) {
|
|
217
|
+
try {
|
|
218
|
+
return execFileSync("git", ["-C", dir, ...args], {
|
|
219
|
+
encoding: "utf8",
|
|
220
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
221
|
+
maxBuffer: 1 << 28,
|
|
222
|
+
});
|
|
223
|
+
} catch (error) {
|
|
224
|
+
const detail =
|
|
225
|
+
error && typeof error === "object" && "stderr" in error ? String(error.stderr).trim() : String(error);
|
|
226
|
+
throw new Failure(`git ${args[0]} failed: ${detail}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** `path -> "new" | "changed" | "removed"` for the working tree against `rev`; untracked files count as new. */
|
|
231
|
+
function changes(dir, rev) {
|
|
232
|
+
const status = new Map();
|
|
233
|
+
const diff = git(dir, ["diff", "--name-status", "--no-renames", "-z", "--relative", rev, "--"]).split("\0");
|
|
234
|
+
for (let i = 0; i + 1 < diff.length; i += 2) {
|
|
235
|
+
const letter = (diff[i] ?? "")[0];
|
|
236
|
+
const path = diff[i + 1];
|
|
237
|
+
if (!path) continue;
|
|
238
|
+
status.set(path, letter === "A" || letter === "C" ? "new" : letter === "D" ? "removed" : "changed");
|
|
239
|
+
}
|
|
240
|
+
for (const path of git(dir, ["ls-files", "--others", "--exclude-standard", "-z"]).split("\0")) {
|
|
241
|
+
if (path && !status.has(path)) status.set(path, "new");
|
|
242
|
+
}
|
|
243
|
+
return status;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The removed files as a trie, so a folder listing can add the names the disk no longer has. */
|
|
247
|
+
function removedTrie(status) {
|
|
248
|
+
const root = { children: new Map(), file: false };
|
|
249
|
+
for (const [path, tag] of status) {
|
|
250
|
+
if (tag !== "removed") continue;
|
|
251
|
+
let at = root;
|
|
252
|
+
for (const part of path.split("/")) {
|
|
253
|
+
const next = at.children.get(part) ?? { children: new Map(), file: false };
|
|
254
|
+
at.children.set(part, next);
|
|
255
|
+
at = next;
|
|
256
|
+
}
|
|
257
|
+
at.file = true;
|
|
258
|
+
}
|
|
259
|
+
return root;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---- the walk -------------------------------------------------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
const compare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
265
|
+
|
|
266
|
+
function snapshot(settings) {
|
|
267
|
+
const root = resolve(settings.dir);
|
|
268
|
+
let stat;
|
|
269
|
+
try {
|
|
270
|
+
stat = statSync(root);
|
|
271
|
+
} catch {
|
|
272
|
+
throw new Failure(`${settings.dir}: no such folder`);
|
|
273
|
+
}
|
|
274
|
+
if (!stat.isDirectory()) throw new Failure(`${settings.dir}: not a folder`);
|
|
275
|
+
|
|
276
|
+
const status = settings.since === undefined ? new Map() : changes(root, settings.since);
|
|
277
|
+
const removed = settings.since === undefined || settings.dirsOnly ? undefined : removedTrie(status);
|
|
278
|
+
const outer = settings.gitignore ? ancestorIgnores(root) : [];
|
|
279
|
+
// What -L hides still decides whether a folder is empty or holds a match.
|
|
280
|
+
const needsAll = settings.prune || settings.include.length > 0;
|
|
281
|
+
const filtering = !settings.dirsOnly;
|
|
282
|
+
const pruning = filtering && (settings.prune || settings.include.length > 0);
|
|
283
|
+
|
|
284
|
+
/** The entries of a folder that survive -a, -I, .gitignore, and -d, in listing order. */
|
|
285
|
+
function entries(abs, parts, trie, files) {
|
|
286
|
+
const found = new Map();
|
|
287
|
+
if (abs !== undefined) {
|
|
288
|
+
let listing = [];
|
|
289
|
+
try {
|
|
290
|
+
listing = readdirSync(abs, { withFileTypes: true });
|
|
291
|
+
} catch (error) {
|
|
292
|
+
process.stderr.write(`pbs-tree: cannot read ${abs}: ${error instanceof Error ? error.message : error}\n`);
|
|
293
|
+
}
|
|
294
|
+
for (const entry of listing)
|
|
295
|
+
found.set(entry.name, { name: entry.name, dir: entry.isDirectory(), virtual: false });
|
|
296
|
+
}
|
|
297
|
+
if (trie) {
|
|
298
|
+
for (const [name, child] of trie.children) {
|
|
299
|
+
if (!found.has(name)) found.set(name, { name, dir: !child.file, virtual: true });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const kept = [...found.values()].filter((entry) => {
|
|
303
|
+
if (entry.name === ".git") return false;
|
|
304
|
+
if (!settings.dotFiles && entry.name.startsWith(".")) return false;
|
|
305
|
+
if (matches(settings.exclude, entry.name)) return false;
|
|
306
|
+
if (settings.dirsOnly && !entry.dir) return false;
|
|
307
|
+
// A removed path has no file to look at, but its name still meets the same rules.
|
|
308
|
+
const where = join(abs ?? join(root, ...parts), entry.name);
|
|
309
|
+
if (files.length > 0 && ignored(files, where, entry.dir)) return false;
|
|
310
|
+
return true;
|
|
311
|
+
});
|
|
312
|
+
kept.sort((a, b) => (settings.dirsFirst && a.dir !== b.dir ? (a.dir ? -1 : 1) : compare(a.name, b.name)));
|
|
313
|
+
return kept;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The nodes of a folder and whether it holds anything that survives -P and --prune.
|
|
318
|
+
* `emit` is false below the -L cut: nothing is returned, but `holds` is still worked out.
|
|
319
|
+
*/
|
|
320
|
+
function walk(abs, parts, trie, level, emit, files) {
|
|
321
|
+
const list = entries(abs, parts, trie, files);
|
|
322
|
+
if (settings.fileLimit !== undefined && list.length > settings.fileLimit) {
|
|
323
|
+
return {
|
|
324
|
+
nodes: emit ? [{ name: `… ${list.length} more`, dir: false, tags: [], children: [], more: list.length }] : [],
|
|
325
|
+
holds: true,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const nodes = [];
|
|
329
|
+
let holds = false;
|
|
330
|
+
for (const entry of list) {
|
|
331
|
+
const path = [...parts, entry.name];
|
|
332
|
+
if (!entry.dir) {
|
|
333
|
+
if (filtering && settings.include.length > 0 && !matches(settings.include, entry.name)) continue;
|
|
334
|
+
holds = true;
|
|
335
|
+
if (emit) {
|
|
336
|
+
const tag = status.get(path.join("/"));
|
|
337
|
+
nodes.push({
|
|
338
|
+
name: entry.name,
|
|
339
|
+
dir: false,
|
|
340
|
+
tags: entry.virtual ? ["removed"] : tag ? [tag] : [],
|
|
341
|
+
children: [],
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
const below = trie?.children.get(entry.name);
|
|
347
|
+
const deeper = level < (settings.depth ?? Number.POSITIVE_INFINITY);
|
|
348
|
+
const inside = entry.virtual ? undefined : join(abs ?? "", entry.name);
|
|
349
|
+
let result = { nodes: [], holds: false };
|
|
350
|
+
if (deeper || needsAll || entry.virtual) {
|
|
351
|
+
const nested = inside !== undefined && settings.gitignore ? [...files, ...ignoreFile(inside)] : files;
|
|
352
|
+
result = walk(inside, path, below, level + 1, emit && deeper, nested);
|
|
353
|
+
}
|
|
354
|
+
// A folder that only exists as the home of removed files is shown only while one of them is.
|
|
355
|
+
if (entry.virtual && !result.holds) continue;
|
|
356
|
+
if (pruning && !result.holds) continue;
|
|
357
|
+
holds = true;
|
|
358
|
+
if (emit) nodes.push({ name: entry.name, dir: true, tags: [], children: result.nodes });
|
|
359
|
+
}
|
|
360
|
+
return { nodes, holds };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const name = basename(root) || root;
|
|
364
|
+
return { name, dir: true, tags: [], children: walk(root, [], removed, 1, true, outer).nodes };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ---- output ------------------------------------------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
const NBSP = "\u00a0";
|
|
370
|
+
/** A name as one line of the block: control characters become `?`, and what would read as markup is kept apart by a no-break space. */
|
|
371
|
+
function safe(name) {
|
|
372
|
+
return (
|
|
373
|
+
[...name]
|
|
374
|
+
.map((char) => (char < " " || char === "\u007f" ? "?" : char))
|
|
375
|
+
.join("")
|
|
376
|
+
.replace(/^ +| +$/g, (spaces) => NBSP.repeat(spaces.length))
|
|
377
|
+
.replace(/ # /g, ` #${NBSP}`)
|
|
378
|
+
// A trailing " #" would meet the " {tags}" suffix and read as a note.
|
|
379
|
+
.replace(/ #$/, `${NBSP}#`)
|
|
380
|
+
.replace(/(^| )(\{[^{}]*\})$/, `${NBSP}$2`)
|
|
381
|
+
.replace(/^… (\d+) more$/, `…${NBSP}$1 more`)
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function render(tree) {
|
|
386
|
+
let count = 0;
|
|
387
|
+
let deepest = 0;
|
|
388
|
+
const out = [];
|
|
389
|
+
const longest = { backticks: 0 };
|
|
390
|
+
const walk = (node, level) => {
|
|
391
|
+
count++;
|
|
392
|
+
deepest = Math.max(deepest, level + 1);
|
|
393
|
+
const name = node.more === undefined ? safe(node.name) : node.name;
|
|
394
|
+
for (const run of name.match(/`+/g) ?? []) longest.backticks = Math.max(longest.backticks, run.length);
|
|
395
|
+
const tags = node.tags.length > 0 ? ` {${node.tags.join(", ")}}` : "";
|
|
396
|
+
out.push(`${" ".repeat(level)}${name}${node.dir ? "/" : ""}${tags}`);
|
|
397
|
+
for (const child of node.children) walk(child, level + 1);
|
|
398
|
+
};
|
|
399
|
+
walk(tree, 0);
|
|
400
|
+
if (count > MAX_NODES) {
|
|
401
|
+
throw new Failure(
|
|
402
|
+
`${count} nodes; a tree block holds at most ${MAX_NODES}. Narrow it with -L, -I, -P, --gitignore, --prune or --filelimit.`,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
if (deepest > MAX_DEPTH) {
|
|
406
|
+
throw new Failure(`${deepest} levels; a tree block holds at most ${MAX_DEPTH}. Narrow it with -L.`);
|
|
407
|
+
}
|
|
408
|
+
const fence = "`".repeat(Math.max(3, longest.backticks + 1));
|
|
409
|
+
return `${fence}tree\n${out.join("\n")}\n${fence}\n`;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
const settings = options(process.argv.slice(2));
|
|
414
|
+
if (settings.help) process.stdout.write(USAGE);
|
|
415
|
+
else process.stdout.write(render(snapshot(settings)));
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (error instanceof Usage) {
|
|
418
|
+
process.stderr.write(`pbs-tree: ${error.message}\n\n${USAGE}`);
|
|
419
|
+
process.exitCode = 2;
|
|
420
|
+
} else if (error instanceof Failure) {
|
|
421
|
+
process.stderr.write(`pbs-tree: ${error.message}\n`);
|
|
422
|
+
process.exitCode = 1;
|
|
423
|
+
} else throw error;
|
|
424
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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",
|
|
7
7
|
"author": "wayne930242",
|
|
8
|
+
"bin": {
|
|
9
|
+
"pbs-tree": "./bin/pbs-tree.js"
|
|
10
|
+
},
|
|
8
11
|
"files": [
|
|
12
|
+
"bin",
|
|
9
13
|
"src",
|
|
10
14
|
"README.md",
|
|
11
15
|
"LICENSE"
|
package/src/core/parse.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parse as parseYaml } from "yaml";
|
|
2
2
|
import * as legacy from "./blocks.ts";
|
|
3
3
|
import * as added from "./blocks-new.ts";
|
|
4
|
+
import { tree } from "./tree.ts";
|
|
4
5
|
import {
|
|
5
6
|
type AlertData,
|
|
6
7
|
type AlertTone,
|
|
@@ -49,6 +50,7 @@ const CONVERTERS: { [K in Exclude<BlockKind, "alert">]: Convert<K> } = {
|
|
|
49
50
|
table: yaml(added.table),
|
|
50
51
|
steps: yaml(added.steps),
|
|
51
52
|
stats: yaml(added.stats),
|
|
53
|
+
tree,
|
|
52
54
|
};
|
|
53
55
|
|
|
54
56
|
/** The first line of the error: YAML's own messages end it with a colon and append a source excerpt. */
|
package/src/core/text.ts
CHANGED
|
@@ -21,6 +21,8 @@ import type {
|
|
|
21
21
|
TableData,
|
|
22
22
|
TextLang,
|
|
23
23
|
TextProfile,
|
|
24
|
+
TreeData,
|
|
25
|
+
TreeNode,
|
|
24
26
|
} from "./types.ts";
|
|
25
27
|
import { displayWidth } from "./width.ts";
|
|
26
28
|
|
|
@@ -230,6 +232,26 @@ function stats(dialect: Dialect, data: StatsData): string {
|
|
|
230
232
|
.join("\n");
|
|
231
233
|
}
|
|
232
234
|
|
|
235
|
+
/** A tree in `tree` style, one line per node: tags as `[new]`, the note after ` — `. Notes lose their Markdown: the lines sit in a fence. */
|
|
236
|
+
function tree(dialect: Dialect, data: TreeData): string {
|
|
237
|
+
const lines: string[] = [];
|
|
238
|
+
const label = (node: TreeNode): string => {
|
|
239
|
+
const tags = node.tags.map((tag) => `[${tag}]`);
|
|
240
|
+
const note = node.note === undefined ? "" : ` — ${oneLine(inlinePlain(node.note))}`;
|
|
241
|
+
return `${[`${node.name}${node.dir ? "/" : ""}`, ...tags].join(" ")}${note}`;
|
|
242
|
+
};
|
|
243
|
+
const walk = (node: TreeNode, prefix: string) => {
|
|
244
|
+
node.children.forEach((child, index) => {
|
|
245
|
+
const last = index === node.children.length - 1;
|
|
246
|
+
lines.push(`${prefix}${last ? "└── " : "├── "}${label(child)}`);
|
|
247
|
+
walk(child, `${prefix}${last ? " " : "│ "}`);
|
|
248
|
+
});
|
|
249
|
+
};
|
|
250
|
+
lines.push(label(data.root));
|
|
251
|
+
walk(data.root, "");
|
|
252
|
+
return code(dialect, lines.join("\n"));
|
|
253
|
+
}
|
|
254
|
+
|
|
233
255
|
const widest = (text: string): number => Math.max(0, ...text.split("\n").map(displayWidth));
|
|
234
256
|
|
|
235
257
|
/** A diagram as a text drawing when the hook can and it fits; else its source and a pointer to the web view. */
|
|
@@ -272,6 +294,8 @@ function block(dialect: Dialect, segment: BlockSegment): string {
|
|
|
272
294
|
return steps(dialect, segment.data);
|
|
273
295
|
case "stats":
|
|
274
296
|
return stats(dialect, segment.data);
|
|
297
|
+
case "tree":
|
|
298
|
+
return tree(dialect, segment.data);
|
|
275
299
|
}
|
|
276
300
|
}
|
|
277
301
|
|
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
|
+
}
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
import { homedir, tmpdir } from "node:os";
|
|
14
14
|
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
15
15
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
16
|
-
import { encodeAnswer } from "../core/
|
|
16
|
+
import { encodeAnswer } from "../core/answer.ts";
|
|
17
17
|
import type { Answer } from "../core/types.ts";
|
|
18
18
|
import {
|
|
19
19
|
ANSWER_EVENT,
|
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
} from "./contract.ts";
|
|
29
29
|
import { createEditSession, defaultLaunch, defaultRun, EDITOR_ENV, type EditDeps, WATCH_MS } from "./edit.ts";
|
|
30
30
|
import { createAllowList, HTML_FILE, IMAGE_FILE, MARKDOWN_FILE, REACT_FILE } from "./files.ts";
|
|
31
|
-
import {
|
|
31
|
+
import type { PageServer, PageServerOptions } from "./server.ts";
|
|
32
32
|
|
|
33
33
|
export const MESSAGE_TYPE = "better-show";
|
|
34
34
|
export const MINI_SDD_FILE = /(^|\/)docs\/specs\/[^/]+\/(decision|spec|design|verification)\.md$/;
|
|
@@ -59,6 +59,13 @@ export interface Deps extends EditDeps {
|
|
|
59
59
|
now: () => number;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Starts the page server, loading it (with the renderers, Mermaid, and the page bundler it pulls in) on the first
|
|
64
|
+
* call. An idle session that never shows a page never pays for any of it.
|
|
65
|
+
*/
|
|
66
|
+
export const createPageServer = async (options: PageServerOptions): Promise<PageServer> =>
|
|
67
|
+
(await import("./server.ts")).createPageServer(options);
|
|
68
|
+
|
|
62
69
|
export const defaultDeps = (): Deps => ({
|
|
63
70
|
editor: process.env[EDITOR_ENV],
|
|
64
71
|
onPath: (command) => spawnSync("sh", ["-c", 'command -v "$1"', "sh", command], { stdio: "ignore" }).status === 0,
|
|
@@ -174,21 +181,32 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
|
|
|
174
181
|
const pathOfDoc = (id: string): string | undefined => [...docs.values()].find((entry) => entry.id === id)?.path;
|
|
175
182
|
const displayOf = (path: string): string => docs.get(path)?.display ?? basename(path);
|
|
176
183
|
|
|
184
|
+
/** The server being started; two first uses at once share it, so only one server listens. */
|
|
185
|
+
let starting: Promise<PageServer> | undefined;
|
|
177
186
|
const ensureServer = async (): Promise<PageServer> => {
|
|
178
|
-
server
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
187
|
+
if (server) return server;
|
|
188
|
+
starting ??= deps
|
|
189
|
+
.servePages({
|
|
190
|
+
canServe: allow.canServe,
|
|
191
|
+
pathOfDoc,
|
|
192
|
+
displayOf,
|
|
193
|
+
onAnswer: ({ answerId, answer, page }) => {
|
|
194
|
+
const entry = page ? docs.get(page) : undefined;
|
|
195
|
+
const result = decide(entry?.id, answerId, answer, true);
|
|
196
|
+
return result.reason === undefined
|
|
197
|
+
? { accepted: result.accepted }
|
|
198
|
+
: { accepted: result.accepted, reason: result.reason };
|
|
199
|
+
},
|
|
200
|
+
onIdle,
|
|
201
|
+
})
|
|
202
|
+
.then((started) => {
|
|
203
|
+
server = started;
|
|
204
|
+
return started;
|
|
205
|
+
})
|
|
206
|
+
.finally(() => {
|
|
207
|
+
starting = undefined;
|
|
208
|
+
});
|
|
209
|
+
return starting;
|
|
192
210
|
};
|
|
193
211
|
|
|
194
212
|
/** Lists documents that were just opened: new ones get an id, known ones keep theirs. */
|
package/src/extension/index.ts
CHANGED
|
@@ -18,8 +18,7 @@ import {
|
|
|
18
18
|
import { showDocTool } from "./tool.ts";
|
|
19
19
|
|
|
20
20
|
export * from "./contract.ts";
|
|
21
|
-
export { createBetterShow, type Deps, defaultDeps } from "./controller.ts";
|
|
22
|
-
export { createPageServer } from "./server.ts";
|
|
21
|
+
export { createBetterShow, createPageServer, type Deps, defaultDeps } from "./controller.ts";
|
|
23
22
|
|
|
24
23
|
/** Set to `off` to stop a proposed Mini SDD spec from opening on its own. */
|
|
25
24
|
export const AUTO_OPEN_ENV = "PI_BETTER_SHOW_AUTO_OPEN";
|
package/src/extension/tool.ts
CHANGED
|
@@ -18,12 +18,13 @@ export const DESCRIPTION =
|
|
|
18
18
|
"```checklist holds {title, submit, items: [string | {name, label, checked, note}]}, and the ticked items come back to you as a message; " +
|
|
19
19
|
"```table holds {columns: [string | {name, label, align, type: text|number|date}], rows: [[..] | {..}], sort, filter: true}: the user sorts by a column and filters by a text box; " +
|
|
20
20
|
"```steps holds {items: [{title, status: done|doing|todo|blocked, when, body}]}, a steps or timeline view; " +
|
|
21
|
-
"```stats holds a YAML list of {label, value, delta, tone, note} shown as metric tiles
|
|
21
|
+
"```stats holds a YAML list of {label, value, delta, tone, note} shown as metric tiles; " +
|
|
22
|
+
"```tree is a directory tree for structure reviews, shown with folders that collapse and expand: indented lines, two spaces per level, the first line the root, a folder's name ends with /, optional {tags} (new, changed, removed, focus, risk) then a note after ' # ' (e.g. ` core/ {focus} # parser and text`), and `… N more` for cut entries. Snapshot a workspace with `npx pbs-tree [dir]` (or `bunx pbs-tree`), which prints the fence and takes Linux tree's flags -L n, -d, -a, -I pattern, -P pattern, --dirsfirst, --filelimit n, --prune, plus --gitignore and --changed-since <rev> (tags new/changed/removed from git); keep it under a few hundred nodes (-L, -I, --gitignore), then add notes and tags by hand. body fields are Markdown. " +
|
|
22
23
|
"Images and links resolve against the page's directory; nothing loads from above it or from another site. " +
|
|
23
24
|
"Every Markdown, HTML, and TSX page has a feedback panel: the user comments on selected passages and sends them to you as a message. " +
|
|
24
25
|
"Put decisions that belong to the page (several questions, or a choice after a comparison) in a ```form at its end; ask a single short question with your question tool. " +
|
|
25
26
|
'An .html page runs as written under a sandbox (scripts and forms, no storage, nothing from other sites): a <form action="cgi-bin:pi-answer"> sends its fields to you when submitted, and piBetterShow.send(fields) does the same from a script. ' +
|
|
26
|
-
'When a page needs interaction (inputs that recompute, tabs, filters), write a .tsx or .jsx file and open it with view "page": React is built in, and the "pi-kit" module exports PbsBlock, PbsForm, PbsOptions, PbsReview, PbsChecklist, PbsTable, PbsCallout, PbsCards, PbsMindmap, PbsSuggest, PbsSteps, PbsStats, PbsDiff, PbsDiagram (props data, onAnswer; PbsBlock draws a parsed block), parse, encodeAnswer, and send(answer or fields) to hand you any values as a message. Import sibling modules freely; import no CSS. ' +
|
|
27
|
+
'When a page needs interaction (inputs that recompute, tabs, filters), write a .tsx or .jsx file and open it with view "page": React is built in, and the "pi-kit" module exports PbsBlock, PbsForm, PbsOptions, PbsReview, PbsChecklist, PbsTable, PbsCallout, PbsCards, PbsMindmap, PbsSuggest, PbsSteps, PbsStats, PbsDiff, PbsDiagram, PbsTree (props data, onAnswer; PbsBlock draws a parsed block), parse, encodeAnswer, and send(answer or fields) to hand you any values as a message. Import sibling modules freely; import no CSS. ' +
|
|
27
28
|
"It returns at once without waiting for the user. Pages reload and edited documents refresh when you change them.";
|
|
28
29
|
|
|
29
30
|
export const parameters = Type.Object({
|
|
@@ -47,6 +48,9 @@ export const showDocTool = (show: BetterShow) =>
|
|
|
47
48
|
label: "Show document",
|
|
48
49
|
description: DESCRIPTION,
|
|
49
50
|
parameters,
|
|
51
|
+
// pi runs the calls of one assistant message in parallel; a `write` issued beside this call would not have
|
|
52
|
+
// finished when it reads the file ("cannot read"). Sequential runs the calls in order, the write first.
|
|
53
|
+
executionMode: "sequential",
|
|
50
54
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
51
55
|
show.setContext(ctx);
|
|
52
56
|
const result = await show.show(ctx.cwd, params.paths, params.reason, params.view);
|
package/src/react/index.ts
CHANGED
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
StepsData,
|
|
25
25
|
SuggestData,
|
|
26
26
|
TableData,
|
|
27
|
+
TreeData,
|
|
27
28
|
} from "../core/types.ts";
|
|
28
29
|
import type { AnsweredFields, BlockRef, Density, PbsElement, Scheme, TAGS } from "../elements/index.ts";
|
|
29
30
|
import "../elements/index.ts";
|
|
@@ -124,6 +125,7 @@ export const PbsSteps = component<StepsData>("pbs-steps");
|
|
|
124
125
|
export const PbsStats = component<StatsData>("pbs-stats");
|
|
125
126
|
export const PbsDiff = component<DiffData>("pbs-diff");
|
|
126
127
|
export const PbsDiagram = component<MermaidData>("pbs-diagram");
|
|
128
|
+
export const PbsTree = component<TreeData>("pbs-tree");
|
|
127
129
|
|
|
128
130
|
const BY_KIND: { [K in keyof typeof TAGS]: (props: PbsProps<BlockDataMap[K]>) => ReactElement } = {
|
|
129
131
|
alert: PbsCallout,
|
|
@@ -139,6 +141,7 @@ const BY_KIND: { [K in keyof typeof TAGS]: (props: PbsProps<BlockDataMap[K]>) =>
|
|
|
139
141
|
stats: PbsStats,
|
|
140
142
|
diff: PbsDiff,
|
|
141
143
|
mermaid: PbsDiagram,
|
|
144
|
+
tree: PbsTree,
|
|
142
145
|
};
|
|
143
146
|
|
|
144
147
|
export interface PbsBlockProps extends Omit<PbsProps<never>, "data" | "blockRef" | "ref"> {
|