grayling 0.0.0-stage → 0.1.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.
Files changed (55) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +268 -2
  3. package/dist/index.d.ts +290 -0
  4. package/dist/index.js +50 -0
  5. package/dist/node/archive.d.ts +4 -0
  6. package/dist/node/archive.js +115 -0
  7. package/dist/node/client.d.ts +188 -0
  8. package/dist/node/client.js +669 -0
  9. package/dist/node/connection.d.ts +56 -0
  10. package/dist/node/connection.js +240 -0
  11. package/dist/node/errors.d.ts +14 -0
  12. package/dist/node/errors.js +13 -0
  13. package/dist/node/handler.d.ts +56 -0
  14. package/dist/node/handler.js +208 -0
  15. package/dist/node/index.d.ts +15 -0
  16. package/dist/node/index.js +14 -0
  17. package/dist/node/paths.d.ts +51 -0
  18. package/dist/node/paths.js +115 -0
  19. package/dist/node/program.d.ts +74 -0
  20. package/dist/node/program.js +385 -0
  21. package/dist/node/state.d.ts +7 -0
  22. package/dist/node/state.js +12 -0
  23. package/dist/node/suggest.d.ts +13 -0
  24. package/dist/node/suggest.js +87 -0
  25. package/dist/node/types.d.ts +142 -0
  26. package/dist/node/types.js +13 -0
  27. package/dist/node/version.d.ts +10 -0
  28. package/dist/node/version.js +50 -0
  29. package/dist/node/wire.d.ts +32 -0
  30. package/dist/node/wire.js +44 -0
  31. package/dist/react/index.d.ts +121 -0
  32. package/dist/react/index.js +205 -0
  33. package/dist/web/announce.d.ts +51 -0
  34. package/dist/web/announce.js +141 -0
  35. package/dist/web/attach.d.ts +77 -0
  36. package/dist/web/attach.js +89 -0
  37. package/dist/web/box.d.ts +57 -0
  38. package/dist/web/box.js +150 -0
  39. package/dist/web/dom.d.ts +80 -0
  40. package/dist/web/dom.js +265 -0
  41. package/dist/web/index.d.ts +8 -0
  42. package/dist/web/index.js +8 -0
  43. package/dist/web/logic.d.ts +308 -0
  44. package/dist/web/logic.js +467 -0
  45. package/dist/web/overlay.d.ts +56 -0
  46. package/dist/web/overlay.js +211 -0
  47. package/dist/web/style.css +193 -0
  48. package/dist/web/suggester.d.ts +189 -0
  49. package/dist/web/suggester.js +696 -0
  50. package/dist/web/ui.d.ts +65 -0
  51. package/dist/web/ui.js +32 -0
  52. package/dist/web/usage.d.ts +39 -0
  53. package/dist/web/usage.js +84 -0
  54. package/package.json +89 -4
  55. package/program.json +35 -0
