@botiverse/porthole 0.10.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 (68) hide show
  1. package/dist/annotate/types.d.ts +18 -6
  2. package/dist/annotate/validate.d.ts +11 -1
  3. package/dist/annotate/validate.js +18 -1
  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.d.ts +2 -0
  9. package/dist/check/files.js +71 -50
  10. package/dist/check/lint.d.ts +8 -1
  11. package/dist/check/lint.js +18 -0
  12. package/dist/check/markup.d.ts +7 -0
  13. package/dist/check/markup.js +49 -0
  14. package/dist/check/page-source.js +1 -1
  15. package/dist/check/scroll.d.ts +116 -0
  16. package/dist/check/scroll.js +1485 -0
  17. package/dist/config/capabilities.d.ts +16 -3
  18. package/dist/config/capabilities.js +1 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/conformance/runtime.js +6 -0
  21. package/dist/guide/guide.js +1 -1
  22. package/dist/guide/runtime.js +2 -2
  23. package/dist/host/create-host.js +30 -3
  24. package/dist/host/types.d.ts +15 -0
  25. package/dist/index.d.ts +2 -1
  26. package/dist/index.js +1 -0
  27. package/dist/platform/focus-guard.d.ts +143 -0
  28. package/dist/platform/focus-guard.js +445 -0
  29. package/dist/platform/types.d.ts +18 -0
  30. package/dist/platform/web.js +22 -0
  31. package/dist/react/frame.d.ts +10 -1
  32. package/dist/react/frame.js +4 -0
  33. package/dist/runtime/requests.d.ts +5 -0
  34. package/dist/runtime/requests.js +41 -4
  35. package/dist/runtime/types.generated.js +1 -1
  36. package/dist/shell/annotate.d.ts +2 -1
  37. package/dist/shell/annotate.js +29 -12
  38. package/dist/shell/use.js +9 -1
  39. package/docs/ADOPTING.md +106 -5
  40. package/docs/ARCHITECTURE.md +2 -1
  41. package/docs/DECISIONS.md +741 -2
  42. package/docs/DESIGN.md +38 -9
  43. package/docs/THREAT_MODEL.md +146 -19
  44. package/package.json +1 -1
  45. package/src/annotate/types.ts +19 -6
  46. package/src/annotate/validate.ts +20 -1
  47. package/src/bridge/bridge.ts +17 -1
  48. package/src/bridge/unseen.ts +24 -0
  49. package/src/check/files.ts +72 -54
  50. package/src/check/lint.ts +24 -0
  51. package/src/check/markup.ts +53 -0
  52. package/src/check/scroll.ts +1825 -0
  53. package/src/config/capabilities.ts +16 -3
  54. package/src/conformance/runtime.ts +9 -0
  55. package/src/guide/guide.ts +1 -0
  56. package/src/guide/runtime.ts +2 -2
  57. package/src/host/create-host.ts +38 -3
  58. package/src/host/types.ts +13 -0
  59. package/src/index.ts +2 -0
  60. package/src/platform/focus-guard.ts +572 -0
  61. package/src/platform/types.ts +17 -0
  62. package/src/platform/web.ts +22 -0
  63. package/src/react/frame.tsx +12 -1
  64. package/src/runtime/requests.ts +50 -6
  65. package/src/runtime/types.generated.ts +1 -1
  66. package/src/shell/annotate.ts +29 -12
  67. package/src/shell/use.ts +9 -1
  68. package/types/runtime/v1/comments.d.ts +20 -6
