pi-better-show 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/package.json +1 -1
- package/src/core/blocks.ts +5 -0
- package/src/core/index.ts +1 -0
- package/src/core/text.ts +41 -5
- package/src/core/types.ts +7 -0
- package/src/core/validate.ts +133 -0
- package/src/elements/choice.ts +1 -3
- 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/server.ts +20 -2
- package/src/extension/tool.ts +1 -1
package/README.md
CHANGED
|
@@ -54,10 +54,13 @@ interface TextProfile {
|
|
|
54
54
|
width?: number; // columns a diagram may take; default 60
|
|
55
55
|
mermaid?: (source: string, width: number) => string | undefined;
|
|
56
56
|
keep?: readonly BlockKind[]; // kinds emitted as their `raw` text instead of converted
|
|
57
|
+
lang?: "en" | "zh-TW"; // language of the reply instructions; default "en", anything else is "en"
|
|
57
58
|
}
|
|
58
59
|
```
|
|
59
60
|
|
|
60
|
-
|
|
61
|
+
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
|
+
|
|
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.
|
|
61
64
|
|
|
62
65
|
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`.
|
|
63
66
|
|
|
@@ -87,6 +90,14 @@ encodeAnswer(answer: Answer): string
|
|
|
87
90
|
| `suggest` | `[["text", text]]` | the text itself |
|
|
88
91
|
| `checklist` | one `[name, "checked" \| "unchecked"]` per item | `User updated the checklist "title":` then `☑`/`☐` lines |
|
|
89
92
|
|
|
93
|
+
```ts
|
|
94
|
+
validateAnswer(block: BlockSegment, answer: Answer): { ok: true } | { ok: false; reason: string }
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`validateAnswer` is for a host that receives an `Answer` from an untrusted client. It accepts the answer when its `kind` fits the block (`options` takes `pick`, the others their own kind), every field names a question, choice, or item of that block, and there are at most 64 fields of at most 1,024 characters each. Several values for one name are accepted only for a `multi` form question (as repeated fields, or the joined value the form element sends); a `single` or `text` question, a pick, and a suggestion take one. A required question must be answered (an empty value or `(no answer)` is not an answer). On a `form` question without an `other` box, a value must be one of its choices. A `checklist` field is an item name once with `checked` or `unchecked`; a `review` may carry `picked` only when the block has `pick`. On refusal `reason` says why, for the host's error reply. Blocks that take no answer (display kinds) are refused.
|
|
98
|
+
|
|
99
|
+
**Several values.** A block that gathers several values (a `form` with a `multi` question, a `checklist`, a `review`) sends nothing on a tick, a pick, or typing: choices stay changeable until the reader presses Send, and a required `multi` question with none chosen is refused at that question. Only `options` and `suggest` send on the click.
|
|
100
|
+
|
|
90
101
|
## Server API
|
|
91
102
|
|
|
92
103
|
```ts
|
|
@@ -208,7 +219,7 @@ Then `/reload` in a running session.
|
|
|
208
219
|
|
|
209
220
|
**Markdown pages.** Prose is Markdown with raw HTML left as text; every block above becomes its element. Select a passage to comment on it; the panel collects comments and an overall note and sends them in one message. A form, pick, chip, checklist, or review reaches the agent as a message: steered into a running turn, or starting a turn when the agent is idle (`encodeAnswer`). Diagrams are drawn on the server, in the page's colour scheme. Images and links resolve against the page's directory: nothing loads from above it, from a dot file or directory, or from another site. Every response carries a CSP, and the server answers only the loopback host.
|
|
210
221
|
|
|
211
|
-
**Agent pages.** `.html` and `.tsx`/`.jsx` run in `<iframe sandbox="allow-scripts allow-forms">` without `allow-same-origin`: no storage, no cookies, and no way to answer on its own: the server refuses a POST whose Origin is not its own (a frame's is `null`) or that is not JSON, and an event stream not opened from its own page. A `<form action="cgi-bin:pi-answer">` or `piBetterShow.send(fields)` answers through the page around the frame. A TSX page's default export is a React component, built by esbuild on each load with the React this package ships; `import {PbsBlock, PbsForm, ..., parse, encodeAnswer, send} from "pi-kit"` gives it the wrappers.
|
|
222
|
+
**Agent pages.** `.html` and `.tsx`/`.jsx` run in `<iframe sandbox="allow-scripts allow-forms">` without `allow-same-origin`: no storage, no cookies, and no way to answer on its own: the server refuses a POST whose Origin is not its own (a frame's is `null`) or that is not JSON, and an event stream not opened from its own page. A `<form action="cgi-bin:pi-answer">` or `piBetterShow.send(fields)` answers through the page around the frame. The page around the frame carries the same feedback panel as a Markdown page: the frame reports the text the user selects to its parent by `postMessage({source: "pbs-frame", type: "selection", text})` (cut to 2000 characters, accepted only from the page's own frame with origin `null`), the user comments on passages and adds an overall note, and one Send delivers a `feedback` answer named by the HTML `<title>`, else the file name. A TSX page works the same way. A TSX page's default export is a React component, built by esbuild on each load with the React this package ships; `import {PbsBlock, PbsForm, ..., parse, encodeAnswer, send} from "pi-kit"` gives it the wrappers.
|
|
212
223
|
|
|
213
224
|
**Edit mode.** Your editor opens the file and the extension watches it. When you save, the change since the version the agent last saw goes to it as a zero-context diff (`@@` headers carry line numbers): steered into a running turn, or attached to your next message when idle, so a save never starts a turn. A save in the same instant as the agent's own write is not reported.
|
|
214
225
|
|
|
@@ -225,7 +236,7 @@ Then `/reload` in a running session.
|
|
|
225
236
|
| `better-show:answer` | `{version, id, answerId, answer}` with `answer` an `Answer`. It reaches the agent as the same message a page answer produces. |
|
|
226
237
|
| `better-show:answer-result` | `{version, id, answerId, accepted, reason?}`; `reason` is `closed`, `invalid` (wrong version or shape, or a `text` document), `empty`, or a delivery error. A repeated `answerId` gets its first result back and delivers nothing again. A payload without a string `id` and `answerId` gets no reply. |
|
|
227
238
|
|
|
228
|
-
A viewer that shows an `html` document in a frame receives its answers as `postMessage({source: "pbs-frame", type: "answer", answerId, answer})` from the frame (origin `"null"`) and replies `{source: "pbs-host", type: "answer-result", answerId, accepted, reason?}`.
|
|
239
|
+
A viewer that shows an `html` document in a frame receives its answers as `postMessage({source: "pbs-frame", type: "answer", answerId, answer})` from the frame (origin `"null"`) and replies `{source: "pbs-host", type: "answer-result", answerId, accepted, reason?}`. It also receives `{source: "pbs-frame", type: "selection", text, top?, left?}` whenever the user's selection in the frame changes (`text` is empty when it was cleared) and may offer its own feedback panel with it.
|
|
229
240
|
|
|
230
241
|
**Moving from pi-herdr-doc-review.** Uninstall it and install this package; `show_doc` keeps its name and parameters. Gone: Herdr panes, nvim and vim, Chawan and terminal-browser, and the `<pi-*>` page-kit tags (write `form`, `review`, ... blocks instead, or use the `pbs-*` elements). The event names changed from `doc-review:*` (version 1) to `better-show:*` (version 2).
|
|
231
242
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/core/blocks.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { inlinePlain } from "./inline.ts";
|
|
1
2
|
import { entryOf, itemsOf, list, mappingOf, oneOf, positiveNumber, recommended, record, text } from "./normalize.ts";
|
|
2
3
|
import type {
|
|
3
4
|
CardsData,
|
|
@@ -112,6 +113,10 @@ export function reviewNames(names: (string | undefined)[]): string[] {
|
|
|
112
113
|
export const reviewItemName = (item: { name: string; label?: string }): string =>
|
|
113
114
|
item.label ? `${item.name} (${item.label})` : item.name;
|
|
114
115
|
|
|
116
|
+
/** The name an option answers with: its plain title, else its 1-based number. */
|
|
117
|
+
export const optionName = (option: { title?: string }, index: number): string =>
|
|
118
|
+
option.title ? inlinePlain(option.title) : String(index + 1);
|
|
119
|
+
|
|
115
120
|
export function review(data: unknown): ReviewData {
|
|
116
121
|
const raw = mappingOf(data);
|
|
117
122
|
const entries = itemsOf(data, "items").map((entry) => entryOf(entry, "image", "item"));
|
package/src/core/index.ts
CHANGED
package/src/core/text.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type {
|
|
|
19
19
|
StepsData,
|
|
20
20
|
SuggestData,
|
|
21
21
|
TableData,
|
|
22
|
+
TextLang,
|
|
22
23
|
TextProfile,
|
|
23
24
|
} from "./types.ts";
|
|
24
25
|
import { displayWidth } from "./width.ts";
|
|
@@ -32,8 +33,40 @@ interface Dialect {
|
|
|
32
33
|
markdown: boolean;
|
|
33
34
|
width: number;
|
|
34
35
|
mermaid: TextProfile["mermaid"];
|
|
36
|
+
say: Replies;
|
|
35
37
|
}
|
|
36
38
|
|
|
39
|
+
/** The reply instructions of the interactive kinds. */
|
|
40
|
+
interface Replies {
|
|
41
|
+
options: string;
|
|
42
|
+
/** Followed by an example, `1: b`. */
|
|
43
|
+
form: (example: string) => string;
|
|
44
|
+
/** Followed by the pick sentence, when the review has one. */
|
|
45
|
+
review: string;
|
|
46
|
+
pick: (label: string | undefined) => string;
|
|
47
|
+
suggest: string;
|
|
48
|
+
checklist: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const REPLIES: Record<TextLang, Replies> = {
|
|
52
|
+
en: {
|
|
53
|
+
options: "Reply with a number.",
|
|
54
|
+
form: (example) => `Reply in text, one line per question, like ${example}.`,
|
|
55
|
+
review: "Reply with a comment for each item, naming the item.",
|
|
56
|
+
pick: (label) => ` Say which one you pick${label === undefined ? "" : ` (${label})`}.`,
|
|
57
|
+
suggest: "You can reply: ",
|
|
58
|
+
checklist: "Reply with the items you tick or leave unticked, naming each.",
|
|
59
|
+
},
|
|
60
|
+
"zh-TW": {
|
|
61
|
+
options: "請回覆編號。",
|
|
62
|
+
form: (example) => `請用文字回覆,每題一行,例如 ${example}。`,
|
|
63
|
+
review: "請逐項回覆意見,並寫明是哪一項。",
|
|
64
|
+
pick: (label) => `請說明你選哪一項${label === undefined ? "" : `(${label})`}。`,
|
|
65
|
+
suggest: "可以回覆:",
|
|
66
|
+
checklist: "請回覆你勾選或不勾選的項目,逐項寫明。",
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
37
70
|
const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim();
|
|
38
71
|
const letter = (index: number): string => (index < 26 ? String.fromCharCode(97 + index) : String(index + 1));
|
|
39
72
|
const star = (recommended: Recommended | undefined): string =>
|
|
@@ -87,7 +120,7 @@ function options(dialect: Dialect, data: OptionsData): string {
|
|
|
87
120
|
...option.cons.map((con) => ` − ${oneLine(field(dialect, con))}`),
|
|
88
121
|
];
|
|
89
122
|
});
|
|
90
|
-
return [...lines, "",
|
|
123
|
+
return [...lines, "", dialect.say.options].join("\n");
|
|
91
124
|
}
|
|
92
125
|
|
|
93
126
|
function form(dialect: Dialect, data: FormData): string {
|
|
@@ -106,7 +139,7 @@ function form(dialect: Dialect, data: FormData): string {
|
|
|
106
139
|
});
|
|
107
140
|
const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
|
|
108
141
|
const example = dialect.markdown ? "`1: b`" : "1: b";
|
|
109
|
-
return [...title, ...lines, "",
|
|
142
|
+
return [...title, ...lines, "", dialect.say.form(example)].join("\n");
|
|
110
143
|
}
|
|
111
144
|
|
|
112
145
|
function review(dialect: Dialect, data: ReviewData): string {
|
|
@@ -115,9 +148,9 @@ function review(dialect: Dialect, data: ReviewData): string {
|
|
|
115
148
|
...(item.image ? [` image: ${item.image}`] : []),
|
|
116
149
|
...(item.page ? [` page: ${item.page}`] : []),
|
|
117
150
|
]);
|
|
118
|
-
const pick = data.pick === undefined ? "" :
|
|
151
|
+
const pick = data.pick === undefined ? "" : dialect.say.pick(data.pick === true ? undefined : data.pick);
|
|
119
152
|
const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
|
|
120
|
-
return [...title, ...lines, "",
|
|
153
|
+
return [...title, ...lines, "", `${dialect.say.review}${pick}`].join("\n");
|
|
121
154
|
}
|
|
122
155
|
|
|
123
156
|
function mindmap(dialect: Dialect, data: MindmapData): string {
|
|
@@ -132,7 +165,7 @@ function mindmap(dialect: Dialect, data: MindmapData): string {
|
|
|
132
165
|
|
|
133
166
|
function suggest(dialect: Dialect, data: SuggestData): string {
|
|
134
167
|
if (data.items.length === 0) return "";
|
|
135
|
-
return
|
|
168
|
+
return `${dialect.say.suggest}${data.items.map((item) => field(dialect, item.label)).join(" | ")}`;
|
|
136
169
|
}
|
|
137
170
|
|
|
138
171
|
function checklist(dialect: Dialect, data: ChecklistData): string {
|
|
@@ -143,6 +176,8 @@ function checklist(dialect: Dialect, data: ChecklistData): string {
|
|
|
143
176
|
(item) =>
|
|
144
177
|
`${item.checked ? "☑" : "☐"} ${joined(dialect, field(dialect, item.label), item.note && oneLine(field(dialect, item.note)))}`,
|
|
145
178
|
),
|
|
179
|
+
"",
|
|
180
|
+
dialect.say.checklist,
|
|
146
181
|
].join("\n");
|
|
147
182
|
}
|
|
148
183
|
|
|
@@ -271,6 +306,7 @@ export function toText(segments: Segment[], profile: TextProfile): string {
|
|
|
271
306
|
markdown: profile.flavor === "discord",
|
|
272
307
|
width: profile.width ?? DEFAULT_WIDTH,
|
|
273
308
|
mermaid: profile.mermaid,
|
|
309
|
+
say: REPLIES[profile.lang === "zh-TW" ? "zh-TW" : "en"],
|
|
274
310
|
};
|
|
275
311
|
const keep = new Set<string>(profile.keep ?? []);
|
|
276
312
|
return segments
|
package/src/core/types.ts
CHANGED
|
@@ -233,7 +233,14 @@ export interface TextProfile {
|
|
|
233
233
|
mermaid?: (source: string, width: number) => string | undefined;
|
|
234
234
|
/** Kinds whose blocks (valid or invalid) are emitted as their `raw` text, for a surface that draws them itself. */
|
|
235
235
|
keep?: readonly BlockKind[];
|
|
236
|
+
/** Language of the reply instructions: `en` (default) or `zh-TW`; anything else is `en`. */
|
|
237
|
+
lang?: TextLang;
|
|
236
238
|
}
|
|
237
239
|
|
|
240
|
+
export type TextLang = "en" | "zh-TW";
|
|
241
|
+
|
|
238
242
|
/** The kinds a display surface (a chat UI that draws blocks itself) typically keeps through `toText`. */
|
|
239
243
|
export const DISPLAY_KINDS = ["alert", "cards", "mermaid", "mindmap", "diff", "table", "steps", "stats"] as const;
|
|
244
|
+
|
|
245
|
+
/** The kinds a reader answers; a surface that cannot draw them gets their reply instructions from `toText`. */
|
|
246
|
+
export const INTERACTIVE_KINDS = ["options", "suggest", "form", "checklist", "review"] as const;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { optionName, reviewItemName } from "./blocks.ts";
|
|
2
|
+
import type { Answer, AnswerKind, BlockSegment, FormData, QuestionData } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
/** `reason` says what is wrong, for a host's refusal. */
|
|
5
|
+
export type Validation = { ok: true } | { ok: false; reason: string };
|
|
6
|
+
|
|
7
|
+
const MAX_FIELDS = 64;
|
|
8
|
+
const MAX_LENGTH = 1024;
|
|
9
|
+
/** What the form element writes for a question left empty. */
|
|
10
|
+
const NO_ANSWER = "(no answer)";
|
|
11
|
+
|
|
12
|
+
const KINDS: Partial<Record<BlockSegment["kind"], AnswerKind>> = {
|
|
13
|
+
options: "pick",
|
|
14
|
+
suggest: "suggest",
|
|
15
|
+
form: "form",
|
|
16
|
+
checklist: "checklist",
|
|
17
|
+
review: "review",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const fail = (reason: string): Validation => ({ ok: false, reason });
|
|
21
|
+
const PASS: Validation = { ok: true };
|
|
22
|
+
const quoted = (text: string): string => JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}…` : text);
|
|
23
|
+
|
|
24
|
+
type Fields = Answer["fields"];
|
|
25
|
+
|
|
26
|
+
const valuesOf = (fields: Fields, name: string): string[] =>
|
|
27
|
+
fields.filter(([key]) => key === name).map(([, value]) => value);
|
|
28
|
+
|
|
29
|
+
/** A choice question's value is a choice's value, or the joined list the form element sends; free text only where `other` allows. */
|
|
30
|
+
function choiceProblem(question: QuestionData, value: string): string | undefined {
|
|
31
|
+
if (question.other !== false || value === NO_ANSWER) return undefined;
|
|
32
|
+
const known = new Set(question.choices.map((choice) => choice.value));
|
|
33
|
+
if (known.has(value)) return undefined;
|
|
34
|
+
const parts = question.type === "multi" ? value.split(", ") : [value];
|
|
35
|
+
const unknown = parts.find((part) => !known.has(part));
|
|
36
|
+
return unknown === undefined ? undefined : `unknown choice ${quoted(unknown)} for question ${quoted(question.name)}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function formProblem(data: FormData, fields: Fields): string | undefined {
|
|
40
|
+
const questions = new Map(data.questions.map((question) => [question.name, question]));
|
|
41
|
+
const seen = new Set<string>();
|
|
42
|
+
for (const [name, value] of fields) {
|
|
43
|
+
if (name === "form") continue;
|
|
44
|
+
const question = questions.get(name);
|
|
45
|
+
if (!question) return `unknown question ${quoted(name)}`;
|
|
46
|
+
if (seen.has(name) && question.type !== "multi")
|
|
47
|
+
return `several values for ${quoted(name)}, which is not a multi question`;
|
|
48
|
+
seen.add(name);
|
|
49
|
+
if (question.type !== "text") {
|
|
50
|
+
const problem = choiceProblem(question, value);
|
|
51
|
+
if (problem) return problem;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const missing = data.questions.find(
|
|
55
|
+
(question) =>
|
|
56
|
+
question.required && !valuesOf(fields, question.name).some((value) => value.trim() !== "" && value !== NO_ANSWER),
|
|
57
|
+
);
|
|
58
|
+
return missing ? `required question ${quoted(missing.name)} is not answered` : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function reviewProblem(block: Extract<BlockSegment, { kind: "review" }>, fields: Fields): string | undefined {
|
|
62
|
+
const names = block.data.items.map(reviewItemName);
|
|
63
|
+
const known = new Set(names);
|
|
64
|
+
for (const [name, value] of fields) {
|
|
65
|
+
if (name === "title" || name === "comment") continue;
|
|
66
|
+
if (name === "picked") {
|
|
67
|
+
if (block.data.pick === undefined) return "this review has no pick";
|
|
68
|
+
if (!known.has(value)) return `unknown item ${quoted(value)}`;
|
|
69
|
+
} else if (name === "item") {
|
|
70
|
+
if (!known.has(value)) return `unknown item ${quoted(value)}`;
|
|
71
|
+
} else if (name === "silent") {
|
|
72
|
+
const unknown = known.has(value) ? undefined : value.split(", ").find((part) => !known.has(part));
|
|
73
|
+
if (unknown !== undefined) return `unknown item ${quoted(unknown)}`;
|
|
74
|
+
} else return `unknown field ${quoted(name)}`;
|
|
75
|
+
}
|
|
76
|
+
if (valuesOf(fields, "picked").length > 1) return "only one item can be picked";
|
|
77
|
+
if (valuesOf(fields, "title").length > 1) return "several titles";
|
|
78
|
+
if (valuesOf(fields, "comment").length > valuesOf(fields, "item").length) return "a comment without an item";
|
|
79
|
+
const items = valuesOf(fields, "item");
|
|
80
|
+
if (new Set(items).size !== items.length) return "an item is named twice";
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function problem(block: BlockSegment, answer: Answer): string | undefined {
|
|
85
|
+
const { fields } = answer;
|
|
86
|
+
switch (block.kind) {
|
|
87
|
+
case "options": {
|
|
88
|
+
if (fields.length !== 1 || fields[0]?.[0] !== "picked") return "a pick carries exactly one picked field";
|
|
89
|
+
const picked = fields[0][1];
|
|
90
|
+
return block.data.options.some((option, index) => optionName(option, index) === picked)
|
|
91
|
+
? undefined
|
|
92
|
+
: `unknown option ${quoted(picked)}`;
|
|
93
|
+
}
|
|
94
|
+
case "suggest": {
|
|
95
|
+
if (fields.length !== 1 || fields[0]?.[0] !== "text") return "a suggestion carries exactly one text field";
|
|
96
|
+
const text = fields[0][1];
|
|
97
|
+
return block.data.items.some((item) => item.text === text) ? undefined : `unknown suggestion ${quoted(text)}`;
|
|
98
|
+
}
|
|
99
|
+
case "form":
|
|
100
|
+
return formProblem(block.data, fields);
|
|
101
|
+
case "review":
|
|
102
|
+
return reviewProblem(block, fields);
|
|
103
|
+
case "checklist": {
|
|
104
|
+
const names = new Set(block.data.items.map((item) => item.name));
|
|
105
|
+
const seen = new Set<string>();
|
|
106
|
+
for (const [name, state] of fields) {
|
|
107
|
+
if (!names.has(name)) return `unknown item ${quoted(name)}`;
|
|
108
|
+
if (seen.has(name)) return `item ${quoted(name)} appears twice`;
|
|
109
|
+
seen.add(name);
|
|
110
|
+
if (state !== "checked" && state !== "unchecked") return `unknown mark ${quoted(state)}`;
|
|
111
|
+
}
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
default:
|
|
115
|
+
return `a ${block.kind} block takes no answer`;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Whether an untrusted `answer` fits `block`: its kind is the block's, every field names a question, choice, or item
|
|
121
|
+
* of the block, several values appear only for a `multi` form question, required questions are answered, and there
|
|
122
|
+
* are at most 64 fields of 1,024 characters each.
|
|
123
|
+
*/
|
|
124
|
+
export function validateAnswer(block: BlockSegment, answer: Answer): Validation {
|
|
125
|
+
const expected = KINDS[block.kind];
|
|
126
|
+
if (expected === undefined) return fail(`a ${block.kind} block takes no answer`);
|
|
127
|
+
if (answer.kind !== expected) return fail(`answer kind ${quoted(answer.kind)} does not fit a ${block.kind} block`);
|
|
128
|
+
if (answer.fields.length > MAX_FIELDS) return fail(`more than ${MAX_FIELDS} fields`);
|
|
129
|
+
if (answer.fields.some(([name, value]) => name.length > MAX_LENGTH || value.length > MAX_LENGTH))
|
|
130
|
+
return fail(`a field is longer than ${MAX_LENGTH} characters`);
|
|
131
|
+
const found = problem(block, answer);
|
|
132
|
+
return found === undefined ? PASS : fail(found);
|
|
133
|
+
}
|
package/src/elements/choice.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { optionName } from "../core/blocks.ts";
|
|
1
2
|
import { inlinePlain } from "../core/inline.ts";
|
|
2
3
|
import type { ChecklistData, OptionData, OptionsData, SuggestData } from "../core/types.ts";
|
|
3
4
|
import { define, PbsElement } from "./base.ts";
|
|
@@ -6,9 +7,6 @@ import { h, inlineNodes, prose, uid } from "./dom.ts";
|
|
|
6
7
|
|
|
7
8
|
/** The elements that answer with a pick or ticks: options, suggest, checklist. */
|
|
8
9
|
|
|
9
|
-
const optionName = (option: OptionData, index: number): string =>
|
|
10
|
-
option.title ? inlinePlain(option.title) : String(index + 1);
|
|
11
|
-
|
|
12
10
|
/**
|
|
13
11
|
* One-shot elements (options, suggest) lock themselves once a listener takes the answer, so a double click sends
|
|
14
12
|
* once; the host's `answered` then shows what was sent. Setting `answered` (even to `undefined`) clears the local lock,
|
|
@@ -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
|
+
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Answer } from "../../core/types.ts";
|
|
1
2
|
import { configure } from "../../elements/index.ts";
|
|
2
3
|
|
|
3
4
|
/** The page server's path prefix (`/<token>`): the first segment of every page it serves. */
|
|
@@ -44,6 +45,25 @@ export interface AnswerReply {
|
|
|
44
45
|
reason?: string;
|
|
45
46
|
}
|
|
46
47
|
|
|
48
|
+
export interface AnswerBody {
|
|
49
|
+
answerId: string;
|
|
50
|
+
answer: Answer;
|
|
51
|
+
/** The path of the page the answer comes from. */
|
|
52
|
+
page: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Delivers one answer to the page server, and tells whether it was taken. */
|
|
56
|
+
export type PostAnswer = (url: string, body: AnswerBody) => Promise<AnswerReply>;
|
|
57
|
+
|
|
58
|
+
export const postAnswerToServer: PostAnswer = async (url, body) => {
|
|
59
|
+
const response = await fetch(url, {
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: { "content-type": "application/json" },
|
|
62
|
+
body: JSON.stringify(body),
|
|
63
|
+
});
|
|
64
|
+
return (await response.json().catch(() => ({ accepted: false, reason: `HTTP ${response.status}` }))) as AnswerReply;
|
|
65
|
+
};
|
|
66
|
+
|
|
47
67
|
/** A random id for one answer, so a repeated send is delivered once. */
|
|
48
68
|
export const newAnswerId = (): string =>
|
|
49
69
|
typeof crypto.randomUUID === "function"
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { frameAnswer, frameSelection } from "./bridge.ts";
|
|
2
|
+
import { type FeedbackWords, mountFeedback } from "./feedback.ts";
|
|
3
|
+
import { type AnswerReply, newAnswerId, type PostAnswer } from "./host-config.ts";
|
|
4
|
+
|
|
5
|
+
export interface HostOptions {
|
|
6
|
+
frame: HTMLIFrameElement;
|
|
7
|
+
/** The page server's path prefix (`/<token>`). */
|
|
8
|
+
prefix: string;
|
|
9
|
+
/** The name the agent knows the page by: the HTML title, else the file name. */
|
|
10
|
+
page: string;
|
|
11
|
+
words: FeedbackWords;
|
|
12
|
+
storage: Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
|
13
|
+
storageKey: string;
|
|
14
|
+
post: PostAnswer;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The page around an agent's HTML or TSX page. The page itself runs in a sandboxed frame without `allow-same-origin`,
|
|
19
|
+
* so the server refuses its own requests (Origin null); it asks this parent, by `postMessage`, to carry its answers and
|
|
20
|
+
* to report the text the user selects. The parent trusts a message only from its own frame (see bridge.ts), and the
|
|
21
|
+
* feedback panel lives here, outside the frame, where the user's comments and the server's answer check are the same
|
|
22
|
+
* as on a Markdown page.
|
|
23
|
+
*/
|
|
24
|
+
export function mountHost(options: HostOptions): { destroy: () => void } {
|
|
25
|
+
const { frame, prefix, post } = options;
|
|
26
|
+
const answerUrl = `${prefix}/answer`;
|
|
27
|
+
const feedback = mountFeedback({
|
|
28
|
+
page: options.page,
|
|
29
|
+
words: options.words,
|
|
30
|
+
storage: options.storage,
|
|
31
|
+
storageKey: options.storageKey,
|
|
32
|
+
watchDocument: false,
|
|
33
|
+
send: async (answer) => {
|
|
34
|
+
const reply = await post(answerUrl, { answerId: newAnswerId(), answer, page: location.pathname });
|
|
35
|
+
if (!reply.accepted) throw new Error(reply.reason ?? "refused");
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const onMessage = (event: MessageEvent): void => {
|
|
40
|
+
const selection = frameSelection(event, frame.contentWindow);
|
|
41
|
+
if (selection) {
|
|
42
|
+
// The position is in the frame's viewport; the Add button sits in this one.
|
|
43
|
+
const origin = frame.getBoundingClientRect();
|
|
44
|
+
feedback.offer({
|
|
45
|
+
text: selection.text,
|
|
46
|
+
...(selection.top === undefined ? {} : { top: selection.top + origin.top }),
|
|
47
|
+
...(selection.left === undefined ? {} : { left: selection.left + origin.left }),
|
|
48
|
+
});
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const taken = frameAnswer(event, frame.contentWindow);
|
|
52
|
+
if (!taken) return;
|
|
53
|
+
const reply = (result: AnswerReply): void =>
|
|
54
|
+
frame.contentWindow?.postMessage(
|
|
55
|
+
{ source: "pbs-host", type: "answer-result", answerId: taken.answerId, ...result },
|
|
56
|
+
"*",
|
|
57
|
+
);
|
|
58
|
+
post(answerUrl, { ...taken, page: location.pathname }).then(reply, (error: unknown) =>
|
|
59
|
+
reply({ accepted: false, reason: error instanceof Error ? error.message : String(error) }),
|
|
60
|
+
);
|
|
61
|
+
};
|
|
62
|
+
// A frame that loads again has lost its selection.
|
|
63
|
+
const onLoad = (): void => feedback.offer(undefined);
|
|
64
|
+
window.addEventListener("message", onMessage);
|
|
65
|
+
frame.addEventListener("load", onLoad);
|
|
66
|
+
return {
|
|
67
|
+
destroy: () => {
|
|
68
|
+
window.removeEventListener("message", onMessage);
|
|
69
|
+
frame.removeEventListener("load", onLoad);
|
|
70
|
+
feedback.destroy();
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -1,33 +1,21 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { wordsFor } from "./feedback.ts";
|
|
2
|
+
import { postAnswerToServer, serverPrefix } from "./host-config.ts";
|
|
3
|
+
import { mountHost } from "./host-page.ts";
|
|
3
4
|
|
|
4
|
-
/**
|
|
5
|
-
* The page around an agent's HTML or TSX page. The page itself runs in a sandboxed frame without
|
|
6
|
-
* `allow-same-origin`, so the server refuses its own requests (Origin null); it asks this parent, by `postMessage`, to carry its answers.
|
|
7
|
-
* The parent trusts a message only from its own frame (see bridge.ts).
|
|
8
|
-
*/
|
|
5
|
+
/** The script of the page around an agent's HTML or TSX page: carries its answers, mounts the feedback panel, and reloads the frame when the document changes. */
|
|
9
6
|
|
|
10
7
|
const prefix = serverPrefix();
|
|
11
8
|
const frame = document.querySelector("iframe");
|
|
12
9
|
if (!frame) throw new Error("no frame to host");
|
|
13
10
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
fetch(`${prefix}/answer`, {
|
|
23
|
-
method: "POST",
|
|
24
|
-
headers: { "content-type": "application/json" },
|
|
25
|
-
body: JSON.stringify({ ...taken, page: location.pathname }),
|
|
26
|
-
})
|
|
27
|
-
.then((response) => response.json() as Promise<AnswerReply>)
|
|
28
|
-
.then(reply, (error: unknown) =>
|
|
29
|
-
reply({ accepted: false, reason: error instanceof Error ? error.message : String(error) }),
|
|
30
|
-
);
|
|
11
|
+
mountHost({
|
|
12
|
+
frame,
|
|
13
|
+
prefix,
|
|
14
|
+
page: document.title || location.pathname.split("/").pop() || "",
|
|
15
|
+
words: wordsFor(document.documentElement.lang || navigator.language),
|
|
16
|
+
storage: sessionStorage,
|
|
17
|
+
storageKey: `pbs-feedback:${location.pathname}`,
|
|
18
|
+
post: postAnswerToServer,
|
|
31
19
|
});
|
|
32
20
|
|
|
33
21
|
new EventSource(`${prefix}/events?page=${encodeURIComponent(location.pathname)}`).addEventListener("reload", () => {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Answer } from "../../core/types.ts";
|
|
2
2
|
import "../../elements/index.ts";
|
|
3
3
|
import { mountFeedback, wordsFor } from "./feedback.ts";
|
|
4
|
-
import { type AnswerReply, configureElements, newAnswerId, serverPrefix } from "./host-config.ts";
|
|
4
|
+
import { type AnswerReply, configureElements, newAnswerId, postAnswerToServer, serverPrefix } from "./host-config.ts";
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* The script of a rendered Markdown page: wires the elements to the page server (diagrams, images, answers),
|
|
@@ -11,17 +11,8 @@ import { type AnswerReply, configureElements, newAnswerId, serverPrefix } from "
|
|
|
11
11
|
const prefix = serverPrefix();
|
|
12
12
|
configureElements(prefix);
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
method: "POST",
|
|
17
|
-
headers: { "content-type": "application/json" },
|
|
18
|
-
body: JSON.stringify({ answerId: newAnswerId(), answer, page: location.pathname }),
|
|
19
|
-
});
|
|
20
|
-
const reply = (await response
|
|
21
|
-
.json()
|
|
22
|
-
.catch(() => ({ accepted: false, reason: `HTTP ${response.status}` }))) as AnswerReply;
|
|
23
|
-
return reply;
|
|
24
|
-
}
|
|
14
|
+
const postAnswer = (answer: Answer): Promise<AnswerReply> =>
|
|
15
|
+
postAnswerToServer(`${prefix}/answer`, { answerId: newAnswerId(), answer, page: location.pathname });
|
|
25
16
|
|
|
26
17
|
const toast = (text: string): void => {
|
|
27
18
|
const box = document.createElement("div");
|
package/src/extension/server.ts
CHANGED
|
@@ -100,6 +100,22 @@ const finish = (response: ServerResponse, status: number) => {
|
|
|
100
100
|
const titleOf = (markdown: string, fallback: string): string =>
|
|
101
101
|
/^#\s+(.+?)\s*#*\s*$/m.exec(markdown)?.[1]?.replace(/[*_`]/g, "") ?? fallback;
|
|
102
102
|
|
|
103
|
+
const HTML_ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
104
|
+
|
|
105
|
+
/** The `<title>` of an HTML page, as the text it shows, else the fallback. */
|
|
106
|
+
export function htmlTitleOf(html: string, fallback: string): string {
|
|
107
|
+
const raw = /<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(html)?.[1];
|
|
108
|
+
const text = raw
|
|
109
|
+
?.replace(/&#(\d+);|&#x([\da-f]+);|&(\w+);/gi, (whole, dec?: string, hex?: string, name?: string) => {
|
|
110
|
+
const code = dec ? Number(dec) : hex ? Number.parseInt(hex, 16) : undefined;
|
|
111
|
+
if (code === undefined) return HTML_ENTITIES[(name ?? "").toLowerCase()] ?? whole;
|
|
112
|
+
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
|
|
113
|
+
})
|
|
114
|
+
.replace(/\s+/g, " ")
|
|
115
|
+
.trim();
|
|
116
|
+
return text || fallback;
|
|
117
|
+
}
|
|
118
|
+
|
|
103
119
|
export function createPageServer(options: PageServerOptions): Promise<PageServer> {
|
|
104
120
|
const idleMs = options.idleMs ?? PAGE_IDLE_MS;
|
|
105
121
|
const prefix = `/${randomUUID()}`;
|
|
@@ -365,9 +381,11 @@ export function createPageServer(options: PageServerOptions): Promise<PageServer
|
|
|
365
381
|
}
|
|
366
382
|
if (HTML_FILE.test(path) || REACT_FILE.test(path)) {
|
|
367
383
|
const frame = `${framePrefix}${url.pathname.slice(filesPrefix.length)}`;
|
|
384
|
+
const source = content.toString("utf8");
|
|
368
385
|
const html = pageShell({
|
|
369
|
-
title
|
|
370
|
-
|
|
386
|
+
// The panel on this page names the document by it, as the page's own title would.
|
|
387
|
+
title: HTML_FILE.test(path) ? htmlTitleOf(source, basename(path)) : basename(path),
|
|
388
|
+
lang: langOf(source),
|
|
371
389
|
prefix,
|
|
372
390
|
body: `<iframe class="pbs-frame" title="${escapeHtml(basename(path))}" src="${escapeHtml(frame)}" sandbox="allow-scripts allow-forms"></iframe>`,
|
|
373
391
|
scripts: ["host.js"],
|
package/src/extension/tool.ts
CHANGED
|
@@ -20,7 +20,7 @@ export const DESCRIPTION =
|
|
|
20
20
|
"```steps holds {items: [{title, status: done|doing|todo|blocked, when, body}]}, a steps or timeline view; " +
|
|
21
21
|
"```stats holds a YAML list of {label, value, delta, tone, note} shown as metric tiles. body fields are Markdown. " +
|
|
22
22
|
"Images and links resolve against the page's directory; nothing loads from above it or from another site. " +
|
|
23
|
-
"Every Markdown page has a feedback panel: the user comments on selected passages and sends them to you as a message. " +
|
|
23
|
+
"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
24
|
"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
25
|
'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
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. ' +
|