@dasl/tile-loader 3.0.0 → 3.2.0

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 (87) hide show
  1. package/README.md +841 -26
  2. package/dist/at.d.ts +126 -12
  3. package/dist/at.d.ts.map +1 -1
  4. package/dist/at.js +574 -90
  5. package/dist/at.js.map +1 -1
  6. package/dist/car.d.ts +21 -2
  7. package/dist/car.d.ts.map +1 -1
  8. package/dist/car.js +78 -15
  9. package/dist/car.js.map +1 -1
  10. package/dist/content-scheme.d.ts +17 -3
  11. package/dist/content-scheme.d.ts.map +1 -1
  12. package/dist/content-scheme.js +32 -6
  13. package/dist/content-scheme.js.map +1 -1
  14. package/dist/guard.d.ts +242 -0
  15. package/dist/guard.d.ts.map +1 -0
  16. package/dist/guard.js +956 -0
  17. package/dist/guard.js.map +1 -0
  18. package/dist/index.d.ts +297 -13
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +917 -78
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/cid.d.ts +25 -0
  23. package/dist/lib/cid.d.ts.map +1 -0
  24. package/dist/lib/cid.js +65 -0
  25. package/dist/lib/cid.js.map +1 -0
  26. package/dist/lib/defaults.d.ts +8 -0
  27. package/dist/lib/defaults.d.ts.map +1 -0
  28. package/dist/lib/defaults.js +14 -0
  29. package/dist/lib/defaults.js.map +1 -0
  30. package/dist/lib/destinations.d.ts +25 -0
  31. package/dist/lib/destinations.d.ts.map +1 -0
  32. package/dist/lib/destinations.js +94 -0
  33. package/dist/lib/destinations.js.map +1 -0
  34. package/dist/lib/drisl.d.ts +10 -0
  35. package/dist/lib/drisl.d.ts.map +1 -0
  36. package/dist/lib/drisl.js +169 -0
  37. package/dist/lib/drisl.js.map +1 -0
  38. package/dist/lib/errors.d.ts +80 -0
  39. package/dist/lib/errors.d.ts.map +1 -0
  40. package/dist/lib/errors.js +44 -0
  41. package/dist/lib/errors.js.map +1 -0
  42. package/dist/lib/fetching.d.ts +24 -0
  43. package/dist/lib/fetching.d.ts.map +1 -0
  44. package/dist/lib/fetching.js +135 -0
  45. package/dist/lib/fetching.js.map +1 -0
  46. package/dist/lib/limits.d.ts +34 -0
  47. package/dist/lib/limits.d.ts.map +1 -0
  48. package/dist/lib/limits.js +33 -0
  49. package/dist/lib/limits.js.map +1 -0
  50. package/dist/lib/pointer.d.ts +83 -0
  51. package/dist/lib/pointer.d.ts.map +1 -0
  52. package/dist/lib/pointer.js +244 -0
  53. package/dist/lib/pointer.js.map +1 -0
  54. package/dist/link.d.ts +110 -13
  55. package/dist/link.d.ts.map +1 -1
  56. package/dist/link.js +336 -43
  57. package/dist/link.js.map +1 -1
  58. package/dist/memory.d.ts +1 -0
  59. package/dist/memory.d.ts.map +1 -1
  60. package/dist/memory.js +5 -0
  61. package/dist/memory.js.map +1 -1
  62. package/dist/mount.d.ts +54 -0
  63. package/dist/mount.d.ts.map +1 -0
  64. package/dist/mount.js +286 -0
  65. package/dist/mount.js.map +1 -0
  66. package/dist/size.d.ts +43 -2
  67. package/dist/size.d.ts.map +1 -1
  68. package/dist/size.js +296 -15
  69. package/dist/size.js.map +1 -1
  70. package/package.json +13 -3
  71. package/src/at.ts +582 -84
  72. package/src/car.ts +75 -16
  73. package/src/content-scheme.ts +38 -7
  74. package/src/guard.ts +1013 -0
  75. package/src/index.ts +1011 -80
  76. package/src/lib/cid.ts +65 -0
  77. package/src/lib/defaults.ts +12 -0
  78. package/src/lib/destinations.ts +79 -0
  79. package/src/lib/drisl.ts +160 -0
  80. package/src/lib/errors.ts +111 -0
  81. package/src/lib/fetching.ts +138 -0
  82. package/src/lib/limits.ts +61 -0
  83. package/src/lib/pointer.ts +290 -0
  84. package/src/link.ts +365 -48
  85. package/src/memory.ts +5 -0
  86. package/src/mount.ts +356 -0
  87. package/src/size.ts +304 -16
