@botiverse/porthole 0.12.0 → 0.13.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 (47) hide show
  1. package/dist/bridge/bridge.d.ts +8 -1
  2. package/dist/bridge/bridge.js +7 -0
  3. package/dist/bridge/unseen.d.ts +8 -0
  4. package/dist/bridge/unseen.js +17 -0
  5. package/dist/check/files.js +14 -10
  6. package/dist/check/lint.js +1 -1
  7. package/dist/check/page-source.js +1 -1
  8. package/dist/check/scroll.d.ts +29 -13
  9. package/dist/check/scroll.js +74 -18
  10. package/dist/config/capabilities.d.ts +16 -3
  11. package/dist/config/capabilities.js +1 -0
  12. package/dist/conformance/harness-source.js +1 -1
  13. package/dist/guide/runtime.js +1 -1
  14. package/dist/host/create-host.js +27 -0
  15. package/dist/host/types.d.ts +15 -0
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.js +1 -0
  18. package/dist/platform/focus-guard.d.ts +143 -0
  19. package/dist/platform/focus-guard.js +445 -0
  20. package/dist/platform/types.d.ts +18 -0
  21. package/dist/platform/web.js +22 -0
  22. package/dist/react/frame.d.ts +8 -0
  23. package/dist/react/frame.js +4 -0
  24. package/dist/runtime/requests.js +34 -12
  25. package/dist/runtime/types.generated.js +1 -1
  26. package/docs/ADOPTING.md +85 -6
  27. package/docs/DECISIONS.md +355 -5
  28. package/docs/DESIGN.md +9 -2
  29. package/docs/THREAT_MODEL.md +121 -29
  30. package/package.json +1 -1
  31. package/src/bridge/bridge.ts +17 -1
  32. package/src/bridge/unseen.ts +24 -0
  33. package/src/check/files.ts +14 -10
  34. package/src/check/lint.ts +1 -1
  35. package/src/check/scroll.ts +106 -38
  36. package/src/config/capabilities.ts +16 -3
  37. package/src/guide/runtime.ts +1 -1
  38. package/src/host/create-host.ts +29 -0
  39. package/src/host/types.ts +13 -0
  40. package/src/index.ts +1 -0
  41. package/src/platform/focus-guard.ts +572 -0
  42. package/src/platform/types.ts +17 -0
  43. package/src/platform/web.ts +22 -0
  44. package/src/react/frame.tsx +10 -0
  45. package/src/runtime/requests.ts +36 -14
  46. package/src/runtime/types.generated.ts +1 -1
  47. package/types/runtime/v1/comments.d.ts +8 -4
