@dasl/tile-loader 3.1.0 → 4.0.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 (92) hide show
  1. package/README.md +1463 -36
  2. package/dist/at.d.ts +126 -12
  3. package/dist/at.d.ts.map +1 -1
  4. package/dist/at.js +582 -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 +82 -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 +342 -0
  15. package/dist/guard.d.ts.map +1 -0
  16. package/dist/guard.js +1544 -0
  17. package/dist/guard.js.map +1 -0
  18. package/dist/index.d.ts +416 -16
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +999 -74
  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/lib/tab-order.d.ts +16 -0
  55. package/dist/lib/tab-order.d.ts.map +1 -0
  56. package/dist/lib/tab-order.js +66 -0
  57. package/dist/lib/tab-order.js.map +1 -0
  58. package/dist/link.d.ts +110 -13
  59. package/dist/link.d.ts.map +1 -1
  60. package/dist/link.js +336 -43
  61. package/dist/link.js.map +1 -1
  62. package/dist/memory.d.ts +1 -0
  63. package/dist/memory.d.ts.map +1 -1
  64. package/dist/memory.js +5 -0
  65. package/dist/memory.js.map +1 -1
  66. package/dist/mount.d.ts +54 -0
  67. package/dist/mount.d.ts.map +1 -0
  68. package/dist/mount.js +289 -0
  69. package/dist/mount.js.map +1 -0
  70. package/dist/size.d.ts +43 -2
  71. package/dist/size.d.ts.map +1 -1
  72. package/dist/size.js +296 -15
  73. package/dist/size.js.map +1 -1
  74. package/package.json +13 -3
  75. package/src/at.ts +590 -84
  76. package/src/car.ts +79 -16
  77. package/src/content-scheme.ts +38 -7
  78. package/src/guard.ts +1659 -0
  79. package/src/index.ts +1124 -74
  80. package/src/lib/cid.ts +65 -0
  81. package/src/lib/defaults.ts +12 -0
  82. package/src/lib/destinations.ts +79 -0
  83. package/src/lib/drisl.ts +160 -0
  84. package/src/lib/errors.ts +111 -0
  85. package/src/lib/fetching.ts +138 -0
  86. package/src/lib/limits.ts +61 -0
  87. package/src/lib/pointer.ts +290 -0
  88. package/src/lib/tab-order.ts +66 -0
  89. package/src/link.ts +365 -48
  90. package/src/memory.ts +5 -0
  91. package/src/mount.ts +359 -0
  92. package/src/size.ts +304 -16
