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