@lightblues/jig 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/agent-chat/markdown.d.ts +4 -0
- package/dist/agent-chat/markdown.js +223 -15
- package/dist/agent-chat/react.d.ts +7 -1
- package/dist/agent-chat/react.js +98 -9
- package/dist/canvas/bridge.d.ts +110 -0
- package/dist/canvas/bridge.js +255 -0
- package/dist/canvas/build.d.ts +25 -0
- package/dist/canvas/build.js +54 -0
- package/dist/canvas/compile.d.ts +29 -0
- package/dist/canvas/compile.js +218 -0
- package/dist/canvas/context.d.ts +43 -0
- package/dist/canvas/context.js +79 -0
- package/dist/canvas/document.d.ts +50 -0
- package/dist/canvas/document.js +128 -0
- package/dist/canvas/frame.d.ts +65 -0
- package/dist/canvas/frame.js +197 -0
- package/dist/canvas/names.d.ts +1 -0
- package/dist/canvas/names.js +6 -0
- package/dist/canvas/protocol.d.ts +93 -0
- package/dist/canvas/protocol.js +152 -0
- package/dist/canvas/runtime.d.ts +25 -0
- package/dist/canvas/runtime.js +110 -0
- package/dist/canvas/server.d.ts +5 -0
- package/dist/canvas/server.js +8 -0
- package/dist/canvas/state.d.ts +31 -0
- package/dist/canvas/state.js +72 -0
- package/dist/canvas/store.d.ts +39 -0
- package/dist/canvas/store.js +82 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +30 -1
package/README.md
CHANGED
|
@@ -11,5 +11,6 @@ Planned parts (design: baton `.ea/log/2026-11-24-shared-agent-ui.md`, item #274)
|
|
|
11
11
|
| `@lightblues/jig/agent-chat` | a thin headless client: follow a thread over SSE, reconnect, fold events into messages |
|
|
12
12
|
| `@lightblues/jig/markdown` | one markdown-it config for server and client: CJK, KaTeX, highlighting, safe for innerHTML, streaming-aware; fenced blocks with validated params, mermaid |
|
|
13
13
|
| `@lightblues/jig/markdown/react` | `FillSlots`: host components portalled into a document's block slots, mounted across streaming re-renders |
|
|
14
|
+
| `@lightblues/jig/canvas/server`, `/state`, `/frame`, `/runtime`, `/build` | model-written pages in a sandboxed frame (compile, CSP document, `<CanvasFrame>`, runtime build) and one state/event/action protocol for in-page blocks and frames; `.ea/docs/canvas.md` |
|
|
14
15
|
|
|
15
16
|
The protocol is AG-UI (`@ag-ui/core`), used as is.
|
|
@@ -18,5 +18,9 @@ export interface CloseOpenMarkdownOptions {
|
|
|
18
18
|
* opens nothing, and an inline `$` closes only on its own line, so `$5 and $6` is prose. An inline `$` left open
|
|
19
19
|
* before a digit (`costs $5`) is read as money and left alone. A closer is never placed where the renderer would not
|
|
20
20
|
* read it (after a space or a backslash); an opener with nothing after it yet is dropped instead.
|
|
21
|
+
*
|
|
22
|
+
* Beyond closing: a formula left open is repaired so KaTeX can draw it (`repairTex`: groups, `\left`, environments
|
|
23
|
+
* and missing arguments closed, a half-typed command or a trailing `^` dropped), and a table is held back until it can
|
|
24
|
+
* be drawn (`holdTable`: a header row whose delimiter row is not complete, and a row still being written, are left out).
|
|
21
25
|
*/
|
|
22
26
|
export declare function closeOpenMarkdown(text: string, o?: CloseOpenMarkdownOptions): string;
|
|
@@ -13,6 +13,10 @@ const INLINE_MATH = /\$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$/y;
|
|
|
13
13
|
* opens nothing, and an inline `$` closes only on its own line, so `$5 and $6` is prose. An inline `$` left open
|
|
14
14
|
* before a digit (`costs $5`) is read as money and left alone. A closer is never placed where the renderer would not
|
|
15
15
|
* read it (after a space or a backslash); an opener with nothing after it yet is dropped instead.
|
|
16
|
+
*
|
|
17
|
+
* Beyond closing: a formula left open is repaired so KaTeX can draw it (`repairTex`: groups, `\left`, environments
|
|
18
|
+
* and missing arguments closed, a half-typed command or a trailing `^` dropped), and a table is held back until it can
|
|
19
|
+
* be drawn (`holdTable`: a header row whose delimiter row is not complete, and a row still being written, are left out).
|
|
16
20
|
*/
|
|
17
21
|
export function closeOpenMarkdown(text, o = {}) {
|
|
18
22
|
if (o.strip) {
|
|
@@ -42,11 +46,22 @@ export function closeOpenMarkdown(text, o = {}) {
|
|
|
42
46
|
}
|
|
43
47
|
if (fence)
|
|
44
48
|
return text + (text.endsWith("\n") ? "" : "\n") + fence.char.repeat(fence.len);
|
|
45
|
-
|
|
49
|
+
text = holdTable(text, from);
|
|
50
|
+
// An opener with nothing after it yet is dropped first, then what is left is closed innermost first (so a closer is
|
|
51
|
+
// never put inside something that went away, and the result is stable under a second call).
|
|
52
|
+
let open = scan(text, from);
|
|
53
|
+
for (const x of open) {
|
|
54
|
+
if (x.kind !== "bold" && x.kind !== "math2" && x.kind !== "code")
|
|
55
|
+
continue;
|
|
56
|
+
const body = x.kind === "code" ? text.slice(x.at + x.ticks.length) : text.slice(x.at + 2);
|
|
57
|
+
if (!body.trim()) {
|
|
58
|
+
text = text.slice(0, x.at) + body;
|
|
59
|
+
open = scan(text, from);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
46
62
|
if (!open.length)
|
|
47
63
|
return text;
|
|
48
64
|
let out = text;
|
|
49
|
-
// Close innermost first.
|
|
50
65
|
for (const x of open.reverse())
|
|
51
66
|
out = close(out, x);
|
|
52
67
|
return out;
|
|
@@ -59,6 +74,10 @@ function inDisplayMath(s) {
|
|
|
59
74
|
function scan(text, from) {
|
|
60
75
|
const open = [];
|
|
61
76
|
let bold = null;
|
|
77
|
+
/** The last `$` that opened nothing though a non-space follows it: texmath may pair it with a later closer. */
|
|
78
|
+
let looseFrom = -1;
|
|
79
|
+
/** Whether math has been read: a `$` before a digit is then more likely math than money. */
|
|
80
|
+
let sawMath = false;
|
|
62
81
|
let i = from;
|
|
63
82
|
const n = text.length;
|
|
64
83
|
while (i < n) {
|
|
@@ -85,7 +104,7 @@ function scan(text, from) {
|
|
|
85
104
|
i = j;
|
|
86
105
|
continue;
|
|
87
106
|
}
|
|
88
|
-
return [...withBold(open, bold), { kind: "code", ticks }];
|
|
107
|
+
return [...withBold(open, bold), { kind: "code", ticks, at: i }];
|
|
89
108
|
}
|
|
90
109
|
i = end + ticks.length;
|
|
91
110
|
continue;
|
|
@@ -100,9 +119,10 @@ function scan(text, from) {
|
|
|
100
119
|
}
|
|
101
120
|
const end = text.indexOf("$$", i + 2);
|
|
102
121
|
if (end < 0) {
|
|
103
|
-
const
|
|
104
|
-
return [...withBold(open, bold), { kind: "math2", at: i, block:
|
|
122
|
+
const atLineStart = i === 0 || text[i - 1] === "\n";
|
|
123
|
+
return [...withBold(open, bold), { kind: "math2", at: i, block: atLineStart }];
|
|
105
124
|
}
|
|
125
|
+
sawMath = true;
|
|
106
126
|
i = end + 2;
|
|
107
127
|
continue;
|
|
108
128
|
}
|
|
@@ -112,14 +132,24 @@ function scan(text, from) {
|
|
|
112
132
|
if (m) {
|
|
113
133
|
const nxt = text[INLINE_MATH.lastIndex] ?? "";
|
|
114
134
|
if (!(nxt >= "0" && nxt <= "9")) {
|
|
135
|
+
sawMath = true;
|
|
115
136
|
i = INLINE_MATH.lastIndex;
|
|
116
137
|
continue;
|
|
117
138
|
}
|
|
118
139
|
}
|
|
119
|
-
else if (!text.includes("\n", i) &&
|
|
120
|
-
// Open on the last line,
|
|
121
|
-
|
|
140
|
+
else if (!text.includes("\n", i) && looseFrom < lineStart(text, i)) {
|
|
141
|
+
// Open on the last line, unless an earlier `$` on it would take the closer. A lone `$` at the end is an
|
|
142
|
+
// opener with nothing after it yet. Before a digit it is money (`costs $5 and`, `$5元`), unless only
|
|
143
|
+
// ASCII has come after it and it looks like math (`$1/3`), or is bare digits in a text that already has
|
|
144
|
+
// math (`答案是 $1` before `/3$`).
|
|
145
|
+
const rest = text.slice(i + 1);
|
|
146
|
+
const mathy = /^[!-~]*$/.test(rest) && (/[\\/^_=+<>()[\]{}]/.test(rest) || (sawMath && /^[0-9.]+$/.test(rest)));
|
|
147
|
+
if (!rest || (/^\S/.test(rest) && (!/^[0-9]/.test(rest) || mathy))) {
|
|
148
|
+
return [...withBold(open, bold), { kind: "math1", at: i }];
|
|
149
|
+
}
|
|
122
150
|
}
|
|
151
|
+
if (/\S/.test(text[i + 1] ?? " "))
|
|
152
|
+
looseFrom = i;
|
|
123
153
|
}
|
|
124
154
|
i++;
|
|
125
155
|
continue;
|
|
@@ -133,6 +163,7 @@ function scan(text, from) {
|
|
|
133
163
|
}
|
|
134
164
|
return withBold(open, bold);
|
|
135
165
|
}
|
|
166
|
+
const lineStart = (text, i) => text.lastIndexOf("\n", i - 1) + 1;
|
|
136
167
|
const withBold = (open, bold) => (bold === null ? open : [...open, { kind: "bold", at: bold }]);
|
|
137
168
|
/** Index of a run of exactly `ticks` after `from` within the paragraph, or -1. */
|
|
138
169
|
function closingTicks(text, from, ticks) {
|
|
@@ -158,8 +189,12 @@ function paragraphEnd(text, from) {
|
|
|
158
189
|
}
|
|
159
190
|
function close(text, x) {
|
|
160
191
|
switch (x.kind) {
|
|
161
|
-
case "code":
|
|
192
|
+
case "code": {
|
|
193
|
+
// An opening backtick with nothing after it yet is dropped.
|
|
194
|
+
if (!text.slice(x.at + x.ticks.length).trim())
|
|
195
|
+
return text.slice(0, x.at);
|
|
162
196
|
return text + x.ticks;
|
|
197
|
+
}
|
|
163
198
|
case "bold": {
|
|
164
199
|
const body = text.slice(x.at + 2);
|
|
165
200
|
if (!body.trim())
|
|
@@ -171,16 +206,189 @@ function close(text, x) {
|
|
|
171
206
|
const body = text.slice(x.at + 2);
|
|
172
207
|
if (!body.trim())
|
|
173
208
|
return text.slice(0, x.at) + body;
|
|
174
|
-
|
|
209
|
+
// Half the closer has come.
|
|
210
|
+
if (/(^|[^\\])\$$/.test(body))
|
|
211
|
+
return text + "$";
|
|
212
|
+
const tex = repairTex(x.block ? body : body.trimEnd());
|
|
213
|
+
if (!tex.trim())
|
|
214
|
+
return text.slice(0, x.at);
|
|
215
|
+
const end = text.slice(0, x.at + 2) + tex;
|
|
175
216
|
return x.block ? end + (end.endsWith("\n") ? "" : "\n") + "$$" : end.trimEnd() + "$$";
|
|
176
217
|
}
|
|
177
218
|
case "math1": {
|
|
178
|
-
const
|
|
179
|
-
if (
|
|
219
|
+
const tex = repairTex(text.slice(x.at + 1).trimEnd()).trimEnd();
|
|
220
|
+
if (!tex)
|
|
180
221
|
return text.slice(0, x.at);
|
|
181
|
-
return
|
|
222
|
+
return text.slice(0, x.at + 1) + tex + "$";
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/** Commands whose arguments KaTeX requires: a formula cut before them is given empty ones (`\frac{a` → `\frac{a}{}`). */
|
|
227
|
+
const ARGS = {
|
|
228
|
+
frac: 2, dfrac: 2, tfrac: 2, cfrac: 2, binom: 2, dbinom: 2, tbinom: 2, overset: 2, underset: 2, stackrel: 2,
|
|
229
|
+
sqrt: 1, text: 1, textbf: 1, textit: 1, textrm: 1, mathrm: 1, mathbf: 1, mathit: 1, mathbb: 1, mathcal: 1,
|
|
230
|
+
mathsf: 1, mathtt: 1, mathfrak: 1, mathscr: 1, boldsymbol: 1, bm: 1, operatorname: 1, hat: 1, widehat: 1, bar: 1,
|
|
231
|
+
overline: 1, underline: 1, vec: 1, tilde: 1, widetilde: 1, dot: 1, ddot: 1, check: 1, breve: 1, acute: 1, grave: 1,
|
|
232
|
+
overbrace: 1, underbrace: 1, overrightarrow: 1, overleftarrow: 1, cancel: 1, boxed: 1, mbox: 1, pmod: 1,
|
|
233
|
+
};
|
|
234
|
+
/** Whole commands without arguments kept at the end of a formula; any other trailing command may be half typed. */
|
|
235
|
+
const KNOWN = new Set(("alpha beta gamma delta epsilon varepsilon zeta eta theta vartheta iota kappa lambda mu nu xi pi varpi rho varrho " +
|
|
236
|
+
"sigma varsigma tau upsilon phi varphi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega " +
|
|
237
|
+
"cdot cdots ldots dots vdots ddots times div pm mp ast star circ bullet le leq ge geq ne neq approx sim simeq " +
|
|
238
|
+
"equiv cong propto ll gg in notin ni subset subseteq supset supseteq cup cap setminus emptyset varnothing forall " +
|
|
239
|
+
"exists neg land lor wedge vee to rightarrow leftarrow Rightarrow Leftarrow leftrightarrow Leftrightarrow mapsto " +
|
|
240
|
+
"implies iff infty partial nabla int iint oint sum prod lim limsup liminf max min sup inf arg det exp log ln lg " +
|
|
241
|
+
"sin cos tan cot sec csc arcsin arccos arctan sinh cosh tanh Pr mid nmid parallel perp angle prime ell hbar Re Im " +
|
|
242
|
+
"quad qquad langle rangle lfloor rfloor lceil rceil lvert rvert lVert rVert vert Vert displaystyle textstyle " +
|
|
243
|
+
"top bot dagger therefore because cdotp colon iff uparrow downarrow mathbin over choose").split(" "));
|
|
244
|
+
/**
|
|
245
|
+
* A formula cut anywhere, made whole enough for KaTeX to draw (no red error text while it streams): a half-typed
|
|
246
|
+
* command (or `\begin{…` / `\end{…`) at the end is dropped, then what is left open is closed innermost first: an
|
|
247
|
+
* argument a command or `^` / `_` still needs (`{}`), `\sqrt[`'s `]`, a `{` group, `\left` (with `\right.`) and an
|
|
248
|
+
* environment (`\end{name}`). Text that is already whole comes back unchanged.
|
|
249
|
+
*/
|
|
250
|
+
function repairTex(tex) {
|
|
251
|
+
let s = tex.replace(/\\(?:begin|end)\{[^}]*$/, "");
|
|
252
|
+
// A command at the end may be half typed (`\fr`): kept only when it is a known whole one.
|
|
253
|
+
const cmd = /(^|[^\\])((?:\\\\)*)\\([A-Za-z]*)$/.exec(s);
|
|
254
|
+
if (cmd && !(cmd[3] in ARGS || KNOWN.has(cmd[3])))
|
|
255
|
+
s = s.slice(0, cmd.index + cmd[1].length + cmd[2].length);
|
|
256
|
+
const stack = [];
|
|
257
|
+
/** One argument (a group, a token, or a finished command with arguments) is complete at this level. */
|
|
258
|
+
const done = () => {
|
|
259
|
+
const top = stack.at(-1);
|
|
260
|
+
if (top?.kind !== "args")
|
|
261
|
+
return;
|
|
262
|
+
if (--top.need === 0) {
|
|
263
|
+
stack.pop();
|
|
264
|
+
done();
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
const n = s.length;
|
|
268
|
+
let i = 0;
|
|
269
|
+
while (i < n) {
|
|
270
|
+
const c = s[i];
|
|
271
|
+
if (/\s/.test(c)) {
|
|
272
|
+
i++;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (c === "\\") {
|
|
276
|
+
const m = /^\\(?:[A-Za-z]+|.)/.exec(s.slice(i));
|
|
277
|
+
const name = m[0].slice(1);
|
|
278
|
+
i += m[0].length;
|
|
279
|
+
if (name === "begin" || name === "end") {
|
|
280
|
+
const e = /^\s*\{([^}]*)\}/.exec(s.slice(i));
|
|
281
|
+
if (e)
|
|
282
|
+
i += e[0].length;
|
|
283
|
+
if (name === "begin")
|
|
284
|
+
stack.push({ kind: "env", name: e?.[1] ?? "" });
|
|
285
|
+
else {
|
|
286
|
+
while (stack.length && stack.at(-1).kind !== "env")
|
|
287
|
+
stack.pop();
|
|
288
|
+
stack.pop();
|
|
289
|
+
done();
|
|
290
|
+
}
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (name === "left") {
|
|
294
|
+
// The delimiter: one character or one command.
|
|
295
|
+
const d = /^\s*(?:\\(?:[A-Za-z]+|.)|[^\s\\])/.exec(s.slice(i));
|
|
296
|
+
if (!d) {
|
|
297
|
+
s = s.slice(0, i - m[0].length);
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
i += d[0].length;
|
|
301
|
+
stack.push({ kind: "left" });
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (name === "right") {
|
|
305
|
+
const d = /^\s*(?:\\(?:[A-Za-z]+|.)|[^\s\\])/.exec(s.slice(i));
|
|
306
|
+
if (!d) {
|
|
307
|
+
s = s.slice(0, i - m[0].length);
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
i += d[0].length;
|
|
311
|
+
if (stack.at(-1)?.kind === "left")
|
|
312
|
+
stack.pop();
|
|
313
|
+
done();
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
const need = ARGS[name];
|
|
317
|
+
if (need) {
|
|
318
|
+
stack.push({ kind: "args", need });
|
|
319
|
+
if (name === "sqrt" && /^\s*\[/.test(s.slice(i))) {
|
|
320
|
+
i = s.indexOf("[", i) + 1;
|
|
321
|
+
stack.push({ kind: "opt" });
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
else
|
|
325
|
+
done();
|
|
326
|
+
continue;
|
|
182
327
|
}
|
|
328
|
+
if (c === "{")
|
|
329
|
+
stack.push({ kind: "brace" });
|
|
330
|
+
else if (c === "}") {
|
|
331
|
+
while (stack.length && stack.at(-1).kind === "args")
|
|
332
|
+
stack.pop();
|
|
333
|
+
if (stack.at(-1)?.kind === "brace")
|
|
334
|
+
stack.pop();
|
|
335
|
+
done();
|
|
336
|
+
}
|
|
337
|
+
else if (c === "]" && stack.at(-1)?.kind === "opt")
|
|
338
|
+
stack.pop();
|
|
339
|
+
else if (c === "^" || c === "_")
|
|
340
|
+
stack.push({ kind: "args", need: 1 });
|
|
341
|
+
else
|
|
342
|
+
done();
|
|
343
|
+
i++;
|
|
183
344
|
}
|
|
345
|
+
let out = s;
|
|
346
|
+
// Innermost first; a closed group is one argument of the command or `^` around it.
|
|
347
|
+
let closed = false;
|
|
348
|
+
for (const f of stack.reverse()) {
|
|
349
|
+
if (f.kind === "args") {
|
|
350
|
+
out += "{}".repeat(f.need - (closed ? 1 : 0));
|
|
351
|
+
closed = true;
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
out += f.kind === "env" ? `\\end{${f.name}}` : f.kind === "brace" ? "}" : f.kind === "opt" ? "]" : "\\right.";
|
|
355
|
+
closed = f.kind !== "opt";
|
|
356
|
+
}
|
|
357
|
+
// A closing `$` right after a backslash is not read: `\\` (a line break) at the end gets an empty group.
|
|
358
|
+
return /\\$/.test(out) ? out + "{}" : out;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* A table being written, held back until it can be drawn (it would show as text, then jump into a table): the last
|
|
362
|
+
* line when it is a row still being written (no newline yet, and not a whole delimiter row or a whole row of the
|
|
363
|
+
* header's width), then a header row with no delimiter row under it. Only rows that start with `|` are read; the
|
|
364
|
+
* lines before stay as they are, so the result is stable under a second call.
|
|
365
|
+
*/
|
|
366
|
+
function holdTable(text, from) {
|
|
367
|
+
const head = text.slice(0, from);
|
|
368
|
+
const lines = text.slice(from).split("\n");
|
|
369
|
+
const isRow = (l) => l !== undefined && /^ {0,3}\|/.test(l);
|
|
370
|
+
const ended = lines.at(-1) === "";
|
|
371
|
+
const end = ended ? lines.length - 1 : lines.length;
|
|
372
|
+
let start = end;
|
|
373
|
+
while (start > 0 && isRow(lines[start - 1]))
|
|
374
|
+
start--;
|
|
375
|
+
const rows = lines.slice(start, end);
|
|
376
|
+
if (!rows.length)
|
|
377
|
+
return text;
|
|
378
|
+
const width = cells(rows[0]).length;
|
|
379
|
+
if (!ended) {
|
|
380
|
+
const last = rows.at(-1);
|
|
381
|
+
const whole = /[^\\]\|\s*$/.test(last) && cells(last).length === width && (rows.length > 2 || DELIM.test(last));
|
|
382
|
+
if (rows.length === 1 || !whole) {
|
|
383
|
+
rows.pop();
|
|
384
|
+
lines[end - 1] = "";
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (rows.length === 1)
|
|
388
|
+
lines.splice(start, 1);
|
|
389
|
+
if (rows.length >= 2 && !DELIM.test(rows[1]))
|
|
390
|
+
return text;
|
|
391
|
+
return head + lines.join("\n");
|
|
184
392
|
}
|
|
185
|
-
|
|
186
|
-
const
|
|
393
|
+
const DELIM = /^ {0,3}\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
394
|
+
const cells = (row) => row.trim().replace(/^\|/, "").replace(/(?<!\\)\|$/, "").split(/(?<!\\)\|/);
|
|
@@ -64,13 +64,19 @@ interface WindowLike {
|
|
|
64
64
|
/** The scroller of `useStickToBottom`: an element, the window, or a ref to the window or the document's scrolling element. */
|
|
65
65
|
export type StickTarget = RefObject<Scroller | WindowLike | null> | "window";
|
|
66
66
|
/**
|
|
67
|
-
* Keeps a scroller at its end while content grows,
|
|
67
|
+
* Keeps a scroller at its end while content grows, until the reader scrolls up, by any amount; following resumes when
|
|
68
|
+
* they scroll back down to within `slack` px of the end, or call `toBottom()`.
|
|
68
69
|
* `deps` are what grows (`[messages.length, live?.text.length, live?.tools.length]`). The scroller is an element ref,
|
|
69
70
|
* `"window"` (the page scrolls: a phone layout), or a ref to `window` / `document.scrollingElement`. Returns
|
|
70
71
|
* `pinned` (a ref, no re-render on scroll), `below` (state: content arrived under the fold while the reader was
|
|
71
72
|
* scrolled up; cleared when they scroll back to the end or call `toBottom()`), for a "new messages ↓" button, and
|
|
72
73
|
* `toBottom()` to jump to the end and pin again (after the user sends). Without a DOM (React Native: use
|
|
73
74
|
* `ScrollView.onContentSizeChange` instead) it does nothing.
|
|
75
|
+
*
|
|
76
|
+
* Only the reader lets go: an upward wheel, touch drag or key (PageUp, ArrowUp, Home) in the scroller lets go at once,
|
|
77
|
+
* and any upward scroll within a second of their input (wheel, touch, pointer, key there: a scrollbar drag) too. A
|
|
78
|
+
* scroll with no input (content that shrinks, a `scrollTop` set by code) never does. The follow looks again before
|
|
79
|
+
* it moves, so a scroll that has started but not yet reached its scroll event is kept.
|
|
74
80
|
*/
|
|
75
81
|
export declare function useStickToBottom(ref: StickTarget, deps: readonly unknown[], slack?: number): {
|
|
76
82
|
pinned: RefObject<boolean>;
|
package/dist/agent-chat/react.js
CHANGED
|
@@ -73,46 +73,135 @@ function resolve(target) {
|
|
|
73
73
|
const view = el.ownerDocument?.scrollingElement === el ? el.ownerDocument.defaultView : null;
|
|
74
74
|
return { el, on: view && typeof view.addEventListener === "function" ? view : el };
|
|
75
75
|
}
|
|
76
|
+
/** Input that may scroll: its time in the scroller is what tells the reader's moves from the page's own. */
|
|
77
|
+
const INPUTS = ["wheel", "touchstart", "touchmove", "pointerdown", "keydown"];
|
|
78
|
+
/** Keys that scroll up (outside a text field). */
|
|
79
|
+
const UP_KEYS = new Set(["PageUp", "ArrowUp", "Home"]);
|
|
80
|
+
/** How long after an input a scroll counts as the reader's. */
|
|
81
|
+
const INPUT_MS = 1000;
|
|
76
82
|
/**
|
|
77
|
-
*
|
|
83
|
+
* Where an input landed: `null` outside the scroller, `"inner"` when a scroller inside it can still move up (it takes
|
|
84
|
+
* the move, not ours), `"here"` otherwise. The page's scrolling element contains every node of its document.
|
|
85
|
+
*/
|
|
86
|
+
function within(el, target) {
|
|
87
|
+
let inner = false;
|
|
88
|
+
for (let n = target; n; n = n.parentNode) {
|
|
89
|
+
if (n === el)
|
|
90
|
+
return inner ? "inner" : "here";
|
|
91
|
+
if ((n.scrollTop ?? 0) > 0)
|
|
92
|
+
inner = true;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const now = () => (typeof performance === "undefined" ? Date.now() : performance.now());
|
|
97
|
+
/**
|
|
98
|
+
* Keeps a scroller at its end while content grows, until the reader scrolls up, by any amount; following resumes when
|
|
99
|
+
* they scroll back down to within `slack` px of the end, or call `toBottom()`.
|
|
78
100
|
* `deps` are what grows (`[messages.length, live?.text.length, live?.tools.length]`). The scroller is an element ref,
|
|
79
101
|
* `"window"` (the page scrolls: a phone layout), or a ref to `window` / `document.scrollingElement`. Returns
|
|
80
102
|
* `pinned` (a ref, no re-render on scroll), `below` (state: content arrived under the fold while the reader was
|
|
81
103
|
* scrolled up; cleared when they scroll back to the end or call `toBottom()`), for a "new messages ↓" button, and
|
|
82
104
|
* `toBottom()` to jump to the end and pin again (after the user sends). Without a DOM (React Native: use
|
|
83
105
|
* `ScrollView.onContentSizeChange` instead) it does nothing.
|
|
106
|
+
*
|
|
107
|
+
* Only the reader lets go: an upward wheel, touch drag or key (PageUp, ArrowUp, Home) in the scroller lets go at once,
|
|
108
|
+
* and any upward scroll within a second of their input (wheel, touch, pointer, key there: a scrollbar drag) too. A
|
|
109
|
+
* scroll with no input (content that shrinks, a `scrollTop` set by code) never does. The follow looks again before
|
|
110
|
+
* it moves, so a scroll that has started but not yet reached its scroll event is kept.
|
|
84
111
|
*/
|
|
85
112
|
export function useStickToBottom(ref, deps, slack = 80) {
|
|
86
113
|
const pinned = useRef(true);
|
|
114
|
+
const lastTop = useRef(0);
|
|
115
|
+
const inputAt = useRef(-Infinity);
|
|
87
116
|
const [below, setBelow] = useState(false);
|
|
117
|
+
/** The reader moved up since we last looked: their input is recent, and the view is not at the end. */
|
|
118
|
+
const movedUp = (el) => el.scrollTop < lastTop.current - 1 && el.scrollHeight - el.scrollTop - el.clientHeight > 1 && now() - inputAt.current < INPUT_MS;
|
|
88
119
|
useEffect(() => {
|
|
89
120
|
const r = resolve(ref);
|
|
90
121
|
if (!r)
|
|
91
122
|
return;
|
|
92
123
|
const { el, on } = r;
|
|
93
|
-
|
|
94
|
-
|
|
124
|
+
lastTop.current = el.scrollTop;
|
|
125
|
+
const scroll = () => {
|
|
126
|
+
const down = el.scrollTop > lastTop.current;
|
|
127
|
+
if (movedUp(el))
|
|
128
|
+
pinned.current = false;
|
|
129
|
+
else if (down && el.scrollHeight - el.scrollTop - el.clientHeight < slack)
|
|
130
|
+
pinned.current = true;
|
|
131
|
+
lastTop.current = el.scrollTop;
|
|
95
132
|
if (pinned.current)
|
|
96
133
|
setBelow(false);
|
|
97
134
|
};
|
|
98
|
-
on.addEventListener("scroll",
|
|
99
|
-
|
|
135
|
+
on.addEventListener("scroll", scroll, { passive: true });
|
|
136
|
+
// Inputs, seen on the window before anything inside can stop them.
|
|
137
|
+
const doc = el.ownerDocument;
|
|
138
|
+
const view = (doc?.defaultView ?? on);
|
|
139
|
+
let touchY = null;
|
|
140
|
+
const input = (e) => {
|
|
141
|
+
const where = within(el, e.target);
|
|
142
|
+
if (!where)
|
|
143
|
+
return;
|
|
144
|
+
inputAt.current = now();
|
|
145
|
+
if (where === "inner" || el.scrollTop <= 0)
|
|
146
|
+
return;
|
|
147
|
+
let up = false;
|
|
148
|
+
if (e.type === "wheel")
|
|
149
|
+
up = (e.deltaY ?? 0) < 0;
|
|
150
|
+
else if (e.type === "keydown") {
|
|
151
|
+
const t = e.target;
|
|
152
|
+
const editing = Boolean(t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName ?? "")));
|
|
153
|
+
up = !editing && (UP_KEYS.has(e.key ?? "") || (e.key === " " && Boolean(e.shiftKey)));
|
|
154
|
+
}
|
|
155
|
+
else if (e.type === "touchstart" || e.type === "touchmove") {
|
|
156
|
+
const y = e.touches?.[0]?.clientY;
|
|
157
|
+
if (y === undefined)
|
|
158
|
+
touchY = null;
|
|
159
|
+
else {
|
|
160
|
+
// The finger moving down drags the content down: a scroll up.
|
|
161
|
+
up = e.type === "touchmove" && touchY !== null && y > touchY + 1;
|
|
162
|
+
touchY = y;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (up)
|
|
166
|
+
pinned.current = false;
|
|
167
|
+
};
|
|
168
|
+
if (view && typeof view.addEventListener === "function")
|
|
169
|
+
for (const t of INPUTS)
|
|
170
|
+
view.addEventListener(t, input, { passive: true, capture: true });
|
|
171
|
+
return () => {
|
|
172
|
+
on.removeEventListener("scroll", scroll);
|
|
173
|
+
if (view && typeof view.removeEventListener === "function")
|
|
174
|
+
for (const t of INPUTS)
|
|
175
|
+
view.removeEventListener(t, input, { capture: true });
|
|
176
|
+
};
|
|
177
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
100
178
|
}, [ref, slack]);
|
|
101
179
|
useLayout(() => {
|
|
102
180
|
const r = resolve(ref);
|
|
103
181
|
if (!r)
|
|
104
182
|
return;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
183
|
+
const { el } = r;
|
|
184
|
+
// Look again: the reader's scroll may have begun without its scroll event handled yet.
|
|
185
|
+
if (movedUp(el))
|
|
186
|
+
pinned.current = false;
|
|
187
|
+
// Nothing to scroll (content shrank to fit): nothing to read above, follow again.
|
|
188
|
+
if (el.scrollHeight - el.clientHeight <= 1)
|
|
189
|
+
pinned.current = true;
|
|
190
|
+
if (pinned.current) {
|
|
191
|
+
el.scrollTop = el.scrollHeight;
|
|
192
|
+
lastTop.current = el.scrollTop;
|
|
193
|
+
}
|
|
194
|
+
else if (el.scrollHeight - el.scrollTop - el.clientHeight > 1)
|
|
108
195
|
setBelow(true);
|
|
109
196
|
}, deps);
|
|
110
197
|
const toBottom = useCallback(() => {
|
|
111
198
|
const r = resolve(ref);
|
|
112
199
|
pinned.current = true;
|
|
113
200
|
setBelow(false);
|
|
114
|
-
if (r)
|
|
201
|
+
if (r) {
|
|
115
202
|
r.el.scrollTop = r.el.scrollHeight;
|
|
203
|
+
lastTop.current = r.el.scrollTop;
|
|
204
|
+
}
|
|
116
205
|
}, [ref]);
|
|
117
206
|
return { pinned, below, toBottom };
|
|
118
207
|
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { CanvasStore } from './store.ts';
|
|
2
|
+
import { type CanvasAction, type CanvasState, type HostMessage, type PageMessage, type ThemeKind } from './protocol.ts';
|
|
3
|
+
type Post<T> = (message: T & {
|
|
4
|
+
type: string;
|
|
5
|
+
v: number;
|
|
6
|
+
}) => void;
|
|
7
|
+
export interface PageBridge {
|
|
8
|
+
/** The store the hooks read; its writes, events and actions go to the host. */
|
|
9
|
+
store: CanvasStore;
|
|
10
|
+
/** A message from `window.parent` (the runtime checks the source). Invalid messages are ignored. */
|
|
11
|
+
receive(data: unknown): void;
|
|
12
|
+
/** Tell the host the page listens; it answers with `init` (the state it holds now). */
|
|
13
|
+
ready(): void;
|
|
14
|
+
size(height: number): void;
|
|
15
|
+
error(message: string): void;
|
|
16
|
+
/** Post waiting state writes now (before unload). */
|
|
17
|
+
flush(): void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The page side. State writes are coalesced: within `flushMs` only the latest value per key is posted, so a slider
|
|
21
|
+
* dragged at 60 fps sends at most one message per key per window and stays under the host's rate limit. An event or
|
|
22
|
+
* action posts the waiting writes first, so the host sees them in the page's order. Nothing is posted but `ready`
|
|
23
|
+
* until the host's `init` arrives: writes and (up to 20) events made before it are kept and posted then, in order;
|
|
24
|
+
* actions made before it are dropped.
|
|
25
|
+
*
|
|
26
|
+
* Each posted write carries a `seq`; a host `state`/`init` carries `ack`, the last `seq` the host had when it sent it.
|
|
27
|
+
* Writes newer than `ack` (posted, or still waiting) stay on top of the host's values instead of flickering back.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createPageBridge(options: {
|
|
30
|
+
post: Post<PageMessage>;
|
|
31
|
+
init: {
|
|
32
|
+
state: CanvasState;
|
|
33
|
+
theme: ThemeKind;
|
|
34
|
+
};
|
|
35
|
+
surface?: string;
|
|
36
|
+
/** Coalescing window for state writes. Default 50 ms. */
|
|
37
|
+
flushMs?: number;
|
|
38
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
39
|
+
}): PageBridge;
|
|
40
|
+
export interface RateLimit {
|
|
41
|
+
/** Messages accepted at once. */
|
|
42
|
+
burst: number;
|
|
43
|
+
/** Refill per second. */
|
|
44
|
+
perSecond: number;
|
|
45
|
+
}
|
|
46
|
+
export interface HostBridgeOptions {
|
|
47
|
+
post: Post<HostMessage>;
|
|
48
|
+
/** The state the host holds for this surface now. */
|
|
49
|
+
state: CanvasState;
|
|
50
|
+
theme: ThemeKind;
|
|
51
|
+
/** Debounced state writes: every key the page changed since the last call, latest value each. */
|
|
52
|
+
onState?: (set: CanvasState) => void;
|
|
53
|
+
onEvent?: (name: string, data: unknown) => void;
|
|
54
|
+
/** Called only while `userActive()` is true. */
|
|
55
|
+
onAction?: (action: CanvasAction) => void;
|
|
56
|
+
onSize?: (height: number) => void;
|
|
57
|
+
/** The page's render error (its error box is showing). */
|
|
58
|
+
onError?: (message: string) => void;
|
|
59
|
+
onReady?: () => void;
|
|
60
|
+
/** The page tried to leave (the relay removed it). The bridge stops. */
|
|
61
|
+
onNavigated?: () => void;
|
|
62
|
+
/** Every message dropped, with the reason. */
|
|
63
|
+
onReject?: (reason: string, data: unknown) => void;
|
|
64
|
+
/** Event names allowed (a block's manifest). Without it, the first 20 distinct names are allowed. */
|
|
65
|
+
events?: readonly string[];
|
|
66
|
+
/** State writes are passed on after this long without another write. Default 800 ms. */
|
|
67
|
+
debounceMs?: number;
|
|
68
|
+
/** All page messages. Default 100 at once, 50 a second. */
|
|
69
|
+
rate?: RateLimit;
|
|
70
|
+
/** Events, within `rate`. Default 20 at once, 1 a second (60 a minute). */
|
|
71
|
+
eventRate?: RateLimit;
|
|
72
|
+
/** Whether the host page has transient user activation (`navigator.userActivation.isActive`); no API: false. */
|
|
73
|
+
userActive?: () => boolean;
|
|
74
|
+
now?: () => number;
|
|
75
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
76
|
+
clearTimer?: (timer: unknown) => void;
|
|
77
|
+
}
|
|
78
|
+
/** The host side: validates, rate-limits, debounces and answers. One per live frame. */
|
|
79
|
+
export declare class HostBridge {
|
|
80
|
+
private o;
|
|
81
|
+
private state;
|
|
82
|
+
private theme;
|
|
83
|
+
private pending;
|
|
84
|
+
private lastSeq;
|
|
85
|
+
private timer;
|
|
86
|
+
private isReady;
|
|
87
|
+
private disposed;
|
|
88
|
+
private readonly names;
|
|
89
|
+
private readonly rate;
|
|
90
|
+
private readonly eventRate;
|
|
91
|
+
private readonly setTimer;
|
|
92
|
+
private readonly clearTimer;
|
|
93
|
+
constructor(options: HostBridgeOptions);
|
|
94
|
+
/** Swap callbacks for the latest props (state and theme go through `setState` / `setTheme`). */
|
|
95
|
+
update(options: Partial<Pick<HostBridgeOptions, 'onState' | 'onEvent' | 'onAction' | 'onSize' | 'onError' | 'onReady' | 'onNavigated' | 'onReject' | 'events' | 'userActive'>>): void;
|
|
96
|
+
get ready(): boolean;
|
|
97
|
+
/** What the page should show now: the host's state with the page's not-yet-passed-on writes on top. */
|
|
98
|
+
private current;
|
|
99
|
+
receive(data: unknown): void;
|
|
100
|
+
private handle;
|
|
101
|
+
/** The host's state changed (the agent, another device, or its own save): replace the page's values. */
|
|
102
|
+
setState(values: CanvasState): void;
|
|
103
|
+
setTheme(kind: ThemeKind): void;
|
|
104
|
+
/** Pass on waiting state writes now. */
|
|
105
|
+
flush(): void;
|
|
106
|
+
/** Flush and stop: later messages are ignored and nothing more is posted. */
|
|
107
|
+
dispose(): void;
|
|
108
|
+
private reject;
|
|
109
|
+
}
|
|
110
|
+
export {};
|