@@ -0,0 +1,150 @@
1
+ // One <textarea> or <input type="text"> as the suggester sees it: reading it, putting words in it, the events that make the
2
+ // suggester look again, and the class it carries while suggestions are on in it. Shared by `attach` and the React hook.
3
+ import { insertInto, isFocused, replaceIn } from './dom.js';
4
+ import { allowed } from './logic.js';
5
+ import { BOX_CLASS } from './ui.js';
6
+ /** The adapter of one box: the suggester reads the box and writes into it through this. */
7
+ export class BoxAdapter {
8
+ box;
9
+ state;
10
+ /** An input method (Japanese, Chinese, an accent key…) is composing. */
11
+ composing = false;
12
+ constructor(box, state) {
13
+ this.box = box;
14
+ this.state = state;
15
+ }
16
+ get place() {
17
+ return this.state().place;
18
+ }
19
+ read() {
20
+ const el = this.box();
21
+ if (!el || this.state().off || !isFocused(el))
22
+ return null;
23
+ const a = el.selectionStart ?? 0;
24
+ const z = el.selectionEnd ?? a;
25
+ return { before: el.value.slice(0, a), after: el.value.slice(z), selected: a !== z, ...(a !== z ? { picked: el.value.slice(a, z) } : {}), composing: this.composing };
26
+ }
27
+ insert(text) {
28
+ const el = this.box();
29
+ if (el)
30
+ insertInto(el, text);
31
+ }
32
+ replace(start, end, word) {
33
+ const el = this.box();
34
+ return !!el && replaceIn(el, start, end, word);
35
+ }
36
+ context() {
37
+ return this.state().context?.() ?? {};
38
+ }
39
+ }
40
+ /**
41
+ * The box's own events, so that the suggester looks again after each: typing, a composition, the focus, a click, a key up, a
42
+ * caret move. Returns what takes them off. `warm` is called when the box gets the focus.
43
+ */
44
+ export function bindBox(el, ctl, ad, warm) {
45
+ // Never while the box's own event is still being handled: these listeners run before a framework's onChange, and a grey
46
+ // word hidden or changed right there re-rendered the box with the text it had before the key, so a controlled
47
+ // textarea put that text back. The key was lost: with a suggestion showing, Backspace and any letter but the
48
+ // grey one did nothing. The check waits for the event to be over (a task later), once per burst of events.
49
+ let pending;
50
+ const sync = () => {
51
+ if (pending === undefined)
52
+ pending = setTimeout(() => ((pending = undefined), ctl.sync()), 0);
53
+ };
54
+ const start = () => ((ad.composing = true), sync());
55
+ const end = () => ((ad.composing = false), sync());
56
+ const focus = () => (warm?.(), sync());
57
+ const blur = () => {
58
+ clearTimeout(pending);
59
+ pending = undefined;
60
+ ad.composing = false;
61
+ ctl.reset();
62
+ };
63
+ const doc = el.ownerDocument;
64
+ const sel = () => isFocused(el) && sync();
65
+ const on = [
66
+ [el, 'input', sync],
67
+ [el, 'compositionstart', start],
68
+ [el, 'compositionend', end],
69
+ [el, 'focus', focus],
70
+ [el, 'blur', blur],
71
+ [el, 'click', sync],
72
+ [el, 'keyup', sync],
73
+ [doc, 'selectionchange', sel],
74
+ ];
75
+ for (const [t, n, f] of on)
76
+ t.addEventListener(n, f);
77
+ if (isFocused(el))
78
+ focus();
79
+ return () => {
80
+ clearTimeout(pending);
81
+ pending = undefined;
82
+ on.forEach(([t, n, f]) => t.removeEventListener(n, f));
83
+ };
84
+ }
85
+ /** Whether suggestions are on in a box in `place` now: the switches allow the place, and the box is not off. */
86
+ export const isOn = (gate, s) => !s.off && allowed(gate(), s.place);
87
+ const AUTOCOMPLETE = 'aria-autocomplete';
88
+ /** What `aria-autocomplete` says while suggestions are on, given what the page set (`null`: nothing): a box that completes inline says so. */
89
+ const saying = (page) => (page === 'inline' || page === 'both' ? page : page === 'list' ? 'both' : 'inline');
90
+ /** How many boxes were given an `id` of ours. */
91
+ let named = 0;
92
+ /**
93
+ * Keep the class `grayling-box` and `aria-autocomplete` on a box exactly while `on()` says so, even when something else (a framework's
94
+ * render) rewrites the box's attributes. Both say, to the desktop app and to assistive technology, that the box completes by itself,
95
+ * so that suggestions never show twice in it: `aria-autocomplete` is `inline` when the page gave none or `none`, `both` when it gave
96
+ * `list` (and what it gave when that already says inline). Firefox shows neither of them to accessibility clients on macOS, but a box's
97
+ * `id`: one without an `id` gets `grayling-box-…`. What the page set is put back when `on()` says no, and by `stop`; a page
98
+ * that changes it meanwhile is followed. Returns `refresh` (check now) and what stops it.
99
+ */
100
+ export function keepBoxClass(el, on) {
101
+ // What the page set, and what we put there (`null`: nothing of ours is on the box).
102
+ let page = el.getAttribute(AUTOCOMPLETE);
103
+ let ours = null;
104
+ const put = (v) => {
105
+ if (v === null)
106
+ el.removeAttribute(AUTOCOMPLETE);
107
+ else if (el.getAttribute(AUTOCOMPLETE) !== v)
108
+ el.setAttribute(AUTOCOMPLETE, v);
109
+ };
110
+ let id = null;
111
+ const name = (want) => {
112
+ if (id !== null && el.id !== id)
113
+ id = null; // the page gave it an id of its own
114
+ if (want && !el.id)
115
+ el.id = id = `${BOX_CLASS}-${++named}`;
116
+ else if (!want && id !== null) {
117
+ el.removeAttribute('id');
118
+ id = null;
119
+ }
120
+ };
121
+ const refresh = () => {
122
+ const want = on();
123
+ if (el.classList.contains(BOX_CLASS) !== want)
124
+ el.classList.toggle(BOX_CLASS, want);
125
+ name(want);
126
+ // A value that is not the one we put is the page's, also when it changed it meanwhile.
127
+ const cur = el.getAttribute(AUTOCOMPLETE);
128
+ if (ours === null || cur !== ours)
129
+ page = cur;
130
+ const target = want ? saying(page) : page;
131
+ ours = target === page ? null : target;
132
+ put(target);
133
+ };
134
+ refresh();
135
+ // A render that sets the box's className drops the class, one that sets the attribute drops ours: put back (a change that is already
136
+ // right does nothing, so no loop).
137
+ const mo = typeof MutationObserver === 'function' ? new MutationObserver(refresh) : null;
138
+ mo?.observe(el, { attributes: true, attributeFilter: ['class', 'id', AUTOCOMPLETE] });
139
+ return {
140
+ refresh,
141
+ stop() {
142
+ mo?.disconnect();
143
+ el.classList.remove(BOX_CLASS);
144
+ name(false);
145
+ if (ours !== null && el.getAttribute(AUTOCOMPLETE) === ours)
146
+ put(page);
147
+ ours = null;
148
+ },
149
+ };
150
+ }
@@ -0,0 +1,80 @@
1
+ import type { Spot } from './logic.js';
2
+ /** A box that suggestions go in. */
3
+ export type TextBox = HTMLTextAreaElement | HTMLInputElement;
4
+ /** Whether the box has the focus (in a shadow tree too). */
5
+ export declare function isFocused(el: Element): boolean;
6
+ /** Put text in a box at its caret the way typing does, so that Undo takes it out again. */
7
+ export declare function insertInto(el: TextBox, text: string): void;
8
+ /**
9
+ * Put `word` in place of the stretch from `start` to `end` of a box's text the way typing does (one change for Undo), and
10
+ * keep its caret where it was in relation to the text after it.
11
+ */
12
+ export declare function replaceIn(el: TextBox, start: number, end: number, word: string): boolean;
13
+ /** The inline style a mirror always has (so that it is right with no stylesheet): over the box, letting the pointer through. */
14
+ export declare const MIRROR_STYLE: {
15
+ readonly position: 'absolute';
16
+ readonly pointerEvents: 'none';
17
+ readonly boxSizing: 'border-box';
18
+ readonly overflow: 'hidden';
19
+ readonly borderWidth: '0';
20
+ };
21
+ /**
22
+ * Lay `mirror` exactly over `ta`'s inside: same font, wrapping, padding, width and scroll. The mirror is positioned in the
23
+ * same box as the textarea (anywhere in the page: its place is measured from where it lands at 0, 0). A one-line input keeps
24
+ * its text on one line, centred, and scrolls sideways with it.
25
+ */
26
+ export declare function placeMirror(mirror: HTMLElement, ta: TextBox): void;
27
+ /** Keep `mirror` over `ta` as it resizes, scrolls, and as anything it sits in scrolls or the window resizes. Returns what stops that. */
28
+ export declare function followBox(place: () => void, ta: TextBox): () => void;
29
+ /** One piece of a text drawn with its marks: a stretch of text (marked or not, the first of the fix's mark or not), or the place of the caret. */
30
+ export type Segment = {
31
+ text: string;
32
+ marked: boolean;
33
+ first: boolean;
34
+ } | {
35
+ caret: true;
36
+ };
37
+ /**
38
+ * The text cut where a mark begins or ends and at the caret, each stretch with whether it stands in a mark. `fixAt` is where
39
+ * the mark a chip points at begins (its first stretch is `first`).
40
+ */
41
+ export declare function segments(text: string, marks: Spot[], fixAt: number | null, caret: number | null): Segment[];
42
+ /** The letters of the word being typed right before the caret (the part of a suggested word that is typed already). */
43
+ export declare const typedLetters: (before: string) => string;
44
+ /** Whether the screen has no hover (a phone or a tablet): there is no Tab key to show, and the chip is the button. */
45
+ export declare const isTouch: () => boolean;
46
+ /** What of an element can be seen: its box cut by every box around it that clips what scrolls out of it. */
47
+ export declare function visibleRect(el: Element): {
48
+ top: number;
49
+ bottom: number;
50
+ left: number;
51
+ right: number;
52
+ };
53
+ /** The z-index of a chip over `el`: just over the layer its box is in, or the default. */
54
+ export declare function layerOf(el: Element | null): number;
55
+ /** The inline style a chip's wrapper always has: fixed in the page, hidden until it is placed. */
56
+ export declare const LAYER_STYLE: {
57
+ readonly position: 'fixed';
58
+ readonly left: '0px';
59
+ readonly top: '0px';
60
+ readonly zIndex: string;
61
+ readonly visibility: 'hidden';
62
+ };
63
+ /**
64
+ * Place a chip's wrapper: just above its anchor (below when there is no room above), inside the screen, and hidden when the
65
+ * anchor is scrolled out of the box it is in.
66
+ */
67
+ export declare function placeChip(el: HTMLElement, a: DOMRect | null, w: Element | null): void;
68
+ /** requestAnimationFrame where there is one. */
69
+ export declare const frame: (f: () => void) => number;
70
+ export declare const unframe: (n: number) => void;
71
+ /**
72
+ * Keep a chip's wrapper placed as the page scrolls and resizes (and as the chip and its box change size). `place` is what
73
+ * places it; the returned function schedules it for the next frame, `stop` ends it all.
74
+ */
75
+ export declare function followChip(el: HTMLElement, w: () => Element | null, place: () => void): {
76
+ soon: () => void;
77
+ stop: () => void;
78
+ };
79
+ /** A new client id, one per page (a new request cancels the client's one before): `t-` and 16 hex digits. */
80
+ export declare function newClientId(): string;
@@ -0,0 +1,265 @@
1
+ const isInput = (el) => el.tagName === 'INPUT';
2
+ /** The box's value setter that does not go through a framework's wrapper (React tracks the value by its own property). */
3
+ function setValue(el, value) {
4
+ const proto = isInput(el) ? HTMLInputElement.prototype : HTMLTextAreaElement.prototype;
5
+ const set = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
6
+ if (set)
7
+ set.call(el, value);
8
+ else
9
+ el.value = value;
10
+ }
11
+ /** Whether the box has the focus (in a shadow tree too). */
12
+ export function isFocused(el) {
13
+ const root = el.getRootNode();
14
+ return (root.activeElement ?? el.ownerDocument.activeElement) === el;
15
+ }
16
+ /** Put text in a box at its caret the way typing does, so that Undo takes it out again. */
17
+ export function insertInto(el, text) {
18
+ el.focus();
19
+ el.setSelectionRange(el.selectionEnd, el.selectionEnd);
20
+ if (el.ownerDocument.execCommand?.('insertText', false, text))
21
+ return;
22
+ // Where the browser has no insertText for a box: set the value, and tell a framework as typing would.
23
+ const at = el.selectionEnd ?? el.value.length;
24
+ setValue(el, el.value.slice(0, at) + text + el.value.slice(at));
25
+ el.setSelectionRange(at + text.length, at + text.length);
26
+ el.dispatchEvent(new Event('input', { bubbles: true }));
27
+ }
28
+ /**
29
+ * Put `word` in place of the stretch from `start` to `end` of a box's text the way typing does (one change for Undo), and
30
+ * keep its caret where it was in relation to the text after it.
31
+ */
32
+ export function replaceIn(el, start, end, word) {
33
+ if (start < 0 || end < start || end > el.value.length)
34
+ return false;
35
+ const tail = el.value.length - Math.max(el.selectionStart ?? 0, end);
36
+ el.focus();
37
+ el.setSelectionRange(start, end);
38
+ if (!el.ownerDocument.execCommand?.('insertText', false, word)) {
39
+ setValue(el, el.value.slice(0, start) + word + el.value.slice(end));
40
+ el.dispatchEvent(new Event('input', { bubbles: true }));
41
+ }
42
+ const at = Math.max(0, el.value.length - tail);
43
+ el.setSelectionRange(at, at);
44
+ return true;
45
+ }
46
+ const COPIED = [
47
+ 'fontFamily',
48
+ 'fontSize',
49
+ 'fontWeight',
50
+ 'fontStyle',
51
+ 'fontStretch',
52
+ 'fontKerning',
53
+ 'fontFeatureSettings',
54
+ 'fontVariantLigatures',
55
+ 'letterSpacing',
56
+ 'wordSpacing',
57
+ 'lineHeight',
58
+ 'textTransform',
59
+ 'textIndent',
60
+ 'textAlign',
61
+ 'textRendering',
62
+ 'tabSize',
63
+ 'direction',
64
+ 'writingMode',
65
+ 'whiteSpace',
66
+ 'wordBreak',
67
+ 'overflowWrap',
68
+ 'lineBreak',
69
+ 'paddingTop',
70
+ 'paddingRight',
71
+ 'paddingBottom',
72
+ 'paddingLeft',
73
+ ];
74
+ /** The inline style a mirror always has (so that it is right with no stylesheet): over the box, letting the pointer through. */
75
+ export const MIRROR_STYLE = { position: 'absolute', pointerEvents: 'none', boxSizing: 'border-box', overflow: 'hidden', borderWidth: '0' };
76
+ /**
77
+ * Lay `mirror` exactly over `ta`'s inside: same font, wrapping, padding, width and scroll. The mirror is positioned in the
78
+ * same box as the textarea (anywhere in the page: its place is measured from where it lands at 0, 0). A one-line input keeps
79
+ * its text on one line, centred, and scrolls sideways with it.
80
+ */
81
+ export function placeMirror(mirror, ta) {
82
+ if (!ta.isConnected || !mirror.isConnected)
83
+ return;
84
+ const cs = getComputedStyle(ta);
85
+ for (const k of COPIED)
86
+ mirror.style[k] = cs[k];
87
+ const r = ta.getBoundingClientRect();
88
+ // The box's inside, inside its borders. (An <input>'s clientLeft and clientWidth count its padding as border, so its borders are read from its style.)
89
+ let [bl, bt, w, h] = [ta.clientLeft, ta.clientTop, ta.clientWidth, ta.clientHeight];
90
+ if (isInput(ta)) {
91
+ const px = (v) => parseFloat(v) || 0;
92
+ bl = px(cs.borderLeftWidth);
93
+ bt = px(cs.borderTopWidth);
94
+ w = r.width - bl - px(cs.borderRightWidth);
95
+ h = r.height - bt - px(cs.borderBottomWidth);
96
+ mirror.style.whiteSpace = 'pre';
97
+ mirror.style.overflowWrap = 'normal';
98
+ mirror.style.wordBreak = 'normal';
99
+ // One line, as high as the inside of the input: its line is centred like the input's own.
100
+ mirror.style.lineHeight = `${Math.max(0, h - px(cs.paddingTop) - px(cs.paddingBottom))}px`;
101
+ }
102
+ mirror.style.left = '0px';
103
+ mirror.style.top = '0px';
104
+ const o = mirror.getBoundingClientRect();
105
+ mirror.style.left = `${r.left + bl - o.left}px`;
106
+ mirror.style.top = `${r.top + bt - o.top}px`;
107
+ mirror.style.width = `${w}px`;
108
+ mirror.style.height = `${h}px`;
109
+ mirror.scrollTop = ta.scrollTop;
110
+ mirror.scrollLeft = ta.scrollLeft;
111
+ }
112
+ /** Keep `mirror` over `ta` as it resizes, scrolls, and as anything it sits in scrolls or the window resizes. Returns what stops that. */
113
+ export function followBox(place, ta) {
114
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(place) : null;
115
+ ro?.observe(ta);
116
+ ta.addEventListener('scroll', place, { passive: true });
117
+ // Anything it sits in that scrolls (a panel, the page) moves the textarea: measured again.
118
+ window.addEventListener('scroll', place, { passive: true, capture: true });
119
+ window.addEventListener('resize', place);
120
+ return () => {
121
+ ro?.disconnect();
122
+ ta.removeEventListener('scroll', place);
123
+ window.removeEventListener('scroll', place, true);
124
+ window.removeEventListener('resize', place);
125
+ };
126
+ }
127
+ /**
128
+ * The text cut where a mark begins or ends and at the caret, each stretch with whether it stands in a mark. `fixAt` is where
129
+ * the mark a chip points at begins (its first stretch is `first`).
130
+ */
131
+ export function segments(text, marks, fixAt, caret) {
132
+ const live = marks.filter((m) => m.start < m.end && m.end <= text.length).sort((a, b) => a.start - b.start);
133
+ const cuts = new Set([0, text.length]);
134
+ for (const m of live)
135
+ (cuts.add(m.start), cuts.add(m.end));
136
+ if (caret !== null && caret <= text.length)
137
+ cuts.add(caret);
138
+ const at = [...cuts].sort((a, b) => a - b);
139
+ const out = [];
140
+ at.forEach((a, i) => {
141
+ if (a === caret)
142
+ out.push({ caret: true });
143
+ const b = at[i + 1];
144
+ if (b === undefined)
145
+ return;
146
+ const m = live.find((x) => x.start <= a && b <= x.end);
147
+ out.push({ text: text.slice(a, b), marked: !!m, first: !!m && m.start === fixAt && a === m.start });
148
+ });
149
+ return out;
150
+ }
151
+ /** The letters of the word being typed right before the caret (the part of a suggested word that is typed already). */
152
+ export const typedLetters = (before) => /[\p{L}\p{N}\p{M}'’]*$/u.exec(before)[0];
153
+ const NO_HOVER = '(hover:none)';
154
+ /** Whether the screen has no hover (a phone or a tablet): there is no Tab key to show, and the chip is the button. */
155
+ export const isTouch = () => typeof matchMedia === 'function' && matchMedia(NO_HOVER).matches;
156
+ // ---- chips
157
+ const GAP = 6;
158
+ const EDGE = 8;
159
+ /** Just under popovers and dialogs, or just over the one its box is in. */
160
+ const Z = 40;
161
+ /** What of an element can be seen: its box cut by every box around it that clips what scrolls out of it. */
162
+ export function visibleRect(el) {
163
+ const r = el.getBoundingClientRect();
164
+ const out = { top: r.top, bottom: r.bottom, left: r.left, right: r.right };
165
+ for (let p = el.parentElement; p; p = p.parentElement) {
166
+ const cs = getComputedStyle(p);
167
+ if (/(auto|scroll|hidden|clip)/.test(cs.overflowX + cs.overflowY)) {
168
+ const b = p.getBoundingClientRect();
169
+ out.top = Math.max(out.top, b.top);
170
+ out.bottom = Math.min(out.bottom, b.bottom);
171
+ out.left = Math.max(out.left, b.left);
172
+ out.right = Math.min(out.right, b.right);
173
+ }
174
+ // What is fixed to the screen is clipped by nothing around it.
175
+ if (cs.position === 'fixed')
176
+ break;
177
+ }
178
+ return out;
179
+ }
180
+ /** The z-index of a chip over `el`: just over the layer its box is in, or the default. */
181
+ export function layerOf(el) {
182
+ let top = 0;
183
+ for (let p = el; p; p = p.parentElement) {
184
+ const cs = getComputedStyle(p);
185
+ if (cs.position !== 'static')
186
+ top = Math.max(top, Number(cs.zIndex) || 0);
187
+ }
188
+ return top >= Z ? top + 1 : Z;
189
+ }
190
+ /** The inline style a chip's wrapper always has: fixed in the page, hidden until it is placed. */
191
+ export const LAYER_STYLE = { position: 'fixed', left: '0px', top: '0px', zIndex: String(Z), visibility: 'hidden' };
192
+ /**
193
+ * Place a chip's wrapper: just above its anchor (below when there is no room above), inside the screen, and hidden when the
194
+ * anchor is scrolled out of the box it is in.
195
+ */
196
+ export function placeChip(el, a, w) {
197
+ const clip = w ? visibleRect(w) : null;
198
+ // A place scrolled out of its box (or a box scrolled out of sight) shows no chip.
199
+ if (!a || (clip && (a.bottom <= clip.top || a.top >= clip.bottom || a.right < clip.left || a.left > clip.right))) {
200
+ el.style.visibility = 'hidden';
201
+ return;
202
+ }
203
+ const vv = window.visualViewport;
204
+ const vx = vv?.offsetLeft ?? 0;
205
+ const vy = vv?.offsetTop ?? 0;
206
+ const vw = vv?.width ?? window.innerWidth;
207
+ const vh = vv?.height ?? window.innerHeight;
208
+ const r = el.getBoundingClientRect();
209
+ let top = a.top - r.height - GAP;
210
+ if (top < vy + EDGE)
211
+ top = a.bottom + GAP;
212
+ top = Math.max(vy + EDGE, Math.min(top, vy + vh - r.height - EDGE));
213
+ const left = Math.max(vx + EDGE, Math.min(a.left, vx + vw - r.width - EDGE));
214
+ el.style.left = `${Math.round(left)}px`;
215
+ el.style.top = `${Math.round(top)}px`;
216
+ el.style.zIndex = String(layerOf(w));
217
+ el.style.visibility = 'visible';
218
+ }
219
+ /** requestAnimationFrame where there is one. */
220
+ export const frame = (f) => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame(f) : setTimeout(f, 16));
221
+ export const unframe = (n) => (typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame(n) : clearTimeout(n));
222
+ /**
223
+ * Keep a chip's wrapper placed as the page scrolls and resizes (and as the chip and its box change size). `place` is what
224
+ * places it; the returned function schedules it for the next frame, `stop` ends it all.
225
+ */
226
+ export function followChip(el, w, place) {
227
+ let id = 0;
228
+ const soon = () => {
229
+ if (!id)
230
+ id = frame(() => ((id = 0), place()));
231
+ };
232
+ window.addEventListener('scroll', soon, { passive: true, capture: true });
233
+ window.addEventListener('resize', soon);
234
+ window.visualViewport?.addEventListener('resize', soon);
235
+ window.visualViewport?.addEventListener('scroll', soon);
236
+ // The chip itself (its words change), and the box it points into (it grows as the person types, and its lines move).
237
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(soon) : null;
238
+ ro?.observe(el);
239
+ const box = w();
240
+ if (box)
241
+ ro?.observe(box);
242
+ return {
243
+ soon,
244
+ stop() {
245
+ unframe(id);
246
+ id = 0;
247
+ window.removeEventListener('scroll', soon, true);
248
+ window.removeEventListener('resize', soon);
249
+ window.visualViewport?.removeEventListener('scroll', soon);
250
+ window.visualViewport?.removeEventListener('resize', soon);
251
+ ro?.disconnect();
252
+ },
253
+ };
254
+ }
255
+ /** A new client id, one per page (a new request cancels the client's one before): `t-` and 16 hex digits. */
256
+ export function newClientId() {
257
+ const b = new Uint8Array(8);
258
+ const c = globalThis.crypto;
259
+ if (c?.getRandomValues)
260
+ c.getRandomValues(b);
261
+ else
262
+ for (let i = 0; i < b.length; i++)
263
+ b[i] = Math.floor(Math.random() * 256);
264
+ return `t-${Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')}`;
265
+ }
@@ -0,0 +1,8 @@
1
+ export * from './logic.js';
2
+ export * from './suggester.js';
3
+ export * from './usage.js';
4
+ export * from './attach.js';
5
+ export { ANNOUNCE_MS, Announcer, spokenOf, type AnnouncerOptions, type Spoken } from './announce.js';
6
+ export { BOX_CLASS, DEFAULT_CLASSES, DEFAULT_LABELS, type Attributes, type Classes, type Labels } from './ui.js';
7
+ export { newClientId, type TextBox } from './dom.js';
8
+ export { isOn, keepBoxClass, type BoxState } from './box.js';
@@ -0,0 +1,8 @@
1
+ export * from './logic.js';
2
+ export * from './suggester.js';
3
+ export * from './usage.js';
4
+ export * from './attach.js';
5
+ export { ANNOUNCE_MS, Announcer, spokenOf } from './announce.js';
6
+ export { BOX_CLASS, DEFAULT_CLASSES, DEFAULT_LABELS } from './ui.js';
7
+ export { newClientId } from './dom.js';
8
+ export { isOn, keepBoxClass } from './box.js';