@botiverse/porthole 0.12.0 → 0.14.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 (94) hide show
  1. package/dist/annotate/types.d.ts +32 -3
  2. package/dist/annotate/types.js +4 -0
  3. package/dist/annotate/validate.js +19 -2
  4. package/dist/bridge/bridge.d.ts +8 -1
  5. package/dist/bridge/bridge.js +7 -0
  6. package/dist/bridge/unseen.d.ts +8 -0
  7. package/dist/bridge/unseen.js +17 -0
  8. package/dist/check/files.js +14 -10
  9. package/dist/check/lint.js +1 -1
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/scroll.d.ts +29 -13
  12. package/dist/check/scroll.js +74 -18
  13. package/dist/compile/policy.d.ts +7 -0
  14. package/dist/compile/policy.js +13 -1
  15. package/dist/config/capabilities.d.ts +16 -3
  16. package/dist/config/capabilities.js +1 -0
  17. package/dist/config/schema.d.ts +11 -0
  18. package/dist/config/validate.js +19 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.js +3 -1
  21. package/dist/guide/limits.js +1 -1
  22. package/dist/guide/runtime.js +1 -1
  23. package/dist/host/create-host.d.ts +2 -0
  24. package/dist/host/create-host.js +100 -3
  25. package/dist/host/pass-on.d.ts +15 -0
  26. package/dist/host/pass-on.js +65 -0
  27. package/dist/host/types.d.ts +37 -0
  28. package/dist/index.d.ts +5 -1
  29. package/dist/index.js +5 -1
  30. package/dist/isolation/types.d.ts +8 -0
  31. package/dist/isolation/types.js +8 -0
  32. package/dist/platform/focus-guard.d.ts +212 -0
  33. package/dist/platform/focus-guard.js +620 -0
  34. package/dist/platform/types.d.ts +25 -0
  35. package/dist/platform/web.js +80 -2
  36. package/dist/presets/presets.d.ts +2 -0
  37. package/dist/presets/presets.js +1 -0
  38. package/dist/react/frame.d.ts +8 -0
  39. package/dist/react/frame.js +4 -0
  40. package/dist/runtime/requests.js +34 -12
  41. package/dist/runtime/types.generated.js +1 -1
  42. package/dist/server/files.js +19 -3
  43. package/dist/server/index.d.ts +1 -0
  44. package/dist/server/index.js +4 -0
  45. package/dist/server/nested.d.ts +37 -0
  46. package/dist/server/nested.js +70 -0
  47. package/dist/server/server.js +57 -7
  48. package/dist/shell/annotate.d.ts +1 -1
  49. package/dist/shell/annotate.js +157 -7
  50. package/dist/shell/frame.d.ts +45 -0
  51. package/dist/shell/frame.js +250 -0
  52. package/dist/shell/plan.js +2 -1
  53. package/dist/shell/runtime.js +49 -14
  54. package/docs/ADOPTING.md +140 -7
  55. package/docs/ARCHITECTURE.md +23 -0
  56. package/docs/DECISIONS.md +564 -5
  57. package/docs/DESIGN.md +18 -2
  58. package/docs/THREAT_MODEL.md +192 -30
  59. package/package.json +1 -1
  60. package/src/annotate/types.ts +28 -3
  61. package/src/annotate/validate.ts +23 -2
  62. package/src/bridge/bridge.ts +17 -1
  63. package/src/bridge/unseen.ts +24 -0
  64. package/src/check/files.ts +14 -10
  65. package/src/check/lint.ts +1 -1
  66. package/src/check/scroll.ts +106 -38
  67. package/src/compile/policy.ts +14 -1
  68. package/src/config/capabilities.ts +16 -3
  69. package/src/config/schema.ts +11 -0
  70. package/src/config/validate.ts +23 -0
  71. package/src/displays/displays.ts +3 -1
  72. package/src/guide/limits.ts +1 -1
  73. package/src/guide/runtime.ts +1 -1
  74. package/src/host/create-host.ts +105 -4
  75. package/src/host/pass-on.ts +73 -0
  76. package/src/host/types.ts +33 -0
  77. package/src/index.ts +5 -1
  78. package/src/isolation/types.ts +12 -0
  79. package/src/platform/focus-guard.ts +815 -0
  80. package/src/platform/types.ts +24 -0
  81. package/src/platform/web.ts +96 -2
  82. package/src/presets/presets.ts +3 -0
  83. package/src/react/frame.tsx +10 -0
  84. package/src/runtime/requests.ts +36 -14
  85. package/src/runtime/types.generated.ts +1 -1
  86. package/src/server/files.ts +19 -3
  87. package/src/server/index.ts +10 -0
  88. package/src/server/nested.ts +86 -0
  89. package/src/server/server.ts +65 -6
  90. package/src/shell/annotate.ts +157 -7
  91. package/src/shell/frame.ts +268 -0
  92. package/src/shell/plan.ts +2 -1
  93. package/src/shell/runtime.ts +49 -14
  94. package/types/runtime/v1/comments.d.ts +8 -4
