@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,620 @@
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
+ /** How long the person's Tab counts as moving focus (the move follows its keydown at once). */
23
+ export const TAB_MS = 1_000;
24
+ /**
25
+ * How long transient activation lasts after a gesture (measured: 5 s on all three engines): a
26
+ * host page with activation and no gesture of its own for longer had one in a frame.
27
+ */
28
+ export const ACTIVATION_SPAN_MS = 5_000;
29
+ /** The person is typing: a key on the host's page within this long. */
30
+ export const TYPING_MS = 1_000;
31
+ /**
32
+ * After a take-back, the guard keeps watching (each animation frame) until focus has stayed in the
33
+ * text field this long: a page that takes it again at once (on its own blur, which the take-back
34
+ * fires) is caught as it does, on Firefox too (P109, after the review of the guard: GK-1).
35
+ */
36
+ export const HELD_MS = 300;
37
+ /** A take-back that hasn't put focus back in the field after this long failed: counted, and tried again. */
38
+ export const GIVE_BACK_MS = 50;
39
+ /**
40
+ * A frame that holds focus isn't the person's for this long after they press the host's page: the
41
+ * press gives the page activation before focus leaves the frame (on Firefox, a move between
42
+ * processes), and a call the frame sends in between would borrow it.
43
+ */
44
+ export const HOST_PRESS_MS = 1_000;
45
+ /**
46
+ * When a display is stopped for taking the keyboard (P109): focus given back can't stop its frame
47
+ * calling `focus()` again (nothing the host sets on the frame does, `inert` included: measured),
48
+ * and each try leaves it the keys typed until focus is back. So three undone moves within 10 s
49
+ * that came while the person typed on the page or that kept focus from going back (a take-back that
50
+ * failed: the keys then go to the frame, and the page sees no typing to count), or five at all
51
+ * within 2 s, stop it. A person's own move never fails a take-back.
52
+ */
53
+ export const TAKES = {
54
+ typing: { most: 3, withinMs: 10_000 },
55
+ any: { most: 5, withinMs: 2_000 },
56
+ };
57
+ /**
58
+ * A nested page's shell (P111) says its own activation turned on: a press or key of the person's
59
+ * in that page (activation goes up to ancestors, never down, so nothing on the host's page turns
60
+ * it on). A move of focus into the frame within this long of it, with no press or key on the
61
+ * host's page since, is the person's; so is a `comments.open` the page sends within it.
62
+ */
63
+ export const SHELL_GESTURE_MS = 1_000;
64
+ /**
65
+ * How long a move into a nested page's frame waits for its shell's word before it is taken for
66
+ * the page's: the shell says what it saw at its next animation frame, after the host's page
67
+ * already heard the move. A shell that says nothing in time (gone, stalled) has its frame's move
68
+ * taken back, as any page's.
69
+ */
70
+ export const SHELL_WAIT_MS = 500;
71
+ /**
72
+ * A shell's word that came this long before the host's page heard the move is about that move
73
+ * (the shell's frame can come first); one from before then is about an earlier one.
74
+ */
75
+ export const SHELL_EARLY_MS = 150;
76
+ /**
77
+ * A shell that went this long without a look, or without a word to the host (its heartbeat is every
78
+ * 50 ms), was stalled (P111, after its review): where the page shares the shell's thread (WebKit,
79
+ * Firefox), a page that holds it from its own click handler pushes the moment the shell sees its
80
+ * activation turn on past the person's next keys on the host's page. An activation it saw then is
81
+ * uncertain: it is no one's gesture until it lapses.
82
+ */
83
+ export const SHELL_STALL_MS = 100;
84
+ /**
85
+ * Whether the person moved focus into the frame themselves:
86
+ * - the host did (`DisplayHandle.focus()`);
87
+ * - by the keyboard: their last key on the host's page was Tab (or Shift+Tab), just now;
88
+ * - by a press on the frame: where the engine tells the move as it happens (Chromium, WebKit),
89
+ * the frame element is `:active`; where it doesn't (Firefox), the pointer is over the frame and
90
+ * came over it after the text field got focus and after the person last typed in the host's page
91
+ * (a page can't move the pointer; a composer that opened beside the frame while the pointer
92
+ * rested over it, and a person typing with it there, keep their keys);
93
+ * - by a gesture the host's own events don't explain: the host's page has transient activation,
94
+ * and for longer than activation lasts it saw no gesture of its own and the text field has had
95
+ * focus, so the person pressed or activated something in a frame since (an assistive
96
+ * technology's activation, which moves no pointer and sends the host no key, is one). The
97
+ * gesture that opened a composer (a selection in the frame, `selected`) is older than the
98
+ * composer's focus, and doesn't count.
99
+ * Anything else is the page's: focus goes back.
100
+ */
101
+ export function personMoved(move) {
102
+ if (move.hostMoved) {
103
+ return true;
104
+ }
105
+ if (move.lastKey !== null && move.lastKey.key === "Tab" && move.now - move.lastKey.at <= TAB_MS) {
106
+ return true;
107
+ }
108
+ // A nested page (P111): its shell's activation turned on within the last second, and the host's
109
+ // page had no press or key of its own since (the person went back to it); or, where the engine
110
+ // tells it, a press on the frame. Nothing else: no pointer over it, no host-wide activation.
111
+ if (move.shell !== undefined && move.shell.word.supported) {
112
+ return ((move.seen && move.pressed) || shellGesture(move.shell.word, move.shell.hostInputAt, move.now));
113
+ }
114
+ if (move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)) {
115
+ return true;
116
+ }
117
+ return (move.activation === true &&
118
+ move.now - Math.max(move.gestureAt, move.focusedAt) > ACTIVATION_SPAN_MS);
119
+ }
120
+ /**
121
+ * Whether a nested page's shell saw the person's gesture just now (P111): its activation turned on
122
+ * within `SHELL_GESTURE_MS`, after the host's page's last trusted press or key.
123
+ */
124
+ export function shellGesture(word, hostInputAt, now) {
125
+ return (word.supported &&
126
+ now - word.activatedAt <= SHELL_GESTURE_MS &&
127
+ now >= word.activatedAt &&
128
+ hostInputAt < word.activatedAt);
129
+ }
130
+ /** Keys that type nothing on their own: they don't count as typing (a gesture still). */
131
+ const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta", "AltGraph", "CapsLock", "Fn"]);
132
+ /** The `<input>` types that take typed text (an unknown type is `text`). */
133
+ const TEXT_INPUTS = new Set(["text", "search", "url", "tel", "email", "password", "number"]);
134
+ /** Whether `element` takes the person's typed text: a text field, a text area, an editable region. */
135
+ export function takesText(element) {
136
+ if (element === null) {
137
+ return false;
138
+ }
139
+ switch (element.localName) {
140
+ case "textarea":
141
+ return true;
142
+ case "input":
143
+ return TEXT_INPUTS.has(element.type);
144
+ default:
145
+ return element.isContentEditable ?? false;
146
+ }
147
+ }
148
+ /** The element that has focus, inside open shadow roots too. */
149
+ function deepActive(document) {
150
+ let active = document.activeElement;
151
+ for (let inner = active?.shadowRoot?.activeElement; inner !== null && inner !== undefined; inner = active?.shadowRoot?.activeElement) {
152
+ active = inner;
153
+ }
154
+ return active;
155
+ }
156
+ const guards = new WeakMap();
157
+ /** The guard for `view`'s page, made on first use. */
158
+ export function focusGuard(view) {
159
+ const existing = guards.get(view);
160
+ if (existing !== undefined) {
161
+ return existing;
162
+ }
163
+ const document = view.document;
164
+ const frames = new Map();
165
+ const now = () => view.performance.now();
166
+ let known = deepActive(document);
167
+ let focusedAt = now();
168
+ let lastKey = null;
169
+ let typedAt = -Infinity;
170
+ let gestureAt = -Infinity;
171
+ let pressAt = -Infinity;
172
+ /** The host's page's last trusted press or key (P111: a nested page's gesture must be later). */
173
+ let inputAt = -Infinity;
174
+ /**
175
+ * A move into a nested page's frame waiting for its shell's word (P111): from a text field
176
+ * (`field`: taken back unless the shell says the person's), or from anything else (null: only
177
+ * whether the frame is the person's for a gesture gate).
178
+ */
179
+ let waiting = null;
180
+ /** When focus last went into a guarded frame, and whether the person moved it there. */
181
+ let enteredAt = -Infinity;
182
+ let earned = false;
183
+ /** The text field the person last pressed, when, and what had focus as they pressed it. */
184
+ let pressed = null;
185
+ let hostMove = null;
186
+ let polling = 0;
187
+ /**
188
+ * A take-back in progress: the field focus goes back to, the frame it came from, when focus was
189
+ * last given back, and since when it has stayed in the field. Ends once it has stayed `HELD_MS`,
190
+ * the person moves focus somewhere of their own, or the field or frame is gone.
191
+ */
192
+ let contest = null;
193
+ const activation = () => {
194
+ try {
195
+ const state = view.navigator
196
+ .userActivation;
197
+ return state === undefined ? undefined : state.isActive;
198
+ }
199
+ catch {
200
+ return undefined;
201
+ }
202
+ };
203
+ /**
204
+ * What the person's move would need, read now: see `personMoved`. Into a nested page's frame
205
+ * whose shell hasn't spoken of this move yet, `wait` (P111).
206
+ */
207
+ const judge = (frame, guarded, seen, at) => {
208
+ const word = guarded.word;
209
+ const moved = personMoved({
210
+ now: at,
211
+ seen,
212
+ pressed: frame.matches(":active"),
213
+ over: frame.matches(":hover"),
214
+ overSince: guarded.overSince,
215
+ lastKey,
216
+ typedAt,
217
+ focusedAt,
218
+ gestureAt,
219
+ activation: activation(),
220
+ hostMoved: hostMove !== null && hostMove.frame === frame && at - hostMove.at <= TAB_MS,
221
+ ...(word === null ? {} : { shell: { word, hostInputAt: inputAt } }),
222
+ });
223
+ hostMove = null;
224
+ // The shell tells a move at its next frame, the host's page hears it first: until the shell
225
+ // said focus came in (around now), its activation may be on its way.
226
+ if (!moved && word !== null && word.supported && word.focusedAt < at - SHELL_EARLY_MS) {
227
+ return "wait";
228
+ }
229
+ return moved;
230
+ };
231
+ /** Waits for a nested page's shell's word on a move (P111): decided by `settle`. */
232
+ const wait = (field, frame, guarded, at, failed) => {
233
+ waiting = { field, frame, guarded, since: at, failed };
234
+ known = frame;
235
+ enteredAt = at;
236
+ earned = false;
237
+ schedule();
238
+ };
239
+ /**
240
+ * A waiting move, once its shell spoke or the wait is over: the person's (the frame keeps
241
+ * focus), or the page's (from a text field, taken back). A move elsewhere since ends it.
242
+ */
243
+ const settle = (at) => {
244
+ const held = waiting;
245
+ if (held === null) {
246
+ return;
247
+ }
248
+ const { field, frame, guarded } = held;
249
+ if (deepActive(document) !== frame || !frames.has(frame)) {
250
+ // Moved on since: from the frame, as the next look judges it.
251
+ waiting = null;
252
+ known = frame;
253
+ return;
254
+ }
255
+ const word = guarded.word;
256
+ const theirs = word !== null && shellGesture(word, inputAt, at);
257
+ const spoke = word !== null && word.focusedAt >= held.since - SHELL_EARLY_MS;
258
+ if (theirs) {
259
+ waiting = null;
260
+ known = frame;
261
+ earned = true;
262
+ return;
263
+ }
264
+ if (!spoke && at - held.since < SHELL_WAIT_MS) {
265
+ return;
266
+ }
267
+ waiting = null;
268
+ if (field !== null && field.isConnected) {
269
+ takeBack(field, frame, guarded, at, held.failed);
270
+ }
271
+ };
272
+ /**
273
+ * Focus goes back to `field` once the engine has finished the move: given back inside its blur
274
+ * it stays with the frame on Chromium and WebKit, and Firefox takes it back only from a frame
275
+ * that was blurred first (measured). Unless the person has since put focus somewhere of their own.
276
+ */
277
+ const giveBack = (field, frame) => {
278
+ view.setTimeout(() => {
279
+ const current = deepActive(document);
280
+ if (field.isConnected &&
281
+ (current === frame || current === null || current === document.body)) {
282
+ frame.blur();
283
+ field.focus({ preventScroll: true });
284
+ }
285
+ }, 0);
286
+ };
287
+ /** A move the guard undoes: focus goes back, the display hears it, and the guard keeps watching. */
288
+ const takeBack = (field, frame, guarded, at, failed) => {
289
+ // Until it is back, the field counts as the page's focus, so a move that didn't take is seen.
290
+ known = field;
291
+ focusedAt = at;
292
+ contest = { field, frame, guarded, gaveAt: at, heldSince: null };
293
+ giveBack(field, frame);
294
+ schedule();
295
+ const take = { typing: at - typedAt <= TYPING_MS, failed };
296
+ for (const taken of guarded.taken) {
297
+ taken(take);
298
+ }
299
+ };
300
+ /**
301
+ * While a take-back is in progress: whether focus stayed in the field, or the frame has it again
302
+ * (or it landed on nothing), which is the page's doing unless the person moved it there.
303
+ */
304
+ const watch = (seen, active, at) => {
305
+ const watched = contest;
306
+ if (watched === null) {
307
+ return false;
308
+ }
309
+ const { field, frame, guarded } = watched;
310
+ if (!field.isConnected || pressAt > watched.gaveAt) {
311
+ // Gone, or the person pressed the page since: theirs to place focus now.
312
+ contest = null;
313
+ return false;
314
+ }
315
+ if (!frames.has(frame)) {
316
+ // The frame was removed mid-fight (its display stopped): Firefox may leave focus on nothing
317
+ // once the focused frame goes. Back into the field, for a moment after.
318
+ if ((active === null || active === document.body) && at - watched.gaveAt <= HELD_MS) {
319
+ field.focus({ preventScroll: true });
320
+ return true;
321
+ }
322
+ contest = null;
323
+ return false;
324
+ }
325
+ if (active === field) {
326
+ watched.heldSince ??= at;
327
+ if (at - watched.heldSince >= HELD_MS) {
328
+ contest = null;
329
+ }
330
+ known = field;
331
+ return true;
332
+ }
333
+ const lost = active === frame || active === null || active === document.body;
334
+ if (!lost) {
335
+ // Somewhere else of the person's (another field, a button, another frame): judged as any.
336
+ contest = null;
337
+ return false;
338
+ }
339
+ if (active === frame) {
340
+ const verdict = judge(frame, guarded, seen, at);
341
+ if (verdict === true) {
342
+ contest = null;
343
+ known = frame;
344
+ enteredAt = at;
345
+ earned = true;
346
+ return true;
347
+ }
348
+ if (verdict === "wait") {
349
+ // A nested page's frame took it again (P111): its shell decides, as it would at first.
350
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
351
+ contest = null;
352
+ wait(field, frame, guarded, at, true);
353
+ }
354
+ return true;
355
+ }
356
+ }
357
+ // Taken again once it was back (within `HELD_MS`), or not back yet after `GIVE_BACK_MS`: a
358
+ // take-back that failed, given again and counted.
359
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
360
+ takeBack(field, frame, guarded, at, true);
361
+ }
362
+ return true;
363
+ };
364
+ /** Judges a change of focus since the last look: `seen` when the engine told it (a blur). */
365
+ const look = (seen) => {
366
+ const active = deepActive(document);
367
+ const at = now();
368
+ if (waiting !== null) {
369
+ settle(at);
370
+ return;
371
+ }
372
+ if (watch(seen, active, at)) {
373
+ return;
374
+ }
375
+ const was = known;
376
+ // The person pressed a text field and focus is on nothing: on Firefox, a page that takes focus
377
+ // as they press, or takes it back on its blur with a gesture of theirs, leaves it there
378
+ // (measured, on a slow machine too), and their keys are lost. Into the field, once: as a
379
+ // take-back the page failed if a frame had focus as they pressed, else simply.
380
+ const press = pressed;
381
+ if (press !== null &&
382
+ (active === null || active === document.body) &&
383
+ at - press.at <= HELD_MS &&
384
+ press.field.isConnected) {
385
+ pressed = null;
386
+ const from = press.from ?? was;
387
+ const blamed = from === null ? undefined : frames.get(from);
388
+ if (blamed === undefined) {
389
+ known = active;
390
+ press.field.focus({ preventScroll: true });
391
+ }
392
+ else {
393
+ takeBack(press.field, from, blamed, at, true);
394
+ }
395
+ return;
396
+ }
397
+ known = active;
398
+ if (active === was || active === null) {
399
+ return;
400
+ }
401
+ const entered = frames.get(active);
402
+ if (entered !== undefined) {
403
+ // From a text field it is judged below; from anything else it is let be, but only the
404
+ // person's own move makes the frame theirs for a gesture gate (`focused`).
405
+ enteredAt = at;
406
+ const verdict = takesText(was) || judge(active, entered, seen, at);
407
+ if (verdict === "wait") {
408
+ // A nested page's (P111): theirs once its shell says so; nothing to take back.
409
+ wait(null, active, entered, at, false);
410
+ return;
411
+ }
412
+ earned = verdict;
413
+ }
414
+ // Into a text field from a display's frame (the person pressed the composer while the frame
415
+ // had focus): watched as a take-back is, since a page that takes focus back on its own blur
416
+ // leaves it on nothing on Firefox (measured), where the keys are lost to the page's doing.
417
+ const left = was === null ? undefined : frames.get(was);
418
+ if (left !== undefined && takesText(active)) {
419
+ contest = {
420
+ field: active,
421
+ frame: was,
422
+ guarded: left,
423
+ gaveAt: at,
424
+ heldSince: at,
425
+ };
426
+ return;
427
+ }
428
+ const guarded = frames.get(active);
429
+ if (guarded === undefined || !takesText(was) || !was.isConnected) {
430
+ return;
431
+ }
432
+ const frame = active;
433
+ const verdict = judge(frame, guarded, seen, at);
434
+ if (verdict === true) {
435
+ return;
436
+ }
437
+ if (verdict === "wait") {
438
+ wait(was, frame, guarded, at, false);
439
+ return;
440
+ }
441
+ takeBack(was, frame, guarded, at, false);
442
+ };
443
+ /**
444
+ * Firefox moves focus into a frame without a word to the host's page: while a frame is guarded,
445
+ * look at each animation frame (one read of the focused element), so the guard knows where focus
446
+ * is when it next leaves a text field, or comes into one from a frame.
447
+ */
448
+ const poll = () => {
449
+ polling = 0;
450
+ look(false);
451
+ schedule();
452
+ };
453
+ const schedule = () => {
454
+ if (polling === 0 && (frames.size > 0 || contest !== null || waiting !== null)) {
455
+ polling = view.requestAnimationFrame(poll);
456
+ }
457
+ };
458
+ const gesture = () => {
459
+ gestureAt = now();
460
+ };
461
+ const press = (event) => {
462
+ pressAt = now();
463
+ if (event.isTrusted) {
464
+ inputAt = pressAt;
465
+ }
466
+ gestureAt = pressAt;
467
+ const target = event.composedPath()[0];
468
+ pressed =
469
+ target instanceof Element && takesText(target)
470
+ ? { field: target, at: pressAt, from: deepActive(document) }
471
+ : null;
472
+ };
473
+ view.addEventListener("keydown", (event) => {
474
+ const at = now();
475
+ gestureAt = at;
476
+ lastKey = { key: event.key, at };
477
+ if (event.isTrusted) {
478
+ inputAt = at;
479
+ }
480
+ if (event.key !== "Tab" && !MODIFIERS.has(event.key)) {
481
+ typedAt = at;
482
+ }
483
+ }, true);
484
+ // A click too (an assistive technology's click on the host's own UI dispatches no press), and
485
+ // text that comes without a key (dictation, a paste, an input method): typing all the same.
486
+ for (const type of ["pointerup", "touchend", "click"]) {
487
+ view.addEventListener(type, gesture, true);
488
+ }
489
+ for (const type of ["pointerdown", "mousedown"]) {
490
+ view.addEventListener(type, press, true);
491
+ }
492
+ view.addEventListener("input", () => {
493
+ typedAt = now();
494
+ gestureAt = typedAt;
495
+ }, true);
496
+ // Focus moving within the page: what had it, for the next move out of a text field.
497
+ document.addEventListener("focusin", () => {
498
+ focusedAt = now();
499
+ look(false);
500
+ schedule();
501
+ }, true);
502
+ // Chromium and WebKit blur the window as focus goes into a frame. Firefox may send the field a
503
+ // focusout first (seen in one review's runs, not in another's): looked at once it's over.
504
+ view.addEventListener("blur", (event) => {
505
+ if (event.target === view) {
506
+ look(true);
507
+ }
508
+ });
509
+ document.addEventListener("focusout", () => {
510
+ view.setTimeout(() => look(false), 0);
511
+ }, true);
512
+ const guard = {
513
+ add(frame, taken, options) {
514
+ let guarded = frames.get(frame);
515
+ if (guarded === undefined) {
516
+ const entry = {
517
+ taken: new Set(),
518
+ overSince: -Infinity,
519
+ heardAt: -Infinity,
520
+ word: options?.nested === true
521
+ ? { supported: true, activatedAt: -Infinity, focused: false, focusedAt: -Infinity }
522
+ : null,
523
+ };
524
+ frame.addEventListener("pointerover", () => {
525
+ entry.overSince = now();
526
+ });
527
+ frames.set(frame, entry);
528
+ guarded = entry;
529
+ }
530
+ guarded.taken.add(taken);
531
+ schedule();
532
+ const own = guarded;
533
+ return () => {
534
+ own.taken.delete(taken);
535
+ if (own.taken.size === 0) {
536
+ frames.delete(frame);
537
+ }
538
+ };
539
+ },
540
+ shell(frame, said) {
541
+ const guarded = frames.get(frame);
542
+ const before = guarded?.word ?? null;
543
+ if (guarded === undefined || before === null) {
544
+ return;
545
+ }
546
+ const at = now();
547
+ // Off to on after a stall, the shell's or the host's (no word for longer than its beat
548
+ // allows): uncertain, and so until it goes off (P111, after its review).
549
+ const turnedOn = said.ago !== null && before.activatedAt === -Infinity && !before.uncertain;
550
+ const stalled = said.gap > SHELL_STALL_MS || at - guarded.heardAt > SHELL_STALL_MS;
551
+ const uncertain = said.ago !== null && (before.uncertain === true || (turnedOn && stalled));
552
+ guarded.heardAt = at;
553
+ guarded.word = {
554
+ supported: said.supported,
555
+ activatedAt: said.ago === null || uncertain ? -Infinity : at - said.ago,
556
+ focused: said.focused,
557
+ focusedAt: said.focused && !before.focused ? at : before.focusedAt,
558
+ ...(uncertain ? { uncertain: true } : {}),
559
+ };
560
+ if (waiting?.frame === frame) {
561
+ settle(at);
562
+ }
563
+ },
564
+ beat(frame) {
565
+ const guarded = frames.get(frame);
566
+ if (guarded !== undefined && guarded.word !== null) {
567
+ guarded.heardAt = now();
568
+ }
569
+ },
570
+ gesture(frame) {
571
+ const word = frames.get(frame)?.word ?? null;
572
+ return word !== null && shellGesture(word, inputAt, now());
573
+ },
574
+ focus(frame) {
575
+ hostMove = { frame, at: now() };
576
+ frame.focus();
577
+ look(true);
578
+ },
579
+ focused(frame) {
580
+ look(false);
581
+ // A press on the host's page since focus went into the frame, just now: the activation is
582
+ // that press's, and focus is about to leave (a call that lands in between doesn't count).
583
+ const pressedHost = pressAt > enteredAt && now() - pressAt < HOST_PRESS_MS;
584
+ return known === frame && document.activeElement === frame && earned && !pressedHost;
585
+ },
586
+ field(field) {
587
+ const holder = deepActive(document);
588
+ const guarded = holder === null ? undefined : frames.get(holder);
589
+ if (guarded === undefined) {
590
+ field.focus({ preventScroll: true });
591
+ return;
592
+ }
593
+ // Watched as a take-back: a frame that keeps focus fails it, and is counted.
594
+ const frame = holder;
595
+ frame.blur();
596
+ field.focus({ preventScroll: true });
597
+ known = field;
598
+ focusedAt = now();
599
+ contest = { field, frame, guarded, gaveAt: focusedAt, heldSince: null };
600
+ schedule();
601
+ },
602
+ };
603
+ guards.set(view, guard);
604
+ return guard;
605
+ }
606
+ /**
607
+ * Moves focus into one of the host page's text fields (a composer that opens beside a display,
608
+ * P109): `field.focus()` for a host to call instead. Firefox doesn't move focus from a frame that
609
+ * holds it with a gesture of the person's and takes it back on its own blur (measured: the keys
610
+ * then go to the frame); this blurs the frame first, and the focus guard watches that focus lands,
611
+ * counting a frame that keeps it toward stopping its display. Elsewhere it is `field.focus()`.
612
+ */
613
+ export function focusField(field) {
614
+ const view = field.ownerDocument.defaultView;
615
+ if (view === null) {
616
+ field.focus({ preventScroll: true });
617
+ return;
618
+ }
619
+ focusGuard(view).field(field);
620
+ }
@@ -22,6 +22,12 @@ export interface SurfaceSpec {
22
22
  readonly fill?: boolean;
23
23
  /** The height to start at (a remembered height, so a frame mounting again doesn't jump). */
24
24
  readonly initialHeightPx: number;
25
+ /**
26
+ * The frame holds a nested page's shell (P111): the host's config says so, never the frame. What
27
+ * the shell says of itself (`porthole/shell/state`) decides moves of focus into it and the
28
+ * gesture its page's calls need; nothing else in that namespace reaches the transport.
29
+ */
30
+ readonly nested?: boolean;
25
31
  }
