@dasl/tile-loader 3.2.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/guard.ts CHANGED
@@ -11,6 +11,11 @@
11
11
  // const frame = tile.renderContent();
12
12
  // guardFocus(tile, frame);
13
13
  //
14
+ // The frame is out of the tab order then, so that nobody tabbing down the
15
+ // page ends up in the tile by chance, and the guard puts a stop of its own
16
+ // in its place, which the user tabs to and presses, and their next Tab
17
+ // takes them in.
18
+ //
14
19
  // A tile can also scroll the page it is in: asking the browser to bring an
15
20
  // element of its own into view scrolls every scroller above it, the page's
16
21
  // document included. That takes the page to the tile, holds it there, or
@@ -37,6 +42,7 @@
37
42
  import type { Tile } from './index.js';
38
43
  import { withDefaults } from './lib/defaults.js';
39
44
  import { SHIELD_CLASS, watchPointer } from './lib/pointer.js';
45
+ import { holdOut, letIn } from './lib/tab-order.js';
40
46
 
41
47
  const now = () => performance.now();
42
48
  const editable = (el: Element | null): boolean => Boolean(el) && ((el as HTMLElement).isContentEditable || /^(input|textarea|select)$/.test(el?.localName || ''));
@@ -55,6 +61,24 @@ export interface GuardControl {
55
61
  stop (): void;
56
62
  }
57
63
 
64
+ /** What `guardFocus` gives its host. */
65
+ export interface FocusGuardControl extends GuardControl {
66
+ /**
67
+ * Puts the keyboard in the tile for the host, as the user asked: what a
68
+ * control of the host's own calls, for someone who goes into a tile with
69
+ * the keyboard alone (a frame out of the tab order has no other way in,
70
+ * where the guard has no stop of its own in its place: see `tabOrder`).
71
+ * The page sees no Tab then, and the user did not act in the tile, so
72
+ * focus the host gave the frame with `frame.focus()` would be taken for a
73
+ * script's and given back. Given this way it is the user's, as if they
74
+ * had tabbed in. Call it from that control's own handler: the guard takes
75
+ * the host at its word. From a key, only Chrome lets a page put the
76
+ * keyboard in a frame: Firefox and WebKit leave it where it was, and only
77
+ * a press goes in there. The guard's own stop does not go this way.
78
+ */
79
+ focus (): void;
80
+ }
81
+
58
82
  /**
59
83
  * A guard stopped a tile, because it kept taking the keyboard (`focus`) or
60
84
  * the page (`scroll`) from the user. Raised on the tile as a `stopped` event,
@@ -82,33 +106,60 @@ function halt (tile: Tile, frame: HTMLElement, reason: GuardStoppedEvent['reason
82
106
  }
83
107
 
84
108
  const DOCK_STATUS = 'tiles-dock-status';
109
+ const DOCK_KEYBOARD = 'tiles-dock-keyboard';
85
110
 
86
111
  // What the tile's dock says of the user and that tile, asked for when it
87
112
  // matters (see `DockStamp`): whether the user has just pressed or typed
88
- // inside the tile. `ask()` resolves `undefined` when no answer comes within
89
- // `ms`. A loading server from before its dock knew the question never
90
- // answers; `answers` says whether this one ever has. The answer is only ever
91
- // used to refuse, so that one that is not the dock's own gains nothing.
92
- function dockStatus (tile: Tile, frame: HTMLIFrameElement, ms: number) {
113
+ // inside the tile (`activated`), and, from a dock that was asked to watch,
114
+ // whether they had when the keyboard came into it (`arrivalActivated`).
115
+ // `ask()` resolves `undefined` when no answer comes within `ms`. A loading
116
+ // server from before its dock knew the question never answers; `answers`
117
+ // says whether this one ever has. `watch()` asks the dock to watch the
118
+ // keyboard, or to stop, and `entered()` tells it that the user went into the
119
+ // tile themselves (`into`: with a press, and the keyboard is to go on into
120
+ // the tile from the dock's own page, where the way in puts it), on the same
121
+ // question, which a dock never passes on to the tile: one from before it
122
+ // knew of watching answers it, and that is all. A
123
+ // dock that watches also says, unasked, when it finds the keyboard come into
124
+ // the tile with no one acting there: `refused` is called then. All of it is
125
+ // only ever used to refuse, so that what is not the dock's own gains
126
+ // nothing. Where a no of the dock's is only its best guess (someone did act
127
+ // in the tile, and it may have been the user), it says so (`unsure`), and
128
+ // that only ever spares the tile being counted for it.
129
+ interface DockAnswer {
130
+ activated: boolean;
131
+ arrivalActivated?: boolean | null;
132
+ unsure?: boolean;
133
+ }
134
+ function dockStatus (tile: Tile, frame: HTMLIFrameElement, ms: number, refused: (unsure: boolean) => void) {
93
135
  const win = frame.ownerDocument.defaultView as Window;
94
136
  const origin = new URL(tile.getLoadSource()).origin;
95
- const waiting = new Map<string, (activated: boolean | undefined) => void>();
137
+ const waiting = new Map<string, (answer: DockAnswer | undefined) => void>();
96
138
  let n = 0;
97
139
  let answers = false;
98
140
  const onMessage = (ev: MessageEvent) => {
99
- if (ev.source !== frame.contentWindow || ev.origin !== origin || ev.data?.action !== DOCK_STATUS) return;
100
- const { id, activated } = ev.data.payload ?? {};
141
+ if (ev.source !== frame.contentWindow || ev.origin !== origin) return;
142
+ if (ev.data?.action === DOCK_KEYBOARD) {
143
+ if (ev.data.payload?.arrivalActivated === false) refused(ev.data.payload.unsure === true);
144
+ return;
145
+ }
146
+ if (ev.data?.action !== DOCK_STATUS) return;
147
+ const { id, activated, arrivalActivated, unsure } = ev.data.payload ?? {};
101
148
  if (typeof activated !== 'boolean') return;
102
149
  answers = true;
103
150
  const resolve = waiting.get(id);
104
151
  if (!resolve) return;
105
152
  waiting.delete(id);
106
- resolve(activated);
153
+ resolve({ activated, arrivalActivated: typeof arrivalActivated === 'boolean' ? arrivalActivated : null, unsure: unsure === true });
107
154
  };
108
155
  win.addEventListener('message', onMessage);
109
156
  return {
110
157
  get answers () { return answers; },
111
- ask (): Promise<boolean | undefined> {
158
+ // (`fromPage`: the keyboard has just left the page, and what the dock finds in the tile has just come;
159
+ // `at` says when, by the clock the dock has too, so that it can tell when our word reached it late.)
160
+ watch (on: boolean, fromPage: boolean) { tile.post(DOCK_STATUS, { id: `w${++n}`, watch: on, ...(fromPage ? { fromPage, at: Date.now() } : {}) }); },
161
+ entered (into: boolean) { tile.post(DOCK_STATUS, { id: `e${++n}`, entered: true, ...(into ? { into } : {}) }); },
162
+ ask (): Promise<DockAnswer | undefined> {
112
163
  const id = `d${++n}`;
113
164
  return new Promise((resolve) => {
114
165
  waiting.set(id, resolve);
@@ -156,30 +207,163 @@ export interface FocusGuardOptions {
156
207
  * the user's doing.
157
208
  */
