@lightblues/jig 0.1.1 → 0.1.3
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/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 +111 -11
- package/package.json +1 -1
|
@@ -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,146 @@ 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
|
+
/**
|
|
118
|
+
* The scroller the listeners are on. A ref object never changes when its element mounts later (a panel that renders
|
|
119
|
+
* null while closed), so the layout effect re-resolves on every `deps` change and on mount, and attaching follows it.
|
|
120
|
+
*/
|
|
121
|
+
const [scroller, setScroller] = useState(null);
|
|
122
|
+
/** The reader moved up since we last looked: their input is recent, and the view is not at the end. */
|
|
123
|
+
const movedUp = (el) => el.scrollTop < lastTop.current - 1 && el.scrollHeight - el.scrollTop - el.clientHeight > 1 && now() - inputAt.current < INPUT_MS;
|
|
88
124
|
useEffect(() => {
|
|
89
125
|
const r = resolve(ref);
|
|
90
|
-
if (!r)
|
|
126
|
+
if (!r || r.el !== scroller)
|
|
91
127
|
return;
|
|
92
128
|
const { el, on } = r;
|
|
93
|
-
|
|
94
|
-
|
|
129
|
+
lastTop.current = el.scrollTop;
|
|
130
|
+
const scroll = () => {
|
|
131
|
+
const down = el.scrollTop > lastTop.current;
|
|
132
|
+
if (movedUp(el))
|
|
133
|
+
pinned.current = false;
|
|
134
|
+
else if (down && el.scrollHeight - el.scrollTop - el.clientHeight < slack)
|
|
135
|
+
pinned.current = true;
|
|
136
|
+
lastTop.current = el.scrollTop;
|
|
95
137
|
if (pinned.current)
|
|
96
138
|
setBelow(false);
|
|
97
139
|
};
|
|
98
|
-
on.addEventListener("scroll",
|
|
99
|
-
|
|
100
|
-
|
|
140
|
+
on.addEventListener("scroll", scroll, { passive: true });
|
|
141
|
+
// Inputs, seen on the window before anything inside can stop them.
|
|
142
|
+
const doc = el.ownerDocument;
|
|
143
|
+
const view = (doc?.defaultView ?? on);
|
|
144
|
+
let touchY = null;
|
|
145
|
+
const input = (e) => {
|
|
146
|
+
const where = within(el, e.target);
|
|
147
|
+
if (!where)
|
|
148
|
+
return;
|
|
149
|
+
inputAt.current = now();
|
|
150
|
+
if (where === "inner" || el.scrollTop <= 0)
|
|
151
|
+
return;
|
|
152
|
+
let up = false;
|
|
153
|
+
if (e.type === "wheel")
|
|
154
|
+
up = (e.deltaY ?? 0) < 0;
|
|
155
|
+
else if (e.type === "keydown") {
|
|
156
|
+
const t = e.target;
|
|
157
|
+
const editing = Boolean(t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName ?? "")));
|
|
158
|
+
up = !editing && (UP_KEYS.has(e.key ?? "") || (e.key === " " && Boolean(e.shiftKey)));
|
|
159
|
+
}
|
|
160
|
+
else if (e.type === "touchstart" || e.type === "touchmove") {
|
|
161
|
+
const y = e.touches?.[0]?.clientY;
|
|
162
|
+
if (y === undefined)
|
|
163
|
+
touchY = null;
|
|
164
|
+
else {
|
|
165
|
+
// The finger moving down drags the content down: a scroll up.
|
|
166
|
+
up = e.type === "touchmove" && touchY !== null && y > touchY + 1;
|
|
167
|
+
touchY = y;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (up)
|
|
171
|
+
pinned.current = false;
|
|
172
|
+
};
|
|
173
|
+
if (view && typeof view.addEventListener === "function")
|
|
174
|
+
for (const t of INPUTS)
|
|
175
|
+
view.addEventListener(t, input, { passive: true, capture: true });
|
|
176
|
+
return () => {
|
|
177
|
+
on.removeEventListener("scroll", scroll);
|
|
178
|
+
if (view && typeof view.removeEventListener === "function")
|
|
179
|
+
for (const t of INPUTS)
|
|
180
|
+
view.removeEventListener(t, input, { capture: true });
|
|
181
|
+
};
|
|
182
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
183
|
+
}, [ref, slack, scroller]);
|
|
184
|
+
// Every render: the scroller may have mounted (or been replaced) since the last one, with `deps` unchanged.
|
|
185
|
+
useLayout(() => {
|
|
186
|
+
const el = resolve(ref)?.el ?? null;
|
|
187
|
+
if (el !== scroller)
|
|
188
|
+
setScroller(el);
|
|
189
|
+
});
|
|
101
190
|
useLayout(() => {
|
|
102
191
|
const r = resolve(ref);
|
|
103
192
|
if (!r)
|
|
104
193
|
return;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
194
|
+
const { el } = r;
|
|
195
|
+
// Look again: the reader's scroll may have begun without its scroll event handled yet.
|
|
196
|
+
if (movedUp(el))
|
|
197
|
+
pinned.current = false;
|
|
198
|
+
// Nothing to scroll (content shrank to fit): nothing to read above, follow again.
|
|
199
|
+
if (el.scrollHeight - el.clientHeight <= 1)
|
|
200
|
+
pinned.current = true;
|
|
201
|
+
if (pinned.current) {
|
|
202
|
+
el.scrollTop = el.scrollHeight;
|
|
203
|
+
lastTop.current = el.scrollTop;
|
|
204
|
+
}
|
|
205
|
+
else if (el.scrollHeight - el.scrollTop - el.clientHeight > 1)
|
|
108
206
|
setBelow(true);
|
|
109
207
|
}, deps);
|
|
110
208
|
const toBottom = useCallback(() => {
|
|
111
209
|
const r = resolve(ref);
|
|
112
210
|
pinned.current = true;
|
|
113
211
|
setBelow(false);
|
|
114
|
-
if (r)
|
|
212
|
+
if (r) {
|
|
115
213
|
r.el.scrollTop = r.el.scrollHeight;
|
|
214
|
+
lastTop.current = r.el.scrollTop;
|
|
215
|
+
}
|
|
116
216
|
}, [ref]);
|
|
117
217
|
return { pinned, below, toBottom };
|
|
118
218
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lightblues/jig",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, one markdown renderer, and more as they prove reusable.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|