@@ -0,0 +1,572 @@
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
+ /** One move of the keyboard the guard undid. */
66
+ export interface FocusTake {
67
+ /** The person pressed a key on the host's page within the last second. */
68
+ readonly typing: boolean;
69
+ /**
70
+ * Focus didn't stay back in the field: the frame kept it, took it again within `HELD_MS`, or it
71
+ * landed nowhere.
72
+ */
73
+ readonly failed: boolean;
74
+ }
75
+
76
+ /** What the host's page knew when focus left one of its text fields for a display's frame. */
77
+ export interface FocusMove {
78
+ readonly now: number;
79
+ /** The engine told the host's page as it happened (its window blurred): Chromium, WebKit. */
80
+ readonly seen: boolean;
81
+ /** The frame element is `:active`: a press on it, pointer or touch (Chromium, WebKit). */
82
+ readonly pressed: boolean;
83
+ /** The pointer is over the frame element (`:hover`). */
84
+ readonly over: boolean;
85
+ /** When the pointer last came over the frame element (`pointerover`); -Infinity if never. */
86
+ readonly overSince: number;
87
+ /** The person's last key on the host's page, and when. */
88
+ readonly lastKey: { readonly key: string; readonly at: number } | null;
89
+ /** When the person last typed on the host's page (a key other than Tab and the modifiers). */
90
+ readonly typedAt: number;
91
+ /** When the text field focus left got it. */
92
+ readonly focusedAt: number;
93
+ /** When the host's page last saw a gesture of its own (a key, a press, a click, typed text). */
94
+ readonly gestureAt: number;
95
+ /** Whether the host's page has transient activation now; undefined where it can't tell. */
96
+ readonly activation: boolean | undefined;
97
+ /** The host moved focus into the frame itself (`DisplayHandle.focus()`), just now. */
98
+ readonly hostMoved: boolean;
99
+ }
100
+
101
+ /**
102
+ * Whether the person moved focus into the frame themselves:
103
+ * - the host did (`DisplayHandle.focus()`);
104
+ * - by the keyboard: their last key on the host's page was Tab (or Shift+Tab), just now;
105
+ * - by a press on the frame: where the engine tells the move as it happens (Chromium, WebKit),
106
+ * the frame element is `:active`; where it doesn't (Firefox), the pointer is over the frame and
107
+ * came over it after the text field got focus and after the person last typed in the host's page
108
+ * (a page can't move the pointer; a composer that opened beside the frame while the pointer
109
+ * rested over it, and a person typing with it there, keep their keys);
110
+ * - by a gesture the host's own events don't explain: the host's page has transient activation,
111
+ * and for longer than activation lasts it saw no gesture of its own and the text field has had
112
+ * focus, so the person pressed or activated something in a frame since (an assistive
113
+ * technology's activation, which moves no pointer and sends the host no key, is one). The
114
+ * gesture that opened a composer (a selection in the frame, `selected`) is older than the
115
+ * composer's focus, and doesn't count.
116
+ * Anything else is the page's: focus goes back.
117
+ */
118
+ export function personMoved(move: FocusMove): boolean {
119
+ if (move.hostMoved) {
120
+ return true;
121
+ }
122
+ if (move.lastKey !== null && move.lastKey.key === "Tab" && move.now - move.lastKey.at <= TAB_MS) {
123
+ return true;
124
+ }
125
+ if (
126
+ move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)
127
+ ) {
128
+ return true;
129
+ }
130
+ return (
131
+ move.activation === true &&
132
+ move.now - Math.max(move.gestureAt, move.focusedAt) > ACTIVATION_SPAN_MS
133
+ );
134
+ }
135
+
136
+ /** Keys that type nothing on their own: they don't count as typing (a gesture still). */
137
+ const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta", "AltGraph", "CapsLock", "Fn"]);
138
+
139
+ /** The `<input>` types that take typed text (an unknown type is `text`). */
140
+ const TEXT_INPUTS = new Set(["text", "search", "url", "tel", "email", "password", "number"]);
141
+
142
+ /** Whether `element` takes the person's typed text: a text field, a text area, an editable region. */
143
+ export function takesText(element: Element | null): element is HTMLElement {
144
+ if (element === null) {
145
+ return false;
146
+ }
147
+ switch (element.localName) {
148
+ case "textarea":
149
+ return true;
150
+ case "input":
151
+ return TEXT_INPUTS.has((element as HTMLInputElement).type);
152
+ default:
153
+ return (element as Partial<HTMLElement>).isContentEditable ?? false;
154
+ }
155
+ }
156
+
157
+ /** The element that has focus, inside open shadow roots too. */
158
+ function deepActive(document: Document): Element | null {
159
+ let active = document.activeElement;
160
+ for (
161
+ let inner = active?.shadowRoot?.activeElement;
162
+ inner !== null && inner !== undefined;
163
+ inner = active?.shadowRoot?.activeElement
164
+ ) {
165
+ active = inner;
166
+ }
167
+ return active;
168
+ }
169
+
170
+ /** One page's guard, shared by every display's frame on it. */
171
+ export interface FocusGuard {
172
+ /** Guards `frame`: `taken` hears each move into it that was undone. */
173
+ add(frame: HTMLIFrameElement, taken: (take: FocusTake) => void): () => void;
174
+ /** The host moves focus into `frame` itself. */
175
+ focus(frame: HTMLIFrameElement): void;
176
+ /**
177
+ * Whether the page's focus is in `frame` now, the person's own (once any move into it was
178
+ * judged; on an engine that tells the host's page nothing, here and then).
179
+ */
180
+ focused(frame: HTMLIFrameElement): boolean;
181
+ /** The host moves focus into one of its text fields: see `focusField`. */
182
+ field(field: HTMLElement): void;
183
+ }
184
+
185
+ interface Guarded {
186
+ readonly taken: Set<(take: FocusTake) => void>;
187
+ overSince: number;
188
+ }
189
+
190
+ const guards = new WeakMap<Window, FocusGuard>();
191
+
192
+ /** The guard for `view`'s page, made on first use. */
193
+ export function focusGuard(view: Window): FocusGuard {
194
+ const existing = guards.get(view);
195
+ if (existing !== undefined) {
196
+ return existing;
197
+ }
198
+ const document = view.document;
199
+ const frames = new Map<HTMLIFrameElement, Guarded>();
200
+ const now = () => view.performance.now();
201
+ let known: Element | null = deepActive(document);
202
+ let focusedAt = now();
203
+ let lastKey: { key: string; at: number } | null = null;
204
+ let typedAt = -Infinity;
205
+ let gestureAt = -Infinity;
206
+ let pressAt = -Infinity;
207
+ /** When focus last went into a guarded frame, and whether the person moved it there. */
208
+ let enteredAt = -Infinity;
209
+ let earned = false;
210
+ /** The text field the person last pressed, when, and what had focus as they pressed it. */
211
+ let pressed: {
212
+ readonly field: HTMLElement;
213
+ readonly at: number;
214
+ readonly from: Element | null;
215
+ } | null = null;
216
+ let hostMove: { frame: HTMLIFrameElement; at: number } | null = null;
217
+ let polling = 0;
218
+ /**
219
+ * A take-back in progress: the field focus goes back to, the frame it came from, when focus was
220
+ * last given back, and since when it has stayed in the field. Ends once it has stayed `HELD_MS`,
221
+ * the person moves focus somewhere of their own, or the field or frame is gone.
222
+ */
223
+ let contest: {
224
+ readonly field: HTMLElement;
225
+ readonly frame: HTMLIFrameElement;
226
+ readonly guarded: Guarded;
227
+ gaveAt: number;
228
+ heldSince: number | null;
229
+ } | null = null;
230
+
231
+ const activation = (): boolean | undefined => {
232
+ try {
233
+ const state = (view.navigator as Navigator & { userActivation?: { isActive: boolean } })
234
+ .userActivation;
235
+ return state === undefined ? undefined : state.isActive;
236
+ } catch {
237
+ return undefined;
238
+ }
239
+ };
240
+
241
+ /** What the person's move would need, read now: see `personMoved`. */
242
+ const judge = (
243
+ frame: HTMLIFrameElement,
244
+ guarded: Guarded,
245
+ seen: boolean,
246
+ at: number,
247
+ ): boolean => {
248
+ const moved = personMoved({
249
+ now: at,
250
+ seen,
251
+ pressed: frame.matches(":active"),
252
+ over: frame.matches(":hover"),
253
+ overSince: guarded.overSince,
254
+ lastKey,
255
+ typedAt,
256
+ focusedAt,
257
+ gestureAt,
258
+ activation: activation(),
259
+ hostMoved: hostMove !== null && hostMove.frame === frame && at - hostMove.at <= TAB_MS,
260
+ });
261
+ hostMove = null;
262
+ return moved;
263
+ };
264
+
265
+ /**
266
+ * Focus goes back to `field` once the engine has finished the move: given back inside its blur
267
+ * it stays with the frame on Chromium and WebKit, and Firefox takes it back only from a frame
268
+ * that was blurred first (measured). Unless the person has since put focus somewhere of their own.
269
+ */
270
+ const giveBack = (field: HTMLElement, frame: HTMLIFrameElement) => {
271
+ view.setTimeout(() => {
272
+ const current = deepActive(document);
273
+ if (
274
+ field.isConnected &&
275
+ (current === frame || current === null || current === document.body)
276
+ ) {
277
+ frame.blur();
278
+ field.focus({ preventScroll: true });
279
+ }
280
+ }, 0);
281
+ };
282
+
283
+ /** A move the guard undoes: focus goes back, the display hears it, and the guard keeps watching. */
284
+ const takeBack = (
285
+ field: HTMLElement,
286
+ frame: HTMLIFrameElement,
287
+ guarded: Guarded,
288
+ at: number,
289
+ failed: boolean,
290
+ ) => {
291
+ // Until it is back, the field counts as the page's focus, so a move that didn't take is seen.
292
+ known = field;
293
+ focusedAt = at;
294
+ contest = { field, frame, guarded, gaveAt: at, heldSince: null };
295
+ giveBack(field, frame);
296
+ schedule();
297
+ const take: FocusTake = { typing: at - typedAt <= TYPING_MS, failed };
298
+ for (const taken of guarded.taken) {
299
+ taken(take);
300
+ }
301
+ };
302
+
303
+ /**
304
+ * While a take-back is in progress: whether focus stayed in the field, or the frame has it again
305
+ * (or it landed on nothing), which is the page's doing unless the person moved it there.
306
+ */
307
+ const watch = (seen: boolean, active: Element | null, at: number): boolean => {
308
+ const watched = contest;
309
+ if (watched === null) {
310
+ return false;
311
+ }
312
+ const { field, frame, guarded } = watched;
313
+ if (!field.isConnected || pressAt > watched.gaveAt) {
314
+ // Gone, or the person pressed the page since: theirs to place focus now.
315
+ contest = null;
316
+ return false;
317
+ }
318
+ if (!frames.has(frame)) {
319
+ // The frame was removed mid-fight (its display stopped): Firefox may leave focus on nothing
320
+ // once the focused frame goes. Back into the field, for a moment after.
321
+ if ((active === null || active === document.body) && at - watched.gaveAt <= HELD_MS) {
322
+ field.focus({ preventScroll: true });
323
+ return true;
324
+ }
325
+ contest = null;
326
+ return false;
327
+ }
328
+ if (active === field) {
329
+ watched.heldSince ??= at;
330
+ if (at - watched.heldSince >= HELD_MS) {
331
+ contest = null;
332
+ }
333
+ known = field;
334
+ return true;
335
+ }
336
+ const lost = active === frame || active === null || active === document.body;
337
+ if (!lost) {
338
+ // Somewhere else of the person's (another field, a button, another frame): judged as any.
339
+ contest = null;
340
+ return false;
341
+ }
342
+ if (active === frame && judge(frame, guarded, seen, at)) {
343
+ contest = null;
344
+ known = frame;
345
+ enteredAt = at;
346
+ earned = true;
347
+ return true;
348
+ }
349
+ // Taken again once it was back (within `HELD_MS`), or not back yet after `GIVE_BACK_MS`: a
350
+ // take-back that failed, given again and counted.
351
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
352
+ takeBack(field, frame, guarded, at, true);
353
+ }
354
+ return true;
355
+ };
356
+
357
+ /** Judges a change of focus since the last look: `seen` when the engine told it (a blur). */
358
+ const look = (seen: boolean) => {
359
+ const active = deepActive(document);
360
+ const at = now();
361
+ if (watch(seen, active, at)) {
362
+ return;
363
+ }
364
+ const was = known;
365
+ // The person pressed a text field and focus is on nothing: on Firefox, a page that takes focus
366
+ // as they press, or takes it back on its blur with a gesture of theirs, leaves it there
367
+ // (measured, on a slow machine too), and their keys are lost. Into the field, once: as a
368
+ // take-back the page failed if a frame had focus as they pressed, else simply.
369
+ const press = pressed;
370
+ if (
371
+ press !== null &&
372
+ (active === null || active === document.body) &&
373
+ at - press.at <= HELD_MS &&
374
+ press.field.isConnected
375
+ ) {
376
+ pressed = null;
377
+ const from = press.from ?? was;
378
+ const blamed = from === null ? undefined : frames.get(from as HTMLIFrameElement);
379
+ if (blamed === undefined) {
380
+ known = active;
381
+ press.field.focus({ preventScroll: true });
382
+ } else {
383
+ takeBack(press.field, from as HTMLIFrameElement, blamed, at, true);
384
+ }
385
+ return;
386
+ }
387
+ known = active;
388
+ if (active === was || active === null) {
389
+ return;
390
+ }
391
+ const entered = frames.get(active as HTMLIFrameElement);
392
+ if (entered !== undefined) {
393
+ // From a text field it is judged below; from anything else it is let be, but only the
394
+ // person's own move makes the frame theirs for a gesture gate (`focused`).
395
+ enteredAt = at;
396
+ earned = takesText(was) || judge(active as HTMLIFrameElement, entered, seen, at);
397
+ }
398
+ // Into a text field from a display's frame (the person pressed the composer while the frame
399
+ // had focus): watched as a take-back is, since a page that takes focus back on its own blur
400
+ // leaves it on nothing on Firefox (measured), where the keys are lost to the page's doing.
401
+ const left = was === null ? undefined : frames.get(was as HTMLIFrameElement);
402
+ if (left !== undefined && takesText(active)) {
403
+ contest = {
404
+ field: active,
405
+ frame: was as HTMLIFrameElement,
406
+ guarded: left,
407
+ gaveAt: at,
408
+ heldSince: at,
409
+ };
410
+ return;
411
+ }
412
+ const guarded = frames.get(active as HTMLIFrameElement);
413
+ if (guarded === undefined || !takesText(was) || !was.isConnected) {
414
+ return;
415
+ }
416
+ const frame = active as HTMLIFrameElement;
417
+ if (judge(frame, guarded, seen, at)) {
418
+ return;
419
+ }
420
+ takeBack(was, frame, guarded, at, false);
421
+ };
422
+
423
+ /**
424
+ * Firefox moves focus into a frame without a word to the host's page: while a frame is guarded,
425
+ * look at each animation frame (one read of the focused element), so the guard knows where focus
426
+ * is when it next leaves a text field, or comes into one from a frame.
427
+ */
428
+ const poll = () => {
429
+ polling = 0;
430
+ look(false);
431
+ schedule();
432
+ };
433
+ const schedule = () => {
434
+ if (polling === 0 && (frames.size > 0 || contest !== null)) {
435
+ polling = view.requestAnimationFrame(poll);
436
+ }
437
+ };
438
+
439
+ const gesture = () => {
440
+ gestureAt = now();
441
+ };
442
+ const press = (event: Event) => {
443
+ pressAt = now();
444
+ gestureAt = pressAt;
445
+ const target = event.composedPath()[0];
446
+ pressed =
447
+ target instanceof Element && takesText(target)
448
+ ? { field: target, at: pressAt, from: deepActive(document) }
449
+ : null;
450
+ };
451
+ view.addEventListener(
452
+ "keydown",
453
+ (event) => {
454
+ const at = now();
455
+ gestureAt = at;
456
+ lastKey = { key: event.key, at };
457
+ if (event.key !== "Tab" && !MODIFIERS.has(event.key)) {
458
+ typedAt = at;
459
+ }
460
+ },
461
+ true,
462
+ );
463
+ // A click too (an assistive technology's click on the host's own UI dispatches no press), and
464
+ // text that comes without a key (dictation, a paste, an input method): typing all the same.
465
+ for (const type of ["pointerup", "touchend", "click"]) {
466
+ view.addEventListener(type, gesture, true);
467
+ }
468
+ for (const type of ["pointerdown", "mousedown"]) {
469
+ view.addEventListener(type, press, true);
470
+ }
471
+ view.addEventListener(
472
+ "input",
473
+ () => {
474
+ typedAt = now();
475
+ gestureAt = typedAt;
476
+ },
477
+ true,
478
+ );
479
+ // Focus moving within the page: what had it, for the next move out of a text field.
480
+ document.addEventListener(
481
+ "focusin",
482
+ () => {
483
+ focusedAt = now();
484
+ look(false);
485
+ schedule();
486
+ },
487
+ true,
488
+ );
489
+ // Chromium and WebKit blur the window as focus goes into a frame. Firefox may send the field a
490
+ // focusout first (seen in one review's runs, not in another's): looked at once it's over.
491
+ view.addEventListener("blur", (event) => {
492
+ if (event.target === view) {
493
+ look(true);
494
+ }
495
+ });
496
+ document.addEventListener(
497
+ "focusout",
498
+ () => {
499
+ view.setTimeout(() => look(false), 0);
500
+ },
501
+ true,
502
+ );
503
+
504
+ const guard: FocusGuard = {
505
+ add(frame, taken) {
506
+ let guarded = frames.get(frame);
507
+ if (guarded === undefined) {
508
+ const entry: Guarded = { taken: new Set(), overSince: -Infinity };
509
+ frame.addEventListener("pointerover", () => {
510
+ entry.overSince = now();
511
+ });
512
+ frames.set(frame, entry);
513
+ guarded = entry;
514
+ }
515
+ guarded.taken.add(taken);
516
+ schedule();
517
+ const own = guarded;
518
+ return () => {
519
+ own.taken.delete(taken);
520
+ if (own.taken.size === 0) {
521
+ frames.delete(frame);
522
+ }
523
+ };
524
+ },
525
+ focus(frame) {
526
+ hostMove = { frame, at: now() };
527
+ frame.focus();
528
+ look(true);
529
+ },
530
+ focused(frame) {
531
+ look(false);
532
+ // A press on the host's page since focus went into the frame, just now: the activation is
533
+ // that press's, and focus is about to leave (a call that lands in between doesn't count).
534
+ const pressedHost = pressAt > enteredAt && now() - pressAt < HOST_PRESS_MS;
535
+ return known === frame && document.activeElement === frame && earned && !pressedHost;
536
+ },
537
+ field(field) {
538
+ const holder = deepActive(document);
539
+ const guarded = holder === null ? undefined : frames.get(holder as HTMLIFrameElement);
540
+ if (guarded === undefined) {
541
+ field.focus({ preventScroll: true });
542
+ return;
543
+ }
544
+ // Watched as a take-back: a frame that keeps focus fails it, and is counted.
545
+ const frame = holder as HTMLIFrameElement;
546
+ frame.blur();
547
+ field.focus({ preventScroll: true });
548
+ known = field;
549
+ focusedAt = now();
550
+ contest = { field, frame, guarded, gaveAt: focusedAt, heldSince: null };
551
+ schedule();
552
+ },
553
+ };
554
+ guards.set(view, guard);
555
+ return guard;
556
+ }
557
+
558
+ /**
559
+ * Moves focus into one of the host page's text fields (a composer that opens beside a display,
560
+ * P109): `field.focus()` for a host to call instead. Firefox doesn't move focus from a frame that
561
+ * holds it with a gesture of the person's and takes it back on its own blur (measured: the keys
562
+ * then go to the frame); this blurs the frame first, and the focus guard watches that focus lands,
563
+ * counting a frame that keeps it toward stopping its display. Elsewhere it is `field.focus()`.
564
+ */
565
+ export function focusField(field: HTMLElement): void {
566
+ const view = field.ownerDocument.defaultView;
567
+ if (view === null) {
568
+ field.focus({ preventScroll: true });
569
+ return;
570
+ }
571
+ focusGuard(view).field(field);
572
+ }
@@ -46,6 +46,23 @@ export interface Surface {
46
46
  * throw (P105).
47
47
  */
48
48
  viewport?(): { readonly width: number; readonly height: number } | undefined;
49
+ /**
50
+ * Whether the embedding page's focus is in this frame now, once the platform's focus guard
51
+ * judged any move into it (P109); undefined, or absent, where the platform can't tell. A gesture
52
+ * gate that asks for the person in the calling frame (`comments`) reads it: false refuses.
53
+ */
54
+ focused?(): boolean | undefined;
55
+ /**
56
+ * Each time the content moved the keyboard into its frame from one of the embedding page's text
57
+ * fields without the person (no press on the frame, no Tab) and the platform gave focus back
58
+ * (P109): whether the person was typing then (a key within the last second), and whether focus
59
+ * failed to go back (the frame kept it or took it again). Absent where the platform has no guard.
60
+ */
61
+ onFocusTaken?(
62
+ listener: (take: { readonly typing: boolean; readonly failed: boolean }) => void,
63
+ ): () => void;
64
+ /** The host moves focus into the frame itself: the guard takes it as the person's (P109). */
65
+ focus?(): void;
49
66
  /**
50
67
  * The frame loaded a document other than the one it was given: the content navigated it. The
51
68
  * framework starts it again from its content and reports it.
@@ -1,6 +1,7 @@
1
1
  import type { ColorScheme } from "../config/schema.ts";
2
2
  import { FRAME_STATUS_METHOD } from "../isolation/types.ts";
3
3
  import { postMessageTransport } from "../transport/post-message.ts";
4
+ import { focusGuard, type FocusTake } from "./focus-guard.ts";
4
5
  import type { PlatformHost, Surface, SurfaceSpec } from "./types.ts";
5
6
 
6
7
  /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
@@ -62,6 +63,15 @@ export const webPlatform: PlatformHost = {
62
63
  container.append(frame);
63
64
 
64
65
  const view = container.ownerDocument.defaultView ?? window;
66
+ // The focus guard (P109): a move of the keyboard into this frame from one of the page's text
67
+ // fields that the person didn't make is undone.
68
+ const guard = focusGuard(view);
69
+ const taken = new Set<(take: FocusTake) => void>();
70
+ const unguard = guard.add(frame, (take) => {
71
+ for (const listener of taken) {
72
+ listener(take);
73
+ }
74
+ });
65
75
  // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
66
76
  // say of the frame's status is heard too, and nothing else from there.
67
77
  const own = view.origin;
@@ -100,6 +110,16 @@ export const webPlatform: PlatformHost = {
100
110
  ).userActivation;
101
111
  return activation === undefined ? undefined : activation.isActive;
102
112
  },
113
+ focused() {
114
+ return guard.focused(frame);
115
+ },
116
+ onFocusTaken(listener) {
117
+ taken.add(listener);
118
+ return () => taken.delete(listener);
119
+ },
120
+ focus() {
121
+ guard.focus(frame);
122
+ },
103
123
  onLoad(listener) {
104
124
  loaded.add(listener);
105
125
  return () => loaded.delete(listener);
@@ -111,6 +131,8 @@ export const webPlatform: PlatformHost = {
111
131
  destroy() {
112
132
  navigated.clear();
113
133
  loaded.clear();
134
+ taken.clear();
135
+ unguard();
114
136
  transport.close();
115
137
  frame.remove();
116
138
  },
@@ -564,6 +564,12 @@ export interface PortholeFrameProps {
564
564
  readonly onRefused?: (capability: CapabilityName, refusal: Refusal) => void;
565
565
  /** Too many declines: the display stops asking until it runs again. */
566
566
  readonly onMuted?: () => void;
567
+ /**
568
+ * The content moved the keyboard into its frame from one of the page's text fields without the
569
+ * person, and focus went back (P109); `typing`: the person was typing on the page. A display
570
+ * that keeps doing it is stopped (`onContentError` says so).
571
+ */
572
+ readonly onFocusTaken?: (taken: { readonly typing: boolean }) => void;
567
573
  /**
568
574
  * How the frame's first document went: loaded, blocked (and why), or a timeout. A host shows its
569
575
  * own fallback (a url-mode app "Open in a new tab") on anything but loaded.
@@ -839,6 +845,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
839
845
  case "muted":
840
846
  frame.onMuted?.();
841
847
  return;
848
+ case "focusTaken":
849
+ frame.onFocusTaken?.(detail as DisplayEvents["focusTaken"]);
850
+ return;
842
851
  case "outcome":
843
852
  frame.onOutcome?.(detail as DisplayEvents["outcome"]);
844
853
  return;
@@ -967,6 +976,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
967
976
  "navigationBlocked",
968
977
  "refused",
969
978
  "muted",
979
+ "focusTaken",
970
980
  "outcome",
971
981
  "annotation",
972
982
  "contentError",