158
209
  engaged?: () => boolean;
210
+ /**
211
+ * What a no of the dock's that is only its best guess does: one where the
212
+ * user did act in the tile or on a page of the dock's, and may have
213
+ * pressed in it (a slow device busy loading another tile, say). By
214
+ * default (`true`) the keyboard is given back, that is not counted against
215
+ * the tile, and a layer of the page's lies over the tile until the user
216
+ * picks it, with a press or Enter or Space on it, which puts the keyboard
217
+ * in the tile as `focus()` does, or until the dock's no is over (what it
218
+ * went by has run out with the keyboard out of the tile), when it lifts on
219
+ * its own. Until then the keyboard coming into the tile is never the
220
+ * user's doing, and is given back and counted. Such a no in the `spareMs`
221
+ * after a layer lifted on its own is counted too, and has a layer as well.
222
+ * `false`: given back and counted, as any other no of the dock's.
223
+ */
224
+ pick?: boolean;
225
+ /**
226
+ * How long after the layer lifted on its own a no of the dock's that is
227
+ * only its best guess is counted all the same, in milliseconds (see
228
+ * `pick`): a tile that can have its dock's nos taken for guesses is spared
229
+ * one giving back for each time the user picks it, and at most one in
230
+ * this time otherwise.
231
+ */
232
+ spareMs?: number;
233
+ /**
234
+ * What the layer says, to those who see it and to those who do not (it is
235
+ * the name of the button it is). Default: "Tap or click to use".
236
+ */
237
+ pickLabel?: string;
238
+ /**
239
+ * Where the frame is in the tab order while the guard runs. `'stop'` (the
240
+ * default): out of it, so that someone tabbing down the page passes over
241
+ * the tile, with a stop of the guard's own in its place, right before the
242
+ * frame (`ENTER_CLASS`): Enter or Space there lets the frame into the tab
243
+ * order for the user's next Tab, which takes them into the tile, and the
244
+ * stop says so (`tabLabel`). It cannot be seen until it has the keyboard,
245
+ * and then lies over the tile, taking no press, and says what it is for
246
+ * (`enterLabel`).
247
+ * `'out'`: out of it, and the way in is the host's own (`focus()`).
248
+ * `'keep'`: as its host made it; a frame in the tab order then has Tab
249
+ * take the user into it. The frame gets back what its host gave it when
250
+ * the guard stops. A tabindex the host gave the frame itself is not a
251
+ * `'keep'`.
252
+ */
253
+ tabOrder?: 'stop' | 'out' | 'keep';
254
+ /**
255
+ * What the stop in the frame's place says (see `tabOrder`), to those who
256
+ * see it and to those who do not. Default: "Use the keyboard in" and the
257
+ * tile's name, or "this tile" for a tile with none.
258
+ */
259
+ enterLabel?: string;
260
+ /**
261
+ * What the stop says once the user has pressed it, while their next Tab
262
+ * takes them into the tile (see `tabOrder`). Default: "Press Tab to go in".
263
+ */
264
+ tabLabel?: string;
265
+ }
266
+
267
+ /** The class of the layer `guardFocus` lays over a tile for the user to pick it, besides `ENGAGE_CLASS`. */
268
+ export const PICK_CLASS = 'tile-pick';
269
+ /** The class of what the layer says, inside it, and of what the stop in the frame's place says. */
270
+ export const PICK_LABEL_CLASS = 'tile-pick-label';
271
+ /** The class of the stop `guardFocus` puts in the frame's place in the tab order (see `tabOrder`). */
272
+ export const ENTER_CLASS = 'tile-enter';
273
+
274
+ // What the layer looks like where its host gives it no look of its own: a
275
+ // ring round the tile, and what it says in the middle, so that a user whose
276
+ // press seemed to do nothing sees that the tile waits for them. The stop in
277
+ // the frame's place looks the same while it has the keyboard, the only time
278
+ // it can be seen. Every rule here weighs nothing (`:where`), so that any
279
+ // rule of the host's for `.tile-pick`, `.tile-enter` or `.tile-pick-label`
280
+ // wins. Given once to each document, as a sheet of its own where the browser
281
+ // has those (a page whose policy refuses inline style does not refuse one),
282
+ // else as a style element. And once to each shadow tree a frame is in, where
283
+ // the layer and the stop go too: no rule of the document's reaches into one.
284
+ const PICK_LOOK = `
285
+ :where(.${PICK_CLASS}) { display: flex; align-items: center; justify-content: center; box-sizing: border-box;
286
+ box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.6), inset 0 0 0 4px rgba(255, 255, 255, 0.75); }
287
+ :where(.${PICK_CLASS}:focus-visible) { outline: 3px solid Highlight; outline-offset: -3px; }
288
+ :where(.${ENTER_CLASS}) { display: flex; align-items: center; justify-content: center; box-sizing: border-box;
289
+ box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.6), inset 0 0 0 4px rgba(255, 255, 255, 0.75); }
290
+ :where(.${ENTER_CLASS}:focus-visible) { outline: 3px solid Highlight; outline-offset: -3px; }
291
+ :where(.${PICK_LABEL_CLASS}) { max-width: calc(100% - 16px); padding: 6px 12px; border-radius: 999px; box-sizing: border-box;
292
+ background: rgba(0, 0, 0, 0.78); color: #fff; font: 600 13px/1.3 system-ui, sans-serif; text-align: center;
293
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; pointer-events: none; }
294
+ `;
295
+ const looked = new WeakSet<Document | ShadowRoot>();
296
+ function pickLook (doc: Document, root: Document | ShadowRoot) {
297
+ if (looked.has(root)) return;
298
+ looked.add(root);
299
+ const win = doc.defaultView as (Window & typeof globalThis) | null;
300
+ try {
301
+ if (win && 'adoptedStyleSheets' in root && typeof win.CSSStyleSheet?.prototype.replaceSync === 'function') {
302
+ const sheet = new win.CSSStyleSheet();
303
+ sheet.replaceSync(PICK_LOOK);
304
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
305
+ return;
306
+ }
307
+ }
308
+ catch { /* a style element, then */ }
309
+ const style = doc.createElement('style');
310
+ style.textContent = PICK_LOOK;
311
+ // First, so that the host's own sheets come after it.
312
+ (root === doc ? doc.head : root)?.prepend(style);
159
313
  }
160
314
 
161
315
  /** `guardFocus`'s numbers where a host gives none. */