package/src/guard.ts ADDED
@@ -0,0 +1,1013 @@
1
+ // Guards for a page that runs a tile among things of its own: its fields, its
2
+ // buttons, the rest of a feed.
3
+ //
4
+ // A tile cannot reach the page that frames it. But it runs in the middle of
5
+ // it, and what it does to itself can land on the user of that page: a tile's
6
+ // script can put the keyboard into the tile while the user types in a field
7
+ // of the page's. Nothing in the frame's sandbox governs that, so a host that
8
+ // has fields of its own turns a guard on:
9
+ //
10
+ // import { guardFocus } from '@dasl/tile-loader/guard';
11
+ // const frame = tile.renderContent();
12
+ // guardFocus(tile, frame);
13
+ //
14
+ // A tile can also scroll the page it is in: asking the browser to bring an
15
+ // element of its own into view scrolls every scroller above it, the page's
16
+ // document included. That takes the page to the tile, holds it there, or
17
+ // slides a control of the page's under a pointer that has not moved.
18
+ // `guardScroll` accounts for every move of the page and takes back the
19
+ // tile's; `clickGate` keeps what an unexplained move slid under the pointer
20
+ // from taking a press for a moment.
21
+ //
22
+ // Giving back what a tile took is a contest with one that takes it again, and
23
+ // the tile is the faster. So a tile that keeps at it is stopped: hidden at
24
+ // once, closed, and the host told why (a `stopped` event on the tile, with a
25
+ // `reason` of `focus` or `scroll`). `stop: false` has a guard only report.
26
+ //
27
+ // And a tile takes whatever input lands on it. On a touch screen that is the
28
+ // finger that was scrolling the feed: a tile can keep the page from moving
29
+ // for as long as the finger started on it. `engage` puts a layer of the
30
+ // host's over the tile until the user picks it, so that until then the tile
31
+ // runs and shows, and gets no input at all.
32
+ //
33
+ // A guard listens to the page, so unlike the modules that only listen to the
34
+ // tile it does not go when the tile is dropped: it stops when the tile is
35
+ // closed (`tile.close()`), or when it is told to (`stop()`).
36
+
37
+ import type { Tile } from './index.js';
38
+ import { withDefaults } from './lib/defaults.js';
39
+ import { SHIELD_CLASS, watchPointer } from './lib/pointer.js';
40
+
41
+ const now = () => performance.now();
42
+ const editable = (el: Element | null): boolean => Boolean(el) && ((el as HTMLElement).isContentEditable || /^(input|textarea|select)$/.test(el?.localName || ''));
43
+ // The element that has the keyboard, looked for through shadow trees.
44
+ const focused = (doc: Document): Element | null => {
45
+ let el = doc.activeElement;
46
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
47
+ return el;
48
+ };
49
+ // Whether the keyboard is in `frame`. Asked of the tree the frame is in, so
50
+ // that a frame in a shadow tree is found as well.
51
+ const holds = (frame: Element): boolean => (frame.getRootNode() as Document | ShadowRoot).activeElement === frame;
52
+
53
+ export interface GuardControl {
54
+ /** Stops guarding. What the tile does from then on is left as it is. */
55
+ stop (): void;
56
+ }
57
+
58
+ /**
59
+ * A guard stopped a tile, because it kept taking the keyboard (`focus`) or
60
+ * the page (`scroll`) from the user. Raised on the tile as a `stopped` event,
61
+ * as the dock's are; the tile is closed, and a host that wants it back
62
+ * renders it again.
63
+ */
64
+ export interface GuardStoppedEvent extends Event {
65
+ reason: 'focus' | 'scroll';
66
+ }
67
+
68
+ // The tiles a guard is in the middle of stopping.
69
+ const halting = new WeakSet<Tile>();
70
+
71
+ // Stops a tile that would not stop. It is out of the way at once: a frame
72
+ // that is not rendered takes no focus and scrolls nothing. Its frame stays in
73
+ // the document for the moment closing takes, since a tile's runtime needs it
74
+ // there to clean up after itself; the guards go on until it is gone.
75
+ function halt (tile: Tile, frame: HTMLElement, reason: GuardStoppedEvent['reason']) {
76
+ if (halting.has(tile)) return;
77
+ halting.add(tile);
78
+ frame.style.display = 'none';
79
+ tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
80
+ // Rendered again, it is a tile like any other.
81
+ tile.close().finally(() => halting.delete(tile));
82
+ }
83
+
84
+ const DOCK_STATUS = 'tiles-dock-status';
85
+
86
+ // What the tile's dock says of the user and that tile, asked for when it
87
+ // matters (see `DockStamp`): whether the user has just pressed or typed
88
+ // inside the tile. `ask()` resolves `undefined` when no answer comes within
89
+ // `ms`. A loading server from before its dock knew the question never
90
+ // answers; `answers` says whether this one ever has. The answer is only ever
91
+ // used to refuse, so that one that is not the dock's own gains nothing.
92
+ function dockStatus (tile: Tile, frame: HTMLIFrameElement, ms: number) {
93
+ const win = frame.ownerDocument.defaultView as Window;
94
+ const origin = new URL(tile.getLoadSource()).origin;
95
+ const waiting = new Map<string, (activated: boolean | undefined) => void>();
96
+ let n = 0;
97
+ let answers = false;
98
+ const onMessage = (ev: MessageEvent) => {
99
+ if (ev.source !== frame.contentWindow || ev.origin !== origin || ev.data?.action !== DOCK_STATUS) return;
100
+ const { id, activated } = ev.data.payload ?? {};
101
+ if (typeof activated !== 'boolean') return;
102
+ answers = true;
103
+ const resolve = waiting.get(id);
104
+ if (!resolve) return;
105
+ waiting.delete(id);
106
+ resolve(activated);
107
+ };
108
+ win.addEventListener('message', onMessage);
109
+ return {
110
+ get answers () { return answers; },
111
+ ask (): Promise<boolean | undefined> {
112
+ const id = `d${++n}`;
113
+ return new Promise((resolve) => {
114
+ waiting.set(id, resolve);
115
+ win.setTimeout(() => { if (waiting.delete(id)) resolve(undefined); }, ms);
116
+ tile.post(DOCK_STATUS, { id });
117
+ });
118
+ },
119
+ stop () { win.removeEventListener('message', onMessage); },
120
+ };
121
+ }
122
+
123
+ // ---------------------------------------------------------------- the keyboard
124
+
125
+ /** The numbers `guardFocus` goes by. First guesses, all of them. */
126
+ export interface FocusGuardOptions {
127
+ /** How long after a Tab pressed on the page focus arriving in the tile is the user tabbing in, in milliseconds. */
128
+ tabMs?: number;
129
+ /** How long after a key typed into a field of the page focus arriving in the tile cannot be the user's click, in milliseconds. */
130
+ typingMs?: number;
131
+ /** How many times the tile may take the keyboard, within `withinMs`, before that is abuse. */
132
+ grabs?: number;
133
+ /** The time those are counted over, in milliseconds. */
134
+ withinMs?: number;
135
+ /**
136
+ * How long the tile's dock gets to say whether the user acted in the tile,
137
+ * in milliseconds. It answers in a few; what the user types while it has
138
+ * not goes to the tile.
139
+ */
140
+ dockMs?: number;
141
+ /** How often the page is looked at for focus that arrived unannounced, in milliseconds. */
142
+ pollMs?: number;
143
+ /**
144
+ * Called when focus was given back: `script` when the page saw nothing
145
+ * that would make it the user's doing, `dock` when the tile's dock said
146
+ * the user had not acted in the tile.
147
+ */
148
+ onReturn?: (why: 'script' | 'dock') => void;
149
+ /** Called when the tile has taken the keyboard `grabs` times within `withinMs`, with how often it has been given back in all. */
150
+ onAbuse?: (what: 'focus', count: number) => void;
151
+ /** Stop the tile then (the default), or only report it (`false`). */
152
+ stop?: boolean;
153
+ /**
154
+ * Whether the user has picked the tile, for a host that has it wait to be
155
+ * picked (`engage`): focus arriving in a tile that is not picked is never
156
+ * the user's doing.
157
+ */
158
+ engaged?: () => boolean;
159
+ }
160
+
161
+ /** `guardFocus`'s numbers where a host gives none. */
162
+ export const FOCUS_GUARD: Readonly<Record<'tabMs' | 'typingMs' | 'grabs' | 'withinMs' | 'dockMs' | 'pollMs', number>> = Object.freeze({
163
+ tabMs: 400,
164
+ typingMs: 1000,
165
+ grabs: 3,
166
+ withinMs: 10000,
167
+ dockMs: 150,
168
+ pollMs: 100,
169
+ });
170
+
171
+ /**
172
+ * Gives back keyboard focus that a tile's script took, and leaves it with a
173
+ * user who went into the tile.
174
+ *
175
+ * Focus arriving in the frame is the user's doing when they tabbed into it,
176
+ * or pressed on it. The page sees the Tab key. It never sees the press: only
177
+ * that a mouse is over the frame, and not even that for a finger. So focus
178
+ * stays in the tile when a Tab was just pressed on the page; otherwise, when
179
+ * a mouse is in the frame (or the user has none) and they were not typing in
180
+ * a field of the page a moment ago, the tile's dock is asked, which knows
181
+ * whether the user pressed or typed inside this tile. In every other case,
182
+ * and when the dock says no, focus goes back to what had it.
183
+ *
184
+ * A dock that has answered before and now does not is taken to say no: its
185
+ * silence is not to be had by keeping it busy. One that has never answered
186
+ * (an older loading server's) leaves the guard with what the page can see:
187
+ * a mouse resting on the tile, or a finger, cannot be told from a press.
188
+ *
189
+ * Giving it back does not win against a tile that keeps taking it: a tile
190
+ * that does so `grabs` times within `withinMs` is reported (`onAbuse`) and
191
+ * stopped (see `GuardStoppedEvent`), unless told otherwise (`stop: false`).
192
+ */
193
+ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: FocusGuardOptions = {}): GuardControl {
194
+ const doc = frame.ownerDocument;
195
+ const win = doc.defaultView as Window;
196
+ const pointer = watchPointer(doc);
197
+ const cfg = withDefaults(FOCUS_GUARD, options);
198
+ const dock = dockStatus(tile, frame, cfg.dockMs);
199
+ // Whether this dock answers at all is learnt while nothing is at stake:
200
+ // now, and when the tile's runtime says it is up, before the tile runs.
201
+ const probe = () => { dock.ask(); };
202
+ probe();
203
+ tile.addEventListener('load', probe);
204
+ // What had the keyboard before the tile did.
205
+ let holder = focused(doc) as HTMLElement | null;
206
+ if (holder === frame || holder === doc.body) holder = null;
207
+ // Whether this window has the keyboard. Which element is the active one is
208
+ // not enough to go by: that says which element WOULD have it. The window's
209
+ // own focus and blur events say whether a frame inside it has taken it.
210
+ let winFocused = doc.hasFocus() && !holds(frame);
211
+ let inTile = false;
212
+ let accepted = false;
213
+ let lastTab = -Infinity;
214
+ let lastTyped = -Infinity;
215
+ let returned = 0;
216
+ let round = 0; // which giving back is under way: one that was overtaken does nothing more
217
+ let grabs: number[] = [];
218
+ let stopped = false;
219
+
220
+ // Whether `el` is the frame, or something the frame is in (the element
221
+ // whose shadow tree it is in is all the page is told of it, where that
222
+ // tree is closed).
223
+ const around = (el: Node): boolean => {
224
+ for (let node: Node | null = frame; node; node = node.parentNode ?? (node as ShadowRoot).host ?? null) if (node === el) return true;
225
+ return false;
226
+ };
227
+ const onFocusIn = (ev: Event) => {
228
+ const target = (ev.composedPath?.()[0] ?? ev.target) as HTMLElement | null;
229
+ if (target && target !== frame) holder = target;
230
+ // The Tab that brought the user here took them to something of the
231
+ // page's, not into the tile: it explains nothing that arrives there next.
232
+ if (target && !around(target)) lastTab = -Infinity;
233
+ };
234
+ // Whether a key picks the tile, for a host that has it wait to be picked:
235
+ // Enter or Space on the layer over it (see `engage`), which then puts the
236
+ // keyboard into the tile itself.
237
+ const picks = (ev: KeyboardEvent): boolean => {
238
+ if (ev.key !== 'Enter' && ev.key !== ' ') return false;
239
+ const target = (ev.composedPath?.()[0] ?? ev.target) as Element | null;
240
+ return Boolean(target?.classList?.contains(ENGAGE_CLASS) && target.parentNode?.contains(frame));
241
+ };
242
+ const onKey = (ev: KeyboardEvent) => {
243
+ if (!ev.isTrusted) return;
244
+ // (Picking the tile from the keyboard is going into it by the keyboard, as tabbing into it is.)
245
+ if (ev.key === 'Tab' || picks(ev)) lastTab = now();
246
+ else if (editable(focused(doc))) lastTyped = now();
247
+ };
248
+ // Whether focus that has just arrived in the frame can be the user's
249
+ // doing: `tab` when the page saw them tab, `ask` when only the dock can
250
+ // tell, `false` when it cannot be.
251
+ const judge = (): 'tab' | 'ask' | false => {
252
+ const t = now();
253
+ if (options.engaged && !options.engaged()) return false;
254
+ if (t - lastTab < cfg.tabMs) return 'tab';
255
+ if (t - lastTyped < cfg.typingMs) return false;
256
+ // A finger gives the page nothing to go by.
257
+ if (!pointer.hovers || pointer.state.kind === 'none') return 'ask';
258
+ return pointer.inside(frame) ? 'ask' : false;
259
+ };
260
+ // Never from inside the blur that tells us: the browser is still moving
261
+ // focus into the frame then, and finishes the move after the handler
262
+ // returns, leaving the element "focused" in a window that has no keyboard.
263
+ // So it is done from a later task, checked by the window's own focus event,
264
+ // and done again if it did not take.
265
+ const takeBack = (tries: number, mine: number) => {
266
+ if (stopped || winFocused || mine !== round) return;
267
+ if (tries === 0 && holder?.isConnected) holder.focus({ preventScroll: true });
268
+ else {
269
+ frame.blur();
270
+ win.focus();
271
+ if (holder?.isConnected) holder.focus({ preventScroll: true });
272
+ }
273
+ if (tries < 4) win.setTimeout(() => takeBack(tries + 1, mine), 30);
274
+ };
275
+ const giveBack = (why: 'script' | 'dock') => {
276
+ returned++;
277
+ const t = now();
278
+ grabs = grabs.filter(g => t - g < cfg.withinMs);
279
+ grabs.push(t);
280
+ takeBack(0, ++round);
281
+ options.onReturn?.(why);
282
+ if (grabs.length < cfg.grabs) return;
283
+ grabs = [];
284
+ options.onAbuse?.('focus', returned);
285
+ if (options.stop !== false) halt(tile, frame, 'focus');
286
+ };
287
+ const check = () => {
288
+ if (stopped || winFocused || !doc.hasFocus()) return;
289
+ if (holds(frame)) inTile = true;
290
+ // The keyboard is in another frame of the page's. It left the tile, and
291
+ // what was decided when it came no longer stands: should it come back,
292
+ // that is judged afresh. (The window hears nothing of focus going from
293
+ // one frame to another.)
294
+ else inTile = accepted = false;
295
+ if (!inTile || accepted) return;
296
+ const how = judge();
297
+ if (!how) {
298
+ inTile = false;
299
+ return giveBack('script');
300
+ }
301
+ accepted = true;
302
+ round++; // nothing still on its way from an earlier giving back takes this one away
303
+ if (how === 'tab') return;
304
+ // A second opinion, which takes a moment: the dock's.
305
+ dock.ask().then((acted) => {
306
+ if (acted === true || !accepted || winFocused || stopped) return;
307
+ // No answer, from a dock that never gave one: nothing more to go by.
308
+ if (acted === undefined && !dock.answers) return;
309
+ accepted = false;
310
+ inTile = false;
311
+ giveBack('dock');
312
+ });
313
+ };
314
+ const onWinBlur = () => {
315
+ winFocused = false;
316
+ // The keyboard has gone again, and that is for `check` to judge and to
317
+ // count. A giving back still making sure of an earlier time is over: it
318
+ // would take this one back as well, before it had been counted.
319
+ round++;
320
+ win.setTimeout(check, 0);
321
+ };
322
+ const onWinFocus = () => {
323
+ winFocused = true;
324
+ inTile = false;
325
+ accepted = false;
326
+ };
327
+ win.addEventListener('blur', onWinBlur);
328
+ win.addEventListener('focus', onWinFocus);
329
+ doc.addEventListener('focusin', onFocusIn, true);
330
+ doc.addEventListener('keydown', onKey, true);
331
+ // (The page's own timers throughout: they go with the page.)
332
+ const poll = win.setInterval(check, cfg.pollMs);
333
+ const stop = () => {
334
+ if (stopped) return;
335
+ stopped = true;
336
+ win.clearInterval(poll);
337
+ dock.stop();
338
+ win.removeEventListener('blur', onWinBlur);
339
+ win.removeEventListener('focus', onWinFocus);
340
+ doc.removeEventListener('focusin', onFocusIn, true);
341
+ doc.removeEventListener('keydown', onKey, true);
342
+ tile.removeEventListener('close', stop);
343
+ tile.removeEventListener('load', probe);
344
+ };
345
+ // A tile that is closed has no frame left to guard.
346
+ tile.addEventListener('close', stop);
347
+ return { stop };
348
+ }
349
+
350
+ // ---------------------------------------------------------------- the click gate
351
+
352
+ export interface ClickGate {
353
+ /** Whether presses on the page are being ignored right now. */
354
+ readonly closed: boolean;
355
+ /** Has the page ignore presses for `ms` from now (`CLICK_GATE.ms` by default). */
356
+ arm (ms?: number): void;
357
+ /** Has it take them again at once. */
358
+ open (): void;
359
+ }
360
+
361
+ /** The numbers `clickGate` goes by where it is given none. First guesses. */
362
+ export const CLICK_GATE: Readonly<Record<'ms' | 'travel', number>> = Object.freeze({
363
+ /** How long presses are ignored, in milliseconds. */
364
+ ms: 600,
365
+ /** How far the pointer has to really move for them to be taken again sooner, in pixels. */
366
+ travel: 24,
367
+ });
368
+
369
+ const gates = new WeakMap<Document, ClickGate>();
370
+ const PRESSES = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'auxclick', 'contextmenu'];
371
+ // What keeps its own counsel about presses: the blocks the loader itself
372
+ // puts up, its link prompt, and anything the host marks.
373
+ const PASSES = `.${SHIELD_CLASS}, .tile-link-dialog, [data-tile-gate="pass"]`;
374
+
375
+ /**
376
+ * The page's own controls ignore presses and clicks for a moment after
377
+ * something moved them that neither the page nor, as far as it can see, the
378
+ * user did. One per document: `arm(ms)` starts the moment, a press that is
379
+ * ignored starts it again, and a real movement of the pointer across the
380
+ * page, which is the user aiming afresh at what is there now, ends it.
381
+ *
382
+ * A key is not a press: what the keyboard activates is where the focus is,
383
+ * and nothing that moved the page moved that. An element of the host's that
384
+ * must take presses regardless is marked `data-tile-gate="pass"`.
385
+ */
386
+ export function clickGate (doc: Document = document, options: { travel?: number } = {}): ClickGate {
387
+ const known = gates.get(doc);
388
+ if (known) return known;
389
+ const win = doc.defaultView as Window;
390
+ const travel = options.travel ?? CLICK_GATE.travel;
391
+ let until = 0;
392
+ let ms: number = CLICK_GATE.ms;
393
+ let anchor: { x: number; y: number } | undefined;
394
+ const gate: ClickGate = {
395
+ get closed () { return now() < until; },
396
+ arm (forMs = CLICK_GATE.ms) {
397
+ ms = forMs;
398
+ until = Math.max(until, now() + forMs);
399
+ anchor = undefined;
400
+ },
401
+ open () { until = 0; },
402
+ };
403
+ const swallow = (ev: Event) => {
404
+ const e = ev as PointerEvent;
405
+ if (!e.isTrusted || now() >= until) return;
406
+ if (e.type === 'click' && e.detail === 0) return; // the keyboard's
407
+ if ((e.target as Element | null)?.closest?.(PASSES)) return;
408
+ e.stopImmediatePropagation();
409
+ // A finger going down may be the start of a scroll: that is let be, and the tap it may become is what is refused.
410
+ if (!(e.pointerType === 'touch' && e.type !== 'click')) e.preventDefault();
411
+ if (e.type === 'pointerdown' || e.type === 'click') until = now() + ms;
412
+ };
413
+ for (const type of PRESSES) win.addEventListener(type, swallow, true);
414
+ win.addEventListener('pointermove', (ev) => {
415
+ const e = ev as PointerEvent;
416
+ if (!e.isTrusted || now() >= until || e.pointerType === 'touch') return;
417
+ if (!anchor) { anchor = { x: e.clientX, y: e.clientY }; return; }
418
+ if (Math.hypot(e.clientX - anchor.x, e.clientY - anchor.y) >= travel) until = 0;
419
+ }, { capture: true, passive: true });
420
+ gates.set(doc, gate);
421
+ return gate;
422
+ }
423
+
424
+ // ---------------------------------------------------------------- scrolling
425
+
426
+ /** How a move of the page was accounted for (see `guardScroll`). */
427
+ export interface ScrollMove {
428
+ /** The page's vertical scroll position before and after. */
429
+ from: number;
430
+ to: number;
431
+ verdict: 'user' | 'own' | 'layout' | 'ambiguous' | 'tile' | 'elsewhere';
432
+ /** Whether the move was taken back. */
433
+ undone: boolean;
434
+ }
435
+
436
+ /** The numbers `guardScroll` goes by. First guesses, all of them. */
437
+ export interface ScrollGuardOptions {
438
+ /** How long input that asked for a scroll goes on explaining one, in milliseconds. */
439
+ inputMs?: number;
440
+ /** How long a page may coast on, the way it was going, after a finger let go, in milliseconds. */
441
+ flingMs?: number;
442
+ /** How much further than the input asked a move may go and still be the user's, in pixels. */
443
+ slack?: number;
444
+ /** How many times the tile may pull the page back against the user's own scrolling, within `withinMs`, before that is abuse. */
445
+ pulls?: number;
446
+ /** The time those are counted over, in milliseconds. */
447
+ withinMs?: number;
448
+ /** How long the page's controls take no press after a move that is not accounted for, in milliseconds. */
449
+ gateMs?: number;
450
+ /** A move of more than this many pixels in one go is a jump, */
451
+ jumpPx?: number;
452
+ /** after which they take no press for this long, in milliseconds. */
453
+ jumpGateMs?: number;
454
+ /** Take the tile's moves back (the default), or let them stand and only keep presses off what they moved (`false`). */
455
+ undo?: boolean;
456
+ /** The gate that keeps presses off what moved: the document's own by default, `false` for none. */
457
+ gate?: ClickGate | false;
458
+ /**
459
+ * How the page's own scrolling is known for its own: `'patch'` wraps the
460
+ * calls a page scrolls itself with (`scrollTo`, `scrollBy`, `scroll`,
461
+ * `scrollIntoView`, `focus`) so that each says so first. Without it the
462
+ * page says so itself, with `expect()`.
463
+ */
464
+ own?: 'patch';
465
+ /** Called with every move of the page and how it was accounted for. */
466
+ onMove?: (move: ScrollMove) => void;
467
+ /** Called when the tile has pulled the page back `pulls` times within `withinMs`, with how often it was undone in all. */
468
+ onAbuse?: (what: 'scroll', count: number) => void;
469
+ /** Stop the tile then (the default), or only report it (`false`). */
470
+ stop?: boolean;
471
+ /**
472
+ * Whether the user has picked the tile, for a host that has it wait to be
473
+ * picked (`engage`): a tile that is not picked gets no input, so the user
474
+ * cannot have scrolled the page through it.
475
+ */
476
+ engaged?: () => boolean;
477
+ }
478
+
479
+ /** `guardScroll`'s numbers where a host gives none. */
480
+ export const SCROLL_GUARD: Readonly<Record<'inputMs' | 'flingMs' | 'slack' | 'pulls' | 'withinMs' | 'gateMs' | 'jumpPx' | 'jumpGateMs', number>> = Object.freeze({
481
+ inputMs: 1200,
482
+ flingMs: 2500,
483
+ slack: 60,
484
+ pulls: 3,
485
+ withinMs: 10000,
486
+ gateMs: CLICK_GATE.ms,
487
+ jumpPx: 150,
488
+ jumpGateMs: 2500,
489
+ });
490
+
491
+ export interface ScrollGuardControl extends GuardControl {
492
+ /** The page is about to scroll itself (a "back to top", a change of route): leave it be for `ms` (1000 by default). */
493
+ expect (ms?: number): void;
494
+ }
495
+
496
+ // What a key scrolls by: pixels, pages (viewport heights), or all the way.
497
+ const SCROLL_KEYS: Record<string, ['px' | 'page' | 'all', number]> = { ArrowDown: ['px', 40], ArrowUp: ['px', -40], PageDown: ['page', 1], PageUp: ['page', -1], ' ': ['page', 1], End: ['all', 1], Home: ['all', -1] };
498
+ const framed = (el: Element | null): boolean => el?.localName === 'iframe' || el?.localName === 'frame';
499
+
500
+ // The frames of a page that have a scroll guard on them, each with whether
501
+ // input can reach it: always, unless it waits to be picked. A guard is one
502
+ // tile's, and the page it watches is everyone's. So each has to know of the
503
+ // others: which of two tiles at the viewport moved the page cannot be told.
504
+ const scrollGuarded = new WeakMap<Document, Map<Element, () => boolean>>();
505
+
506
+ // The calls a page scrolls itself with, wrapped so that each says so first:
507
+ // once for a page, however many of its guards asked, and put back as they
508
+ // were when the last of those stops.
509
+ const declaring = new WeakMap<Window, { tell: Set<() => void>; restore: (() => void)[] }>();
510
+ function declareOwn (win: Window, tell: () => void): () => void {
511
+ let shared = declaring.get(win);
512
+ if (!shared) {
513
+ const made = { tell: new Set<() => void>(), restore: [] as (() => void)[] };
514
+ const wrap = (obj: Record<string, unknown> | undefined, name: string) => {
515
+ const original = obj?.[name];
516
+ if (!obj || typeof original !== 'function') return;
517
+ obj[name] = function (this: unknown, ...args: unknown[]) {
518
+ // (A focus() that says it will not scroll explains no scroll: the
519
+ // focus guard gives the keyboard back with one, whenever a tile
520
+ // takes it.)
521
+ if (!(name === 'focus' && (args[0] as FocusOptions | undefined)?.preventScroll)) for (const fn of made.tell) fn();
522
+ return original.apply(this, args);
523
+ };
524
+ made.restore.push(() => { obj[name] = original; });
525
+ };
526
+ const w = win as unknown as Record<string, { prototype: Record<string, unknown> }> & Record<string, unknown>;
527
+ for (const name of ['scrollTo', 'scrollBy', 'scroll']) {
528
+ wrap(w, name);
529
+ wrap(w.Element.prototype, name);
530
+ }
531
+ wrap(w.Element.prototype, 'scrollIntoView');
532
+ wrap(w.HTMLElement.prototype, 'focus');
533
+ declaring.set(win, made);
534
+ shared = made;
535
+ }
536
+ const mine = shared;
537
+ mine.tell.add(tell);
538
+ return () => {
539
+ mine.tell.delete(tell);
540
+ if (mine.tell.size || declaring.get(win) !== mine) return;
541
+ mine.restore.forEach(fn => fn());
542
+ declaring.delete(win);
543
+ };
544
+ }
545
+
546
+ /**
547
+ * Accounts for every move of the page a tile is in, and takes back the
548
+ * tile's own.
549
+ *
550
+ * The page's vertical scroll position is followed, and each move is one of:
551
+ *
552
+ * - `user`: the page saw the input for it (a wheel, a key, a finger, a
553
+ * mouse button held down, a pointer on the scrollbar), and the move goes
554
+ * that way and no further than the input asked: a wheel turned by 100
555
+ * does not explain a jump of 1500.
556
+ * - `own`: the page said it would (`expect()`, or `own: 'patch'`), or it
557
+ * navigated, or the user tabbed on.
558
+ * - `layout`: the document's height changed, by as much as the move or
559
+ * more. It stands. Where the tile's own box changed with it, the gate is
560
+ * armed: the move may be the tile's doing after all.
561
+ * - `ambiguous`: none of those, but the page cannot rule the user out. A
562
+ * mouse was inside the tile and may have been wheeling there, the
563
+ * keyboard is in the tile, or a finger may be on it. The same goes for
564
+ * any other frame of the page's: what the user does in one scrolls the
565
+ * page too, and the page sees none of it. The move stands, and the gate
566
+ * is armed: what slid under the pointer takes no press for a moment
567
+ * (`gateMs`; `jumpGateMs` after a jump), or until the pointer has really
568
+ * moved.
569
+ * - `tile`: none of those, and the tile's frame is at or in the viewport
570
+ * once it is done, which is where its own scrolling leaves it. It is
571
+ * taken back before it is painted. (The gate is armed only where the page
572
+ * could not be put back whole: a move that is undone slid nothing under
573
+ * the pointer.)
574
+ * - `elsewhere`: unexplained, and nowhere near the tile. Left alone (the
575
+ * browser and assistive tools scroll pages too), gate armed.
576
+ *
577
+ * A tile that pulls the page back against the way the user has just
578
+ * scrolled is doing it on purpose: `pulls` of those within `withinMs` are
579
+ * reported (`onAbuse`), and the tile is stopped (see `GuardStoppedEvent`)
580
+ * unless told otherwise (`stop: false`). Where another tile with a guard on
581
+ * it is at the viewport as well, which of them it was cannot be told: the
582
+ * move is taken back all the same, and neither is held to it.
583
+ *
584
+ * The page has to say when it scrolls itself, or let the guard wrap its
585
+ * calls: an unexplained move of the page's own that ends at the tile is
586
+ * taken back like the tile's. Only the document's own scrolling is
587
+ * followed, not that of a box inside it.
588
+ */
589
+ export function guardScroll (tile: Tile, frame: HTMLIFrameElement, options: ScrollGuardOptions = {}): ScrollGuardControl {
590
+ const doc = frame.ownerDocument;
591
+ const win = doc.defaultView as Window;
592
+ const pointer = watchPointer(doc);
593
+ const cfg = { ...withDefaults(SCROLL_GUARD, options), undo: options.undo !== false };
594
+ const gate = options.gate === false ? undefined : (options.gate ?? clickGate(doc));
595
+ const root = () => doc.scrollingElement || doc.documentElement;
596
+ // How much of the frame is in the viewport, in pixels of height.
597
+ const visible = () => {
598
+ const r = frame.getBoundingClientRect();
599
+ return Math.max(0, Math.min(r.bottom, win.innerHeight) - Math.max(r.top, 0));
600
+ };
601
+ // Whether an element is at or in the viewport.
602
+ const at = (el: Element) => {
603
+ const r = el.getBoundingClientRect();
604
+ return r.height > 0 && r.bottom >= -2 && r.top <= win.innerHeight + 2;
605
+ };
606
+ const near = () => at(frame);
607
+ // Whether a point was in a frame's box before the page moved by `d`.
608
+ const within = (el: Element, p: { x: number; y: number }, d: number) => {
609
+ const r = el.getBoundingClientRect();
610
+ const top = r.top + d;
611
+ return p.x >= r.left - 2 && p.x <= r.right + 2 && p.y >= top - 2 && p.y <= top + r.height + 2;
612
+ };
613
+ const others = scrollGuarded.get(doc) ?? new Map<Element, () => boolean>();
614
+ scrollGuarded.set(doc, others);
615
+ others.set(frame, () => !options.engaged || options.engaged());
616
+ // Whether ours is the only guarded tile at the viewport: the only one
617
+ // that can have brought the page to where it is.
618
+ const alone = () => {
619
+ for (const el of others.keys()) if (el !== frame && el.isConnected && at(el)) return false;
620
+ return true;
621
+ };
622
+ // Whether a finger may have been on another frame of the page's: one that
623
+ // was in view before the page moved by `d`, and that input reaches. (A
624
+ // frame in a shadow tree is only known of here if it has a guard.)
625
+ const fingerElsewhere = (d: number) => {
626
+ for (const el of new Set<Element>([...doc.getElementsByTagName('iframe'), ...others.keys()])) {
627
+ if (el === frame || !el.isConnected || others.get(el)?.() === false) continue;
628
+ const r = el.getBoundingClientRect();
629
+ const top = r.top + d;
630
+ if (r.width > 0 && r.height > 0 && top < win.innerHeight && top + r.height > 0) return true;
631
+ }
632
+ return false;
633
+ };
634
+ let y = win.scrollY;
635
+ let docHeight = root().scrollHeight;
636
+ let frameHeight = frame.getBoundingClientRect().height;
637
+ let seen = visible();
638
+ // What the user has asked for and the page has not scrolled yet, in pixels (signed).
639
+ let credit = 0;
640
+ let inputAt = -Infinity;
641
+ let lastDir = 0; // the way the user last scrolled
642
+ let lastDirAt = -Infinity;
643
+ let down = false; // a mouse button is down on the page: a scrollbar, a drag, autoscroll
644
+ let downAt = -Infinity;
645
+ let flingUntil = -Infinity;
646
+ let flingDir = 0;
647
+ let expected = -Infinity;
648
+ let restoring: number | undefined; // where the page was put back to, until that move is heard of
649
+ let undone = 0;
650
+ let tookBackAt = -Infinity; // when a move of the tile's was last taken back
651
+ let typedAt = -Infinity; // when the user last typed into a field of the page's
652
+ let pulls: number[] = [];
653
+ let stopped = false;
654
+ let touchY: number | undefined;
655
+ // Where the page was when the pointer was last seen going into a frame.
656
+ let entered: { at: number; y: number } | undefined;
657
+ const onPointer = () => {
658
+ const p = pointer.state;
659
+ if (p.kind !== 'frame') entered = undefined;
660
+ else if (entered?.at !== p.at) entered = { at: p.at, y: win.scrollY };
661
+ };
662
+ onPointer();
663
+ const offPointer = pointer.onChange(onPointer);
664
+
665
+ const ask = (px: number) => {
666
+ const t = now();
667
+ if (t - inputAt > cfg.inputMs || Math.sign(px) !== Math.sign(credit)) credit = 0; // stale, or the user turned round
668
+ credit += px;
669
+ inputAt = t;
670
+ lastDir = Math.sign(px);
671
+ lastDirAt = t;
672
+ };
673
+ const onWheel = (ev: Event) => {
674
+ const e = ev as WheelEvent;
675
+ if (e.isTrusted && e.deltaY) ask(e.deltaY * (e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? win.innerHeight : 1));
676
+ };
677
+ const onKey = (ev: Event) => {
678
+ const e = ev as KeyboardEvent;
679
+ if (!e.isTrusted || holds(frame)) return;
680
+ if (e.key === 'Tab') { expected = Math.max(expected, now() + 300); return; } // focus moving on may scroll to it
681
+ // A key typed into a field of the page's scrolls nothing itself, but the
682
+ // browser may move the page to keep the caret in view.
683
+ if (editable(focused(doc))) { typedAt = now(); return; }
684
+ const k = SCROLL_KEYS[e.key];
685
+ if (!k) return;
686
+ const sign = e.key === ' ' && e.shiftKey ? -1 : 1;
687
+ ask(sign * (k[0] === 'px' ? k[1] : k[0] === 'page' ? k[1] * win.innerHeight : k[1] * 1e9));
688
+ };
689
+ const onTouchStart = (ev: Event) => {
690
+ const e = ev as TouchEvent;
691
+ if (!e.isTrusted) return;
692
+ touchY = e.touches[0]?.clientY;
693
+ flingUntil = -Infinity;
694
+ };
695
+ const onTouchMove = (ev: Event) => {
696
+ const e = ev as TouchEvent;
697
+ if (!e.isTrusted) return;
698
+ const ty = e.touches[0]?.clientY;
699
+ if (touchY !== undefined && ty !== undefined && ty !== touchY) ask(touchY - ty);
700
+ touchY = ty;
701
+ };
702
+ // The finger is up; the page may coast on, the way it was going.
703
+ const onTouchEnd = (ev: Event) => {
704
+ if (!ev.isTrusted || !lastDir || now() - lastDirAt >= 300) return;
705
+ flingUntil = now() + cfg.flingMs;
706
+ flingDir = lastDir;
707
+ };
708
+ const onDown = (ev: Event) => { if (ev.isTrusted && (ev as PointerEvent).pointerType !== 'touch') { down = true; downAt = now(); } };
709
+ const onUp = (ev: Event) => { if (ev.isTrusted && (ev as PointerEvent).pointerType !== 'touch') { down = false; downAt = now(); } };
710
+ const onNav = () => { expected = now() + 1500; };
711
+
712
+ const byUser = (d: number, t: number): boolean => {
713
+ // A button held down on the page, or just let go: the page may scroll
714
+ // for it (a drag, a click on something that scrolls). Not while the tile
715
+ // has just been trying: its next try would pass for the page's answer to
716
+ // a press that had nothing to do with it.
717
+ if ((down || t - downAt < 300) && t - tookBackAt >= cfg.gateMs) return true;
718
+ // The user is typing in a field of the page's, and the browser keeps the
719
+ // caret in view: a line or two at a time, with the field still there to
720
+ // see afterwards. (Under the same condition: a tile that keeps trying
721
+ // does not get to creep the page along under the typing.)
722
+ if (t - typedAt < 300 && Math.abs(d) <= cfg.slack && t - tookBackAt >= cfg.gateMs) {
723
+ const field = focused(doc);
724
+ if (field && editable(field) && at(field)) return true;
725
+ }
726
+ // The viewport's own scrollbar gives the page no events: a pointer last seen at the right edge may be on it.
727
+ const p = pointer.state;
728
+ if (p.kind === 'host' && p.type !== 'touch' && p.x >= Math.min(root().clientWidth, win.innerWidth - 18)) return true;
729
+ if (t < flingUntil && Math.sign(d) === flingDir) return true;
730
+ if (t - inputAt > cfg.inputMs || Math.sign(d) !== Math.sign(credit)) return false;
731
+ if (Math.abs(d) > Math.abs(credit) + cfg.slack) return false;
732
+ credit -= d;
733
+ if (Math.sign(credit) !== Math.sign(d)) credit = 0; // spent (the slack is not carried over)
734
+ return true;
735
+ };
736
+ // Whether a mouse the page last saw going into `el` can still have been
737
+ // in it before the page moved by `d`. The page is told when a mouse goes
738
+ // into a frame, and where; nothing of where it goes from there. So it may
739
+ // be resting anywhere in the frame, and is still in it for as long as the
740
+ // page has not moved by the frame's own height since. One that did not
741
+ // move there is another matter: the frame came to it, and it is where it
742
+ // was, which is all the frame's box before the move is asked.
743
+ const mouseIn = (el: Element, d: number): boolean => {
744
+ const p = pointer.state;
745
+ if (!p.moved) return within(el, p, d);
746
+ const r = el.getBoundingClientRect();
747
+ const top = r.top + d;
748
+ const shifted = Math.abs(y - (entered?.y ?? y));
749
+ return r.width > 0 && shifted < r.height && top < win.innerHeight && top + r.height > 0;
750
+ };
751
+ // Could the user have scrolled through a frame, where the page sees no
752
+ // input? Judged by where things were BEFORE the move: a tile that scrolls
753
+ // itself under a pointer resting on the page is then "hovered", and that
754
+ // must not count for it. `d` is how far the page has just moved.
755
+ const cannotTell = (d: number): boolean => {
756
+ const p = pointer.state;
757
+ const fingers = !pointer.hovers || p.kind === 'none';
758
+ const into = !fingers && p.kind === 'frame' ? pointer.frame : undefined;
759
+ // The page's other frames first. What the user does in one scrolls the
760
+ // page as well, and is no more the page's to see than what they do in
761
+ // the tile: the keyboard in one, a mouse that went into one, a finger
762
+ // that may be on one.
763
+ const active = focused(doc);
764
+ if (framed(active) && active !== frame) return true;
765
+ if (into && into !== frame && mouseIn(into, d)) return true;
766
+ if (fingers && fingerElsewhere(d)) return true;
767
+ if (options.engaged && !options.engaged()) return false; // no input reaches a tile that is not picked
768
+ if (holds(frame)) return true; // keys pressed in the tile scroll the page too
769
+ if (fingers) return seen > 0; // a finger may be on it, if it was in view
770
+ if (into === frame) return mouseIn(frame, d); // a mouse that went into it
771
+ return p.kind === 'host' && within(frame, p, d); // or one the page sees over it (it lies under something of the page's)
772
+ };
773
+
774
+ const onScroll = (ev: Event) => {
775
+ if (stopped || (ev.target !== doc && ev.target !== root())) return;
776
+ const to = win.scrollY;
777
+ const h = root().scrollHeight;
778
+ const fh = frame.getBoundingClientRect().height;
779
+ // Our own move, putting the page back. Unless it has been moved again
780
+ // before this was heard of: that is accounted for like any other move,
781
+ // from where we had put it.
782
+ const ours = restoring !== undefined && Math.abs(to - restoring) < 1;
783
+ if (restoring !== undefined) y = restoring;
784
+ restoring = undefined;
785
+ if (ours || to === y) {
786
+ y = to;
787
+ docHeight = h;
788
+ frameHeight = fh;
789
+ seen = visible();
790
+ return;
791
+ }
792
+ const t = now();
793
+ const from = y;
794
+ const d = to - from;
795
+ const against = lastDir !== 0 && t - lastDirAt < cfg.inputMs && Math.sign(d) !== lastDir;
796
+ // A jump in one go is not how a wheel or a finger moves a page: what it
797
+ // put under the pointer stays untouchable for longer.
798
+ const hush = Math.abs(d) > cfg.jumpPx ? cfg.jumpGateMs : cfg.gateMs;
799
+ let verdict: ScrollMove['verdict'];
800
+ if (t < expected) verdict = 'own';
801
+ else if (h !== docHeight && Math.abs(d) <= Math.abs(h - docHeight) + cfg.slack) {
802
+ verdict = 'layout';
803
+ // The tile's own box changed with it: this may be its doing after all.
804
+ if (fh !== frameHeight) gate?.arm(hush);
805
+ }
806
+ else if (byUser(d, t)) verdict = 'user';
807
+ else if (cannotTell(d)) verdict = 'ambiguous';
808
+ else if (near()) verdict = 'tile';
809
+ else verdict = 'elsewhere';
810
+ docHeight = h;
811
+ frameHeight = fh;
812
+ const take = verdict === 'tile' && cfg.undo;
813
+ // Asked before the page is put back: it is where the move left things
814
+ // that says which tiles can have made it.
815
+ const mine = take && alone();
816
+ // Whether the page is back where it was, to the pixel: nothing has then
817
+ // moved under the pointer.
818
+ let whole = false;
819
+ if (take) {
820
+ undone++;
821
+ credit = 0;
822
+ tookBackAt = t;
823
+ win.scrollTo({ top: Math.max(0, Math.min(from, h - win.innerHeight)), left: win.scrollX, behavior: 'instant' });
824
+ restoring = win.scrollY;
825
+ whole = Math.abs(restoring - from) < 1;
826
+ }
827
+ else {
828
+ y = to;
829
+ seen = visible();
830
+ }
831
+ // What a move left standing slid under the pointer takes no press for a
832
+ // moment. One that was put back whole slid nothing anywhere: were it to
833
+ // close the gate, a tile that kept asking would keep the page from
834
+ // taking any press at all.
835
+ if (verdict === 'ambiguous' || verdict === 'elsewhere' || (verdict === 'tile' && !take)) gate?.arm(hush);
836
+ else if (take && !whole) gate?.arm(cfg.gateMs);
837
+ options.onMove?.({ from, to, verdict, undone: take });
838
+ // Taken back whoever made it. Held against this tile only where no
839
+ // other can have: a tile is not stopped for what its neighbour did.
840
+ if (!mine || !against) return;
841
+ pulls = pulls.filter(p => t - p < cfg.withinMs);
842
+ pulls.push(t);
843
+ if (pulls.length < cfg.pulls) return;
844
+ pulls = [];
845
+ options.onAbuse?.('scroll', undone);
846
+ if (options.stop !== false) halt(tile, frame, 'scroll');
847
+ };
848
+
849
+ // The page's own scrolling, declared for it: the calls a page scrolls
850
+ // itself with are wrapped so that each says so first. Only when asked: a
851
+ // page that would rather not have them touched calls expect() itself.
852
+ const undeclare = options.own === 'patch' ? declareOwn(win, () => { expected = Math.max(expected, now() + 1000); }) : undefined;
853
+
854
+ const opts = { capture: true, passive: true };
855
+ const onResize = () => {
856
+ docHeight = root().scrollHeight;
857
+ frameHeight = frame.getBoundingClientRect().height;
858
+ seen = visible();
859
+ y = win.scrollY;
860
+ };
861
+ doc.addEventListener('wheel', onWheel, opts);
862
+ doc.addEventListener('keydown', onKey, true);
863
+ doc.addEventListener('touchstart', onTouchStart, opts);
864
+ doc.addEventListener('touchmove', onTouchMove, opts);
865
+ doc.addEventListener('touchend', onTouchEnd, opts);
866
+ doc.addEventListener('pointerdown', onDown, opts);
867
+ doc.addEventListener('pointerup', onUp, opts);
868
+ win.addEventListener('hashchange', onNav);
869
+ win.addEventListener('popstate', onNav);
870
+ win.addEventListener('resize', onResize);
871
+ doc.addEventListener('scroll', onScroll, opts);
872
+ const stop = () => {
873
+ if (stopped) return;
874
+ stopped = true;
875
+ undeclare?.();
876
+ offPointer();
877
+ others.delete(frame);
878
+ doc.removeEventListener('wheel', onWheel, opts);
879
+ doc.removeEventListener('keydown', onKey, true);
880
+ doc.removeEventListener('touchstart', onTouchStart, opts);
881
+ doc.removeEventListener('touchmove', onTouchMove, opts);
882
+ doc.removeEventListener('touchend', onTouchEnd, opts);
883
+ doc.removeEventListener('pointerdown', onDown, opts);
884
+ doc.removeEventListener('pointerup', onUp, opts);
885
+ doc.removeEventListener('scroll', onScroll, opts);
886
+ win.removeEventListener('hashchange', onNav);
887
+ win.removeEventListener('popstate', onNav);
888
+ win.removeEventListener('resize', onResize);
889
+ tile.removeEventListener('close', stop);
890
+ };
891
+ // A tile that is closed has no frame left to guard.
892
+ tile.addEventListener('close', stop);
893
+ return {
894
+ expect (ms = 1000) { expected = Math.max(expected, now() + ms); },
895
+ stop,
896
+ };
897
+ }
898
+
899
+ // ---------------------------------------------------------------- picking a tile
900
+
901
+ export interface EngageOptions {
902
+ /**
903
+ * The element of the host's that holds the frame, and nothing else: the
904
+ * layer is put in it, over the frame. The frame's parent by default. It
905
+ * has to be there before the frame is put in it, since moving a frame
906
+ * reloads it.
907
+ */
908
+ wrapper?: HTMLElement;
909
+ /** What the layer is called for those who do not see it. Default: "Use this tile". */
910
+ label?: string;
911
+ /** Start with the tile picked, as for one the user has just started themselves. Default: not picked. */
912
+ start?: 'idle' | 'engaged';
913
+ /** Called when the tile is picked (`true`) or let go of (`false`), and why. */
914
+ onChange?: (engaged: boolean, why: 'picked' | 'started' | 'pressed elsewhere' | 'escape' | 'out of view' | 'released') => void;
915
+ }
916
+
917
+ export interface EngageControl extends GuardControl {
918
+ /** The layer's element, for a host to style or to say something on. */
919
+ readonly layer: HTMLElement;
920
+ /** Whether the user has picked the tile. */
921
+ readonly engaged: boolean;
922
+ /** Lets go of the tile: the layer is back over it. */
923
+ release (): void;
924
+ }
925
+
926
+ /** The class of the layer's element. */
927
+ export const ENGAGE_CLASS = 'tile-engage';
928
+
929
+ /**
930
+ * "Press to use": until the user picks the tile, a layer of the host's lies
931
+ * over it. The tile runs and shows, and gets no input. A wheel or a finger
932
+ * on it scrolls the page, the page sees every pointer that crosses it, and
933
+ * focus arriving in the frame is by definition the tile's own doing. A
934
+ * press on the layer picks the tile (that press is spent on it: nothing can
935
+ * hand an event on to another origin's frame). A press anywhere else on the
936
+ * page, the tile leaving the viewport, or Escape, puts the layer back.
937
+ *
938
+ * Until it is picked the tile is not a stop on the way through the page with
939
+ * Tab either (its frame has `tabindex="-1"` meanwhile): the layer is, right
940
+ * after it, and Enter or Space there picks the tile and goes into it.
941
+ *
942
+ * The layer paints, though too faintly to see: a block that paints nothing
943
+ * does not take a press over a frame. `stop()` takes it away for good.
944
+ */
945
+ export function engage (tile: Tile, frame: HTMLIFrameElement, options: EngageOptions = {}): EngageControl {
946
+ const doc = frame.ownerDocument;
947
+ const win = doc.defaultView as Window & typeof globalThis;
948
+ const wrapper = options.wrapper ?? frame.parentElement;
949
+ if (!wrapper) throw new Error('engage() needs the frame to be in an element that holds it.');
950
+ const position = win.getComputedStyle(wrapper).position;
951
+ if (!position || position === 'static') wrapper.style.position = 'relative';
952
+ const layer = doc.createElement('div');
953
+ layer.className = ENGAGE_CLASS;
954
+ layer.setAttribute('role', 'button');
955
+ layer.setAttribute('tabindex', '0');
956
+ layer.setAttribute('aria-label', options.label ?? 'Use this tile');
957
+ layer.style.cssText = 'position:absolute;inset:0;z-index:1;background:rgba(127,127,127,0.03);cursor:pointer;';
958
+ let engaged = false;
959
+ let stopped = false;
960
+ // A tile that is not picked is not to be tabbed into: Tab would take the
961
+ // keyboard past the layer and into it. (With a guard on the keyboard that
962
+ // would be given back, every time, and count against the tile.)
963
+ const tabindex = frame.getAttribute('tabindex');
964
+ const reach = (on: boolean) => {
965
+ if (!on) frame.setAttribute('tabindex', '-1');
966
+ else if (tabindex === null) frame.removeAttribute('tabindex');
967
+ else frame.setAttribute('tabindex', tabindex);
968
+ };
969
+ const set = (on: boolean, why: Parameters<NonNullable<EngageOptions['onChange']>>[1]) => {
970
+ if (on === engaged || stopped) return;
971
+ engaged = on;
972
+ layer.style.display = on ? 'none' : 'block';
973
+ reach(on);
974
+ if (!on && holds(frame)) frame.blur();
975
+ options.onChange?.(on, why);
976
+ };
977
+ layer.addEventListener('click', (ev) => { if (ev.isTrusted) set(true, 'picked'); });
978
+ layer.addEventListener('keydown', (ev) => {
979
+ if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
980
+ ev.preventDefault();
981
+ set(true, 'picked');
982
+ frame.focus();
983
+ });
984
+ const onDown = (ev: Event) => { if (ev.isTrusted && engaged && !wrapper.contains((ev.composedPath?.()[0] ?? ev.target) as Node)) set(false, 'pressed elsewhere'); };
985
+ const onKey = (ev: KeyboardEvent) => { if (ev.isTrusted && engaged && ev.key === 'Escape') set(false, 'escape'); };
986
+ doc.addEventListener('pointerdown', onDown, true);
987
+ doc.addEventListener('keydown', onKey, true);
988
+ const seen = typeof win.IntersectionObserver === 'function'
989
+ ? new win.IntersectionObserver((entries) => { if (entries.some(en => !en.isIntersecting)) set(false, 'out of view'); })
990
+ : undefined;
991
+ seen?.observe(frame);
992
+ wrapper.append(layer);
993
+ reach(false);
994
+ if (options.start === 'engaged') set(true, 'started');
995
+ const stop = () => {
996
+ if (stopped) return;
997
+ stopped = true;
998
+ reach(true);
999
+ doc.removeEventListener('pointerdown', onDown, true);
1000
+ doc.removeEventListener('keydown', onKey, true);
1001
+ seen?.disconnect();
1002
+ layer.remove();
1003
+ tile.removeEventListener('close', stop);
1004
+ };
1005
+ // A tile that is closed has no frame left to lay anything over.
1006
+ tile.addEventListener('close', stop);
1007
+ return {
1008
+ layer,
1009
+ get engaged () { return engaged; },
1010
+ release () { set(false, 'released'); },
1011
+ stop,
1012
+ };
1013
+ }