pi-better-show 0.3.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 +2 -2
- package/package.json +1 -1
- 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
|
@@ -219,7 +219,7 @@ Then `/reload` in a running session.
|
|
|
219
219
|
|
|
220
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.
|
|
221
221
|
|
|
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. 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.
|
|
223
223
|
|
|
224
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.
|
|
225
225
|
|
|
@@ -236,7 +236,7 @@ Then `/reload` in a running session.
|
|
|
236
236
|
| `better-show:answer` | `{version, id, answerId, answer}` with `answer` an `Answer`. It reaches the agent as the same message a page answer produces. |
|
|
237
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. |
|
|
238
238
|
|
|
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?}`.
|
|
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.
|
|
240
240
|
|
|
241
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).
|
|
242
242
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.3.
|
|
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",
|
|
@@ -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. ' +
|