@@ -0,0 +1,445 @@
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
+ * Whether the person moved focus into the frame themselves:
59
+ * - the host did (`DisplayHandle.focus()`);
60
+ * - by the keyboard: their last key on the host's page was Tab (or Shift+Tab), just now;
61
+ * - by a press on the frame: where the engine tells the move as it happens (Chromium, WebKit),
62
+ * the frame element is `:active`; where it doesn't (Firefox), the pointer is over the frame and
63
+ * came over it after the text field got focus and after the person last typed in the host's page
64
+ * (a page can't move the pointer; a composer that opened beside the frame while the pointer
65
+ * rested over it, and a person typing with it there, keep their keys);
66
+ * - by a gesture the host's own events don't explain: the host's page has transient activation,
67
+ * and for longer than activation lasts it saw no gesture of its own and the text field has had
68
+ * focus, so the person pressed or activated something in a frame since (an assistive
69
+ * technology's activation, which moves no pointer and sends the host no key, is one). The
70
+ * gesture that opened a composer (a selection in the frame, `selected`) is older than the
71
+ * composer's focus, and doesn't count.
72
+ * Anything else is the page's: focus goes back.
73
+ */
74
+ export function personMoved(move) {
75
+ if (move.hostMoved) {
76
+ return true;
77
+ }
78
+ if (move.lastKey !== null && move.lastKey.key === "Tab" && move.now - move.lastKey.at <= TAB_MS) {
79
+ return true;
80
+ }
81
+ if (move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)) {
82
+ return true;
83
+ }
84
+ return (move.activation === true &&
85
+ move.now - Math.max(move.gestureAt, move.focusedAt) > ACTIVATION_SPAN_MS);
86
+ }
87
+ /** Keys that type nothing on their own: they don't count as typing (a gesture still). */
88
+ const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta", "AltGraph", "CapsLock", "Fn"]);
89
+ /** The `<input>` types that take typed text (an unknown type is `text`). */
90
+ const TEXT_INPUTS = new Set(["text", "search", "url", "tel", "email", "password", "number"]);
91
+ /** Whether `element` takes the person's typed text: a text field, a text area, an editable region. */
92
+ export function takesText(element) {
93
+ if (element === null) {
94
+ return false;
95
+ }
96
+ switch (element.localName) {
97
+ case "textarea":
98
+ return true;
99
+ case "input":
100
+ return TEXT_INPUTS.has(element.type);
101
+ default:
102
+ return element.isContentEditable ?? false;
103
+ }
104
+ }
105
+ /** The element that has focus, inside open shadow roots too. */
106
+ function deepActive(document) {
107
+ let active = document.activeElement;
108
+ for (let inner = active?.shadowRoot?.activeElement; inner !== null && inner !== undefined; inner = active?.shadowRoot?.activeElement) {
109
+ active = inner;
110
+ }
111
+ return active;
112
+ }
113
+ const guards = new WeakMap();
114
+ /** The guard for `view`'s page, made on first use. */
115
+ export function focusGuard(view) {
116
+ const existing = guards.get(view);
117
+ if (existing !== undefined) {
118
+ return existing;
119
+ }
120
+ const document = view.document;
121
+ const frames = new Map();
122
+ const now = () => view.performance.now();
123
+ let known = deepActive(document);
124
+ let focusedAt = now();
125
+ let lastKey = null;
126
+ let typedAt = -Infinity;
127
+ let gestureAt = -Infinity;
128
+ let pressAt = -Infinity;
129
+ /** When focus last went into a guarded frame, and whether the person moved it there. */
130
+ let enteredAt = -Infinity;
131
+ let earned = false;
132
+ /** The text field the person last pressed, when, and what had focus as they pressed it. */
133
+ let pressed = null;
134
+ let hostMove = null;
135
+ let polling = 0;
136
+ /**
137
+ * A take-back in progress: the field focus goes back to, the frame it came from, when focus was
138
+ * last given back, and since when it has stayed in the field. Ends once it has stayed `HELD_MS`,
139
+ * the person moves focus somewhere of their own, or the field or frame is gone.
140
+ */
141
+ let contest = null;
142
+ const activation = () => {
143
+ try {
144
+ const state = view.navigator
145
+ .userActivation;
146
+ return state === undefined ? undefined : state.isActive;
147
+ }
148
+ catch {
149
+ return undefined;
150
+ }
151
+ };
152
+ /** What the person's move would need, read now: see `personMoved`. */
153
+ const judge = (frame, guarded, seen, at) => {
154
+ const moved = personMoved({
155
+ now: at,
156
+ seen,
157
+ pressed: frame.matches(":active"),
158
+ over: frame.matches(":hover"),
159
+ overSince: guarded.overSince,
160
+ lastKey,
161
+ typedAt,
162
+ focusedAt,
163
+ gestureAt,
164
+ activation: activation(),
165
+ hostMoved: hostMove !== null && hostMove.frame === frame && at - hostMove.at <= TAB_MS,
166
+ });
167
+ hostMove = null;
168
+ return moved;
169
+ };
170
+ /**
171
+ * Focus goes back to `field` once the engine has finished the move: given back inside its blur
172
+ * it stays with the frame on Chromium and WebKit, and Firefox takes it back only from a frame
173
+ * that was blurred first (measured). Unless the person has since put focus somewhere of their own.
174
+ */
175
+ const giveBack = (field, frame) => {
176
+ view.setTimeout(() => {
177
+ const current = deepActive(document);
178
+ if (field.isConnected &&
179
+ (current === frame || current === null || current === document.body)) {
180
+ frame.blur();
181
+ field.focus({ preventScroll: true });
182
+ }
183
+ }, 0);
184
+ };
185
+ /** A move the guard undoes: focus goes back, the display hears it, and the guard keeps watching. */
186
+ const takeBack = (field, frame, guarded, at, failed) => {
187
+ // Until it is back, the field counts as the page's focus, so a move that didn't take is seen.
188
+ known = field;
189
+ focusedAt = at;
190
+ contest = { field, frame, guarded, gaveAt: at, heldSince: null };
191
+ giveBack(field, frame);
192
+ schedule();
193
+ const take = { typing: at - typedAt <= TYPING_MS, failed };
194
+ for (const taken of guarded.taken) {
195
+ taken(take);
196
+ }
197
+ };
198
+ /**
199
+ * While a take-back is in progress: whether focus stayed in the field, or the frame has it again
200
+ * (or it landed on nothing), which is the page's doing unless the person moved it there.
201
+ */
202
+ const watch = (seen, active, at) => {
203
+ const watched = contest;
204
+ if (watched === null) {
205
+ return false;
206
+ }
207
+ const { field, frame, guarded } = watched;
208
+ if (!field.isConnected || pressAt > watched.gaveAt) {
209
+ // Gone, or the person pressed the page since: theirs to place focus now.
210
+ contest = null;
211
+ return false;
212
+ }
213
+ if (!frames.has(frame)) {
214
+ // The frame was removed mid-fight (its display stopped): Firefox may leave focus on nothing
215
+ // once the focused frame goes. Back into the field, for a moment after.
216
+ if ((active === null || active === document.body) && at - watched.gaveAt <= HELD_MS) {
217
+ field.focus({ preventScroll: true });
218
+ return true;
219
+ }
220
+ contest = null;
221
+ return false;
222
+ }
223
+ if (active === field) {
224
+ watched.heldSince ??= at;
225
+ if (at - watched.heldSince >= HELD_MS) {
226
+ contest = null;
227
+ }
228
+ known = field;
229
+ return true;
230
+ }
231
+ const lost = active === frame || active === null || active === document.body;
232
+ if (!lost) {
233
+ // Somewhere else of the person's (another field, a button, another frame): judged as any.
234
+ contest = null;
235
+ return false;
236
+ }
237
+ if (active === frame && judge(frame, guarded, seen, at)) {
238
+ contest = null;
239
+ known = frame;
240
+ enteredAt = at;
241
+ earned = true;
242
+ return true;
243
+ }
244
+ // Taken again once it was back (within `HELD_MS`), or not back yet after `GIVE_BACK_MS`: a
245
+ // take-back that failed, given again and counted.
246
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
247
+ takeBack(field, frame, guarded, at, true);
248
+ }
249
+ return true;
250
+ };
251
+ /** Judges a change of focus since the last look: `seen` when the engine told it (a blur). */
252
+ const look = (seen) => {
253
+ const active = deepActive(document);
254
+ const at = now();
255
+ if (watch(seen, active, at)) {
256
+ return;
257
+ }
258
+ const was = known;
259
+ // The person pressed a text field and focus is on nothing: on Firefox, a page that takes focus
260
+ // as they press, or takes it back on its blur with a gesture of theirs, leaves it there
261
+ // (measured, on a slow machine too), and their keys are lost. Into the field, once: as a
262
+ // take-back the page failed if a frame had focus as they pressed, else simply.
263
+ const press = pressed;
264
+ if (press !== null &&
265
+ (active === null || active === document.body) &&
266
+ at - press.at <= HELD_MS &&
267
+ press.field.isConnected) {
268
+ pressed = null;
269
+ const from = press.from ?? was;
270
+ const blamed = from === null ? undefined : frames.get(from);
271
+ if (blamed === undefined) {
272
+ known = active;
273
+ press.field.focus({ preventScroll: true });
274
+ }
275
+ else {
276
+ takeBack(press.field, from, blamed, at, true);
277
+ }
278
+ return;
279
+ }
280
+ known = active;
281
+ if (active === was || active === null) {
282
+ return;
283
+ }
284
+ const entered = frames.get(active);
285
+ if (entered !== undefined) {
286
+ // From a text field it is judged below; from anything else it is let be, but only the
287
+ // person's own move makes the frame theirs for a gesture gate (`focused`).
288
+ enteredAt = at;
289
+ earned = takesText(was) || judge(active, entered, seen, at);
290
+ }
291
+ // Into a text field from a display's frame (the person pressed the composer while the frame
292
+ // had focus): watched as a take-back is, since a page that takes focus back on its own blur
293
+ // leaves it on nothing on Firefox (measured), where the keys are lost to the page's doing.
294
+ const left = was === null ? undefined : frames.get(was);
295
+ if (left !== undefined && takesText(active)) {
296
+ contest = {
297
+ field: active,
298
+ frame: was,
299
+ guarded: left,
300
+ gaveAt: at,
301
+ heldSince: at,
302
+ };
303
+ return;
304
+ }
305
+ const guarded = frames.get(active);
306
+ if (guarded === undefined || !takesText(was) || !was.isConnected) {
307
+ return;
308
+ }
309
+ const frame = active;
310
+ if (judge(frame, guarded, seen, at)) {
311
+ return;
312
+ }
313
+ takeBack(was, frame, guarded, at, false);
314
+ };
315
+ /**
316
+ * Firefox moves focus into a frame without a word to the host's page: while a frame is guarded,
317
+ * look at each animation frame (one read of the focused element), so the guard knows where focus
318
+ * is when it next leaves a text field, or comes into one from a frame.
319
+ */
320
+ const poll = () => {
321
+ polling = 0;
322
+ look(false);
323
+ schedule();
324
+ };
325
+ const schedule = () => {
326
+ if (polling === 0 && (frames.size > 0 || contest !== null)) {
327
+ polling = view.requestAnimationFrame(poll);
328
+ }
329
+ };
330
+ const gesture = () => {
331
+ gestureAt = now();
332
+ };
333
+ const press = (event) => {
334
+ pressAt = now();
335
+ gestureAt = pressAt;
336
+ const target = event.composedPath()[0];
337
+ pressed =
338
+ target instanceof Element && takesText(target)
339
+ ? { field: target, at: pressAt, from: deepActive(document) }
340
+ : null;
341
+ };
342
+ view.addEventListener("keydown", (event) => {
343
+ const at = now();
344
+ gestureAt = at;
345
+ lastKey = { key: event.key, at };
346
+ if (event.key !== "Tab" && !MODIFIERS.has(event.key)) {
347
+ typedAt = at;
348
+ }
349
+ }, true);
350
+ // A click too (an assistive technology's click on the host's own UI dispatches no press), and
351
+ // text that comes without a key (dictation, a paste, an input method): typing all the same.
352
+ for (const type of ["pointerup", "touchend", "click"]) {
353
+ view.addEventListener(type, gesture, true);
354
+ }
355
+ for (const type of ["pointerdown", "mousedown"]) {
356
+ view.addEventListener(type, press, true);
357
+ }
358
+ view.addEventListener("input", () => {
359
+ typedAt = now();
360
+ gestureAt = typedAt;
361
+ }, true);
362
+ // Focus moving within the page: what had it, for the next move out of a text field.
363
+ document.addEventListener("focusin", () => {
364
+ focusedAt = now();
365
+ look(false);
366
+ schedule();
367
+ }, true);
368
+ // Chromium and WebKit blur the window as focus goes into a frame. Firefox may send the field a
369
+ // focusout first (seen in one review's runs, not in another's): looked at once it's over.
370
+ view.addEventListener("blur", (event) => {
371
+ if (event.target === view) {
372
+ look(true);
373
+ }
374
+ });
375
+ document.addEventListener("focusout", () => {
376
+ view.setTimeout(() => look(false), 0);
377
+ }, true);
378
+ const guard = {
379
+ add(frame, taken) {
380
+ let guarded = frames.get(frame);
381
+ if (guarded === undefined) {
382
+ const entry = { taken: new Set(), overSince: -Infinity };
383
+ frame.addEventListener("pointerover", () => {
384
+ entry.overSince = now();
385
+ });
386
+ frames.set(frame, entry);
387
+ guarded = entry;
388
+ }
389
+ guarded.taken.add(taken);
390
+ schedule();
391
+ const own = guarded;
392
+ return () => {
393
+ own.taken.delete(taken);
394
+ if (own.taken.size === 0) {
395
+ frames.delete(frame);
396
+ }
397
+ };
398
+ },
399
+ focus(frame) {
400
+ hostMove = { frame, at: now() };
401
+ frame.focus();
402
+ look(true);
403
+ },
404
+ focused(frame) {
405
+ look(false);
406
+ // A press on the host's page since focus went into the frame, just now: the activation is
407
+ // that press's, and focus is about to leave (a call that lands in between doesn't count).
408
+ const pressedHost = pressAt > enteredAt && now() - pressAt < HOST_PRESS_MS;
409
+ return known === frame && document.activeElement === frame && earned && !pressedHost;
410
+ },
411
+ field(field) {
412
+ const holder = deepActive(document);
413
+ const guarded = holder === null ? undefined : frames.get(holder);
414
+ if (guarded === undefined) {
415
+ field.focus({ preventScroll: true });
416
+ return;
417
+ }
418
+ // Watched as a take-back: a frame that keeps focus fails it, and is counted.
419
+ const frame = holder;
420
+ frame.blur();
421
+ field.focus({ preventScroll: true });
422
+ known = field;
423
+ focusedAt = now();
424
+ contest = { field, frame, guarded, gaveAt: focusedAt, heldSince: null };
425
+ schedule();
426
+ },
427
+ };
428
+ guards.set(view, guard);
429
+ return guard;
430
+ }
431
+ /**
432
+ * Moves focus into one of the host page's text fields (a composer that opens beside a display,
433
+ * P109): `field.focus()` for a host to call instead. Firefox doesn't move focus from a frame that
434
+ * holds it with a gesture of the person's and takes it back on its own blur (measured: the keys
435
+ * then go to the frame); this blurs the frame first, and the focus guard watches that focus lands,
436
+ * counting a frame that keeps it toward stopping its display. Elsewhere it is `field.focus()`.
437
+ */
438
+ export function focusField(field) {
439
+ const view = field.ownerDocument.defaultView;
440
+ if (view === null) {
441
+ field.focus({ preventScroll: true });
442
+ return;
443
+ }
444
+ focusGuard(view).field(field);
445
+ }
@@ -46,6 +46,24 @@ export interface Surface {
46
46
  readonly width: number;
47
47
  readonly height: number;
48
48
  } | 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?(listener: (take: {
62
+ readonly typing: boolean;
63
+ readonly failed: boolean;
64
+ }) => void): () => void;
65
+ /** The host moves focus into the frame itself: the guard takes it as the person's (P109). */
66
+ focus?(): void;
49
67
  /**
50
68
  * The frame loaded a document other than the one it was given: the content navigated it. The
51
69
  * framework starts it again from its content and reports it.
@@ -1,5 +1,6 @@
1
1
  import { FRAME_STATUS_METHOD } from "../isolation/types.js";
2
2
  import { postMessageTransport } from "../transport/post-message.js";
3
+ import { focusGuard } from "./focus-guard.js";
3
4
  /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
4
5
  const isFrameStatus = (data) => data !== null &&
5
6
  typeof data === "object" &&
@@ -56,6 +57,15 @@ export const webPlatform = {
56
57
  });
57
58
  container.append(frame);
58
59
  const view = container.ownerDocument.defaultView ?? window;
60
+ // The focus guard (P109): a move of the keyboard into this frame from one of the page's text
61
+ // fields that the person didn't make is undone.
62
+ const guard = focusGuard(view);
63
+ const taken = new Set();
64
+ const unguard = guard.add(frame, (take) => {
65
+ for (const listener of taken) {
66
+ listener(take);
67
+ }
68
+ });
59
69
  // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
60
70
  // say of the frame's status is heard too, and nothing else from there.
61
71
  const own = view.origin;
@@ -85,6 +95,16 @@ export const webPlatform = {
85
95
  const activation = view.navigator.userActivation;
86
96
  return activation === undefined ? undefined : activation.isActive;
87
97
  },
98
+ focused() {
99
+ return guard.focused(frame);
100
+ },
101
+ onFocusTaken(listener) {
102
+ taken.add(listener);
103
+ return () => taken.delete(listener);
104
+ },
105
+ focus() {
106
+ guard.focus(frame);
107
+ },
88
108
  onLoad(listener) {
89
109
  loaded.add(listener);
90
110
  return () => loaded.delete(listener);
@@ -96,6 +116,8 @@ export const webPlatform = {
96
116
  destroy() {
97
117
  navigated.clear();
98
118
  loaded.clear();
119
+ taken.clear();
120
+ unguard();
99
121
  transport.close();
100
122
  frame.remove();
101
123
  },
@@ -229,6 +229,14 @@ export interface PortholeFrameProps {
229
229
  readonly onRefused?: (capability: CapabilityName, refusal: Refusal) => void;
230
230
  /** Too many declines: the display stops asking until it runs again. */