package/src/guard.ts ADDED
@@ -0,0 +1,1659 @@
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
+ // The frame is out of the tab order then, so that nobody tabbing down the
15
+ // page ends up in the tile by chance, and the guard puts a stop of its own
16
+ // in its place, which the user tabs to and presses, and their next Tab
17
+ // takes them in.
18
+ //
19
+ // A tile can also scroll the page it is in: asking the browser to bring an
20
+ // element of its own into view scrolls every scroller above it, the page's
21
+ // document included. That takes the page to the tile, holds it there, or
22
+ // slides a control of the page's under a pointer that has not moved.
23
+ // `guardScroll` accounts for every move of the page and takes back the
24
+ // tile's; `clickGate` keeps what an unexplained move slid under the pointer
25
+ // from taking a press for a moment.
26
+ //
27
+ // Giving back what a tile took is a contest with one that takes it again, and
28
+ // the tile is the faster. So a tile that keeps at it is stopped: hidden at
29
+ // once, closed, and the host told why (a `stopped` event on the tile, with a
30
+ // `reason` of `focus` or `scroll`). `stop: false` has a guard only report.
31
+ //
32
+ // And a tile takes whatever input lands on it. On a touch screen that is the
33
+ // finger that was scrolling the feed: a tile can keep the page from moving
34
+ // for as long as the finger started on it. `engage` puts a layer of the
35
+ // host's over the tile until the user picks it, so that until then the tile
36
+ // runs and shows, and gets no input at all.
37
+ //
38
+ // A guard listens to the page, so unlike the modules that only listen to the
39
+ // tile it does not go when the tile is dropped: it stops when the tile is
40
+ // closed (`tile.close()`), or when it is told to (`stop()`).
41
+
42
+ import type { Tile } from './index.js';
43
+ import { withDefaults } from './lib/defaults.js';
44
+ import { SHIELD_CLASS, watchPointer } from './lib/pointer.js';
45
+ import { holdOut, letIn } from './lib/tab-order.js';
46
+
47
+ const now = () => performance.now();
48
+ const editable = (el: Element | null): boolean => Boolean(el) && ((el as HTMLElement).isContentEditable || /^(input|textarea|select)$/.test(el?.localName || ''));
49
+ // The element that has the keyboard, looked for through shadow trees.
50
+ const focused = (doc: Document): Element | null => {
51
+ let el = doc.activeElement;
52
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
53
+ return el;
54
+ };
55
+ // Whether the keyboard is in `frame`. Asked of the tree the frame is in, so
56
+ // that a frame in a shadow tree is found as well.
57
+ const holds = (frame: Element): boolean => (frame.getRootNode() as Document | ShadowRoot).activeElement === frame;
58
+
59
+ export interface GuardControl {
60
+ /** Stops guarding. What the tile does from then on is left as it is. */
61
+ stop (): void;
62
+ }
63
+
64
+ /** What `guardFocus` gives its host. */
65
+ export interface FocusGuardControl extends GuardControl {
66
+ /**
67
+ * Puts the keyboard in the tile for the host, as the user asked: what a
68
+ * control of the host's own calls, for someone who goes into a tile with
69
+ * the keyboard alone (a frame out of the tab order has no other way in,
70
+ * where the guard has no stop of its own in its place: see `tabOrder`).
71
+ * The page sees no Tab then, and the user did not act in the tile, so
72
+ * focus the host gave the frame with `frame.focus()` would be taken for a
73
+ * script's and given back. Given this way it is the user's, as if they
74
+ * had tabbed in. Call it from that control's own handler: the guard takes
75
+ * the host at its word. From a key, only Chrome lets a page put the
76
+ * keyboard in a frame: Firefox and WebKit leave it where it was, and only
77
+ * a press goes in there. The guard's own stop does not go this way.
78
+ */
79
+ focus (): void;
80
+ }
81
+
82
+ /**
83
+ * A guard stopped a tile, because it kept taking the keyboard (`focus`) or
84
+ * the page (`scroll`) from the user. Raised on the tile as a `stopped` event,
85
+ * as the dock's are; the tile is closed, and a host that wants it back
86
+ * renders it again.
87
+ */
88
+ export interface GuardStoppedEvent extends Event {
89
+ reason: 'focus' | 'scroll';
90
+ }
91
+
92
+ // The tiles a guard is in the middle of stopping.
93
+ const halting = new WeakSet<Tile>();
94
+
95
+ // Stops a tile that would not stop. It is out of the way at once: a frame
96
+ // that is not rendered takes no focus and scrolls nothing. Its frame stays in
97
+ // the document for the moment closing takes, since a tile's runtime needs it
98
+ // there to clean up after itself; the guards go on until it is gone.
99
+ function halt (tile: Tile, frame: HTMLElement, reason: GuardStoppedEvent['reason']) {
100
+ if (halting.has(tile)) return;
101
+ halting.add(tile);
102
+ frame.style.display = 'none';
103
+ tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
104
+ // Rendered again, it is a tile like any other.
105
+ tile.close().finally(() => halting.delete(tile));
106
+ }
107
+
108
+ const DOCK_STATUS = 'tiles-dock-status';
109
+ const DOCK_KEYBOARD = 'tiles-dock-keyboard';
110
+
111
+ // What the tile's dock says of the user and that tile, asked for when it
112
+ // matters (see `DockStamp`): whether the user has just pressed or typed
113
+ // inside the tile (`activated`), and, from a dock that was asked to watch,
114
+ // whether they had when the keyboard came into it (`arrivalActivated`).
115
+ // `ask()` resolves `undefined` when no answer comes within `ms`. A loading
116
+ // server from before its dock knew the question never answers; `answers`
117
+ // says whether this one ever has. `watch()` asks the dock to watch the
118
+ // keyboard, or to stop, and `entered()` tells it that the user went into the
119
+ // tile themselves (`into`: with a press, and the keyboard is to go on into
120
+ // the tile from the dock's own page, where the way in puts it), on the same
121
+ // question, which a dock never passes on to the tile: one from before it
122
+ // knew of watching answers it, and that is all. A
123
+ // dock that watches also says, unasked, when it finds the keyboard come into
124
+ // the tile with no one acting there: `refused` is called then. All of it is
125
+ // only ever used to refuse, so that what is not the dock's own gains
126
+ // nothing. Where a no of the dock's is only its best guess (someone did act
127
+ // in the tile, and it may have been the user), it says so (`unsure`), and
128
+ // that only ever spares the tile being counted for it.
129
+ interface DockAnswer {
130
+ activated: boolean;
131
+ arrivalActivated?: boolean | null;
132
+ unsure?: boolean;
133
+ }
134
+ function dockStatus (tile: Tile, frame: HTMLIFrameElement, ms: number, refused: (unsure: boolean) => void) {
135
+ const win = frame.ownerDocument.defaultView as Window;
136
+ const origin = new URL(tile.getLoadSource()).origin;
137
+ const waiting = new Map<string, (answer: DockAnswer | undefined) => void>();
138
+ let n = 0;
139
+ let answers = false;
140
+ const onMessage = (ev: MessageEvent) => {
141
+ if (ev.source !== frame.contentWindow || ev.origin !== origin) return;
142
+ if (ev.data?.action === DOCK_KEYBOARD) {
143
+ if (ev.data.payload?.arrivalActivated === false) refused(ev.data.payload.unsure === true);
144
+ return;
145
+ }
146
+ if (ev.data?.action !== DOCK_STATUS) return;
147
+ const { id, activated, arrivalActivated, unsure } = ev.data.payload ?? {};
148
+ if (typeof activated !== 'boolean') return;
149
+ answers = true;
150
+ const resolve = waiting.get(id);
151
+ if (!resolve) return;
152
+ waiting.delete(id);
153
+ resolve({ activated, arrivalActivated: typeof arrivalActivated === 'boolean' ? arrivalActivated : null, unsure: unsure === true });
154
+ };
155
+ win.addEventListener('message', onMessage);
156
+ return {
157
+ get answers () { return answers; },
158
+ // (`fromPage`: the keyboard has just left the page, and what the dock finds in the tile has just come;
159
+ // `at` says when, by the clock the dock has too, so that it can tell when our word reached it late.)
160
+ watch (on: boolean, fromPage: boolean) { tile.post(DOCK_STATUS, { id: `w${++n}`, watch: on, ...(fromPage ? { fromPage, at: Date.now() } : {}) }); },
161
+ entered (into: boolean) { tile.post(DOCK_STATUS, { id: `e${++n}`, entered: true, ...(into ? { into } : {}) }); },
162
+ ask (): Promise<DockAnswer | undefined> {
163
+ const id = `d${++n}`;
164
+ return new Promise((resolve) => {
165
+ waiting.set(id, resolve);
166
+ win.setTimeout(() => { if (waiting.delete(id)) resolve(undefined); }, ms);
167
+ tile.post(DOCK_STATUS, { id });
168
+ });
169
+ },
170
+ stop () { win.removeEventListener('message', onMessage); },
171
+ };
172
+ }
173
+
174
+ // ---------------------------------------------------------------- the keyboard
175
+
176
+ /** The numbers `guardFocus` goes by. First guesses, all of them. */
177
+ export interface FocusGuardOptions {
178
+ /** How long after a Tab pressed on the page focus arriving in the tile is the user tabbing in, in milliseconds. */
179
+ tabMs?: number;
180
+ /** 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. */
181
+ typingMs?: number;
182
+ /** How many times the tile may take the keyboard, within `withinMs`, before that is abuse. */
183
+ grabs?: number;
184
+ /** The time those are counted over, in milliseconds. */
185
+ withinMs?: number;
186
+ /**
187
+ * How long the tile's dock gets to say whether the user acted in the tile,
188
+ * in milliseconds. It answers in a few; what the user types while it has
189
+ * not goes to the tile.
190
+ */
191
+ dockMs?: number;
192
+ /** How often the page is looked at for focus that arrived unannounced, in milliseconds. */
193
+ pollMs?: number;
194
+ /**
195
+ * Called when focus was given back: `script` when the page saw nothing
196
+ * that would make it the user's doing, `dock` when the tile's dock said
197
+ * the user had not acted in the tile.
198
+ */
199
+ onReturn?: (why: 'script' | 'dock') => void;
200
+ /** Called when the tile has taken the keyboard `grabs` times within `withinMs`, with how often it has been given back in all. */
201
+ onAbuse?: (what: 'focus', count: number) => void;
202
+ /** Stop the tile then (the default), or only report it (`false`). */
203
+ stop?: boolean;
204
+ /**
205
+ * Whether the user has picked the tile, for a host that has it wait to be
206
+ * picked (`engage`): focus arriving in a tile that is not picked is never
207
+ * the user's doing.
208
+ */
209
+ engaged?: () => boolean;
210
+ /**
211
+ * What a no of the dock's that is only its best guess does: one where the
212
+ * user did act in the tile or on a page of the dock's, and may have
213
+ * pressed in it (a slow device busy loading another tile, say). By
214
+ * default (`true`) the keyboard is given back, that is not counted against
215
+ * the tile, and a layer of the page's lies over the tile until the user
216
+ * picks it, with a press or Enter or Space on it, which puts the keyboard
217
+ * in the tile as `focus()` does, or until the dock's no is over (what it
218
+ * went by has run out with the keyboard out of the tile), when it lifts on
219
+ * its own. Until then the keyboard coming into the tile is never the
220
+ * user's doing, and is given back and counted. Such a no in the `spareMs`
221
+ * after a layer lifted on its own is counted too, and has a layer as well.
222
+ * `false`: given back and counted, as any other no of the dock's.
223
+ */
224
+ pick?: boolean;
225
+ /**
226
+ * How long after the layer lifted on its own a no of the dock's that is
227
+ * only its best guess is counted all the same, in milliseconds (see
228
+ * `pick`): a tile that can have its dock's nos taken for guesses is spared
229
+ * one giving back for each time the user picks it, and at most one in
230
+ * this time otherwise.
231
+ */
232
+ spareMs?: number;
233
+ /**
234
+ * What the layer says, to those who see it and to those who do not (it is
235
+ * the name of the button it is). Default: "Tap or click to use".
236
+ */
237
+ pickLabel?: string;
238
+ /**
239
+ * Where the frame is in the tab order while the guard runs. `'stop'` (the
240
+ * default): out of it, so that someone tabbing down the page passes over
241
+ * the tile, with a stop of the guard's own in its place, right before the
242
+ * frame (`ENTER_CLASS`): Enter or Space there lets the frame into the tab
243
+ * order for the user's next Tab, which takes them into the tile, and the
244
+ * stop says so (`tabLabel`). It cannot be seen until it has the keyboard,
245
+ * and then lies over the tile, taking no press, and says what it is for
246
+ * (`enterLabel`).
247
+ * `'out'`: out of it, and the way in is the host's own (`focus()`).
248
+ * `'keep'`: as its host made it; a frame in the tab order then has Tab
249
+ * take the user into it. The frame gets back what its host gave it when
250
+ * the guard stops. A tabindex the host gave the frame itself is not a
251
+ * `'keep'`.
252
+ */
253
+ tabOrder?: 'stop' | 'out' | 'keep';
254
+ /**
255
+ * What the stop in the frame's place says (see `tabOrder`), to those who
256
+ * see it and to those who do not. Default: "Use the keyboard in" and the
257
+ * tile's name, or "this tile" for a tile with none.
258
+ */
259
+ enterLabel?: string;
260
+ /**
261
+ * What the stop says once the user has pressed it, while their next Tab
262
+ * takes them into the tile (see `tabOrder`). Default: "Press Tab to go in".
263
+ */
264
+ tabLabel?: string;
265
+ }
266
+
267
+ /** The class of the layer `guardFocus` lays over a tile for the user to pick it, besides `ENGAGE_CLASS`. */
268
+ export const PICK_CLASS = 'tile-pick';
269
+ /** The class of what the layer says, inside it, and of what the stop in the frame's place says. */
270
+ export const PICK_LABEL_CLASS = 'tile-pick-label';
271
+ /** The class of the stop `guardFocus` puts in the frame's place in the tab order (see `tabOrder`). */
272
+ export const ENTER_CLASS = 'tile-enter';
273
+
274
+ // What the layer looks like where its host gives it no look of its own: a
275
+ // ring round the tile, and what it says in the middle, so that a user whose
276
+ // press seemed to do nothing sees that the tile waits for them. The stop in
277
+ // the frame's place looks the same while it has the keyboard, the only time
278
+ // it can be seen. Every rule here weighs nothing (`:where`), so that any
279
+ // rule of the host's for `.tile-pick`, `.tile-enter` or `.tile-pick-label`
280
+ // wins. Given once to each document, as a sheet of its own where the browser
281
+ // has those (a page whose policy refuses inline style does not refuse one),
282
+ // else as a style element. And once to each shadow tree a frame is in, where
283
+ // the layer and the stop go too: no rule of the document's reaches into one.
284
+ const PICK_LOOK = `
285
+ :where(.${PICK_CLASS}) { display: flex; align-items: center; justify-content: center; box-sizing: border-box;
286
+ box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.6), inset 0 0 0 4px rgba(255, 255, 255, 0.75); }
287
+ :where(.${PICK_CLASS}:focus-visible) { outline: 3px solid Highlight; outline-offset: -3px; }
288
+ :where(.${ENTER_CLASS}) { display: flex; align-items: center; justify-content: center; box-sizing: border-box;
289
+ box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.6), inset 0 0 0 4px rgba(255, 255, 255, 0.75); }
290
+ :where(.${ENTER_CLASS}:focus-visible) { outline: 3px solid Highlight; outline-offset: -3px; }
291
+ :where(.${PICK_LABEL_CLASS}) { max-width: calc(100% - 16px); padding: 6px 12px; border-radius: 999px; box-sizing: border-box;
292
+ background: rgba(0, 0, 0, 0.78); color: #fff; font: 600 13px/1.3 system-ui, sans-serif; text-align: center;
293
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; pointer-events: none; }
294
+ `;
295
+ const looked = new WeakSet<Document | ShadowRoot>();
296
+ function pickLook (doc: Document, root: Document | ShadowRoot) {
297
+ if (looked.has(root)) return;
298
+ looked.add(root);
299
+ const win = doc.defaultView as (Window & typeof globalThis) | null;
300
+ try {
301
+ if (win && 'adoptedStyleSheets' in root && typeof win.CSSStyleSheet?.prototype.replaceSync === 'function') {
302
+ const sheet = new win.CSSStyleSheet();
303
+ sheet.replaceSync(PICK_LOOK);
304
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
305
+ return;
306
+ }
307
+ }
308
+ catch { /* a style element, then */ }
309
+ const style = doc.createElement('style');
310
+ style.textContent = PICK_LOOK;
311
+ // First, so that the host's own sheets come after it.
312
+ (root === doc ? doc.head : root)?.prepend(style);
313
+ }
314
+
315
+ /** `guardFocus`'s numbers where a host gives none. */
316
+ export const FOCUS_GUARD: Readonly<Record<'tabMs' | 'typingMs' | 'grabs' | 'withinMs' | 'dockMs' | 'pollMs' | 'spareMs', number>> = Object.freeze({
317
+ tabMs: 400,
318
+ typingMs: 1000,
319
+ grabs: 3,
320
+ withinMs: 10000,
321
+ dockMs: 150,
322
+ pollMs: 100,
323
+ spareMs: 60000,
324
+ });
325
+ // How often, at most, a guard with its layer up asks the dock whether its no
326
+ // is over (see `settle`). A guess.
327
+ const SETTLE_MS = 500;
328
+ // How long, at most, a frame is let into the tab order for the Tab from its
329
+ // stop, once the user has pressed the stop (see `enter`). A guess.
330
+ const LET_IN_MS = 10000;
331
+ // How much of a tile's name its stop says, at most, in characters, the
332
+ // ellipsis included. A guess.
333
+ const NAME_MAX = 60;
334
+
335
+ /**
336
+ * Gives back keyboard focus that a tile's script took, and leaves it with a
337
+ * user who went into the tile.
338
+ *
339
+ * Focus arriving in the frame is the user's doing when they went in by the
340
+ * host's own way in (a control of its own calling `focus()`), tabbed into
341
+ * it (from the guard's stop in the frame's place in the tab order, which
342
+ * lets the frame in for that Tab, or into a frame the host keeps in the tab
343
+ * order: see `tabOrder`), or pressed on it. The page sees
344
+ * the Tab key. It never sees the press: only that a mouse is over the
345
+ * frame, and not even that for a finger. So focus
346
+ * stays in the tile when a Tab was just pressed on the page; otherwise, when
347
+ * a mouse is in the frame (or the user has none, or, on a screen that takes
348
+ * fingers, the guard has seen no pointer yet and the keyboard came straight
349
+ * from the page) and they were not typing in a field of the page a moment
350
+ * ago, the tile's dock is asked, which knows
351
+ * whether the user pressed or typed inside this tile. In every other case,
352
+ * and when the dock says no, focus goes back to what had it when the tile
353
+ * took it: to the page alone when nothing of the page's had it then, and
354
+ * never to something the user had left.
355
+ *
356
+ * While the keyboard is in a frame of the page's, where the page cannot see
357
+ * it move, the guard has the tile's dock watch it come into the tile, and a
358
+ * dock that found it come in with no one acting there says no, at once and
359
+ * for as long as what the user typed into the tile before it was given back
360
+ * can make them seem to have acted there.
361
+ *
362
+ * Where the dock's no is only its best guess (someone did act in the tile,
363
+ * and it may have been the user pressing in it), the keyboard is given back
364
+ * all the same, but that is not counted against the tile: a layer of the
365
+ * page's lies over it until the user picks it, which puts the keyboard in,
366
+ * or until the dock's no is over (see `pick`).
367
+ *
368
+ * A dock that has answered before and now does not is taken to say no: its
369
+ * silence is not to be had by keeping it busy. One that has never answered
370
+ * (an older loading server's) leaves the guard with what the page can see:
371
+ * a mouse resting on the tile, or a finger, cannot be told from a press.
372
+ *
373
+ * Giving it back does not win against a tile that keeps taking it: a tile
374
+ * that does so `grabs` times within `withinMs` is reported (`onAbuse`) and
375
+ * stopped (see `GuardStoppedEvent`), unless told otherwise (`stop: false`).
376
+ */
377
+ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: FocusGuardOptions = {}): FocusGuardControl {
378
+ // A host that meant to keep the frame in the tab order, and said so in a
379
+ // way the guard does not know, would be left believing in a Tab key that
380
+ // passes over the tile. So that throws, before anything is set up.
381
+ const tabOrder = options.tabOrder ?? 'stop';
382
+ if (tabOrder !== 'stop' && tabOrder !== 'out' && tabOrder !== 'keep') throw new Error(`guardFocus() takes 'stop', 'out' or 'keep' for where the frame is in the tab order, not ${JSON.stringify(tabOrder)}.`);
383
+ const doc = frame.ownerDocument;
384
+ const win = doc.defaultView as Window;
385
+ const pointer = watchPointer(doc);
386
+ const cfg = withDefaults(FOCUS_GUARD, options);
387
+ const dock = dockStatus(tile, frame, cfg.dockMs, (unsure) => onRefused(unsure));
388
+ // Whether this dock answers at all is learnt while nothing is at stake:
389
+ // now, and when the tile's runtime says it is up, before the tile runs.
390
+ const probe = () => { dock.ask(); };
391
+ probe();
392
+ tile.addEventListener('load', probe);
393
+ // What had the keyboard before the tile did. Nothing of the page's, when
394
+ // the guard is made with the keyboard in another frame of the page's (the
395
+ // user is in a tile, and the page adds this one): given back there, it
396
+ // would be put in a frame by the page's own script, and Chrome then goes on
397
+ // naming that frame as having it after it has gone elsewhere.
398
+ let holder = focused(doc) as HTMLElement | null;
399
+ if (holder === frame || holder === doc.body || framed(holder)) holder = null;
400
+ // Whether this window has the keyboard. Which element is the active one is
401
+ // not enough to go by: that says which element WOULD have it. The window's
402
+ // own focus and blur events say whether a frame inside it has taken it.
403
+ // To begin with there is only the active element to go by: with a frame
404
+ // active the window does not have it, though the document "has focus"
405
+ // then too, and no blur will say so when this tile takes it from there.
406
+ let winFocused = doc.hasFocus() && !holds(frame) && !framed(focused(doc));
407
+ // Whether the keyboard, when it last left the page, went from the page
408
+ // itself (its window said so) and not from another frame of the page's.
409
+ let straight = winFocused;
410
+ let inTile = false;
411
+ let accepted = false;
412
+ let tabbed = false; // accepted for what the page saw: a Tab, or its own way in
413
+ let returning = false; // a giving back is under way
414
+ let lastTab = -Infinity;
415
+ let into = false; // the way in that set lastTab was taken with a press (see `focus`)
416
+ let lastTyped = -Infinity;
417
+ let returned = 0;
418
+ let round = 0; // which giving back is under way: one that was overtaken does nothing more
419
+ let grabs: number[] = [];
420
+ let stopped = false;
421
+ // The layer the user picks the tile on, once a no of the dock's was only
422
+ // its best guess (see `pick`), and how to put back what it took to lay it
423
+ // over the frame.
424
+ let layer: HTMLElement | undefined;
425
+ let unlay: (() => void) | undefined;
426
+ let liftedAt = -Infinity; // when the layer last lifted on its own
427
+ let settling = false; // the dock is being asked whether its no is over
428
+ let settledAt = -Infinity;
429
+ // Whether the dock is watching the keyboard come into the tile. It is
430
+ // asked to while the keyboard is in a frame of the page's (this tile's or
431
+ // another's), which is when the page cannot see it move from one to the
432
+ // next: not while it is on the page, which the page sees at once, nor
433
+ // while the window does not have it at all, and never once stopped.
434
+ // `fromPage`: the window has just said that the keyboard left it.
435
+ let watched = false;
436
+ const watch = (fromPage = false) => {
437
+ const want = !stopped && !winFocused && doc.hasFocus();
438
+ if (want === watched) return;
439
+ watched = want;
440
+ dock.watch(want, want && fromPage);
441
+ };
442
+
443
+ // Whether `el` is the frame, or something the frame is in (the element
444
+ // whose shadow tree it is in is all the page is told of it, where that
445
+ // tree is closed).
446
+ const around = (el: Node): boolean => {
447
+ for (let node: Node | null = frame; node; node = node.parentNode ?? (node as ShadowRoot).host ?? null) if (node === el) return true;
448
+ return false;
449
+ };
450
+ const onFocusIn = (ev: Event) => {
451
+ const target = (ev.composedPath?.()[0] ?? ev.target) as HTMLElement | null;
452
+ if (target && target !== frame) holder = target;
453
+ // The Tab that brought the user here took them to something of the
454
+ // page's, not into the tile: it explains nothing that arrives there next.
455
+ if (target && !around(target)) lastTab = -Infinity;
456
+ };
457
+ // What had the keyboard is where it goes back to only for as long as it
458
+ // still has it. A button the user pressed a while ago and then left, for
459
+ // the plain text of the page, has it no longer: put back there, the
460
+ // keyboard would be on a control its user never returned to, and their
461
+ // next Space or Enter would press it. So what lost the keyboard to nothing
462
+ // of the page's is forgotten, and the keyboard then goes back to the page
463
+ // and to no element of it.
464
+ const onNothing = (): boolean => {
465
+ const el = focused(doc);
466
+ return !el || el === doc.body || el === doc.documentElement;
467
+ };
468
+ const forget = () => {
469
+ if (winFocused && doc.hasFocus() && onNothing()) holder = null;
470
+ };
471
+ const onFocusOut = (ev: FocusEvent) => {
472
+ // To something else of the page's: `focusin` says what.
473
+ if (ev.relatedTarget) return;
474
+ const target = (ev.composedPath?.()[0] ?? ev.target) as Element | null;
475
+ // Out of the tile, and to nothing: the user left it for the page itself.
476
+ if (target === frame) holder = null;
477
+ // Out of what had it: to nothing, or into a frame (the tile's, when its
478
+ // script takes the keyboard, or another of the page's, when the user goes
479
+ // into one), and only the window's own events tell which. In a moment
480
+ // they have: `forget` sees to the first, and `check` to a frame.
481
+ else win.setTimeout(forget, 0);
482
+ };
483
+ // Whether a key picks the tile, for a host that has it wait to be picked:
484
+ // Enter or Space on the layer over it (see `engage`), which then puts the
485
+ // keyboard into the tile itself.
486
+ const picks = (ev: KeyboardEvent): boolean => {
487
+ if (ev.key !== 'Enter' && ev.key !== ' ') return false;
488
+ const target = (ev.composedPath?.()[0] ?? ev.target) as Element | null;
489
+ // Of the layers a focus guard lays, only ours: the box it is in may hold
490
+ // other tiles, each with its guard's layer beside ours.
491
+ if (target?.classList?.contains(PICK_CLASS)) return target === layer;
492
+ return Boolean(target?.classList?.contains(ENGAGE_CLASS) && target.parentNode?.contains(frame));
493
+ };
494
+ const onKey = (ev: KeyboardEvent) => {
495
+ if (!ev.isTrusted) return;
496
+ // (Picking the tile from the keyboard is going into it by the keyboard,
497
+ // as tabbing into it is; on the layer of engage's as well as ours.)
498
+ const pick = picks(ev);
499
+ if (pick) lift();
500
+ if (ev.key === 'Tab' || pick) {
501
+ // A Tab takes nobody into a frame that is out of the tab order: the
502
+ // keyboard arriving there next is not explained by it (it may have
503
+ // gone into another frame, whose tile tells this one when). As the
504
+ // frame is now, which its host may have changed. While it is let in
505
+ // for the Tab from its stop, only that Tab can take the user into it:
506
+ // forward, from the stop, which is right before it.
507
+ const tabsIn = frame.tabIndex >= 0 && (!letOut || (!ev.shiftKey && onStop()));
508
+ if (pick || tabsIn) {
509
+ lastTab = now();
510
+ spent = !pick && Boolean(letOut);
511
+ }
512
+ into = false;
513
+ }
514
+ else if (editable(focused(doc))) lastTyped = now();
515
+ };
516
+ // Whether focus that has just arrived in the frame can be the user's
517
+ // doing: `tab` when the page saw them tab, `ask` when only the dock can
518
+ // tell, `false` when it cannot be.
519
+ const judge = (): 'tab' | 'ask' | false => {
520
+ const t = now();
521
+ if (options.engaged && !options.engaged()) return false;
522
+ // Nor in one that waits for the user to pick it, after a no the dock was not sure of.
523
+ if (layer) return false;
524
+ if (t - lastTab < cfg.tabMs) return 'tab';
525
+ if (t - lastTyped < cfg.typingMs) return false;
526
+ // A finger gives the page nothing to go by.
527
+ if (!pointer.hovers || pointer.state.kind === 'none') return 'ask';
528
+ // Nor, on a screen that takes fingers, does a guard that has seen no
529
+ // pointer yet: one may have come down in the frame unseen. The dock is
530
+ // asked then only when the keyboard came straight from the page, and only
531
+ // a dock that has answered before. Found in the tile after it was in
532
+ // another frame of the page's, it may have been taken while the user was
533
+ // typing there: what they typed since is the tile's by the time the guard
534
+ // looks, and the dock would count it as their having acted in the tile.
535
+ // And a dock that has never answered would leave the tile the keyboard.
536
+ if (pointer.fingers && pointer.state.kind === 'unknown' && straight && dock.answers) return 'ask';
537
+ return pointer.inside(frame) ? 'ask' : false;
538
+ };
539
+ // Never from inside the blur that tells us: the browser is still moving
540
+ // focus into the frame then, and finishes the move after the handler
541
+ // returns, leaving the element "focused" in a window that has no keyboard.
542
+ // So it is done from a later task, checked by the window's own focus event,
543
+ // and done again if it did not take.
544
+ // `to` is what had the keyboard when the tile took it, if anything had:
545
+ // settled before the frame is blurred here, which is the keyboard leaving
546
+ // the tile for nothing.
547
+ const takeBack = (tries: number, mine: number, to: HTMLElement | null) => {
548
+ if (stopped || winFocused || mine !== round) return;
549
+ if (tries === 0 && to?.isConnected) to.focus({ preventScroll: true });
550
+ else {
551
+ frame.blur();
552
+ win.focus();
553
+ if (to?.isConnected) to.focus({ preventScroll: true });
554
+ }
555
+ if (tries < 4) win.setTimeout(() => takeBack(tries + 1, mine, to), 30);
556
+ };
557
+ // `guess`: the dock's no was only its best guess (see `pick`).
558
+ const giveBack = (why: 'script' | 'dock', guess = false) => {
559
+ returned++;
560
+ returning = true;
561
+ // Such a no is not held against the tile: it may have been the user
562
+ // pressing in it. They pick it on a layer instead, which the tile cannot
563
+ // lift, and until they do, the keyboard coming in is counted.
564
+ // (Not where a layer lifted on its own a moment ago: a tile that could
565
+ // have its dock's nos taken for guesses, and waited each time for the
566
+ // layer to go, would never be counted. It has a layer all the same.)
567
+ const spared = now() - liftedAt >= cfg.spareMs;
568
+ const counted = !(guess && lay() && spared);
569
+ if (counted) {
570
+ const t = now();
571
+ grabs = grabs.filter(g => t - g < cfg.withinMs);
572
+ grabs.push(t);
573
+ }
574
+ takeBack(0, ++round, holder);
575
+ options.onReturn?.(why);
576
+ if (!counted || grabs.length < cfg.grabs) return;
577
+ grabs = [];
578
+ options.onAbuse?.('focus', returned);
579
+ if (options.stop !== false) halt(tile, frame, 'focus');
580
+ };
581
+ // A layer of the page's over the frame, for the user to pick the tile on:
582
+ // a press or a tap on it, or Enter or Space, all of which the page sees
583
+ // and the tile cannot make. It shows that the tile waits for them, and
584
+ // says so (see `PICK_LOOK`). Put in the frame's box, right after it, which
585
+ // is made one that it is laid out against if it is not; and the frame is
586
+ // out of the tab order meanwhile, the layer in its place, as with
587
+ // `engage`. Whether it went up: not when it was up already, which the
588
+ // tile had to get past.
589
+ const lay = (): boolean => {
590
+ const box = (frame.parentElement ?? (frame.parentNode as ShadowRoot | null)?.host) as HTMLElement | null | undefined;
591
+ if (layer || options.pick === false || stopped || !box) return false;
592
+ // (In the shadow tree the frame is in, if it is in one: the layer is.)
593
+ const root = frame.getRootNode();
594
+ pickLook(doc, root instanceof (win as Window & typeof globalThis).ShadowRoot ? root : doc);
595
+ const label = options.pickLabel ?? 'Tap or click to use';
596
+ const el = doc.createElement('div');
597
+ el.className = `${ENGAGE_CLASS} ${PICK_CLASS}`;
598
+ el.setAttribute('role', 'button');
599
+ el.setAttribute('tabindex', '0');
600
+ el.setAttribute('aria-label', label);
601
+ el.style.cssText = 'position:absolute;z-index:1;background:rgba(127,127,127,0.03);cursor:pointer;';
602
+ const words = doc.createElement('span');
603
+ words.className = PICK_LABEL_CLASS;
604
+ words.textContent = label;
605
+ el.append(words);
606
+ el.addEventListener('click', (ev) => { if (ev.isTrusted) picked(); });
607
+ el.addEventListener('keydown', (ev) => {
608
+ if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
609
+ ev.preventDefault();
610
+ picked();
611
+ });
612
+ const position = win.getComputedStyle(box).position;
613
+ const own = box.style.position;
614
+ if (!position || position === 'static') box.style.position = 'relative';
615
+ // (Held out with whatever else holds it, engage's among them: see `holdOut`.)
616
+ const back = holdOut(frame);
617
+ unlay = () => {
618
+ box.style.position = own;
619
+ back();
620
+ };
621
+ frame.after(el);
622
+ layer = el;
623
+ place();
624
+ standBy();
625
+ return true;
626
+ };
627
+ // Over the frame wherever it is in its box, which may change as the page
628
+ // is laid out again: done again at every look.
629
+ const place = () => {
630
+ const box = layer?.offsetParent as HTMLElement | null | undefined;
631
+ if (!layer || !box) return;
632
+ const at = frame.getBoundingClientRect();
633
+ const of = box.getBoundingClientRect();
634
+ layer.style.left = `${at.left - of.left - box.clientLeft + box.scrollLeft}px`;
635
+ layer.style.top = `${at.top - of.top - box.clientTop + box.scrollTop}px`;
636
+ layer.style.width = `${at.width}px`;
637
+ layer.style.height = `${at.height}px`;
638
+ };
639
+ const lift = () => {
640
+ if (!layer) return;
641
+ layer.remove();
642
+ layer = undefined;
643
+ unlay?.();
644
+ unlay = undefined;
645
+ standBy();
646
+ };
647
+ // The layer lifts on its own once the dock's no is over: what it went by,
648
+ // its activation, has run out while the keyboard was out of the tile, and
649
+ // the dock says so when asked, as a no that is no longer its best guess
650
+ // (`unsure`) nor a no that stands. Asked now and then while the keyboard
651
+ // is not in the tile, nor on the layer: a user about to pick it with a key
652
+ // keeps it.
653
+ const settle = () => {
654
+ if (!layer || settling || stopped || holds(frame) || focused(doc) === layer || now() - settledAt < SETTLE_MS) return;
655
+ settling = true;
656
+ settledAt = now();
657
+ dock.ask().then((said) => {
658
+ settling = false;
659
+ if (!layer || stopped || holds(frame) || focused(doc) === layer) return;
660
+ if (said?.activated !== false || said.unsure || said.arrivalActivated === false) return;
661
+ lift();
662
+ liftedAt = now();
663
+ });
664
+ };
665
+ // The user picked the tile on the layer: they go in, as by the host's own
666
+ // way in. (Unless the host has it wait to be picked with `engage`, and
667
+ // its layer is back over the tile since: that is where they pick it now.)
668
+ const picked = () => {
669
+ if (options.engaged && !options.engaged()) return lift();
670
+ focus();
671
+ };
672
+ // The stop in the frame's place in the tab order (see `tabOrder`): a
673
+ // button of the page's right before the frame, which the user tabs to and
674
+ // presses as they would the host's own way in. Before it, so that a Tab
675
+ // out of the tile's last field goes on to what comes after the tile, not
676
+ // back to the tile's own stop. It takes no room and
677
+ // cannot be seen until it has the keyboard; then it lies over the tile,
678
+ // with the layer's look, and says what it is for. It takes no press then:
679
+ // a press or a tap where it lies is one into the tile, which goes there,
680
+ // to what is under it, as it would with no stop. While another layer is
681
+ // over the tile (the guard's, or engage's for a tile that is not picked),
682
+ // that is where Tab stops, and this one is out of the tab order.
683
+ // The tile's name is the tile's to choose: cut to a name's length, so
684
+ // that what the stop says, and what it is called for those who do not see
685
+ // it, is a name and not whatever the tile would have it say. (By the
686
+ // character, not the code unit: a character is not cut in half.)
687
+ const named = Array.from(typeof tile.manifest?.name === 'string' ? tile.manifest.name.trim() : '');
688
+ const name = named.length > NAME_MAX ? `${named.slice(0, NAME_MAX - 1).join('')}…` : named.join('');
689
+ const enterLabel = options.enterLabel ?? `Use the keyboard in ${name || 'this tile'}`;
690
+ const tabLabel = options.tabLabel ?? 'Press Tab to go in';
691
+ // (Clipped to nothing, and out of the flow, where it is.)
692
+ const UNSEEN = 'position:absolute;width:1px;height:1px;margin:0;padding:0;border:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;';
693
+ const standIn = tabOrder === 'stop' ? doc.createElement('div') : undefined;
694
+ const words = standIn ? doc.createElement('span') : undefined;
695
+ let shown = false;
696
+ // What it says, to those who see it and to those who do not.
697
+ const say = (label: string) => {
698
+ if (!standIn || !words) return;
699
+ standIn.setAttribute('aria-label', label);
700
+ words.textContent = label;
701
+ };
702
+ const onStop = (): boolean => Boolean(standIn) && (standIn?.getRootNode() as Document | ShadowRoot).activeElement === standIn;
703
+ // The frame let into the tab order for the Tab from the stop (see
704
+ // `enter`), and how to end that; and whether the Tab that last explained
705
+ // the keyboard coming in was that one (`spent` once it has).
706
+ let letOut: (() => void) | undefined;
707
+ let letUntil: number | undefined;
708
+ let spent = false;
709
+ // The Tab from the stop takes the user in from there, and explains the
710
+ // keyboard coming into the frame from the stop and nothing else: should
711
+ // the keyboard be found anywhere else before the tile has it (another
712
+ // tile took it on the way, say), it is spent all the same.
713
+ const spend = () => {
714
+ if (!spent) return;
715
+ lastTab = -Infinity;
716
+ spent = false;
717
+ };
718
+ const shut = () => {
719
+ if (!letOut) return;
720
+ letOut();
721
+ letOut = undefined;
722
+ win.clearTimeout(letUntil);
723
+ say(enterLabel);
724
+ };
725
+ // Over the frame, wherever the box it is laid out against is: put where
726
+ // that box begins, it is as far from the frame as it has to move. Done
727
+ // again at every look, as the layer is, and without making the frame's
728
+ // box one to lay it out against, which is the layer's to do and undo.
729
+ const placeStandIn = () => {
730
+ if (!standIn || !shown) return;
731
+ const at = frame.getBoundingClientRect();
732
+ const was = standIn.getBoundingClientRect();
733
+ standIn.style.left = `${(parseFloat(standIn.style.left) || 0) + at.left - was.left}px`;
734
+ standIn.style.top = `${(parseFloat(standIn.style.top) || 0) + at.top - was.top}px`;
735
+ standIn.style.width = `${at.width}px`;
736
+ standIn.style.height = `${at.height}px`;
737
+ };
738
+ const show = (on: boolean) => {
739
+ if (!standIn) return;
740
+ shown = on;
741
+ standIn.style.cssText = on ? 'position:absolute;z-index:1;left:0;top:0;pointer-events:none;' : UNSEEN;
742
+ placeStandIn();
743
+ };
744
+ if (standIn && words) {
745
+ standIn.className = ENTER_CLASS;
746
+ standIn.setAttribute('role', 'button');
747
+ standIn.setAttribute('tabindex', '0');
748
+ standIn.style.cssText = UNSEEN;
749
+ words.className = PICK_LABEL_CLASS;
750
+ say(enterLabel);
751
+ standIn.append(words);
752
+ // The user pressed the stop: the frame is let into the tab order for
753
+ // their next Tab, which goes from the stop, right before the frame, into
754
+ // the tile as a Tab into any frame in the tab order does, and which the
755
+ // page sees. The stop says so. Not `focus()`, which puts the keyboard
756
+ // in from the page: in answer to a key, that takes in Chrome but not in
757
+ // Firefox nor in WebKit, which leave the keyboard where it was, and in
758
+ // Chrome it leaves the keyboard in a page of the dock's with nothing on
759
+ // screen to say so. This way is the same in all three: Enter, then Tab.
760
+ // It is over once the keyboard has left the stop (into the tile or
761
+ // anywhere else), or after `LET_IN_MS`.
762
+ // (Not into a tile that waits to be picked: engage's layer is the way in to it.)
763
+ const enter = () => {
764
+ if (options.engaged && !options.engaged()) return;
765
+ // The user is going in themselves, as by the host's way in (see `focus`).
766
+ lift();
767
+ liftedAt = -Infinity;
768
+ shut();
769
+ // (A press aimed at the stop can come with the keyboard elsewhere, as
770
+ // a screen reader's can: the frame is let in only while the keyboard
771
+ // is on the stop, and the Tab that takes the user in goes from there.)
772
+ if (!onStop()) standIn.focus({ preventScroll: true });
773
+ letOut = letIn(frame);
774
+ letUntil = win.setTimeout(shut, LET_IN_MS);
775
+ say(tabLabel);
776
+ };
777
+ // (A press the browser makes on the stop itself, as it does for a
778
+ // screen reader's, reaches it all the same: it is aimed at the element,
779
+ // not at where it lies. It puts the keyboard on the stop, see `enter`.)
780
+ standIn.addEventListener('click', (ev) => { if (ev.isTrusted) enter(); });
781
+ standIn.addEventListener('keydown', (ev) => {
782
+ if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
783
+ ev.preventDefault();
784
+ enter();
785
+ });
786
+ standIn.addEventListener('focus', () => show(true));
787
+ standIn.addEventListener('blur', () => {
788
+ show(false);
789
+ // (A task later: the Tab that takes the keyboard into the frame is still on its way.)
790
+ win.setTimeout(() => { if (!onStop()) shut(); }, 0);
791
+ });
792
+ }
793
+ // Right before the frame once it is in a document (a host may guard it
794
+ // before it puts it there), and again where the page has moved the frame
795
+ // or taken the stop away, or put something between them; in the tab order
796
+ // or out of it, as said above.
797
+ // Not where the page has taken the frame out of its document: there is no
798
+ // way into a tile that is not there, and a stop left behind would be one
799
+ // the user tabs to and that does nothing. It goes with the frame, and
800
+ // comes back with it.
801
+ const standBy = () => {
802
+ if (!standIn || stopped) return;
803
+ if (!frame.isConnected || !frame.parentNode) return standIn.remove();
804
+ if (standIn.nextSibling !== frame) {
805
+ // (In the shadow tree the frame is in, if it is in one: so is its look.)
806
+ const root = frame.getRootNode();
807
+ pickLook(doc, root instanceof (win as Window & typeof globalThis).ShadowRoot ? root : doc);
808
+ frame.before(standIn);
809
+ }
810
+ // Seen only while it has the keyboard. A stop the page took away, or
811
+ // moved, with the keyboard on it has lost it, and some browsers (Firefox)
812
+ // say no blur then: put back, it would lie over the tile, with its words,
813
+ // taking the presses meant for the tile.
814
+ if (shown && (standIn.getRootNode() as Document | ShadowRoot).activeElement !== standIn) show(false);
815
+ const tabindex = !layer && (!options.engaged || options.engaged()) ? '0' : '-1';
816
+ if (standIn.getAttribute('tabindex') !== tabindex) standIn.setAttribute('tabindex', tabindex);
817
+ placeStandIn();
818
+ };
819
+ // `refused`: the dock has just said that the keyboard came into the tile
820
+ // with no one acting there, which is its no without being asked, and
821
+ // `unsure`, that it may be the user's doing all the same.
822
+ const check = (refused = false, unsure = false) => {
823
+ place();
824
+ standBy();
825
+ // (Also where the stop was taken away with the keyboard on it, which
826
+ // some browsers say no blur for; and where something took the frame out
827
+ // of the tab order again, engage's layer back over the tile say, which
828
+ // ends the moment: the stop is not to say that Tab goes in then.)
829
+ if (letOut && (!onStop() || frame.tabIndex < 0)) shut();
830
+ settle();
831
+ watch();
832
+ if (stopped || winFocused || !doc.hasFocus()) return;
833
+ if (holds(frame)) inTile = true;
834
+ // The keyboard is in another frame of the page's. It left the tile, and
835
+ // what was decided when it came no longer stands: should it come back,
836
+ // that is judged afresh. (The window hears nothing of focus going from
837
+ // one frame to another.)
838
+ // Nor does what had the keyboard on the page have it still, unless the
839
+ // page put it in that frame itself: the page hears no focusin when the
840
+ // user presses or tabs into another frame, only that the keyboard left.
841
+ else {
842
+ inTile = accepted = tabbed = straight = returning = false;
843
+ if (focused(doc) !== holder) holder = null;
844
+ spend();
845
+ }
846
+ if (!inTile) return;
847
+ if (accepted) {
848
+ // It came in again since, where the page did not see it go: what the
849
+ // page saw of the user going in stands, and nothing else does.
850
+ if (!refused || tabbed) return;
851
+ accepted = inTile = false;
852
+ return giveBack('dock', unsure);
853
+ }
854
+ const how = judge();
855
+ if (!how || (refused && how === 'ask')) {
856
+ inTile = false;
857
+ return how ? giveBack('dock', unsure) : giveBack('script');
858
+ }
859
+ accepted = true;
860
+ tabbed = how === 'tab';
861
+ round++; // nothing still on its way from an earlier giving back takes this one away
862
+ // The user went in themselves, and the dock is told: no earlier no of its
863
+ // stands against them. (And, where they went in with a press, it puts
864
+ // the keyboard on into the tile.)
865
+ if (tabbed) {
866
+ dock.entered(into);
867
+ into = false;
868
+ // The Tab from the stop has taken the user in, and is spent: it
869
+ // explains nothing that comes into the tile after this, should the
870
+ // keyboard go elsewhere first.
871
+ if (spent) lastTab = -Infinity;
872
+ spent = false;
873
+ return;
874
+ }
875
+ // A second opinion, which takes a moment: the dock's. Where it watched
876
+ // the keyboard come in, it also says whether the user had acted in the
877
+ // tile then, which what they typed into the tile since does not change.
878
+ dock.ask().then((said) => {
879
+ if ((said?.activated === true && said.arrivalActivated !== false) || !accepted || winFocused || stopped) return;
880
+ // No answer, from a dock that never gave one: nothing more to go by.
881
+ if (said === undefined && !dock.answers) return;
882
+ accepted = false;
883
+ inTile = false;
884
+ giveBack('dock', said?.unsure === true);
885
+ });
886
+ };
887
+ // The dock's no, unasked: judged as the guard's own look would, then and
888
+ // there, unless the keyboard is on its way back already.
889
+ const onRefused = (unsure: boolean) => { if (!returning) check(true, unsure); };
890
+ const onWinBlur = () => {
891
+ winFocused = false;
892
+ watch(true);
893
+ // Straight from the page, unless the page names another frame of its own
894
+ // as having the keyboard by now: then it went there, and what comes into
895
+ // the tile next comes from that frame, however soon (see `judge`).
896
+ straight = holds(frame) || !framed(focused(doc));
897
+ // Where the keyboard went is known by now. Into another frame of the
898
+ // page's: what had it on the page has it no longer (see `check`), and
899
+ // that is settled at once, not a task later. A tile that took the
900
+ // keyboard from that frame in between would have it put back on what
901
+ // the user had left.
902
+ if (!holds(frame) && !onNothing() && focused(doc) !== holder) holder = null;
903
+ // The keyboard has gone again, and that is for `check` to judge and to
904
+ // count. A giving back still making sure of an earlier time is over: it
905
+ // would take this one back as well, before it had been counted.
906
+ round++;
907
+ win.setTimeout(check, 0);
908
+ };
909
+ const onWinFocus = () => {
910
+ winFocused = true;
911
+ watch();
912
+ inTile = false;
913
+ accepted = tabbed = returning = false;
914
+ // (Nor does the Tab from the stop explain anything after it: see `spend`.)
915
+ spend();
916
+ // Back in the page, and maybe on nothing of it (a press on its plain
917
+ // text): then nothing has the keyboard to be given it back.
918
+ win.setTimeout(forget, 0);
919
+ };
920
+ // Out of the tab order for as long as the guard runs, unless the host
921
+ // keeps it as it made it (see `tabOrder`). Whoever tabs down the page then
922
+ // never ends up in the tile by chance, and a Tab says nothing of the
923
+ // keyboard arriving in it (see `onKey`).
924
+ const back = tabOrder === 'keep' ? undefined : holdOut(frame);
925
+ win.addEventListener('blur', onWinBlur);
926
+ win.addEventListener('focus', onWinFocus);
927
+ doc.addEventListener('focusin', onFocusIn, true);
928
+ doc.addEventListener('focusout', onFocusOut, true);
929
+ doc.addEventListener('keydown', onKey, true);
930
+ // A guard made with the keyboard in another frame of the page's watches from the start.
931
+ watch();
932
+ // (A task later: what `engaged` reads may be made just after the guard.)
933
+ win.setTimeout(standBy, 0);
934
+ // (The page's own timers throughout: they go with the page.)
935
+ const poll = win.setInterval(check, cfg.pollMs);
936
+ const stop = () => {
937
+ if (stopped) return;
938
+ stopped = true;
939
+ lift();
940
+ shut();
941
+ back?.();
942
+ standIn?.remove();
943
+ watch();
944
+ win.clearInterval(poll);
945
+ dock.stop();
946
+ win.removeEventListener('blur', onWinBlur);
947
+ win.removeEventListener('focus', onWinFocus);
948
+ doc.removeEventListener('focusin', onFocusIn, true);
949
+ doc.removeEventListener('focusout', onFocusOut, true);
950
+ doc.removeEventListener('keydown', onKey, true);
951
+ tile.removeEventListener('close', stop);
952
+ tile.removeEventListener('load', probe);
953
+ };
954
+ // A tile that is closed has no frame left to guard.
955
+ tile.addEventListener('close', stop);
956
+ // The host's own way in: what arrives in the tile that way is judged as a
957
+ // Tab into it is, and a Tab is as long ago once it has gone elsewhere.
958
+ // It goes in through the frame's window, not the element: a frame the
959
+ // page's script focused stays the page's active element in Chrome after
960
+ // the user has gone on into another frame, and the guard would not see the
961
+ // keyboard leave the tile, nor the tile take it back.
962
+ // It is the user picking the tile, too, where it waits for them to.
963
+ // That puts the keyboard in the dock's own page, where what is typed
964
+ // reaches nothing; the dock puts it on into the tile when told, for a user
965
+ // who went in with a press (a click or a tap, which this is called from).
966
+ // One who went in from the keyboard is left there: their Tab from there
967
+ // goes to the first thing in the tile, which it would not from inside it.
968
+ const focus = () => {
969
+ lift();
970
+ // The user went in themselves: a guess of the dock's after this is spared
971
+ // again, however soon after a layer lifted on its own (see `spareMs`).
972
+ liftedAt = -Infinity;
973
+ lastTab = now();
974
+ into = pressing();
975
+ frame.contentWindow?.focus();
976
+ };
977
+ // Whether what the page is handling now is a press of the user's, and not
978
+ // a key (a click the keyboard made has no `detail`).
979
+ const pressing = (): boolean => {
980
+ const ev = (win as Window & { event?: Event }).event;
981
+ if (!ev?.isTrusted) return false;
982
+ if (/click$/.test(ev.type)) return (ev as MouseEvent).detail > 0;
983
+ return /^(pointer|mouse|touch)/.test(ev.type);
984
+ };
985
+ return { stop, focus };
986
+ }
987
+
988
+ // ---------------------------------------------------------------- the click gate
989
+
990
+ export interface ClickGate {
991
+ /** Whether presses on the page are being ignored right now. */
992
+ readonly closed: boolean;
993
+ /** Has the page ignore presses for `ms` from now (`CLICK_GATE.ms` by default). */
994
+ arm (ms?: number): void;
995
+ /** Has it take them again at once. */
996
+ open (): void;
997
+ }
998
+
999
+ /** The numbers `clickGate` goes by where it is given none. First guesses. */
1000
+ export const CLICK_GATE: Readonly<Record<'ms' | 'travel', number>> = Object.freeze({
1001
+ /** How long presses are ignored, in milliseconds. */
1002
+ ms: 600,
1003
+ /** How far the pointer has to really move for them to be taken again sooner, in pixels. */
1004
+ travel: 24,
1005
+ });
1006
+
1007
+ const gates = new WeakMap<Document, ClickGate>();
1008
+ const PRESSES = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'auxclick', 'contextmenu'];
1009
+ // What keeps its own counsel about presses: the blocks the loader itself
1010
+ // puts up, its link prompt, and anything the host marks.
1011
+ const PASSES = `.${SHIELD_CLASS}, .tile-link-dialog, [data-tile-gate="pass"]`;
1012
+
1013
+ /**
1014
+ * The page's own controls ignore presses and clicks for a moment after
1015
+ * something moved them that neither the page nor, as far as it can see, the
1016
+ * user did. One per document: `arm(ms)` starts the moment, a press that is
1017
+ * ignored starts it again, and a real movement of the pointer across the
1018
+ * page, which is the user aiming afresh at what is there now, ends it.
1019
+ *
1020
+ * A key is not a press: what the keyboard activates is where the focus is,
1021
+ * and nothing that moved the page moved that. An element of the host's that
1022
+ * must take presses regardless is marked `data-tile-gate="pass"`.
1023
+ */
1024
+ export function clickGate (doc: Document = document, options: { travel?: number } = {}): ClickGate {
1025
+ const known = gates.get(doc);
1026
+ if (known) return known;
1027
+ const win = doc.defaultView as Window;
1028
+ const travel = options.travel ?? CLICK_GATE.travel;
1029
+ let until = 0;
1030
+ let ms: number = CLICK_GATE.ms;
1031
+ let anchor: { x: number; y: number } | undefined;
1032
+ const gate: ClickGate = {
1033
+ get closed () { return now() < until; },
1034
+ arm (forMs = CLICK_GATE.ms) {
1035
+ ms = forMs;
1036
+ until = Math.max(until, now() + forMs);
1037
+ anchor = undefined;
1038
+ },
1039
+ open () { until = 0; },
1040
+ };
1041
+ const swallow = (ev: Event) => {
1042
+ const e = ev as PointerEvent;
1043
+ if (!e.isTrusted || now() >= until) return;
1044
+ if (e.type === 'click' && e.detail === 0) return; // the keyboard's
1045
+ if ((e.target as Element | null)?.closest?.(PASSES)) return;
1046
+ e.stopImmediatePropagation();
1047
+ // 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.
1048
+ if (!(e.pointerType === 'touch' && e.type !== 'click')) e.preventDefault();
1049
+ if (e.type === 'pointerdown' || e.type === 'click') until = now() + ms;
1050
+ };
1051
+ for (const type of PRESSES) win.addEventListener(type, swallow, true);
1052
+ win.addEventListener('pointermove', (ev) => {
1053
+ const e = ev as PointerEvent;
1054
+ if (!e.isTrusted || now() >= until || e.pointerType === 'touch') return;
1055
+ if (!anchor) { anchor = { x: e.clientX, y: e.clientY }; return; }
1056
+ if (Math.hypot(e.clientX - anchor.x, e.clientY - anchor.y) >= travel) until = 0;
1057
+ }, { capture: true, passive: true });
1058
+ gates.set(doc, gate);
1059
+ return gate;
1060
+ }
1061
+
1062
+ // ---------------------------------------------------------------- scrolling
1063
+
1064
+ /** How a move of the page was accounted for (see `guardScroll`). */
1065
+ export interface ScrollMove {
1066
+ /** The page's vertical scroll position before and after. */
1067
+ from: number;
1068
+ to: number;
1069
+ verdict: 'user' | 'own' | 'layout' | 'ambiguous' | 'tile' | 'elsewhere';
1070
+ /** Whether the move was taken back. */
1071
+ undone: boolean;
1072
+ }
1073
+
1074
+ /** The numbers `guardScroll` goes by. First guesses, all of them. */
1075
+ export interface ScrollGuardOptions {
1076
+ /** How long input that asked for a scroll goes on explaining one, in milliseconds. */
1077
+ inputMs?: number;
1078
+ /** How long a page may coast on, the way it was going, after a finger let go, in milliseconds. */
1079
+ flingMs?: number;
1080
+ /** How much further than the input asked a move may go and still be the user's, in pixels. */
1081
+ slack?: number;
1082
+ /** How many times the tile may pull the page back against the user's own scrolling, within `withinMs`, before that is abuse. */
1083
+ pulls?: number;
1084
+ /** The time those are counted over, in milliseconds. */
1085
+ withinMs?: number;
1086
+ /** How long the page's controls take no press after a move that is not accounted for, in milliseconds. */
1087
+ gateMs?: number;
1088
+ /** A move of more than this many pixels in one go is a jump, */
1089
+ jumpPx?: number;
1090
+ /** after which they take no press for this long, in milliseconds. */
1091
+ jumpGateMs?: number;
1092
+ /** Take the tile's moves back (the default), or let them stand and only keep presses off what they moved (`false`). */
1093
+ undo?: boolean;
1094
+ /** The gate that keeps presses off what moved: the document's own by default, `false` for none. */
1095
+ gate?: ClickGate | false;
1096
+ /**
1097
+ * How the page's own scrolling is known for its own: `'patch'` wraps the
1098
+ * calls a page scrolls itself with (`scrollTo`, `scrollBy`, `scroll`,
1099
+ * `scrollIntoView`, `focus`) so that each says so first. Without it the
1100
+ * page says so itself, with `expect()`.
1101
+ */
1102
+ own?: 'patch';
1103
+ /** Called with every move of the page and how it was accounted for. */
1104
+ onMove?: (move: ScrollMove) => void;
1105
+ /** Called when the tile has pulled the page back `pulls` times within `withinMs`, with how often it was undone in all. */
1106
+ onAbuse?: (what: 'scroll', count: number) => void;
1107
+ /** Stop the tile then (the default), or only report it (`false`). */
1108
+ stop?: boolean;
1109
+ /**
1110
+ * Whether the user has picked the tile, for a host that has it wait to be
1111
+ * picked (`engage`): a tile that is not picked gets no input, so the user
1112
+ * cannot have scrolled the page through it.
1113
+ */
1114
+ engaged?: () => boolean;
1115
+ }
1116
+
1117
+ /** `guardScroll`'s numbers where a host gives none. */
1118
+ export const SCROLL_GUARD: Readonly<Record<'inputMs' | 'flingMs' | 'slack' | 'pulls' | 'withinMs' | 'gateMs' | 'jumpPx' | 'jumpGateMs', number>> = Object.freeze({
1119
+ inputMs: 1200,
1120
+ flingMs: 2500,
1121
+ slack: 60,
1122
+ pulls: 3,
1123
+ withinMs: 10000,
1124
+ gateMs: CLICK_GATE.ms,
1125
+ jumpPx: 150,
1126
+ jumpGateMs: 2500,
1127
+ });
1128
+
1129
+ export interface ScrollGuardControl extends GuardControl {
1130
+ /** The page is about to scroll itself (a "back to top", a change of route): leave it be for `ms` (1000 by default). */
1131
+ expect (ms?: number): void;
1132
+ }
1133
+
1134
+ // What a key scrolls by: pixels, pages (viewport heights), or all the way.
1135
+ 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] };
1136
+ const framed = (el: Element | null): boolean => el?.localName === 'iframe' || el?.localName === 'frame';
1137
+
1138
+ // The frames of a page that have a scroll guard on them, each with whether
1139
+ // input can reach it: always, unless it waits to be picked. A guard is one
1140
+ // tile's, and the page it watches is everyone's. So each has to know of the
1141
+ // others: which of two tiles at the viewport moved the page cannot be told.
1142
+ const scrollGuarded = new WeakMap<Document, Map<Element, () => boolean>>();
1143
+
1144
+ // The calls a page scrolls itself with, wrapped so that each says so first:
1145
+ // once for a page, however many of its guards asked, and put back as they
1146
+ // were when the last of those stops.
1147
+ const declaring = new WeakMap<Window, { tell: Set<() => void>; restore: (() => void)[] }>();
1148
+ function declareOwn (win: Window, tell: () => void): () => void {
1149
+ let shared = declaring.get(win);
1150
+ if (!shared) {
1151
+ const made = { tell: new Set<() => void>(), restore: [] as (() => void)[] };
1152
+ const wrap = (obj: Record<string, unknown> | undefined, name: string) => {
1153
+ const original = obj?.[name];
1154
+ if (!obj || typeof original !== 'function') return;
1155
+ obj[name] = function (this: unknown, ...args: unknown[]) {
1156
+ // (A focus() that says it will not scroll explains no scroll: the
1157
+ // focus guard gives the keyboard back with one, whenever a tile
1158
+ // takes it.)
1159
+ if (!(name === 'focus' && (args[0] as FocusOptions | undefined)?.preventScroll)) for (const fn of made.tell) fn();
1160
+ return original.apply(this, args);
1161
+ };
1162
+ made.restore.push(() => { obj[name] = original; });
1163
+ };
1164
+ const w = win as unknown as Record<string, { prototype: Record<string, unknown> }> & Record<string, unknown>;
1165
+ for (const name of ['scrollTo', 'scrollBy', 'scroll']) {
1166
+ wrap(w, name);
1167
+ wrap(w.Element.prototype, name);
1168
+ }
1169
+ wrap(w.Element.prototype, 'scrollIntoView');
1170
+ wrap(w.HTMLElement.prototype, 'focus');
1171
+ declaring.set(win, made);
1172
+ shared = made;
1173
+ }
1174
+ const mine = shared;
1175
+ mine.tell.add(tell);
1176
+ return () => {
1177
+ mine.tell.delete(tell);
1178
+ if (mine.tell.size || declaring.get(win) !== mine) return;
1179
+ mine.restore.forEach(fn => fn());
1180
+ declaring.delete(win);
1181
+ };
1182
+ }
1183
+
1184
+ /**
1185
+ * Accounts for every move of the page a tile is in, and takes back the
1186
+ * tile's own.
1187
+ *
1188
+ * The page's vertical scroll position is followed, and each move is one of:
1189
+ *
1190
+ * - `user`: the page saw the input for it (a wheel, a key, a finger, a
1191
+ * mouse button held down, a pointer on the scrollbar), and the move goes
1192
+ * that way and no further than the input asked: a wheel turned by 100
1193
+ * does not explain a jump of 1500.
1194
+ * - `own`: the page said it would (`expect()`, or `own: 'patch'`), or it
1195
+ * navigated, or the user tabbed on.
1196
+ * - `layout`: the document's height changed, by as much as the move or
1197
+ * more. It stands. Where the tile's own box changed with it, the gate is
1198
+ * armed: the move may be the tile's doing after all.
1199
+ * - `ambiguous`: none of those, but the page cannot rule the user out. A
1200
+ * mouse was inside the tile and may have been wheeling there, the
1201
+ * keyboard is in the tile, or a finger may be on it. The same goes for
1202
+ * any other frame of the page's: what the user does in one scrolls the
1203
+ * page too, and the page sees none of it. The move stands, and the gate
1204
+ * is armed: what slid under the pointer takes no press for a moment
1205
+ * (`gateMs`; `jumpGateMs` after a jump), or until the pointer has really
1206
+ * moved.
1207
+ * - `tile`: none of those, and the tile's frame is at or in the viewport
1208
+ * once it is done, which is where its own scrolling leaves it. It is
1209
+ * taken back before it is painted. (The gate is armed only where the page
1210
+ * could not be put back whole: a move that is undone slid nothing under
1211
+ * the pointer.)
1212
+ * - `elsewhere`: unexplained, and nowhere near the tile. Left alone (the
1213
+ * browser and assistive tools scroll pages too), gate armed.
1214
+ *
1215
+ * A tile that pulls the page back against the way the user has just
1216
+ * scrolled is doing it on purpose: `pulls` of those within `withinMs` are
1217
+ * reported (`onAbuse`), and the tile is stopped (see `GuardStoppedEvent`)
1218
+ * unless told otherwise (`stop: false`). Where another tile with a guard on
1219
+ * it is at the viewport as well, which of them it was cannot be told: the
1220
+ * move is taken back all the same, and neither is held to it.
1221
+ *
1222
+ * The page has to say when it scrolls itself, or let the guard wrap its
1223
+ * calls: an unexplained move of the page's own that ends at the tile is
1224
+ * taken back like the tile's. Only the document's own scrolling is
1225
+ * followed, not that of a box inside it.
1226
+ */
1227
+ export function guardScroll (tile: Tile, frame: HTMLIFrameElement, options: ScrollGuardOptions = {}): ScrollGuardControl {
1228
+ const doc = frame.ownerDocument;
1229
+ const win = doc.defaultView as Window;
1230
+ const pointer = watchPointer(doc);
1231
+ const cfg = { ...withDefaults(SCROLL_GUARD, options), undo: options.undo !== false };
1232
+ const gate = options.gate === false ? undefined : (options.gate ?? clickGate(doc));
1233
+ const root = () => doc.scrollingElement || doc.documentElement;
1234
+ // How much of the frame is in the viewport, in pixels of height.
1235
+ const visible = () => {
1236
+ const r = frame.getBoundingClientRect();
1237
+ return Math.max(0, Math.min(r.bottom, win.innerHeight) - Math.max(r.top, 0));
1238
+ };
1239
+ // Whether an element is at or in the viewport.
1240
+ const at = (el: Element) => {
1241
+ const r = el.getBoundingClientRect();
1242
+ return r.height > 0 && r.bottom >= -2 && r.top <= win.innerHeight + 2;
1243
+ };
1244
+ const near = () => at(frame);
1245
+ // Whether a point was in a frame's box before the page moved by `d`.
1246
+ const within = (el: Element, p: { x: number; y: number }, d: number) => {
1247
+ const r = el.getBoundingClientRect();
1248
+ const top = r.top + d;
1249
+ return p.x >= r.left - 2 && p.x <= r.right + 2 && p.y >= top - 2 && p.y <= top + r.height + 2;
1250
+ };
1251
+ const others = scrollGuarded.get(doc) ?? new Map<Element, () => boolean>();
1252
+ scrollGuarded.set(doc, others);
1253
+ others.set(frame, () => !options.engaged || options.engaged());
1254
+ // Whether ours is the only guarded tile at the viewport: the only one
1255
+ // that can have brought the page to where it is.
1256
+ const alone = () => {
1257
+ for (const el of others.keys()) if (el !== frame && el.isConnected && at(el)) return false;
1258
+ return true;
1259
+ };
1260
+ // Whether a finger may have been on another frame of the page's: one that
1261
+ // was in view before the page moved by `d`, and that input reaches. (A
1262
+ // frame in a shadow tree is only known of here if it has a guard.)
1263
+ const fingerElsewhere = (d: number) => {
1264
+ for (const el of new Set<Element>([...doc.getElementsByTagName('iframe'), ...others.keys()])) {
1265
+ if (el === frame || !el.isConnected || others.get(el)?.() === false) continue;
1266
+ const r = el.getBoundingClientRect();
1267
+ const top = r.top + d;
1268
+ if (r.width > 0 && r.height > 0 && top < win.innerHeight && top + r.height > 0) return true;
1269
+ }
1270
+ return false;
1271
+ };
1272
+ let y = win.scrollY;
1273
+ let docHeight = root().scrollHeight;
1274
+ let frameHeight = frame.getBoundingClientRect().height;
1275
+ let seen = visible();
1276
+ // What the user has asked for and the page has not scrolled yet, in pixels (signed).
1277
+ let credit = 0;
1278
+ let inputAt = -Infinity;
1279
+ let lastDir = 0; // the way the user last scrolled
1280
+ let lastDirAt = -Infinity;
1281
+ let down = false; // a mouse button is down on the page: a scrollbar, a drag, autoscroll
1282
+ let downAt = -Infinity;
1283
+ let flingUntil = -Infinity;
1284
+ let flingDir = 0;
1285
+ let expected = -Infinity;
1286
+ let restoring: number | undefined; // where the page was put back to, until that move is heard of
1287
+ let undone = 0;
1288
+ let tookBackAt = -Infinity; // when a move of the tile's was last taken back
1289
+ let typedAt = -Infinity; // when the user last typed into a field of the page's
1290
+ let pulls: number[] = [];
1291
+ let stopped = false;
1292
+ let touchY: number | undefined;
1293
+ // Where the page was when the pointer was last seen going into a frame.
1294
+ let entered: { at: number; y: number } | undefined;
1295
+ const onPointer = () => {
1296
+ const p = pointer.state;
1297
+ if (p.kind !== 'frame') entered = undefined;
1298
+ else if (entered?.at !== p.at) entered = { at: p.at, y: win.scrollY };
1299
+ };
1300
+ onPointer();
1301
+ const offPointer = pointer.onChange(onPointer);
1302
+
1303
+ const ask = (px: number) => {
1304
+ const t = now();
1305
+ if (t - inputAt > cfg.inputMs || Math.sign(px) !== Math.sign(credit)) credit = 0; // stale, or the user turned round
1306
+ credit += px;
1307
+ inputAt = t;
1308
+ lastDir = Math.sign(px);
1309
+ lastDirAt = t;
1310
+ };
1311
+ const onWheel = (ev: Event) => {
1312
+ const e = ev as WheelEvent;
1313
+ if (e.isTrusted && e.deltaY) ask(e.deltaY * (e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? win.innerHeight : 1));
1314
+ };
1315
+ const onKey = (ev: Event) => {
1316
+ const e = ev as KeyboardEvent;
1317
+ if (!e.isTrusted || holds(frame)) return;
1318
+ if (e.key === 'Tab') { expected = Math.max(expected, now() + 300); return; } // focus moving on may scroll to it
1319
+ // A key typed into a field of the page's scrolls nothing itself, but the
1320
+ // browser may move the page to keep the caret in view.
1321
+ if (editable(focused(doc))) { typedAt = now(); return; }
1322
+ const k = SCROLL_KEYS[e.key];
1323
+ if (!k) return;
1324
+ const sign = e.key === ' ' && e.shiftKey ? -1 : 1;
1325
+ ask(sign * (k[0] === 'px' ? k[1] : k[0] === 'page' ? k[1] * win.innerHeight : k[1] * 1e9));
1326
+ };
1327
+ const onTouchStart = (ev: Event) => {
1328
+ const e = ev as TouchEvent;
1329
+ if (!e.isTrusted) return;
1330
+ touchY = e.touches[0]?.clientY;
1331
+ flingUntil = -Infinity;
1332
+ };
1333
+ const onTouchMove = (ev: Event) => {
1334
+ const e = ev as TouchEvent;
1335
+ if (!e.isTrusted) return;
1336
+ const ty = e.touches[0]?.clientY;
1337
+ if (touchY !== undefined && ty !== undefined && ty !== touchY) ask(touchY - ty);
1338
+ touchY = ty;
1339
+ };
1340
+ // The finger is up; the page may coast on, the way it was going.
1341
+ const onTouchEnd = (ev: Event) => {
1342
+ if (!ev.isTrusted || !lastDir || now() - lastDirAt >= 300) return;
1343
+ flingUntil = now() + cfg.flingMs;
1344
+ flingDir = lastDir;
1345
+ };
1346
+ const onDown = (ev: Event) => { if (ev.isTrusted && (ev as PointerEvent).pointerType !== 'touch') { down = true; downAt = now(); } };
1347
+ const onUp = (ev: Event) => { if (ev.isTrusted && (ev as PointerEvent).pointerType !== 'touch') { down = false; downAt = now(); } };
1348
+ const onNav = () => { expected = now() + 1500; };
1349
+
1350
+ const byUser = (d: number, t: number): boolean => {
1351
+ // A button held down on the page, or just let go: the page may scroll
1352
+ // for it (a drag, a click on something that scrolls). Not while the tile
1353
+ // has just been trying: its next try would pass for the page's answer to
1354
+ // a press that had nothing to do with it.
1355
+ if ((down || t - downAt < 300) && t - tookBackAt >= cfg.gateMs) return true;
1356
+ // The user is typing in a field of the page's, and the browser keeps the
1357
+ // caret in view: a line or two at a time, with the field still there to
1358
+ // see afterwards. (Under the same condition: a tile that keeps trying
1359
+ // does not get to creep the page along under the typing.)
1360
+ if (t - typedAt < 300 && Math.abs(d) <= cfg.slack && t - tookBackAt >= cfg.gateMs) {
1361
+ const field = focused(doc);
1362
+ if (field && editable(field) && at(field)) return true;
1363
+ }
1364
+ // The viewport's own scrollbar gives the page no events: a pointer last seen at the right edge may be on it.
1365
+ const p = pointer.state;
1366
+ if (p.kind === 'host' && p.type !== 'touch' && p.x >= Math.min(root().clientWidth, win.innerWidth - 18)) return true;
1367
+ if (t < flingUntil && Math.sign(d) === flingDir) return true;
1368
+ if (t - inputAt > cfg.inputMs || Math.sign(d) !== Math.sign(credit)) return false;
1369
+ if (Math.abs(d) > Math.abs(credit) + cfg.slack) return false;
1370
+ credit -= d;
1371
+ if (Math.sign(credit) !== Math.sign(d)) credit = 0; // spent (the slack is not carried over)
1372
+ return true;
1373
+ };
1374
+ // Whether a mouse the page last saw going into `el` can still have been
1375
+ // in it before the page moved by `d`. The page is told when a mouse goes
1376
+ // into a frame, and where; nothing of where it goes from there. So it may
1377
+ // be resting anywhere in the frame, and is still in it for as long as the
1378
+ // page has not moved by the frame's own height since. One that did not
1379
+ // move there is another matter: the frame came to it, and it is where it
1380
+ // was, which is all the frame's box before the move is asked.
1381
+ const mouseIn = (el: Element, d: number): boolean => {
1382
+ const p = pointer.state;
1383
+ if (!p.moved) return within(el, p, d);
1384
+ const r = el.getBoundingClientRect();
1385
+ const top = r.top + d;
1386
+ const shifted = Math.abs(y - (entered?.y ?? y));
1387
+ return r.width > 0 && shifted < r.height && top < win.innerHeight && top + r.height > 0;
1388
+ };
1389
+ // Could the user have scrolled through a frame, where the page sees no
1390
+ // input? Judged by where things were BEFORE the move: a tile that scrolls
1391
+ // itself under a pointer resting on the page is then "hovered", and that
1392
+ // must not count for it. `d` is how far the page has just moved.
1393
+ const cannotTell = (d: number): boolean => {
1394
+ const p = pointer.state;
1395
+ const fingers = !pointer.hovers || p.kind === 'none';
1396
+ const into = !fingers && p.kind === 'frame' ? pointer.frame : undefined;
1397
+ // The page's other frames first. What the user does in one scrolls the
1398
+ // page as well, and is no more the page's to see than what they do in
1399
+ // the tile: the keyboard in one, a mouse that went into one, a finger
1400
+ // that may be on one.
1401
+ const active = focused(doc);
1402
+ if (framed(active) && active !== frame) return true;
1403
+ if (into && into !== frame && mouseIn(into, d)) return true;
1404
+ if (fingers && fingerElsewhere(d)) return true;
1405
+ if (options.engaged && !options.engaged()) return false; // no input reaches a tile that is not picked
1406
+ if (holds(frame)) return true; // keys pressed in the tile scroll the page too
1407
+ if (fingers) return seen > 0; // a finger may be on it, if it was in view
1408
+ if (into === frame) return mouseIn(frame, d); // a mouse that went into it
1409
+ return p.kind === 'host' && within(frame, p, d); // or one the page sees over it (it lies under something of the page's)
1410
+ };
1411
+
1412
+ const onScroll = (ev: Event) => {
1413
+ if (stopped || (ev.target !== doc && ev.target !== root())) return;
1414
+ const to = win.scrollY;
1415
+ const h = root().scrollHeight;
1416
+ const fh = frame.getBoundingClientRect().height;
1417
+ // Our own move, putting the page back. Unless it has been moved again
1418
+ // before this was heard of: that is accounted for like any other move,
1419
+ // from where we had put it.
1420
+ const ours = restoring !== undefined && Math.abs(to - restoring) < 1;
1421
+ if (restoring !== undefined) y = restoring;
1422
+ restoring = undefined;
1423
+ if (ours || to === y) {
1424
+ y = to;
1425
+ docHeight = h;
1426
+ frameHeight = fh;
1427
+ seen = visible();
1428
+ return;
1429
+ }
1430
+ const t = now();
1431
+ const from = y;
1432
+ const d = to - from;
1433
+ const against = lastDir !== 0 && t - lastDirAt < cfg.inputMs && Math.sign(d) !== lastDir;
1434
+ // A jump in one go is not how a wheel or a finger moves a page: what it
1435
+ // put under the pointer stays untouchable for longer.
1436
+ const hush = Math.abs(d) > cfg.jumpPx ? cfg.jumpGateMs : cfg.gateMs;
1437
+ let verdict: ScrollMove['verdict'];
1438
+ if (t < expected) verdict = 'own';
1439
+ else if (h !== docHeight && Math.abs(d) <= Math.abs(h - docHeight) + cfg.slack) {
1440
+ verdict = 'layout';
1441
+ // The tile's own box changed with it: this may be its doing after all.
1442
+ if (fh !== frameHeight) gate?.arm(hush);
1443
+ }
1444
+ else if (byUser(d, t)) verdict = 'user';
1445
+ else if (cannotTell(d)) verdict = 'ambiguous';
1446
+ else if (near()) verdict = 'tile';
1447
+ else verdict = 'elsewhere';
1448
+ docHeight = h;
1449
+ frameHeight = fh;
1450
+ const take = verdict === 'tile' && cfg.undo;
1451
+ // Asked before the page is put back: it is where the move left things
1452
+ // that says which tiles can have made it.
1453
+ const mine = take && alone();
1454
+ // Whether the page is back where it was, to the pixel: nothing has then
1455
+ // moved under the pointer.
1456
+ let whole = false;
1457
+ if (take) {
1458
+ undone++;
1459
+ credit = 0;
1460
+ tookBackAt = t;
1461
+ win.scrollTo({ top: Math.max(0, Math.min(from, h - win.innerHeight)), left: win.scrollX, behavior: 'instant' });
1462
+ restoring = win.scrollY;
1463
+ whole = Math.abs(restoring - from) < 1;
1464
+ }
1465
+ else {
1466
+ y = to;
1467
+ seen = visible();
1468
+ }
1469
+ // What a move left standing slid under the pointer takes no press for a
1470
+ // moment. One that was put back whole slid nothing anywhere: were it to
1471
+ // close the gate, a tile that kept asking would keep the page from
1472
+ // taking any press at all.
1473
+ if (verdict === 'ambiguous' || verdict === 'elsewhere' || (verdict === 'tile' && !take)) gate?.arm(hush);
1474
+ else if (take && !whole) gate?.arm(cfg.gateMs);
1475
+ options.onMove?.({ from, to, verdict, undone: take });
1476
+ // Taken back whoever made it. Held against this tile only where no
1477
+ // other can have: a tile is not stopped for what its neighbour did.
1478
+ if (!mine || !against) return;
1479
+ pulls = pulls.filter(p => t - p < cfg.withinMs);
1480
+ pulls.push(t);
1481
+ if (pulls.length < cfg.pulls) return;
1482
+ pulls = [];
1483
+ options.onAbuse?.('scroll', undone);
1484
+ if (options.stop !== false) halt(tile, frame, 'scroll');
1485
+ };
1486
+
1487
+ // The page's own scrolling, declared for it: the calls a page scrolls
1488
+ // itself with are wrapped so that each says so first. Only when asked: a
1489
+ // page that would rather not have them touched calls expect() itself.
1490
+ const undeclare = options.own === 'patch' ? declareOwn(win, () => { expected = Math.max(expected, now() + 1000); }) : undefined;
1491
+
1492
+ const opts = { capture: true, passive: true };
1493
+ const onResize = () => {
1494
+ docHeight = root().scrollHeight;
1495
+ frameHeight = frame.getBoundingClientRect().height;
1496
+ seen = visible();
1497
+ y = win.scrollY;
1498
+ };
1499
+ doc.addEventListener('wheel', onWheel, opts);
1500
+ doc.addEventListener('keydown', onKey, true);
1501
+ doc.addEventListener('touchstart', onTouchStart, opts);
1502
+ doc.addEventListener('touchmove', onTouchMove, opts);
1503
+ doc.addEventListener('touchend', onTouchEnd, opts);
1504
+ doc.addEventListener('pointerdown', onDown, opts);
1505
+ doc.addEventListener('pointerup', onUp, opts);
1506
+ win.addEventListener('hashchange', onNav);
1507
+ win.addEventListener('popstate', onNav);
1508
+ win.addEventListener('resize', onResize);
1509
+ doc.addEventListener('scroll', onScroll, opts);
1510
+ const stop = () => {
1511
+ if (stopped) return;
1512
+ stopped = true;
1513
+ undeclare?.();
1514
+ offPointer();
1515
+ others.delete(frame);
1516
+ doc.removeEventListener('wheel', onWheel, opts);
1517
+ doc.removeEventListener('keydown', onKey, true);
1518
+ doc.removeEventListener('touchstart', onTouchStart, opts);
1519
+ doc.removeEventListener('touchmove', onTouchMove, opts);
1520
+ doc.removeEventListener('touchend', onTouchEnd, opts);
1521
+ doc.removeEventListener('pointerdown', onDown, opts);
1522
+ doc.removeEventListener('pointerup', onUp, opts);
1523
+ doc.removeEventListener('scroll', onScroll, opts);
1524
+ win.removeEventListener('hashchange', onNav);
1525
+ win.removeEventListener('popstate', onNav);
1526
+ win.removeEventListener('resize', onResize);
1527
+ tile.removeEventListener('close', stop);
1528
+ };
1529
+ // A tile that is closed has no frame left to guard.
1530
+ tile.addEventListener('close', stop);
1531
+ return {
1532
+ expect (ms = 1000) { expected = Math.max(expected, now() + ms); },
1533
+ stop,
1534
+ };
1535
+ }
1536
+
1537
+ // ---------------------------------------------------------------- picking a tile
1538
+
1539
+ export interface EngageOptions {
1540
+ /**
1541
+ * The element of the host's that holds the frame, and nothing else: the
1542
+ * layer is put in it, over the frame. The frame's parent by default. It
1543
+ * has to be there before the frame is put in it, since moving a frame
1544
+ * reloads it.
1545
+ */
1546
+ wrapper?: HTMLElement;
1547
+ /** What the layer is called for those who do not see it. Default: "Use this tile". */
1548
+ label?: string;
1549
+ /** Start with the tile picked, as for one the user has just started themselves. Default: not picked. */
1550
+ start?: 'idle' | 'engaged';
1551
+ /** Called when the tile is picked (`true`) or let go of (`false`), and why. */
1552
+ onChange?: (engaged: boolean, why: 'picked' | 'started' | 'pressed elsewhere' | 'escape' | 'out of view' | 'released') => void;
1553
+ }
1554
+
1555
+ export interface EngageControl extends GuardControl {
1556
+ /** The layer's element, for a host to style or to say something on. */
1557
+ readonly layer: HTMLElement;
1558
+ /** Whether the user has picked the tile. */
1559
+ readonly engaged: boolean;
1560
+ /** Lets go of the tile: the layer is back over it. */
1561
+ release (): void;
1562
+ }
1563
+
1564
+ /** The class of the layer's element. */
1565
+ export const ENGAGE_CLASS = 'tile-engage';
1566
+
1567
+ /**
1568
+ * "Press to use": until the user picks the tile, a layer of the host's lies
1569
+ * over it. The tile runs and shows, and gets no input. A wheel or a finger
1570
+ * on it scrolls the page, the page sees every pointer that crosses it, and
1571
+ * focus arriving in the frame is by definition the tile's own doing. A
1572
+ * press on the layer picks the tile (that press is spent on it: nothing can
1573
+ * hand an event on to another origin's frame). A press anywhere else on the
1574
+ * page, the tile leaving the viewport, or Escape, puts the layer back.
1575
+ *
1576
+ * Until it is picked the tile is not a stop on the way through the page with
1577
+ * Tab either (its frame has `tabindex="-1"` meanwhile): the layer is, after
1578
+ * it in its box, and Enter or Space there picks the tile and goes into it.
1579
+ * (With the focus guard on as well, the frame stays out of the tab order
1580
+ * once the tile is picked, and the guard's stop is the way back in.)
1581
+ *
1582
+ * The layer paints, though too faintly to see: a block that paints nothing
1583
+ * does not take a press over a frame. `stop()` takes it away for good.
1584
+ */
1585
+ export function engage (tile: Tile, frame: HTMLIFrameElement, options: EngageOptions = {}): EngageControl {
1586
+ const doc = frame.ownerDocument;
1587
+ const win = doc.defaultView as Window & typeof globalThis;
1588
+ const wrapper = options.wrapper ?? frame.parentElement;
1589
+ if (!wrapper) throw new Error('engage() needs the frame to be in an element that holds it.');
1590
+ const position = win.getComputedStyle(wrapper).position;
1591
+ if (!position || position === 'static') wrapper.style.position = 'relative';
1592
+ const layer = doc.createElement('div');
1593
+ layer.className = ENGAGE_CLASS;
1594
+ layer.setAttribute('role', 'button');
1595
+ layer.setAttribute('tabindex', '0');
1596
+ layer.setAttribute('aria-label', options.label ?? 'Use this tile');
1597
+ layer.style.cssText = 'position:absolute;inset:0;z-index:1;background:rgba(127,127,127,0.03);cursor:pointer;';
1598
+ let engaged = false;
1599
+ let stopped = false;
1600
+ // A tile that is not picked is not to be tabbed into: Tab would take the
1601
+ // keyboard past the layer and into it. (With a guard on the keyboard that
1602
+ // would be given back, every time, and count against the tile.) Held out
1603
+ // with whatever else holds it, the focus guard's layer among them (see
1604
+ // `holdOut`): picked, the frame is back in only once nothing else holds it.
1605
+ let back: (() => void) | undefined;
1606
+ const reach = (on: boolean) => {
1607
+ if (!on) back ??= holdOut(frame);
1608
+ else {
1609
+ back?.();
1610
+ back = undefined;
1611
+ }
1612
+ };
1613
+ const set = (on: boolean, why: Parameters<NonNullable<EngageOptions['onChange']>>[1]) => {
1614
+ if (on === engaged || stopped) return;
1615
+ engaged = on;
1616
+ layer.style.display = on ? 'none' : 'block';
1617
+ reach(on);
1618
+ if (!on && holds(frame)) frame.blur();
1619
+ options.onChange?.(on, why);
1620
+ };
1621
+ layer.addEventListener('click', (ev) => { if (ev.isTrusted) set(true, 'picked'); });
1622
+ layer.addEventListener('keydown', (ev) => {
1623
+ if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
1624
+ ev.preventDefault();
1625
+ set(true, 'picked');
1626
+ // Through the frame's window, as the focus guard's own way in goes (see
1627
+ // `guardFocus`), and for its reason.
1628
+ frame.contentWindow?.focus();
1629
+ });
1630
+ const onDown = (ev: Event) => { if (ev.isTrusted && engaged && !wrapper.contains((ev.composedPath?.()[0] ?? ev.target) as Node)) set(false, 'pressed elsewhere'); };
1631
+ const onKey = (ev: KeyboardEvent) => { if (ev.isTrusted && engaged && ev.key === 'Escape') set(false, 'escape'); };
1632
+ doc.addEventListener('pointerdown', onDown, true);
1633
+ doc.addEventListener('keydown', onKey, true);
1634
+ const seen = typeof win.IntersectionObserver === 'function'
1635
+ ? new win.IntersectionObserver((entries) => { if (entries.some(en => !en.isIntersecting)) set(false, 'out of view'); })
1636
+ : undefined;
1637
+ seen?.observe(frame);
1638
+ wrapper.append(layer);
1639
+ reach(false);
1640
+ if (options.start === 'engaged') set(true, 'started');
1641
+ const stop = () => {
1642
+ if (stopped) return;
1643
+ stopped = true;
1644
+ reach(true);
1645
+ doc.removeEventListener('pointerdown', onDown, true);
1646
+ doc.removeEventListener('keydown', onKey, true);
1647
+ seen?.disconnect();
1648
+ layer.remove();
1649
+ tile.removeEventListener('close', stop);
1650
+ };
1651
+ // A tile that is closed has no frame left to lay anything over.
1652
+ tile.addEventListener('close', stop);
1653
+ return {
1654
+ layer,
1655
+ get engaged () { return engaged; },
1656
+ release () { set(false, 'released'); },
1657
+ stop,
1658
+ };
1659
+ }