@@ -0,0 +1,815 @@
1
+ /**
2
+ * The focus guard (P109): a display's frame can move the keyboard into itself whenever it likes
3
+ * (`element.focus()` in its own realm; on Chromium and WebKit with no gesture at all), and what the
4
+ * person goes on typing into the host's composer or chat box then goes to the page. Porthole can't
5
+ * stop the call, which runs in the content's realm, but the host's page can undo it: when focus
6
+ * leaves one of its text fields for a display's frame and the person didn't move it there, focus
7
+ * goes back once the engine has finished moving it, the guard watches that it stays back, and the
8
+ * display hears `focusTaken`; a display whose frame keeps doing it is stopped (`createHost`).
9
+ *
10
+ * What the host's page can see of a move into a frame, measured on Chromium, WebKit and Firefox
11
+ * (P109): Chromium and WebKit blur the host's window as it happens, and a press on the frame (a
12
+ * click, a tap, held or not) leaves the frame element `:active` then; a Tab is the host's own
13
+ * keydown just before. Firefox doesn't blur the window and shows no `:active` (a focusout on the
14
+ * field was seen in one review's runs, not in another's): its `document.activeElement` changes,
15
+ * which the guard reads at each animation frame while a frame is guarded, and the pointer over the
16
+ * frame (`:hover`, `pointerover`) is all it can tell of a press. A page that takes focus back on
17
+ * its own blur (which a take-back fires) leaves Firefox's focus on nothing (`<body>`) or in the
18
+ * frame again (the review of the guard, GK-1): the guard keeps watching after each take-back and
19
+ * counts one that didn't hold. Every engine keeps a gesture's transient activation for 5 s
20
+ * (measured: 5.04 to 5.10 s).
21
+ */
22
+
23
+ /** How long the person's Tab counts as moving focus (the move follows its keydown at once). */
24
+ export const TAB_MS = 1_000;
25
+
26
+ /**
27
+ * How long transient activation lasts after a gesture (measured: 5 s on all three engines): a
28
+ * host page with activation and no gesture of its own for longer had one in a frame.
29
+ */
30
+ export const ACTIVATION_SPAN_MS = 5_000;
31
+
32
+ /** The person is typing: a key on the host's page within this long. */
33
+ export const TYPING_MS = 1_000;
34
+
35
+ /**
36
+ * After a take-back, the guard keeps watching (each animation frame) until focus has stayed in the
37
+ * text field this long: a page that takes it again at once (on its own blur, which the take-back
38
+ * fires) is caught as it does, on Firefox too (P109, after the review of the guard: GK-1).
39
+ */
40
+ export const HELD_MS = 300;
41
+
42
+ /** A take-back that hasn't put focus back in the field after this long failed: counted, and tried again. */
43
+ export const GIVE_BACK_MS = 50;
44
+
45
+ /**
46
+ * A frame that holds focus isn't the person's for this long after they press the host's page: the
47
+ * press gives the page activation before focus leaves the frame (on Firefox, a move between
48
+ * processes), and a call the frame sends in between would borrow it.
49
+ */
50
+ export const HOST_PRESS_MS = 1_000;
51
+
52
+ /**
53
+ * When a display is stopped for taking the keyboard (P109): focus given back can't stop its frame
54
+ * calling `focus()` again (nothing the host sets on the frame does, `inert` included: measured),
55
+ * and each try leaves it the keys typed until focus is back. So three undone moves within 10 s
56
+ * that came while the person typed on the page or that kept focus from going back (a take-back that
57
+ * failed: the keys then go to the frame, and the page sees no typing to count), or five at all
58
+ * within 2 s, stop it. A person's own move never fails a take-back.
59
+ */
60
+ export const TAKES = {
61
+ typing: { most: 3, withinMs: 10_000 },
62
+ any: { most: 5, withinMs: 2_000 },
63
+ } as const;
64
+
65
+ /**
66
+ * A nested page's shell (P111) says its own activation turned on: a press or key of the person's
67
+ * in that page (activation goes up to ancestors, never down, so nothing on the host's page turns
68
+ * it on). A move of focus into the frame within this long of it, with no press or key on the
69
+ * host's page since, is the person's; so is a `comments.open` the page sends within it.
70
+ */
71
+ export const SHELL_GESTURE_MS = 1_000;
72
+
73
+ /**
74
+ * How long a move into a nested page's frame waits for its shell's word before it is taken for
75
+ * the page's: the shell says what it saw at its next animation frame, after the host's page
76
+ * already heard the move. A shell that says nothing in time (gone, stalled) has its frame's move
77
+ * taken back, as any page's.
78
+ */
79
+ export const SHELL_WAIT_MS = 500;
80
+
81
+ /**
82
+ * A shell's word that came this long before the host's page heard the move is about that move
83
+ * (the shell's frame can come first); one from before then is about an earlier one.
84
+ */
85
+ export const SHELL_EARLY_MS = 150;
86
+
87
+ /**
88
+ * A shell that went this long without a look, or without a word to the host (its heartbeat is every
89
+ * 50 ms), was stalled (P111, after its review): where the page shares the shell's thread (WebKit,
90
+ * Firefox), a page that holds it from its own click handler pushes the moment the shell sees its
91
+ * activation turn on past the person's next keys on the host's page. An activation it saw then is
92
+ * uncertain: it is no one's gesture until it lapses.
93
+ */
94
+ export const SHELL_STALL_MS = 100;
95
+
96
+ /** What a nested page's shell last said (P111), on the host's clock. */
97
+ export interface ShellWord {
98
+ /** Whether its engine tells activation at all (`navigator.userActivation`). */
99
+ readonly supported: boolean;
100
+ /** When its activation last turned on; -Infinity if it hasn't, or is off. */
101
+ readonly activatedAt: number;
102
+ /** Whether it last said the page's focus is in it, and when it last said focus came in. */
103
+ readonly focused: boolean;
104
+ readonly focusedAt: number;
105
+ /** Its activation turned on while it was stalled: uncertain until it goes off (`SHELL_STALL_MS`). */
106
+ readonly uncertain?: boolean;
107
+ }
108
+
109
+ /** One move of the keyboard the guard undid. */
110
+ export interface FocusTake {
111
+ /** The person pressed a key on the host's page within the last second. */
112
+ readonly typing: boolean;
113
+ /**
114
+ * Focus didn't stay back in the field: the frame kept it, took it again within `HELD_MS`, or it
115
+ * landed nowhere.
116
+ */
117
+ readonly failed: boolean;
118
+ }
119
+
120
+ /** What the host's page knew when focus left one of its text fields for a display's frame. */
121
+ export interface FocusMove {
122
+ readonly now: number;
123
+ /** The engine told the host's page as it happened (its window blurred): Chromium, WebKit. */
124
+ readonly seen: boolean;
125
+ /** The frame element is `:active`: a press on it, pointer or touch (Chromium, WebKit). */
126
+ readonly pressed: boolean;
127
+ /** The pointer is over the frame element (`:hover`). */
128
+ readonly over: boolean;
129
+ /** When the pointer last came over the frame element (`pointerover`); -Infinity if never. */
130
+ readonly overSince: number;
131
+ /** The person's last key on the host's page, and when. */
132
+ readonly lastKey: { readonly key: string; readonly at: number } | null;
133
+ /** When the person last typed on the host's page (a key other than Tab and the modifiers). */
134
+ readonly typedAt: number;
135
+ /** When the text field focus left got it. */
136
+ readonly focusedAt: number;
137
+ /** When the host's page last saw a gesture of its own (a key, a press, a click, typed text). */
138
+ readonly gestureAt: number;
139
+ /** Whether the host's page has transient activation now; undefined where it can't tell. */
140
+ readonly activation: boolean | undefined;
141
+ /** The host moved focus into the frame itself (`DisplayHandle.focus()`), just now. */
142
+ readonly hostMoved: boolean;
143
+ /**
144
+ * A nested page's frame (P111): what its shell said, and when the host's page last had a
145
+ * trusted press or key of its own. Absent for any other frame.
146
+ */
147
+ readonly shell?: { readonly word: ShellWord; readonly hostInputAt: number };
148
+ }
149
+
150
+ /**
151
+ * Whether the person moved focus into the frame themselves:
152
+ * - the host did (`DisplayHandle.focus()`);
153
+ * - by the keyboard: their last key on the host's page was Tab (or Shift+Tab), just now;
154
+ * - by a press on the frame: where the engine tells the move as it happens (Chromium, WebKit),
155
+ * the frame element is `:active`; where it doesn't (Firefox), the pointer is over the frame and
156
+ * came over it after the text field got focus and after the person last typed in the host's page
157
+ * (a page can't move the pointer; a composer that opened beside the frame while the pointer
158
+ * rested over it, and a person typing with it there, keep their keys);
159
+ * - by a gesture the host's own events don't explain: the host's page has transient activation,
160
+ * and for longer than activation lasts it saw no gesture of its own and the text field has had
161
+ * focus, so the person pressed or activated something in a frame since (an assistive
162
+ * technology's activation, which moves no pointer and sends the host no key, is one). The
163
+ * gesture that opened a composer (a selection in the frame, `selected`) is older than the
164
+ * composer's focus, and doesn't count.
165
+ * Anything else is the page's: focus goes back.
166
+ */
167
+ export function personMoved(move: FocusMove): boolean {
168
+ if (move.hostMoved) {
169
+ return true;
170
+ }
171
+ if (move.lastKey !== null && move.lastKey.key === "Tab" && move.now - move.lastKey.at <= TAB_MS) {
172
+ return true;
173
+ }
174
+ // A nested page (P111): its shell's activation turned on within the last second, and the host's
175
+ // page had no press or key of its own since (the person went back to it); or, where the engine
176
+ // tells it, a press on the frame. Nothing else: no pointer over it, no host-wide activation.
177
+ if (move.shell !== undefined && move.shell.word.supported) {
178
+ return (
179
+ (move.seen && move.pressed) || shellGesture(move.shell.word, move.shell.hostInputAt, move.now)
180
+ );
181
+ }
182
+ if (
183
+ move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)
184
+ ) {
185
+ return true;
186
+ }
187
+ return (
188
+ move.activation === true &&
189
+ move.now - Math.max(move.gestureAt, move.focusedAt) > ACTIVATION_SPAN_MS
190
+ );
191
+ }
192
+
193
+ /**
194
+ * Whether a nested page's shell saw the person's gesture just now (P111): its activation turned on
195
+ * within `SHELL_GESTURE_MS`, after the host's page's last trusted press or key.
196
+ */
197
+ export function shellGesture(word: ShellWord, hostInputAt: number, now: number): boolean {
198
+ return (
199
+ word.supported &&
200
+ now - word.activatedAt <= SHELL_GESTURE_MS &&
201
+ now >= word.activatedAt &&
202
+ hostInputAt < word.activatedAt
203
+ );
204
+ }
205
+
206
+ /** Keys that type nothing on their own: they don't count as typing (a gesture still). */
207
+ const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta", "AltGraph", "CapsLock", "Fn"]);
208
+
209
+ /** The `<input>` types that take typed text (an unknown type is `text`). */
210
+ const TEXT_INPUTS = new Set(["text", "search", "url", "tel", "email", "password", "number"]);
211
+
212
+ /** Whether `element` takes the person's typed text: a text field, a text area, an editable region. */
213
+ export function takesText(element: Element | null): element is HTMLElement {
214
+ if (element === null) {
215
+ return false;
216
+ }
217
+ switch (element.localName) {
218
+ case "textarea":
219
+ return true;
220
+ case "input":
221
+ return TEXT_INPUTS.has((element as HTMLInputElement).type);
222
+ default:
223
+ return (element as Partial<HTMLElement>).isContentEditable ?? false;
224
+ }
225
+ }
226
+
227
+ /** The element that has focus, inside open shadow roots too. */
228
+ function deepActive(document: Document): Element | null {
229
+ let active = document.activeElement;
230
+ for (
231
+ let inner = active?.shadowRoot?.activeElement;
232
+ inner !== null && inner !== undefined;
233
+ inner = active?.shadowRoot?.activeElement
234
+ ) {
235
+ active = inner;
236
+ }
237
+ return active;
238
+ }
239
+
240
+ /** One page's guard, shared by every display's frame on it. */
241
+ export interface FocusGuard {
242
+ /**
243
+ * Guards `frame`: `taken` hears each move into it that was undone. `nested`: it holds a nested
244
+ * page's shell (P111), whose word (`shell`) decides the moves into it.
245
+ */
246
+ add(
247
+ frame: HTMLIFrameElement,
248
+ taken: (take: FocusTake) => void,
249
+ options?: { readonly nested?: boolean },
250
+ ): () => void;
251
+ /** What a nested page's shell said (P111): its activation, its focus. */
252
+ shell(
253
+ frame: HTMLIFrameElement,
254
+ said: {
255
+ readonly supported: boolean;
256
+ readonly ago: number | null;
257
+ readonly focused: boolean;
258
+ /** How long the shell went without a look before this one (its own clock). */
259
+ readonly gap: number;
260
+ },
261
+ ): void;
262
+ /** A nested page's shell's heartbeat (P111): it is looking. */
263
+ beat(frame: HTMLIFrameElement): void;
264
+ /** Whether a nested page's shell saw the person's gesture just now (`shellGesture`). */
265
+ gesture(frame: HTMLIFrameElement): boolean;
266
+ /** The host moves focus into `frame` itself. */
267
+ focus(frame: HTMLIFrameElement): void;
268
+ /**
269
+ * Whether the page's focus is in `frame` now, the person's own (once any move into it was
270
+ * judged; on an engine that tells the host's page nothing, here and then).
271
+ */
272
+ focused(frame: HTMLIFrameElement): boolean;
273
+ /** The host moves focus into one of its text fields: see `focusField`. */
274
+ field(field: HTMLElement): void;
275
+ }
276
+
277
+ interface Guarded {
278
+ readonly taken: Set<(take: FocusTake) => void>;
279
+ overSince: number;
280
+ /** A nested page's shell's word (P111); null for any other frame. */
281
+ word: ShellWord | null;
282
+ /** When the host last heard the shell (a report or a heartbeat). */
283
+ heardAt: number;
284
+ }
285
+
286
+ const guards = new WeakMap<Window, FocusGuard>();
287
+
288
+ /** The guard for `view`'s page, made on first use. */
289
+ export function focusGuard(view: Window): FocusGuard {
290
+ const existing = guards.get(view);
291
+ if (existing !== undefined) {
292
+ return existing;
293
+ }
294
+ const document = view.document;
295
+ const frames = new Map<HTMLIFrameElement, Guarded>();
296
+ const now = () => view.performance.now();
297
+ let known: Element | null = deepActive(document);
298
+ let focusedAt = now();
299
+ let lastKey: { key: string; at: number } | null = null;
300
+ let typedAt = -Infinity;
301
+ let gestureAt = -Infinity;
302
+ let pressAt = -Infinity;
303
+ /** The host's page's last trusted press or key (P111: a nested page's gesture must be later). */
304
+ let inputAt = -Infinity;
305
+ /**
306
+ * A move into a nested page's frame waiting for its shell's word (P111): from a text field
307
+ * (`field`: taken back unless the shell says the person's), or from anything else (null: only
308
+ * whether the frame is the person's for a gesture gate).
309
+ */
310
+ let waiting: {
311
+ readonly field: HTMLElement | null;
312
+ readonly frame: HTMLIFrameElement;
313
+ readonly guarded: Guarded;
314
+ readonly since: number;
315
+ readonly failed: boolean;
316
+ } | null = null;
317
+ /** When focus last went into a guarded frame, and whether the person moved it there. */
318
+ let enteredAt = -Infinity;
319
+ let earned = false;
320
+ /** The text field the person last pressed, when, and what had focus as they pressed it. */
321
+ let pressed: {
322
+ readonly field: HTMLElement;
323
+ readonly at: number;
324
+ readonly from: Element | null;
325
+ } | null = null;
326
+ let hostMove: { frame: HTMLIFrameElement; at: number } | null = null;
327
+ let polling = 0;
328
+ /**
329
+ * A take-back in progress: the field focus goes back to, the frame it came from, when focus was
330
+ * last given back, and since when it has stayed in the field. Ends once it has stayed `HELD_MS`,
331
+ * the person moves focus somewhere of their own, or the field or frame is gone.
332
+ */
333
+ let contest: {
334
+ readonly field: HTMLElement;
335
+ readonly frame: HTMLIFrameElement;
336
+ readonly guarded: Guarded;
337
+ gaveAt: number;
338
+ heldSince: number | null;
339
+ } | null = null;
340
+
341
+ const activation = (): boolean | undefined => {
342
+ try {
343
+ const state = (view.navigator as Navigator & { userActivation?: { isActive: boolean } })
344
+ .userActivation;
345
+ return state === undefined ? undefined : state.isActive;
346
+ } catch {
347
+ return undefined;
348
+ }
349
+ };
350
+
351
+ /**
352
+ * What the person's move would need, read now: see `personMoved`. Into a nested page's frame
353
+ * whose shell hasn't spoken of this move yet, `wait` (P111).
354
+ */
355
+ const judge = (
356
+ frame: HTMLIFrameElement,
357
+ guarded: Guarded,
358
+ seen: boolean,
359
+ at: number,
360
+ ): boolean | "wait" => {
361
+ const word = guarded.word;
362
+ const moved = personMoved({
363
+ now: at,
364
+ seen,
365
+ pressed: frame.matches(":active"),
366
+ over: frame.matches(":hover"),
367
+ overSince: guarded.overSince,
368
+ lastKey,
369
+ typedAt,
370
+ focusedAt,
371
+ gestureAt,
372
+ activation: activation(),
373
+ hostMoved: hostMove !== null && hostMove.frame === frame && at - hostMove.at <= TAB_MS,
374
+ ...(word === null ? {} : { shell: { word, hostInputAt: inputAt } }),
375
+ });
376
+ hostMove = null;
377
+ // The shell tells a move at its next frame, the host's page hears it first: until the shell
378
+ // said focus came in (around now), its activation may be on its way.
379
+ if (!moved && word !== null && word.supported && word.focusedAt < at - SHELL_EARLY_MS) {
380
+ return "wait";
381
+ }
382
+ return moved;
383
+ };
384
+
385
+ /** Waits for a nested page's shell's word on a move (P111): decided by `settle`. */
386
+ const wait = (
387
+ field: HTMLElement | null,
388
+ frame: HTMLIFrameElement,
389
+ guarded: Guarded,
390
+ at: number,
391
+ failed: boolean,
392
+ ) => {
393
+ waiting = { field, frame, guarded, since: at, failed };
394
+ known = frame;
395
+ enteredAt = at;
396
+ earned = false;
397
+ schedule();
398
+ };
399
+
400
+ /**
401
+ * A waiting move, once its shell spoke or the wait is over: the person's (the frame keeps
402
+ * focus), or the page's (from a text field, taken back). A move elsewhere since ends it.
403
+ */
404
+ const settle = (at: number) => {
405
+ const held = waiting;
406
+ if (held === null) {
407
+ return;
408
+ }
409
+ const { field, frame, guarded } = held;
410
+ if (deepActive(document) !== frame || !frames.has(frame)) {
411
+ // Moved on since: from the frame, as the next look judges it.
412
+ waiting = null;
413
+ known = frame;
414
+ return;
415
+ }
416
+ const word = guarded.word;
417
+ const theirs = word !== null && shellGesture(word, inputAt, at);
418
+ const spoke = word !== null && word.focusedAt >= held.since - SHELL_EARLY_MS;
419
+ if (theirs) {
420
+ waiting = null;
421
+ known = frame;
422
+ earned = true;
423
+ return;
424
+ }
425
+ if (!spoke && at - held.since < SHELL_WAIT_MS) {
426
+ return;
427
+ }
428
+ waiting = null;
429
+ if (field !== null && field.isConnected) {
430
+ takeBack(field, frame, guarded, at, held.failed);
431
+ }
432
+ };
433
+
434
+ /**
435
+ * Focus goes back to `field` once the engine has finished the move: given back inside its blur
436
+ * it stays with the frame on Chromium and WebKit, and Firefox takes it back only from a frame
437
+ * that was blurred first (measured). Unless the person has since put focus somewhere of their own.
438
+ */
439
+ const giveBack = (field: HTMLElement, frame: HTMLIFrameElement) => {
440
+ view.setTimeout(() => {
441
+ const current = deepActive(document);
442
+ if (
443
+ field.isConnected &&
444
+ (current === frame || current === null || current === document.body)
445
+ ) {
446
+ frame.blur();
447
+ field.focus({ preventScroll: true });
448
+ }
449
+ }, 0);
450
+ };
451
+
452
+ /** A move the guard undoes: focus goes back, the display hears it, and the guard keeps watching. */
453
+ const takeBack = (
454
+ field: HTMLElement,
455
+ frame: HTMLIFrameElement,
456
+ guarded: Guarded,
457
+ at: number,
458
+ failed: boolean,
459
+ ) => {
460
+ // Until it is back, the field counts as the page's focus, so a move that didn't take is seen.
461
+ known = field;
462
+ focusedAt = at;
463
+ contest = { field, frame, guarded, gaveAt: at, heldSince: null };
464
+ giveBack(field, frame);
465
+ schedule();
466
+ const take: FocusTake = { typing: at - typedAt <= TYPING_MS, failed };
467
+ for (const taken of guarded.taken) {
468
+ taken(take);
469
+ }
470
+ };
471
+
472
+ /**
473
+ * While a take-back is in progress: whether focus stayed in the field, or the frame has it again
474
+ * (or it landed on nothing), which is the page's doing unless the person moved it there.
475
+ */
476
+ const watch = (seen: boolean, active: Element | null, at: number): boolean => {
477
+ const watched = contest;
478
+ if (watched === null) {
479
+ return false;
480
+ }
481
+ const { field, frame, guarded } = watched;
482
+ if (!field.isConnected || pressAt > watched.gaveAt) {
483
+ // Gone, or the person pressed the page since: theirs to place focus now.
484
+ contest = null;
485
+ return false;
486
+ }
487
+ if (!frames.has(frame)) {
488
+ // The frame was removed mid-fight (its display stopped): Firefox may leave focus on nothing
489
+ // once the focused frame goes. Back into the field, for a moment after.
490
+ if ((active === null || active === document.body) && at - watched.gaveAt <= HELD_MS) {
491
+ field.focus({ preventScroll: true });
492
+ return true;
493
+ }
494
+ contest = null;
495
+ return false;
496
+ }
497
+ if (active === field) {
498
+ watched.heldSince ??= at;
499
+ if (at - watched.heldSince >= HELD_MS) {
500
+ contest = null;
501
+ }
502
+ known = field;
503
+ return true;
504
+ }
505
+ const lost = active === frame || active === null || active === document.body;
506
+ if (!lost) {
507
+ // Somewhere else of the person's (another field, a button, another frame): judged as any.
508
+ contest = null;
509
+ return false;
510
+ }
511
+ if (active === frame) {
512
+ const verdict = judge(frame, guarded, seen, at);
513
+ if (verdict === true) {
514
+ contest = null;
515
+ known = frame;
516
+ enteredAt = at;
517
+ earned = true;
518
+ return true;
519
+ }
520
+ if (verdict === "wait") {
521
+ // A nested page's frame took it again (P111): its shell decides, as it would at first.
522
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
523
+ contest = null;
524
+ wait(field, frame, guarded, at, true);
525
+ }
526
+ return true;
527
+ }
528
+ }
529
+ // Taken again once it was back (within `HELD_MS`), or not back yet after `GIVE_BACK_MS`: a
530
+ // take-back that failed, given again and counted.
531
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
532
+ takeBack(field, frame, guarded, at, true);
533
+ }
534
+ return true;
535
+ };
536
+
537
+ /** Judges a change of focus since the last look: `seen` when the engine told it (a blur). */
538
+ const look = (seen: boolean) => {
539
+ const active = deepActive(document);
540
+ const at = now();
541
+ if (waiting !== null) {
542
+ settle(at);
543
+ return;
544
+ }
545
+ if (watch(seen, active, at)) {
546
+ return;
547
+ }
548
+ const was = known;
549
+ // The person pressed a text field and focus is on nothing: on Firefox, a page that takes focus
550
+ // as they press, or takes it back on its blur with a gesture of theirs, leaves it there
551
+ // (measured, on a slow machine too), and their keys are lost. Into the field, once: as a
552
+ // take-back the page failed if a frame had focus as they pressed, else simply.
553
+ const press = pressed;
554
+ if (
555
+ press !== null &&
556
+ (active === null || active === document.body) &&
557
+ at - press.at <= HELD_MS &&
558
+ press.field.isConnected
559
+ ) {
560
+ pressed = null;
561
+ const from = press.from ?? was;
562
+ const blamed = from === null ? undefined : frames.get(from as HTMLIFrameElement);
563
+ if (blamed === undefined) {
564
+ known = active;
565
+ press.field.focus({ preventScroll: true });
566
+ } else {
567
+ takeBack(press.field, from as HTMLIFrameElement, blamed, at, true);
568
+ }
569
+ return;
570
+ }
571
+ known = active;
572
+ if (active === was || active === null) {
573
+ return;
574
+ }
575
+ const entered = frames.get(active as HTMLIFrameElement);
576
+ if (entered !== undefined) {
577
+ // From a text field it is judged below; from anything else it is let be, but only the
578
+ // person's own move makes the frame theirs for a gesture gate (`focused`).
579
+ enteredAt = at;
580
+ const verdict = takesText(was) || judge(active as HTMLIFrameElement, entered, seen, at);
581
+ if (verdict === "wait") {
582
+ // A nested page's (P111): theirs once its shell says so; nothing to take back.
583
+ wait(null, active as HTMLIFrameElement, entered, at, false);
584
+ return;
585
+ }
586
+ earned = verdict;
587
+ }
588
+ // Into a text field from a display's frame (the person pressed the composer while the frame
589
+ // had focus): watched as a take-back is, since a page that takes focus back on its own blur
590
+ // leaves it on nothing on Firefox (measured), where the keys are lost to the page's doing.
591
+ const left = was === null ? undefined : frames.get(was as HTMLIFrameElement);
592
+ if (left !== undefined && takesText(active)) {
593
+ contest = {
594
+ field: active,
595
+ frame: was as HTMLIFrameElement,
596
+ guarded: left,
597
+ gaveAt: at,
598
+ heldSince: at,
599
+ };
600
+ return;
601
+ }
602
+ const guarded = frames.get(active as HTMLIFrameElement);
603
+ if (guarded === undefined || !takesText(was) || !was.isConnected) {
604
+ return;
605
+ }
606
+ const frame = active as HTMLIFrameElement;
607
+ const verdict = judge(frame, guarded, seen, at);
608
+ if (verdict === true) {
609
+ return;
610
+ }
611
+ if (verdict === "wait") {
612
+ wait(was, frame, guarded, at, false);
613
+ return;
614
+ }
615
+ takeBack(was, frame, guarded, at, false);
616
+ };
617
+
618
+ /**
619
+ * Firefox moves focus into a frame without a word to the host's page: while a frame is guarded,
620
+ * look at each animation frame (one read of the focused element), so the guard knows where focus
621
+ * is when it next leaves a text field, or comes into one from a frame.
622
+ */
623
+ const poll = () => {
624
+ polling = 0;
625
+ look(false);
626
+ schedule();
627
+ };
628
+ const schedule = () => {
629
+ if (polling === 0 && (frames.size > 0 || contest !== null || waiting !== null)) {
630
+ polling = view.requestAnimationFrame(poll);
631
+ }
632
+ };
633
+
634
+ const gesture = () => {
635
+ gestureAt = now();
636
+ };
637
+ const press = (event: Event) => {
638
+ pressAt = now();
639
+ if (event.isTrusted) {
640
+ inputAt = pressAt;
641
+ }
642
+ gestureAt = pressAt;
643
+ const target = event.composedPath()[0];
644
+ pressed =
645
+ target instanceof Element && takesText(target)
646
+ ? { field: target, at: pressAt, from: deepActive(document) }
647
+ : null;
648
+ };
649
+ view.addEventListener(
650
+ "keydown",
651
+ (event) => {
652
+ const at = now();
653
+ gestureAt = at;
654
+ lastKey = { key: event.key, at };
655
+ if (event.isTrusted) {
656
+ inputAt = at;
657
+ }
658
+ if (event.key !== "Tab" && !MODIFIERS.has(event.key)) {
659
+ typedAt = at;
660
+ }
661
+ },
662
+ true,
663
+ );
664
+ // A click too (an assistive technology's click on the host's own UI dispatches no press), and
665
+ // text that comes without a key (dictation, a paste, an input method): typing all the same.
666
+ for (const type of ["pointerup", "touchend", "click"]) {
667
+ view.addEventListener(type, gesture, true);
668
+ }
669
+ for (const type of ["pointerdown", "mousedown"]) {
670
+ view.addEventListener(type, press, true);
671
+ }
672
+ view.addEventListener(
673
+ "input",
674
+ () => {
675
+ typedAt = now();
676
+ gestureAt = typedAt;
677
+ },
678
+ true,
679
+ );
680
+ // Focus moving within the page: what had it, for the next move out of a text field.
681
+ document.addEventListener(
682
+ "focusin",
683
+ () => {
684
+ focusedAt = now();
685
+ look(false);
686
+ schedule();
687
+ },
688
+ true,
689
+ );
690
+ // Chromium and WebKit blur the window as focus goes into a frame. Firefox may send the field a
691
+ // focusout first (seen in one review's runs, not in another's): looked at once it's over.
692
+ view.addEventListener("blur", (event) => {
693
+ if (event.target === view) {
694
+ look(true);
695
+ }
696
+ });
697
+ document.addEventListener(
698
+ "focusout",
699
+ () => {
700
+ view.setTimeout(() => look(false), 0);
701
+ },
702
+ true,
703
+ );
704
+
705
+ const guard: FocusGuard = {
706
+ add(frame, taken, options) {
707
+ let guarded = frames.get(frame);
708
+ if (guarded === undefined) {
709
+ const entry: Guarded = {
710
+ taken: new Set(),
711
+ overSince: -Infinity,
712
+ heardAt: -Infinity,
713
+ word:
714
+ options?.nested === true
715
+ ? { supported: true, activatedAt: -Infinity, focused: false, focusedAt: -Infinity }
716
+ : null,
717
+ };
718
+ frame.addEventListener("pointerover", () => {
719
+ entry.overSince = now();
720
+ });
721
+ frames.set(frame, entry);
722
+ guarded = entry;
723
+ }
724
+ guarded.taken.add(taken);
725
+ schedule();
726
+ const own = guarded;
727
+ return () => {
728
+ own.taken.delete(taken);
729
+ if (own.taken.size === 0) {
730
+ frames.delete(frame);
731
+ }
732
+ };
733
+ },
734
+ shell(frame, said) {
735
+ const guarded = frames.get(frame);
736
+ const before = guarded?.word ?? null;
737
+ if (guarded === undefined || before === null) {
738
+ return;
739
+ }
740
+ const at = now();
741
+ // Off to on after a stall, the shell's or the host's (no word for longer than its beat
742
+ // allows): uncertain, and so until it goes off (P111, after its review).
743
+ const turnedOn = said.ago !== null && before.activatedAt === -Infinity && !before.uncertain;
744
+ const stalled = said.gap > SHELL_STALL_MS || at - guarded.heardAt > SHELL_STALL_MS;
745
+ const uncertain = said.ago !== null && (before.uncertain === true || (turnedOn && stalled));
746
+ guarded.heardAt = at;
747
+ guarded.word = {
748
+ supported: said.supported,
749
+ activatedAt: said.ago === null || uncertain ? -Infinity : at - said.ago,
750
+ focused: said.focused,
751
+ focusedAt: said.focused && !before.focused ? at : before.focusedAt,
752
+ ...(uncertain ? { uncertain: true } : {}),
753
+ };
754
+ if (waiting?.frame === frame) {
755
+ settle(at);
756
+ }
757
+ },
758
+ beat(frame) {
759
+ const guarded = frames.get(frame);
760
+ if (guarded !== undefined && guarded.word !== null) {
761
+ guarded.heardAt = now();
762
+ }
763
+ },
764
+ gesture(frame) {
765
+ const word = frames.get(frame)?.word ?? null;
766
+ return word !== null && shellGesture(word, inputAt, now());
767
+ },
768
+ focus(frame) {
769
+ hostMove = { frame, at: now() };
770
+ frame.focus();
771
+ look(true);
772
+ },
773
+ focused(frame) {
774
+ look(false);
775
+ // A press on the host's page since focus went into the frame, just now: the activation is
776
+ // that press's, and focus is about to leave (a call that lands in between doesn't count).
777
+ const pressedHost = pressAt > enteredAt && now() - pressAt < HOST_PRESS_MS;
778
+ return known === frame && document.activeElement === frame && earned && !pressedHost;
779
+ },
780
+ field(field) {
781
+ const holder = deepActive(document);
782
+ const guarded = holder === null ? undefined : frames.get(holder as HTMLIFrameElement);
783
+ if (guarded === undefined) {
784
+ field.focus({ preventScroll: true });
785
+ return;
786
+ }
787
+ // Watched as a take-back: a frame that keeps focus fails it, and is counted.
788
+ const frame = holder as HTMLIFrameElement;
789
+ frame.blur();
790
+ field.focus({ preventScroll: true });
791
+ known = field;
792
+ focusedAt = now();
793
+ contest = { field, frame, guarded, gaveAt: focusedAt, heldSince: null };
794
+ schedule();
795
+ },
796
+ };
797
+ guards.set(view, guard);
798
+ return guard;
799
+ }
800
+
801
+ /**
802
+ * Moves focus into one of the host page's text fields (a composer that opens beside a display,
803
+ * P109): `field.focus()` for a host to call instead. Firefox doesn't move focus from a frame that
804
+ * holds it with a gesture of the person's and takes it back on its own blur (measured: the keys
805
+ * then go to the frame); this blurs the frame first, and the focus guard watches that focus lands,
806
+ * counting a frame that keeps it toward stopping its display. Elsewhere it is `field.focus()`.
807
+ */
808
+ export function focusField(field: HTMLElement): void {
809
+ const view = field.ownerDocument.defaultView;
810
+ if (view === null) {
811
+ field.focus({ preventScroll: true });
812
+ return;
813
+ }
814
+ focusGuard(view).field(field);
815
+ }