231
231
  readonly onMuted?: () => void;
232
+ /**
233
+ * The content moved the keyboard into its frame from one of the page's text fields without the
234
+ * person, and focus went back (P109); `typing`: the person was typing on the page. A display
235
+ * that keeps doing it is stopped (`onContentError` says so).
236
+ */
237
+ readonly onFocusTaken?: (taken: {
238
+ readonly typing: boolean;
239
+ }) => void;
232
240
  /**
233
241
  * How the frame's first document went: loaded, blocked (and why), or a timeout. A host shows its
234
242
  * own fallback (a url-mode app "Open in a new tab") on anything but loaded.
@@ -252,7 +260,8 @@ export interface PortholeFrameProps {
252
260
  readonly annotating?: AnnotateMode | null;
253
261
  /**
254
262
  * The anchors to mark in the frame (the host's comments). A mark with a `count` gets a
255
- * clickable marker (P104). Compared by value.
263
+ * clickable marker (P104); a draft (`kind: "draft"`, the author's own frame only) a hollow one
264
+ * with no number (P107). Compared by value.
256
265
  */
257
266
  readonly annotations?: readonly AnnotationMark[];
258
267
  /**
@@ -415,6 +415,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
415
415
  case "muted":
416
416
  frame.onMuted?.();
417
417
  return;
418
+ case "focusTaken":
419
+ frame.onFocusTaken?.(detail);
420
+ return;
418
421
  case "outcome":
419
422
  frame.onOutcome?.(detail);
420
423
  return;
@@ -532,6 +535,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
532
535
  "navigationBlocked",
533
536
  "refused",
534
537
  "muted",
538
+ "focusTaken",
535
539
  "outcome",
536
540
  "annotation",
537
541
  "contentError",
@@ -26,6 +26,11 @@ export interface CommentAnchor {
26
26
  }
27
27
  export interface CommentRequest {
28
28
  readonly anchor: CommentAnchor;
29
+ /**
30
+ * Text to start the person's comment with (P108): the content's word, a draft in the composer
31
+ * that the person edits and posts themselves, or doesn't. Never posted by the host on its own.
32
+ */
33
+ readonly draft?: string;
29
34
  }