26
32
  /** One isolated frame. */
27
33
  export interface Surface {
@@ -46,6 +52,25 @@ export interface Surface {
46
52
  readonly width: number;
47
53
  readonly height: number;
48
54
  } | undefined;
55
+ /**
56
+ * Whether the embedding page's focus is in this frame now, once the platform's focus guard
57
+ * judged any move into it (P109); undefined, or absent, where the platform can't tell. A gesture
58
+ * gate that asks for the person in the calling frame (`comments`) reads it: false refuses. A
59
+ * nested page's frame (P111) is the person's too while its shell saw their gesture just now.
60
+ */
61
+ focused?(): boolean | undefined;
62
+ /**
63
+ * Each time the content moved the keyboard into its frame from one of the embedding page's text
64
+ * fields without the person (no press on the frame, no Tab) and the platform gave focus back
65
+ * (P109): whether the person was typing then (a key within the last second), and whether focus
66
+ * failed to go back (the frame kept it or took it again). Absent where the platform has no guard.
67
+ */
68
+ onFocusTaken?(listener: (take: {
69
+ readonly typing: boolean;
70
+ readonly failed: boolean;
71
+ }) => void): () => void;
72
+ /** The host moves focus into the frame itself: the guard takes it as the person's (P109). */
73
+ focus?(): void;
49
74
  /**
50
75
  * The frame loaded a document other than the one it was given: the content navigated it. The
51
76
  * framework starts it again from its content and reports it.