162
- export const FOCUS_GUARD: Readonly<Record<'tabMs' | 'typingMs' | 'grabs' | 'withinMs' | 'dockMs' | 'pollMs', number>> = Object.freeze({
316
+ export const FOCUS_GUARD: Readonly<Record<'tabMs' | 'typingMs' | 'grabs' | 'withinMs' | 'dockMs' | 'pollMs' | 'spareMs', number>> = Object.freeze({
163
317
  tabMs: 400,
164
318
  typingMs: 1000,
165
319
  grabs: 3,
166
320
  withinMs: 10000,
167
321
  dockMs: 150,
168
322
  pollMs: 100,
323
+ spareMs: 60000,
169
324
  });
325
+ // How often, at most, a guard with its layer up asks the dock whether its no
326
+ // is over (see `settle`). A guess.
327
+ const SETTLE_MS = 500;
328
+ // How long, at most, a frame is let into the tab order for the Tab from its
329
+ // stop, once the user has pressed the stop (see `enter`). A guess.
330
+ const LET_IN_MS = 10000;
331
+ // How much of a tile's name its stop says, at most, in characters, the
332
+ // ellipsis included. A guess.
333
+ const NAME_MAX = 60;
170
334
 
171
335
  /**
172
336
  * Gives back keyboard focus that a tile's script took, and leaves it with a
173
337
  * user who went into the tile.
174
338
  *
175
- * Focus arriving in the frame is the user's doing when they tabbed into it,
176
- * or pressed on it. The page sees the Tab key. It never sees the press: only
177
- * that a mouse is over the frame, and not even that for a finger. So focus
339
+ * Focus arriving in the frame is the user's doing when they went in by the
340
+ * host's own way in (a control of its own calling `focus()`), tabbed into
341
+ * it (from the guard's stop in the frame's place in the tab order, which
342
+ * lets the frame in for that Tab, or into a frame the host keeps in the tab
343
+ * order: see `tabOrder`), or pressed on it. The page sees
344
+ * the Tab key. It never sees the press: only that a mouse is over the
345
+ * frame, and not even that for a finger. So focus
178
346
  * stays in the tile when a Tab was just pressed on the page; otherwise, when
179
- * a mouse is in the frame (or the user has none) and they were not typing in
180
- * a field of the page a moment ago, the tile's dock is asked, which knows
347
+ * a mouse is in the frame (or the user has none, or, on a screen that takes
348
+ * fingers, the guard has seen no pointer yet and the keyboard came straight
349
+ * from the page) and they were not typing in a field of the page a moment
350
+ * ago, the tile's dock is asked, which knows
181
351
  * whether the user pressed or typed inside this tile. In every other case,
182
- * and when the dock says no, focus goes back to what had it.
352
+ * and when the dock says no, focus goes back to what had it when the tile
353
+ * took it: to the page alone when nothing of the page's had it then, and
354
+ * never to something the user had left.
355
+ *
356
+ * While the keyboard is in a frame of the page's, where the page cannot see
357
+ * it move, the guard has the tile's dock watch it come into the tile, and a
358
+ * dock that found it come in with no one acting there says no, at once and
359
+ * for as long as what the user typed into the tile before it was given back
360
+ * can make them seem to have acted there.
361
+ *
362
+ * Where the dock's no is only its best guess (someone did act in the tile,
363
+ * and it may have been the user pressing in it), the keyboard is given back
364
+ * all the same, but that is not counted against the tile: a layer of the
365
+ * page's lies over it until the user picks it, which puts the keyboard in,
366
+ * or until the dock's no is over (see `pick`).
183
367
  *
184
368
  * A dock that has answered before and now does not is taken to say no: its
185
369
  * silence is not to be had by keeping it busy. One that has never answered
@@ -190,32 +374,71 @@ export const FOCUS_GUARD: Readonly<Record<'tabMs' | 'typingMs' | 'grabs' | 'with
190
374
  * that does so `grabs` times within `withinMs` is reported (`onAbuse`) and
191
375
  * stopped (see `GuardStoppedEvent`), unless told otherwise (`stop: false`).
192
376
  */
193
- export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: FocusGuardOptions = {}): GuardControl {
377
+ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: FocusGuardOptions = {}): FocusGuardControl {
378
+ // A host that meant to keep the frame in the tab order, and said so in a
379
+ // way the guard does not know, would be left believing in a Tab key that
380
+ // passes over the tile. So that throws, before anything is set up.
381
+ const tabOrder = options.tabOrder ?? 'stop';
382
+ if (tabOrder !== 'stop' && tabOrder !== 'out' && tabOrder !== 'keep') throw new Error(`guardFocus() takes 'stop', 'out' or 'keep' for where the frame is in the tab order, not ${JSON.stringify(tabOrder)}.`);
194
383
  const doc = frame.ownerDocument;
195
384
  const win = doc.defaultView as Window;
196
385
  const pointer = watchPointer(doc);
197
386
  const cfg = withDefaults(FOCUS_GUARD, options);
198
- const dock = dockStatus(tile, frame, cfg.dockMs);
387
+ const dock = dockStatus(tile, frame, cfg.dockMs, (unsure) => onRefused(unsure));
199
388
  // Whether this dock answers at all is learnt while nothing is at stake:
200
389
  // now, and when the tile's runtime says it is up, before the tile runs.
201
390
  const probe = () => { dock.ask(); };
202
391
  probe();
203
392
  tile.addEventListener('load', probe);
204
- // What had the keyboard before the tile did.
393
+ // What had the keyboard before the tile did. Nothing of the page's, when
394
+ // the guard is made with the keyboard in another frame of the page's (the
395
+ // user is in a tile, and the page adds this one): given back there, it
396
+ // would be put in a frame by the page's own script, and Chrome then goes on
397
+ // naming that frame as having it after it has gone elsewhere.
205
398
  let holder = focused(doc) as HTMLElement | null;
206
- if (holder === frame || holder === doc.body) holder = null;
399
+ if (holder === frame || holder === doc.body || framed(holder)) holder = null;
207
400
  // Whether this window has the keyboard. Which element is the active one is
208
401
  // not enough to go by: that says which element WOULD have it. The window's
209
402
  // own focus and blur events say whether a frame inside it has taken it.
210
- let winFocused = doc.hasFocus() && !holds(frame);
403
+ // To begin with there is only the active element to go by: with a frame
404
+ // active the window does not have it, though the document "has focus"
405
+ // then too, and no blur will say so when this tile takes it from there.
406
+ let winFocused = doc.hasFocus() && !holds(frame) && !framed(focused(doc));
407
+ // Whether the keyboard, when it last left the page, went from the page
408
+ // itself (its window said so) and not from another frame of the page's.
409
+ let straight = winFocused;
211
410
  let inTile = false;
212
411
  let accepted = false;
412
+ let tabbed = false; // accepted for what the page saw: a Tab, or its own way in
413
+ let returning = false; // a giving back is under way
213
414
  let lastTab = -Infinity;
415
+ let into = false; // the way in that set lastTab was taken with a press (see `focus`)
214
416
  let lastTyped = -Infinity;
215
417
  let returned = 0;
216
418
  let round = 0; // which giving back is under way: one that was overtaken does nothing more
217
419
  let grabs: number[] = [];
218
420
  let stopped = false;
421
+ // The layer the user picks the tile on, once a no of the dock's was only
422
+ // its best guess (see `pick`), and how to put back what it took to lay it
423
+ // over the frame.
424
+ let layer: HTMLElement | undefined;
425
+ let unlay: (() => void) | undefined;
426
+ let liftedAt = -Infinity; // when the layer last lifted on its own
427
+ let settling = false; // the dock is being asked whether its no is over
428
+ let settledAt = -Infinity;
429
+ // Whether the dock is watching the keyboard come into the tile. It is
430
+ // asked to while the keyboard is in a frame of the page's (this tile's or
431
+ // another's), which is when the page cannot see it move from one to the
432
+ // next: not while it is on the page, which the page sees at once, nor
433
+ // while the window does not have it at all, and never once stopped.
434
+ // `fromPage`: the window has just said that the keyboard left it.
435
+ let watched = false;
436
+ const watch = (fromPage = false) => {
437
+ const want = !stopped && !winFocused && doc.hasFocus();
438
+ if (want === watched) return;
439
+ watched = want;
440
+ dock.watch(want, want && fromPage);
441
+ };
219
442
 
220
443
  // Whether `el` is the frame, or something the frame is in (the element
221
444
  // whose shadow tree it is in is all the page is told of it, where that
@@ -231,18 +454,63 @@ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: Focus
231
454
  // page's, not into the tile: it explains nothing that arrives there next.
232
455
  if (target && !around(target)) lastTab = -Infinity;
233
456
  };
457
+ // What had the keyboard is where it goes back to only for as long as it
458
+ // still has it. A button the user pressed a while ago and then left, for
459
+ // the plain text of the page, has it no longer: put back there, the
460
+ // keyboard would be on a control its user never returned to, and their
461
+ // next Space or Enter would press it. So what lost the keyboard to nothing
462
+ // of the page's is forgotten, and the keyboard then goes back to the page
463
+ // and to no element of it.
464
+ const onNothing = (): boolean => {
465
+ const el = focused(doc);
466
+ return !el || el === doc.body || el === doc.documentElement;
467
+ };
468
+ const forget = () => {
469
+ if (winFocused && doc.hasFocus() && onNothing()) holder = null;
470
+ };
471
+ const onFocusOut = (ev: FocusEvent) => {
472
+ // To something else of the page's: `focusin` says what.
473
+ if (ev.relatedTarget) return;
474
+ const target = (ev.composedPath?.()[0] ?? ev.target) as Element | null;
475
+ // Out of the tile, and to nothing: the user left it for the page itself.
476
+ if (target === frame) holder = null;
477
+ // Out of what had it: to nothing, or into a frame (the tile's, when its
478
+ // script takes the keyboard, or another of the page's, when the user goes
479
+ // into one), and only the window's own events tell which. In a moment
480
+ // they have: `forget` sees to the first, and `check` to a frame.
481
+ else win.setTimeout(forget, 0);
482
+ };
234
483
  // Whether a key picks the tile, for a host that has it wait to be picked:
235
484
  // Enter or Space on the layer over it (see `engage`), which then puts the
236
485
  // keyboard into the tile itself.
237
486
  const picks = (ev: KeyboardEvent): boolean => {
238
487
  if (ev.key !== 'Enter' && ev.key !== ' ') return false;
239
488
  const target = (ev.composedPath?.()[0] ?? ev.target) as Element | null;
489
+ // Of the layers a focus guard lays, only ours: the box it is in may hold
490
+ // other tiles, each with its guard's layer beside ours.
491
+ if (target?.classList?.contains(PICK_CLASS)) return target === layer;
240
492
  return Boolean(target?.classList?.contains(ENGAGE_CLASS) && target.parentNode?.contains(frame));
241
493
  };
242
494
  const onKey = (ev: KeyboardEvent) => {
243
495
  if (!ev.isTrusted) return;
244
- // (Picking the tile from the keyboard is going into it by the keyboard, as tabbing into it is.)
245
- if (ev.key === 'Tab' || picks(ev)) lastTab = now();
496
+ // (Picking the tile from the keyboard is going into it by the keyboard,
497
+ // as tabbing into it is; on the layer of engage's as well as ours.)
498
+ const pick = picks(ev);
499
+ if (pick) lift();
500
+ if (ev.key === 'Tab' || pick) {
501
+ // A Tab takes nobody into a frame that is out of the tab order: the
502
+ // keyboard arriving there next is not explained by it (it may have
503
+ // gone into another frame, whose tile tells this one when). As the
504
+ // frame is now, which its host may have changed. While it is let in
505
+ // for the Tab from its stop, only that Tab can take the user into it:
506
+ // forward, from the stop, which is right before it.
507
+ const tabsIn = frame.tabIndex >= 0 && (!letOut || (!ev.shiftKey && onStop()));
508
+ if (pick || tabsIn) {
509
+ lastTab = now();
510
+ spent = !pick && Boolean(letOut);
511
+ }
512
+ into = false;
513
+ }
246
514
  else if (editable(focused(doc))) lastTyped = now();
247
515
  };
248
516
  // Whether focus that has just arrived in the frame can be the user's
@@ -251,10 +519,21 @@ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: Focus
251
519
  const judge = (): 'tab' | 'ask' | false => {
252
520
  const t = now();
253
521
  if (options.engaged && !options.engaged()) return false;
522
+ // Nor in one that waits for the user to pick it, after a no the dock was not sure of.
523
+ if (layer) return false;
254
524
  if (t - lastTab < cfg.tabMs) return 'tab';
255
525
  if (t - lastTyped < cfg.typingMs) return false;
256
526
  // A finger gives the page nothing to go by.
257
527
  if (!pointer.hovers || pointer.state.kind === 'none') return 'ask';
528
+ // Nor, on a screen that takes fingers, does a guard that has seen no
529
+ // pointer yet: one may have come down in the frame unseen. The dock is
530
+ // asked then only when the keyboard came straight from the page, and only
531
+ // a dock that has answered before. Found in the tile after it was in
532
+ // another frame of the page's, it may have been taken while the user was
533
+ // typing there: what they typed since is the tile's by the time the guard
534
+ // looks, and the dock would count it as their having acted in the tile.
535
+ // And a dock that has never answered would leave the tile the keyboard.
536
+ if (pointer.fingers && pointer.state.kind === 'unknown' && straight && dock.answers) return 'ask';
258
537
  return pointer.inside(frame) ? 'ask' : false;
259
538
  };
260
539
  // Never from inside the blur that tells us: the browser is still moving
@@ -262,57 +541,365 @@ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: Focus
262
541
  // returns, leaving the element "focused" in a window that has no keyboard.
263
542
  // So it is done from a later task, checked by the window's own focus event,
264
543
  // and done again if it did not take.
265
- const takeBack = (tries: number, mine: number) => {
544
+ // `to` is what had the keyboard when the tile took it, if anything had:
545
+ // settled before the frame is blurred here, which is the keyboard leaving
546
+ // the tile for nothing.
547
+ const takeBack = (tries: number, mine: number, to: HTMLElement | null) => {
266
548
  if (stopped || winFocused || mine !== round) return;
267
- if (tries === 0 && holder?.isConnected) holder.focus({ preventScroll: true });
549
+ if (tries === 0 && to?.isConnected) to.focus({ preventScroll: true });
268
550
  else {
269
551
  frame.blur();
270
552
  win.focus();
271
- if (holder?.isConnected) holder.focus({ preventScroll: true });
553
+ if (to?.isConnected) to.focus({ preventScroll: true });
272
554
  }
273
- if (tries < 4) win.setTimeout(() => takeBack(tries + 1, mine), 30);
555
+ if (tries < 4) win.setTimeout(() => takeBack(tries + 1, mine, to), 30);
274
556
  };
275
- const giveBack = (why: 'script' | 'dock') => {
557
+ // `guess`: the dock's no was only its best guess (see `pick`).
558
+ const giveBack = (why: 'script' | 'dock', guess = false) => {
276
559
  returned++;
277
- const t = now();
278
- grabs = grabs.filter(g => t - g < cfg.withinMs);
279
- grabs.push(t);
280
- takeBack(0, ++round);
560
+ returning = true;
561
+ // Such a no is not held against the tile: it may have been the user
562
+ // pressing in it. They pick it on a layer instead, which the tile cannot
563
+ // lift, and until they do, the keyboard coming in is counted.
564
+ // (Not where a layer lifted on its own a moment ago: a tile that could
565
+ // have its dock's nos taken for guesses, and waited each time for the
566
+ // layer to go, would never be counted. It has a layer all the same.)
567
+ const spared = now() - liftedAt >= cfg.spareMs;
568
+ const counted = !(guess && lay() && spared);
569
+ if (counted) {
570
+ const t = now();
571
+ grabs = grabs.filter(g => t - g < cfg.withinMs);
572
+ grabs.push(t);
573
+ }
574
+ takeBack(0, ++round, holder);
281
575
  options.onReturn?.(why);
282
- if (grabs.length < cfg.grabs) return;
576
+ if (!counted || grabs.length < cfg.grabs) return;
283
577
  grabs = [];
284
578
  options.onAbuse?.('focus', returned);
285
579
  if (options.stop !== false) halt(tile, frame, 'focus');
286
580
  };
287
- const check = () => {
581
+ // A layer of the page's over the frame, for the user to pick the tile on:
582
+ // a press or a tap on it, or Enter or Space, all of which the page sees
583
+ // and the tile cannot make. It shows that the tile waits for them, and
584
+ // says so (see `PICK_LOOK`). Put in the frame's box, right after it, which
585
+ // is made one that it is laid out against if it is not; and the frame is
586
+ // out of the tab order meanwhile, the layer in its place, as with
587
+ // `engage`. Whether it went up: not when it was up already, which the
588
+ // tile had to get past.
589
+ const lay = (): boolean => {
590
+ const box = (frame.parentElement ?? (frame.parentNode as ShadowRoot | null)?.host) as HTMLElement | null | undefined;
591
+ if (layer || options.pick === false || stopped || !box) return false;
592
+ // (In the shadow tree the frame is in, if it is in one: the layer is.)
593
+ const root = frame.getRootNode();
594
+ pickLook(doc, root instanceof (win as Window & typeof globalThis).ShadowRoot ? root : doc);
595
+ const label = options.pickLabel ?? 'Tap or click to use';
596
+ const el = doc.createElement('div');
597
+ el.className = `${ENGAGE_CLASS} ${PICK_CLASS}`;
598
+ el.setAttribute('role', 'button');
599
+ el.setAttribute('tabindex', '0');
600
+ el.setAttribute('aria-label', label);
601
+ el.style.cssText = 'position:absolute;z-index:1;background:rgba(127,127,127,0.03);cursor:pointer;';
602
+ const words = doc.createElement('span');
603
+ words.className = PICK_LABEL_CLASS;
604
+ words.textContent = label;
605
+ el.append(words);
606
+ el.addEventListener('click', (ev) => { if (ev.isTrusted) picked(); });
607
+ el.addEventListener('keydown', (ev) => {
608
+ if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
609
+ ev.preventDefault();
610
+ picked();
611
+ });
612
+ const position = win.getComputedStyle(box).position;
613
+ const own = box.style.position;
614
+ if (!position || position === 'static') box.style.position = 'relative';
615
+ // (Held out with whatever else holds it, engage's among them: see `holdOut`.)
616
+ const back = holdOut(frame);
617
+ unlay = () => {
618
+ box.style.position = own;
619
+ back();
620
+ };
621
+ frame.after(el);
622
+ layer = el;
623
+ place();
624
+ standBy();
625
+ return true;
626
+ };
627
+ // Over the frame wherever it is in its box, which may change as the page
628
+ // is laid out again: done again at every look.
629
+ const place = () => {
630
+ const box = layer?.offsetParent as HTMLElement | null | undefined;
631
+ if (!layer || !box) return;
632
+ const at = frame.getBoundingClientRect();
633
+ const of = box.getBoundingClientRect();
634
+ layer.style.left = `${at.left - of.left - box.clientLeft + box.scrollLeft}px`;
635
+ layer.style.top = `${at.top - of.top - box.clientTop + box.scrollTop}px`;
636
+ layer.style.width = `${at.width}px`;
637
+ layer.style.height = `${at.height}px`;
638
+ };
639
+ const lift = () => {
640
+ if (!layer) return;
641
+ layer.remove();
642
+ layer = undefined;
643
+ unlay?.();
644
+ unlay = undefined;
645
+ standBy();
646
+ };
647
+ // The layer lifts on its own once the dock's no is over: what it went by,
648
+ // its activation, has run out while the keyboard was out of the tile, and
649
+ // the dock says so when asked, as a no that is no longer its best guess
650
+ // (`unsure`) nor a no that stands. Asked now and then while the keyboard
651
+ // is not in the tile, nor on the layer: a user about to pick it with a key
652
+ // keeps it.
653
+ const settle = () => {
654
+ if (!layer || settling || stopped || holds(frame) || focused(doc) === layer || now() - settledAt < SETTLE_MS) return;
655
+ settling = true;
656
+ settledAt = now();
657
+ dock.ask().then((said) => {
658
+ settling = false;
659
+ if (!layer || stopped || holds(frame) || focused(doc) === layer) return;
660
+ if (said?.activated !== false || said.unsure || said.arrivalActivated === false) return;
661
+ lift();
662
+ liftedAt = now();
663
+ });
664
+ };
665
+ // The user picked the tile on the layer: they go in, as by the host's own
666
+ // way in. (Unless the host has it wait to be picked with `engage`, and
667
+ // its layer is back over the tile since: that is where they pick it now.)
668
+ const picked = () => {
669
+ if (options.engaged && !options.engaged()) return lift();
670
+ focus();
671
+ };
672
+ // The stop in the frame's place in the tab order (see `tabOrder`): a
673
+ // button of the page's right before the frame, which the user tabs to and
674
+ // presses as they would the host's own way in. Before it, so that a Tab
675
+ // out of the tile's last field goes on to what comes after the tile, not
676
+ // back to the tile's own stop. It takes no room and
677
+ // cannot be seen until it has the keyboard; then it lies over the tile,
678
+ // with the layer's look, and says what it is for. It takes no press then:
679
+ // a press or a tap where it lies is one into the tile, which goes there,
680
+ // to what is under it, as it would with no stop. While another layer is
681
+ // over the tile (the guard's, or engage's for a tile that is not picked),
682
+ // that is where Tab stops, and this one is out of the tab order.
683
+ // The tile's name is the tile's to choose: cut to a name's length, so
684
+ // that what the stop says, and what it is called for those who do not see
685
+ // it, is a name and not whatever the tile would have it say. (By the
686
+ // character, not the code unit: a character is not cut in half.)
687
+ const named = Array.from(typeof tile.manifest?.name === 'string' ? tile.manifest.name.trim() : '');
688
+ const name = named.length > NAME_MAX ? `${named.slice(0, NAME_MAX - 1).join('')}…` : named.join('');
689
+ const enterLabel = options.enterLabel ?? `Use the keyboard in ${name || 'this tile'}`;
690
+ const tabLabel = options.tabLabel ?? 'Press Tab to go in';
691
+ // (Clipped to nothing, and out of the flow, where it is.)
692
+ const UNSEEN = 'position:absolute;width:1px;height:1px;margin:0;padding:0;border:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;';
693
+ const standIn = tabOrder === 'stop' ? doc.createElement('div') : undefined;
694
+ const words = standIn ? doc.createElement('span') : undefined;
695
+ let shown = false;
696
+ // What it says, to those who see it and to those who do not.
697
+ const say = (label: string) => {
698
+ if (!standIn || !words) return;
699
+ standIn.setAttribute('aria-label', label);
700
+ words.textContent = label;
701
+ };
702
+ const onStop = (): boolean => Boolean(standIn) && (standIn?.getRootNode() as Document | ShadowRoot).activeElement === standIn;
703
+ // The frame let into the tab order for the Tab from the stop (see
704
+ // `enter`), and how to end that; and whether the Tab that last explained
705
+ // the keyboard coming in was that one (`spent` once it has).
706
+ let letOut: (() => void) | undefined;
707
+ let letUntil: number | undefined;
708
+ let spent = false;
709
+ // The Tab from the stop takes the user in from there, and explains the
710
+ // keyboard coming into the frame from the stop and nothing else: should
711
+ // the keyboard be found anywhere else before the tile has it (another
712
+ // tile took it on the way, say), it is spent all the same.
713
+ const spend = () => {
714
+ if (!spent) return;
715
+ lastTab = -Infinity;
716
+ spent = false;
717
+ };
718
+ const shut = () => {
719
+ if (!letOut) return;
720
+ letOut();
721
+ letOut = undefined;
722
+ win.clearTimeout(letUntil);
723
+ say(enterLabel);
724
+ };
725
+ // Over the frame, wherever the box it is laid out against is: put where
726
+ // that box begins, it is as far from the frame as it has to move. Done
727
+ // again at every look, as the layer is, and without making the frame's
728
+ // box one to lay it out against, which is the layer's to do and undo.
729
+ const placeStandIn = () => {
730
+ if (!standIn || !shown) return;
731
+ const at = frame.getBoundingClientRect();
732
+ const was = standIn.getBoundingClientRect();
733
+ standIn.style.left = `${(parseFloat(standIn.style.left) || 0) + at.left - was.left}px`;
734
+ standIn.style.top = `${(parseFloat(standIn.style.top) || 0) + at.top - was.top}px`;
735
+ standIn.style.width = `${at.width}px`;
736
+ standIn.style.height = `${at.height}px`;
737
+ };
738
+ const show = (on: boolean) => {
739
+ if (!standIn) return;
740
+ shown = on;
741
+ standIn.style.cssText = on ? 'position:absolute;z-index:1;left:0;top:0;pointer-events:none;' : UNSEEN;
742
+ placeStandIn();
743
+ };
744
+ if (standIn && words) {
745
+ standIn.className = ENTER_CLASS;
746
+ standIn.setAttribute('role', 'button');
747
+ standIn.setAttribute('tabindex', '0');
748
+ standIn.style.cssText = UNSEEN;
749
+ words.className = PICK_LABEL_CLASS;
750
+ say(enterLabel);
751
+ standIn.append(words);
752
+ // The user pressed the stop: the frame is let into the tab order for
753
+ // their next Tab, which goes from the stop, right before the frame, into
754
+ // the tile as a Tab into any frame in the tab order does, and which the
755
+ // page sees. The stop says so. Not `focus()`, which puts the keyboard
756
+ // in from the page: in answer to a key, that takes in Chrome but not in
757
+ // Firefox nor in WebKit, which leave the keyboard where it was, and in
758
+ // Chrome it leaves the keyboard in a page of the dock's with nothing on
759
+ // screen to say so. This way is the same in all three: Enter, then Tab.
760
+ // It is over once the keyboard has left the stop (into the tile or
761
+ // anywhere else), or after `LET_IN_MS`.
762
+ // (Not into a tile that waits to be picked: engage's layer is the way in to it.)
763
+ const enter = () => {
764
+ if (options.engaged && !options.engaged()) return;
765
+ // The user is going in themselves, as by the host's way in (see `focus`).
766
+ lift();
767
+ liftedAt = -Infinity;
768
+ shut();
769
+ // (A press aimed at the stop can come with the keyboard elsewhere, as
770
+ // a screen reader's can: the frame is let in only while the keyboard
771
+ // is on the stop, and the Tab that takes the user in goes from there.)
772
+ if (!onStop()) standIn.focus({ preventScroll: true });
773
+ letOut = letIn(frame);
774
+ letUntil = win.setTimeout(shut, LET_IN_MS);
775
+ say(tabLabel);
776
+ };
777
+ // (A press the browser makes on the stop itself, as it does for a
778
+ // screen reader's, reaches it all the same: it is aimed at the element,
779
+ // not at where it lies. It puts the keyboard on the stop, see `enter`.)
780
+ standIn.addEventListener('click', (ev) => { if (ev.isTrusted) enter(); });
781
+ standIn.addEventListener('keydown', (ev) => {
782
+ if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
783
+ ev.preventDefault();
784
+ enter();
785
+ });
786
+ standIn.addEventListener('focus', () => show(true));
787
+ standIn.addEventListener('blur', () => {
788
+ show(false);
789
+ // (A task later: the Tab that takes the keyboard into the frame is still on its way.)
790
+ win.setTimeout(() => { if (!onStop()) shut(); }, 0);
791
+ });
792
+ }
793
+ // Right before the frame once it is in a document (a host may guard it
794
+ // before it puts it there), and again where the page has moved the frame
795
+ // or taken the stop away, or put something between them; in the tab order
796
+ // or out of it, as said above.
797
+ // Not where the page has taken the frame out of its document: there is no
798
+ // way into a tile that is not there, and a stop left behind would be one
799
+ // the user tabs to and that does nothing. It goes with the frame, and
800
+ // comes back with it.
801
+ const standBy = () => {
802
+ if (!standIn || stopped) return;
803
+ if (!frame.isConnected || !frame.parentNode) return standIn.remove();
804
+ if (standIn.nextSibling !== frame) {
805
+ // (In the shadow tree the frame is in, if it is in one: so is its look.)
806
+ const root = frame.getRootNode();
807
+ pickLook(doc, root instanceof (win as Window & typeof globalThis).ShadowRoot ? root : doc);
808
+ frame.before(standIn);
809
+ }
810
+ // Seen only while it has the keyboard. A stop the page took away, or
811
+ // moved, with the keyboard on it has lost it, and some browsers (Firefox)
812
+ // say no blur then: put back, it would lie over the tile, with its words,
813
+ // taking the presses meant for the tile.
814
+ if (shown && (standIn.getRootNode() as Document | ShadowRoot).activeElement !== standIn) show(false);
815
+ const tabindex = !layer && (!options.engaged || options.engaged()) ? '0' : '-1';
816
+ if (standIn.getAttribute('tabindex') !== tabindex) standIn.setAttribute('tabindex', tabindex);
817
+ placeStandIn();
818
+ };
819
+ // `refused`: the dock has just said that the keyboard came into the tile
820
+ // with no one acting there, which is its no without being asked, and
821
+ // `unsure`, that it may be the user's doing all the same.
822
+ const check = (refused = false, unsure = false) => {
823
+ place();
824
+ standBy();
825
+ // (Also where the stop was taken away with the keyboard on it, which
826
+ // some browsers say no blur for; and where something took the frame out
827
+ // of the tab order again, engage's layer back over the tile say, which
828
+ // ends the moment: the stop is not to say that Tab goes in then.)
829
+ if (letOut && (!onStop() || frame.tabIndex < 0)) shut();
830
+ settle();
831
+ watch();
288
832
  if (stopped || winFocused || !doc.hasFocus()) return;
289
833
  if (holds(frame)) inTile = true;
290
834
  // The keyboard is in another frame of the page's. It left the tile, and
291
835
  // what was decided when it came no longer stands: should it come back,
292
836
  // that is judged afresh. (The window hears nothing of focus going from
293
837
  // one frame to another.)
294
- else inTile = accepted = false;
295
- if (!inTile || accepted) return;
838
+ // Nor does what had the keyboard on the page have it still, unless the
839
+ // page put it in that frame itself: the page hears no focusin when the
840
+ // user presses or tabs into another frame, only that the keyboard left.
841
+ else {
842
+ inTile = accepted = tabbed = straight = returning = false;
843
+ if (focused(doc) !== holder) holder = null;
844
+ spend();
845
+ }
846
+ if (!inTile) return;
847
+ if (accepted) {
848
+ // It came in again since, where the page did not see it go: what the
849
+ // page saw of the user going in stands, and nothing else does.
850
+ if (!refused || tabbed) return;
851
+ accepted = inTile = false;
852
+ return giveBack('dock', unsure);
853
+ }
296
854
  const how = judge();
297
- if (!how) {
855
+ if (!how || (refused && how === 'ask')) {
298
856
  inTile = false;
299
- return giveBack('script');
857
+ return how ? giveBack('dock', unsure) : giveBack('script');
300
858
  }
301
859
  accepted = true;
860
+ tabbed = how === 'tab';
302
861
  round++; // nothing still on its way from an earlier giving back takes this one away
303
- if (how === 'tab') return;
304
- // A second opinion, which takes a moment: the dock's.
305
- dock.ask().then((acted) => {
306
- if (acted === true || !accepted || winFocused || stopped) return;
862
+ // The user went in themselves, and the dock is told: no earlier no of its
863
+ // stands against them. (And, where they went in with a press, it puts
864
+ // the keyboard on into the tile.)
865
+ if (tabbed) {
866
+ dock.entered(into);
867
+ into = false;
868
+ // The Tab from the stop has taken the user in, and is spent: it
869
+ // explains nothing that comes into the tile after this, should the
870
+ // keyboard go elsewhere first.
871
+ if (spent) lastTab = -Infinity;
872
+ spent = false;
873
+ return;
874
+ }
875
+ // A second opinion, which takes a moment: the dock's. Where it watched
876
+ // the keyboard come in, it also says whether the user had acted in the
877
+ // tile then, which what they typed into the tile since does not change.
878
+ dock.ask().then((said) => {
879
+ if ((said?.activated === true && said.arrivalActivated !== false) || !accepted || winFocused || stopped) return;
307
880
  // No answer, from a dock that never gave one: nothing more to go by.
308
- if (acted === undefined && !dock.answers) return;
881
+ if (said === undefined && !dock.answers) return;
309
882
  accepted = false;
310
883
  inTile = false;
311
- giveBack('dock');
884
+ giveBack('dock', said?.unsure === true);
312
885
  });
313
886
  };
887
+ // The dock's no, unasked: judged as the guard's own look would, then and
888
+ // there, unless the keyboard is on its way back already.
889
+ const onRefused = (unsure: boolean) => { if (!returning) check(true, unsure); };
314
890
  const onWinBlur = () => {
315
891
  winFocused = false;
892
+ watch(true);
893
+ // Straight from the page, unless the page names another frame of its own
894
+ // as having the keyboard by now: then it went there, and what comes into
895
+ // the tile next comes from that frame, however soon (see `judge`).
896
+ straight = holds(frame) || !framed(focused(doc));
897
+ // Where the keyboard went is known by now. Into another frame of the
898
+ // page's: what had it on the page has it no longer (see `check`), and
899
+ // that is settled at once, not a task later. A tile that took the
900
+ // keyboard from that frame in between would have it put back on what
901
+ // the user had left.
902
+ if (!holds(frame) && !onNothing() && focused(doc) !== holder) holder = null;
316
903
  // The keyboard has gone again, and that is for `check` to judge and to
317
904
  // count. A giving back still making sure of an earlier time is over: it
318
905
  // would take this one back as well, before it had been counted.
@@ -321,30 +908,81 @@ export function guardFocus (tile: Tile, frame: HTMLIFrameElement, options: Focus
321
908
  };
322
909
  const onWinFocus = () => {
323
910
  winFocused = true;
911
+ watch();
324
912
  inTile = false;
325
- accepted = false;
913
+ accepted = tabbed = returning = false;
914
+ // (Nor does the Tab from the stop explain anything after it: see `spend`.)
915
+ spend();
916
+ // Back in the page, and maybe on nothing of it (a press on its plain
917
+ // text): then nothing has the keyboard to be given it back.
918
+ win.setTimeout(forget, 0);
326
919
  };
920
+ // Out of the tab order for as long as the guard runs, unless the host
921
+ // keeps it as it made it (see `tabOrder`). Whoever tabs down the page then
922
+ // never ends up in the tile by chance, and a Tab says nothing of the
923
+ // keyboard arriving in it (see `onKey`).
924
+ const back = tabOrder === 'keep' ? undefined : holdOut(frame);
327
925
  win.addEventListener('blur', onWinBlur);
328
926
  win.addEventListener('focus', onWinFocus);
329
927
  doc.addEventListener('focusin', onFocusIn, true);
928
+ doc.addEventListener('focusout', onFocusOut, true);
330
929
  doc.addEventListener('keydown', onKey, true);
930
+ // A guard made with the keyboard in another frame of the page's watches from the start.
931
+ watch();
932
+ // (A task later: what `engaged` reads may be made just after the guard.)
933
+ win.setTimeout(standBy, 0);
331
934
  // (The page's own timers throughout: they go with the page.)
332
935
  const poll = win.setInterval(check, cfg.pollMs);
333
936
  const stop = () => {
334
937
  if (stopped) return;
335
938
  stopped = true;
939
+ lift();
940
+ shut();
941
+ back?.();
942
+ standIn?.remove();
943
+ watch();
336
944
  win.clearInterval(poll);
337
945
  dock.stop();
338
946
  win.removeEventListener('blur', onWinBlur);
339
947
  win.removeEventListener('focus', onWinFocus);
340
948
  doc.removeEventListener('focusin', onFocusIn, true);
949
+ doc.removeEventListener('focusout', onFocusOut, true);
341
950
  doc.removeEventListener('keydown', onKey, true);
342
951
  tile.removeEventListener('close', stop);
343
952
  tile.removeEventListener('load', probe);
344
953
  };
345
954
  // A tile that is closed has no frame left to guard.
346
955
  tile.addEventListener('close', stop);
347
- return { stop };
956
+ // The host's own way in: what arrives in the tile that way is judged as a
957
+ // Tab into it is, and a Tab is as long ago once it has gone elsewhere.
958
+ // It goes in through the frame's window, not the element: a frame the
959
+ // page's script focused stays the page's active element in Chrome after
960
+ // the user has gone on into another frame, and the guard would not see the
961
+ // keyboard leave the tile, nor the tile take it back.
962
+ // It is the user picking the tile, too, where it waits for them to.
963
+ // That puts the keyboard in the dock's own page, where what is typed
964
+ // reaches nothing; the dock puts it on into the tile when told, for a user
965
+ // who went in with a press (a click or a tap, which this is called from).
966
+ // One who went in from the keyboard is left there: their Tab from there
967
+ // goes to the first thing in the tile, which it would not from inside it.
968
+ const focus = () => {
969
+ lift();
970
+ // The user went in themselves: a guess of the dock's after this is spared
971
+ // again, however soon after a layer lifted on its own (see `spareMs`).
972
+ liftedAt = -Infinity;
973
+ lastTab = now();
974
+ into = pressing();
975
+ frame.contentWindow?.focus();
976
+ };
977
+ // Whether what the page is handling now is a press of the user's, and not
978
+ // a key (a click the keyboard made has no `detail`).
979
+ const pressing = (): boolean => {
980
+ const ev = (win as Window & { event?: Event }).event;
981
+ if (!ev?.isTrusted) return false;
982
+ if (/click$/.test(ev.type)) return (ev as MouseEvent).detail > 0;
983
+ return /^(pointer|mouse|touch)/.test(ev.type);
984
+ };
985
+ return { stop, focus };
348
986
  }
349
987
 
350
988
  // ---------------------------------------------------------------- the click gate
@@ -936,8 +1574,10 @@ export const ENGAGE_CLASS = 'tile-engage';
936
1574
  * page, the tile leaving the viewport, or Escape, puts the layer back.
937
1575
  *
938
1576
  * Until it is picked the tile is not a stop on the way through the page with
939
- * Tab either (its frame has `tabindex="-1"` meanwhile): the layer is, right
940
- * after it, and Enter or Space there picks the tile and goes into it.
1577
+ * Tab either (its frame has `tabindex="-1"` meanwhile): the layer is, after
1578
+ * it in its box, and Enter or Space there picks the tile and goes into it.
1579
+ * (With the focus guard on as well, the frame stays out of the tab order
1580
+ * once the tile is picked, and the guard's stop is the way back in.)
941
1581
  *
942
1582
  * The layer paints, though too faintly to see: a block that paints nothing
943
1583
  * does not take a press over a frame. `stop()` takes it away for good.
@@ -959,12 +1599,16 @@ export function engage (tile: Tile, frame: HTMLIFrameElement, options: EngageOpt
959
1599
  let stopped = false;
960
1600
  // A tile that is not picked is not to be tabbed into: Tab would take the
961
1601
  // keyboard past the layer and into it. (With a guard on the keyboard that
962
- // would be given back, every time, and count against the tile.)
963
- const tabindex = frame.getAttribute('tabindex');
1602
+ // would be given back, every time, and count against the tile.) Held out
1603
+ // with whatever else holds it, the focus guard's layer among them (see
1604
+ // `holdOut`): picked, the frame is back in only once nothing else holds it.
1605
+ let back: (() => void) | undefined;
964
1606
  const reach = (on: boolean) => {
965
- if (!on) frame.setAttribute('tabindex', '-1');
966
- else if (tabindex === null) frame.removeAttribute('tabindex');
967
- else frame.setAttribute('tabindex', tabindex);
1607
+ if (!on) back ??= holdOut(frame);
1608
+ else {
1609
+ back?.();
1610
+ back = undefined;
1611
+ }
968
1612
  };
969
1613
  const set = (on: boolean, why: Parameters<NonNullable<EngageOptions['onChange']>>[1]) => {
970
1614
  if (on === engaged || stopped) return;
@@ -979,7 +1623,9 @@ export function engage (tile: Tile, frame: HTMLIFrameElement, options: EngageOpt
979
1623
  if (!ev.isTrusted || (ev.key !== 'Enter' && ev.key !== ' ')) return;
980
1624
  ev.preventDefault();
981
1625
  set(true, 'picked');
982
- frame.focus();
1626
+ // Through the frame's window, as the focus guard's own way in goes (see
1627
+ // `guardFocus`), and for its reason.
1628
+ frame.contentWindow?.focus();
983
1629
  });
984
1630
  const onDown = (ev: Event) => { if (ev.isTrusted && engaged && !wrapper.contains((ev.composedPath?.()[0] ?? ev.target) as Node)) set(false, 'pressed elsewhere'); };
985
1631
  const onKey = (ev: KeyboardEvent) => { if (ev.isTrusted && engaged && ev.key === 'Escape') set(false, 'escape'); };