30
35
  export declare function parseCommentRequest(args: unknown): CommentRequest | null;
31
36
  /** One file of a new version: text, bytes as base64, or `null` (removed from the base's set). */
@@ -1,3 +1,4 @@
1
+ import { unseenStrict, withoutUnseen } from "../bridge/unseen.js";
1
2
  import { fileLimits, filePathProblem } from "../files/paths.js";
2
3
  import { fileTypeOf } from "../files/types.js";
3
4
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -20,21 +21,57 @@ export function base64Bytes(value) {
20
21
  return (value.length / 4) * 3 - padding;
21
22
  }
22
23
  const encoder = new TextEncoder();
24
+ /** Characters that draw as a blank: spaces of every kind, tabs, new lines, the braille blank. */
25
+ const BLANK = /^[\p{White_Space}\u2800]*$/u;
26
+ /** More than 32 blanks in a row on a line, or more than two blank lines in a row (P109). */
27
+ const BLANK_RUN = /[\p{Zs}\t\u2800]{33}|\n(?:[\p{Zs}\t\u2800]*\n){3}/u;
28
+ /** Line and paragraph separators: a line break a person may see as nothing (Firefox, WebKit). */
29
+ const SEPARATORS = /[\u2028\u2029]/u;
30
+ /**
31
+ * A draft (P108, P109): text the person will post in their own name, so all of it must be text
32
+ * they can see: at most 2,000 characters, well-formed, and nothing invisible (`unseenStrict`: no
33
+ * zero-width characters, bidi or tag characters, controls but a new line and a tab; a joiner or
34
+ * non-joiner only between two letters or marks, a variation selector only after a pictograph), no line or paragraph
35
+ * separator, not blank-looking, at most 32 blanks in a row and two blank lines in a row (so that
36
+ * "whole" is something a host can show). Lines and tabs are fine: a checklist.
37
+ */
38
+ const draftText = (value) => typeof value === "string" &&
39
+ value.length <= 2_000 &&
40
+ value.isWellFormed() &&
41
+ !BLANK.test(value) &&
42
+ !unseenStrict(value) &&
43
+ !SEPARATORS.test(value) &&
44
+ !BLANK_RUN.test(value);
45
+ /**
46
+ * An anchor's label or quote, shown beside the draft (P109): the page's short text, without what a
47
+ * person can't see (P105's `withoutUnseen`, line and paragraph separators too), or null if nothing
48
+ * visible is left. Shown, never posted as the person's words, so cleaned rather than refused.
49
+ */
50
+ const shownText = (value, max) => {
51
+ if (!shortText(value, max)) {
52
+ return null;
53
+ }
54
+ const seen = withoutUnseen(value).replace(/[\u2028\u2029]/gu, "");
55
+ return BLANK.test(seen) ? null : seen;
56
+ };
23
57
  export function parseCommentRequest(args) {
24
58
  const anchor = isRecord(args) ? args.anchor : undefined;
25
59
  if (!isRecord(anchor) || !shortText(anchor.name, 256)) {
26
60
  return null;
27
61
  }
28
- if ((anchor.label !== undefined && !shortText(anchor.label, 200)) ||
29
- (anchor.quote !== undefined && !shortText(anchor.quote, 2_000))) {
62
+ const draft = isRecord(args) ? args.draft : undefined;
63
+ const label = anchor.label === undefined ? undefined : shownText(anchor.label, 200);
64
+ const quote = anchor.quote === undefined ? undefined : shownText(anchor.quote, 2_000);
65
+ if (label === null || quote === null || (draft !== undefined && !draftText(draft))) {
30
66
  return null;
31
67
  }
32
68
  return {
33
69
  anchor: {
34
70
  name: anchor.name,
35
- ...(anchor.label === undefined ? {} : { label: anchor.label }),
36
- ...(anchor.quote === undefined ? {} : { quote: anchor.quote }),
71
+ ...(label === undefined ? {} : { label }),
72
+ ...(quote === undefined ? {} : { quote }),
37
73
  },
74
+ ...(draft === undefined ? {} : { draft }),
38
75
  };
39
76
  }
40
77
  /** The most files one publish names (as the publish protocol, task #124 §4). */