@dasl/tile-loader 3.1.0 → 4.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.
Files changed (92) hide show
  1. package/README.md +1463 -36
  2. package/dist/at.d.ts +126 -12
  3. package/dist/at.d.ts.map +1 -1
  4. package/dist/at.js +582 -90
  5. package/dist/at.js.map +1 -1
  6. package/dist/car.d.ts +21 -2
  7. package/dist/car.d.ts.map +1 -1
  8. package/dist/car.js +82 -15
  9. package/dist/car.js.map +1 -1
  10. package/dist/content-scheme.d.ts +17 -3
  11. package/dist/content-scheme.d.ts.map +1 -1
  12. package/dist/content-scheme.js +32 -6
  13. package/dist/content-scheme.js.map +1 -1
  14. package/dist/guard.d.ts +342 -0
  15. package/dist/guard.d.ts.map +1 -0
  16. package/dist/guard.js +1544 -0
  17. package/dist/guard.js.map +1 -0
  18. package/dist/index.d.ts +416 -16
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +999 -74
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/cid.d.ts +25 -0
  23. package/dist/lib/cid.d.ts.map +1 -0
  24. package/dist/lib/cid.js +65 -0
  25. package/dist/lib/cid.js.map +1 -0
  26. package/dist/lib/defaults.d.ts +8 -0
  27. package/dist/lib/defaults.d.ts.map +1 -0
  28. package/dist/lib/defaults.js +14 -0
  29. package/dist/lib/defaults.js.map +1 -0
  30. package/dist/lib/destinations.d.ts +25 -0
  31. package/dist/lib/destinations.d.ts.map +1 -0
  32. package/dist/lib/destinations.js +94 -0
  33. package/dist/lib/destinations.js.map +1 -0
  34. package/dist/lib/drisl.d.ts +10 -0
  35. package/dist/lib/drisl.d.ts.map +1 -0
  36. package/dist/lib/drisl.js +169 -0
  37. package/dist/lib/drisl.js.map +1 -0
  38. package/dist/lib/errors.d.ts +80 -0
  39. package/dist/lib/errors.d.ts.map +1 -0
  40. package/dist/lib/errors.js +44 -0
  41. package/dist/lib/errors.js.map +1 -0
  42. package/dist/lib/fetching.d.ts +24 -0
  43. package/dist/lib/fetching.d.ts.map +1 -0
  44. package/dist/lib/fetching.js +135 -0
  45. package/dist/lib/fetching.js.map +1 -0
  46. package/dist/lib/limits.d.ts +34 -0
  47. package/dist/lib/limits.d.ts.map +1 -0
  48. package/dist/lib/limits.js +33 -0
  49. package/dist/lib/limits.js.map +1 -0
  50. package/dist/lib/pointer.d.ts +83 -0
  51. package/dist/lib/pointer.d.ts.map +1 -0
  52. package/dist/lib/pointer.js +244 -0
  53. package/dist/lib/pointer.js.map +1 -0
  54. package/dist/lib/tab-order.d.ts +16 -0
  55. package/dist/lib/tab-order.d.ts.map +1 -0
  56. package/dist/lib/tab-order.js +66 -0
  57. package/dist/lib/tab-order.js.map +1 -0
  58. package/dist/link.d.ts +110 -13
  59. package/dist/link.d.ts.map +1 -1
  60. package/dist/link.js +336 -43
  61. package/dist/link.js.map +1 -1
  62. package/dist/memory.d.ts +1 -0
  63. package/dist/memory.d.ts.map +1 -1
  64. package/dist/memory.js +5 -0
  65. package/dist/memory.js.map +1 -1
  66. package/dist/mount.d.ts +54 -0
  67. package/dist/mount.d.ts.map +1 -0
  68. package/dist/mount.js +289 -0
  69. package/dist/mount.js.map +1 -0
  70. package/dist/size.d.ts +43 -2
  71. package/dist/size.d.ts.map +1 -1
  72. package/dist/size.js +296 -15
  73. package/dist/size.js.map +1 -1
  74. package/package.json +13 -3
  75. package/src/at.ts +590 -84
  76. package/src/car.ts +79 -16
  77. package/src/content-scheme.ts +38 -7
  78. package/src/guard.ts +1659 -0
  79. package/src/index.ts +1124 -74
  80. package/src/lib/cid.ts +65 -0
  81. package/src/lib/defaults.ts +12 -0
  82. package/src/lib/destinations.ts +79 -0
  83. package/src/lib/drisl.ts +160 -0
  84. package/src/lib/errors.ts +111 -0
  85. package/src/lib/fetching.ts +138 -0
  86. package/src/lib/limits.ts +61 -0
  87. package/src/lib/pointer.ts +290 -0
  88. package/src/lib/tab-order.ts +66 -0
  89. package/src/link.ts +365 -48
  90. package/src/memory.ts +5 -0
  91. package/src/mount.ts +359 -0
  92. package/src/size.ts +304 -16
package/src/link.ts CHANGED
@@ -17,8 +17,14 @@
17
17
  // link of the host's own making with the destination in plain sight, and a
18
18
  // host with a handler of its own should do no less. Whatever the host does,
19
19
  // it does somewhere of its own: the tile's frame is never navigated.
20
+ //
21
+ // The tile also chooses the moment it asks, and where on the page its user
22
+ // is pressing at that moment. A prompt that comes up under a press that was
23
+ // already on its way has not asked anybody anything: see `linkPrompt` for
24
+ // what it does about that, which a host's own prompt should do as well.
20
25
 
21
- import type { ProtocolEvent, Tile } from './index.js';
26
+ import type { DockStamp, ProtocolEvent, Tile } from './index.js';
27
+ import { shield } from './lib/pointer.js';
22
28
 
23
29
  /** The tiles protocol this module speaks. */
24
30
  export const LINK_PROTOCOL = 'link';
@@ -28,17 +34,41 @@ const MAX_URL_LENGTH = 8192;
28
34
 
29
35
  export interface LinkRequest {
30
36
  /**
31
- * Whether the user has just interacted with the page (a click in the tile
32
- * counts for the page framing it). False means the tile is asking by
33
- * itself; a host has every reason to refuse then.
37
+ * Whether the user has just pressed or typed inside this tile: its dock,
38
+ * which the tile cannot script, says so with the request. False means the
39
+ * tile is asking by itself, or while the user is busy elsewhere on the
40
+ * page; a host has every reason to refuse then.
41
+ *
42
+ * A loading server from before its dock said this leaves the older, wider
43
+ * meaning: the user has just interacted with the page, anywhere on it.
34
44
  */
35
45
  activated: boolean;
46
+ /**
47
+ * The dock's word by itself: whether the user has just pressed or typed
48
+ * inside this tile. Left out where the dock said nothing. `activated` is
49
+ * this and `pageActivated` together; a host with a rule of its own reads
50
+ * them here. Read it to refuse, never by itself to grant: a loading server
51
+ * from before its dock said this passes on, under the dock's name,
52
+ * whatever the tile put there.
53
+ */
54
+ dockActivated?: boolean;
55
+ /**
56
+ * The page's word by itself: whether the user has just pressed or typed
57
+ * anywhere on the page (`navigator.userActivation.isActive`). Left out
58
+ * where the browser does not say, as some WebViews do not.
59
+ */
60
+ pageActivated?: boolean;
36
61
  /**
37
62
  * Set when the tile asked from script and waits for an answer. A handler
38
63
  * that returns nothing answers later itself, with
39
64
  * `tile.sendProtocol('link', 'result', { id, opened })`.
40
65
  */
41
66
  id?: string;
67
+ /**
68
+ * The tile's frame, when the host named it to `tileLinks`: where the tile
69
+ * may have had its user pressing, which a prompt keeps clear of.
70
+ */
71
+ frame?: HTMLElement;
42
72
  }
43
73
 
44
74
  /**
@@ -52,6 +82,17 @@ export interface TileLinksOptions {
52
82
  open?: LinkHandler;
53
83
  /** The URL schemes that reach `open`; any other is refused. Default: `http:` and `https:`. */
54
84
  schemes?: string[];
85
+ /** The frame the tile runs in. It is handed to `open` with each request, for a prompt to keep clear of. */
86
+ frame?: HTMLElement;
87
+ /** The longest address, in characters, that reaches `open`, as the tile sent it and as `open` is handed it; a longer one is refused. Default: 8192. */
88
+ maxLength?: number;
89
+ /**
90
+ * Whether a request that arrives while `open` is still deciding about
91
+ * another (it returned a promise that has not settled) is refused, as it
92
+ * is by default, or handed to `open` as well (`false`), for a host that
93
+ * queues them or decides about several at once.
94
+ */
95
+ oneAtATime?: boolean;
55
96
  }
56
97
 
57
98
  export interface TileLinksControl {
@@ -59,11 +100,31 @@ export interface TileLinksControl {
59
100
  stop (): void;
60
101
  }
61
102
 
103
+ // Whether the user has just acted inside the tile. The page's own activation
104
+ // says they did something on the page, in any frame of it, in the last few
105
+ // seconds; the tile's dock says whether that was inside this tile. Both have
106
+ // to hold. The dock's word can only take away from the page's, so where a
107
+ // dock does not say (and what arrives under its name is not its own), the
108
+ // answer is what it always was, and never more.
109
+ function userActed (dock?: DockStamp): boolean {
110
+ const onPage = pageActivation() ?? false;
111
+ return onPage && (dock ? dock.activated : true);
112
+ }
113
+
114
+ // The page's own activation, where the browser says.
115
+ function pageActivation (): boolean | undefined {
116
+ const isActive = globalThis.navigator?.userActivation?.isActive;
117
+ return typeof isActive === 'boolean' ? isActive : undefined;
118
+ }
119
+
62
120
  /** Hears a rendered tile's requests to open links, and answers them. */
63
121
  export function tileLinks (tile: Tile, options: TileLinksOptions = {}): TileLinksControl {
64
122
  const schemes = options.schemes ?? ['http:', 'https:'];
65
- // One at a time: while the host (or its user) makes up its mind about a
66
- // link, the tile does not get to queue up others.
123
+ const maxLength = options.maxLength ?? MAX_URL_LENGTH;
124
+ // One at a time, unless the host says otherwise: while the host (or its
125
+ // user) makes up its mind about a link, the tile does not get to queue up
126
+ // others.
127
+ const oneAtATime = options.oneAtATime ?? true;
67
128
  let deciding = false;
68
129
 
69
130
  const answer = (id: unknown, opened: boolean) => {
@@ -73,21 +134,29 @@ export function tileLinks (tile: Tile, options: TileLinksOptions = {}): TileLink
73
134
  };
74
135
 
75
136
  const onProtocol = async (ev: Event) => {
76
- const { protocol, kind, payload } = ev as ProtocolEvent;
137
+ const { protocol, kind, payload, dock } = ev as ProtocolEvent;
77
138
  if (protocol !== LINK_PROTOCOL || kind !== 'open') return;
78
139
  const { id, url: asked } = (payload && typeof payload === 'object' ? payload : {}) as { id?: unknown; url?: unknown };
79
140
  let url: URL | undefined;
80
- if (typeof asked === 'string' && asked.length <= MAX_URL_LENGTH) {
141
+ if (typeof asked === 'string' && asked.length <= maxLength) {
81
142
  try { url = new URL(asked); }
82
143
  catch { /* not a URL */ }
83
144
  }
84
- if (!url || !schemes.includes(url.protocol) || !options.open || deciding) return answer(id, false);
145
+ // What is handed on can be longer than what was sent: an address is
146
+ // written out with escapes for what is not plain ASCII. The limit holds
147
+ // for both.
148
+ if (url && url.href.length > maxLength) url = undefined;
149
+ if (!url || !schemes.includes(url.protocol) || !options.open || (oneAtATime && deciding)) return answer(id, false);
85
150
  deciding = true;
151
+ const onPage = pageActivation();
86
152
  let opened: boolean | void;
87
153
  try {
88
154
  opened = await options.open(url, {
89
- activated: globalThis.navigator?.userActivation?.isActive ?? false,
155
+ activated: userActed(dock),
156
+ ...(typeof dock?.activated === 'boolean' ? { dockActivated: dock.activated } : {}),
157
+ ...(onPage === undefined ? {} : { pageActivated: onPage }),
90
158
  ...(typeof id === 'string' && id ? { id } : {}),
159
+ ...(options.frame ? { frame: options.frame } : {}),
91
160
  });
92
161
  }
93
162
  catch (err) {
@@ -119,61 +188,309 @@ export function openInNewTab (url: URL): boolean {
119
188
  }
120
189
 
121
190
  export interface LinkPromptOptions {
122
- /** The words before the destination. Default: "This tile wants to open". */
191
+ /** The words before the destination. Default: "This tile wants to open a page on". */
123
192
  label?: string;
124
193
  /** The word on the button that refuses. Default: "Dismiss". */
125
194
  dismiss?: string;
195
+ /** The word before the destination on the button that opens. Default: "Open". */
196
+ open?: string;
197
+ /** What is said of an address that is not what it may look like. Each has a default, in English. */
198
+ notes?: {
199
+ /** The link is plain http. */
200
+ insecure?: string;
201
+ /** The address has a user name in it, which can be made to read like a host. */
202
+ userinfo?: string;
203
+ /** The host's name is in its encoded form (`xn--`), so in letters other than the ones shown. */
204
+ encoded?: string;
205
+ };
206
+ /**
207
+ * The registrable domain of a host name (`example.co.uk` for
208
+ * `a.b.example.co.uk`), from a public suffix list of the host's own. With
209
+ * it the prompt sets the site apart from its subdomains; without it the
210
+ * whole name is given the same weight.
211
+ */
212
+ registrableDomain?: (host: string) => string | undefined;
213
+ /** How long the button that opens does nothing: after the prompt appears, and after any press or key that came too soon. Milliseconds; `LINK_PROMPT.armMs` by default. */
214
+ armMs?: number;
215
+ /** How far the pointer has to really move before that button works. Pixels; `LINK_PROMPT.travel` by default. */
216
+ travel?: number;
217
+ /** How long no prompt is shown after the user has dismissed one. Milliseconds; `LINK_PROMPT.restMs` by default. */
218
+ restMs?: number;
219
+ /** How much of a long address is shown after its host. Characters; `LINK_PROMPT.maxShown` by default. */
220
+ maxShown?: number;
221
+ }
222
+
223
+ /** The numbers `linkPrompt` goes by where a host gives none. First guesses. */
224
+ export const LINK_PROMPT: Readonly<{ armMs: number; travel: number; restMs: number; maxShown: number }> = Object.freeze({
225
+ armMs: 800,
226
+ travel: 30,
227
+ restMs: 2000,
228
+ maxShown: 600,
229
+ });
230
+
231
+ const NOTES = {
232
+ insecure: 'The connection is not encrypted (http).',
233
+ userinfo: 'The address has a user name in it, struck through below. That is not where the link goes.',
234
+ encoded: 'This name is written in letters other than these: it is shown in its encoded form.',
235
+ };
236
+
237
+ // The parts of an address, for showing a user where a link leads. The host is
238
+ // what matters. A user name in the address is never part of where it goes,
239
+ // however much it is made to look like it.
240
+ function parts (url: URL, registrableDomain?: (host: string) => string | undefined) {
241
+ const host = url.hostname;
242
+ let site = host;
243
+ try { site = registrableDomain?.(host) || host; }
244
+ catch { /* the host's own business */ }
245
+ return {
246
+ host,
247
+ site,
248
+ sub: site !== host && host.endsWith(`.${site}`) ? host.slice(0, -site.length) : '',
249
+ port: url.port,
250
+ scheme: url.protocol,
251
+ insecure: url.protocol === 'http:',
252
+ userinfo: url.username || url.password ? `${url.username}${url.password ? ':…' : ''}` : '',
253
+ encoded: host.split('.').some(label => label.startsWith('xn--')),
254
+ rest: `${url.pathname}${url.search}${url.hash}`,
255
+ };
126
256
  }
127
257
 
258
+ // The prompt showing in a document, if one is. There is only ever one.
259
+ const showing = new WeakMap<Document, { live (): boolean; finish (opened: boolean): void }>();
260
+ // Until when a document shows no prompt, its user having just dismissed one.
261
+ const resting = new WeakMap<Document, number>();
262
+
128
263
  /**
129
- * A link handler that leaves it to the user: it shows, in `container`, where
130
- * the tile wants to go, as a link of the host's own that the user can follow,
131
- * with a button to dismiss it. The whole address is shown, since the address
132
- * is where a tile would hide what it wants to send out. Nothing opens unless
133
- * the user follows the link, and it opens in a new tab, never in the tile.
264
+ * A link handler that leaves it to the user: a dialog of the host's own says
265
+ * where the tile wants to go and offers a link to follow, with a button to
266
+ * dismiss it. Nothing opens unless the user follows the link, and it opens
267
+ * in a new tab, never in the tile.
134
268
  *
135
- * A request that arrives when the user has not touched the page is refused
136
- * outright, and a new request replaces one still showing.
269
+ * - It says where. The host's name stands alone on a line, large; a user
270
+ * name in the address, plain http and an encoded name are called out; and
271
+ * the whole address is there to read, since the address is where a tile
272
+ * would put what it wants to send out.
273
+ * - One at a time, for the whole page: while one is showing, a request from
274
+ * any tile is refused. Nothing replaces what the user is reading, and for
275
+ * `restMs` after they have dismissed one nothing comes up in its place: a
276
+ * prompt that is back at once, with its link where the button that
277
+ * dismisses was, is not one anybody has read. A request that arrives when
278
+ * the user has not acted in the tile is refused outright.
279
+ * - It is a modal dialog, on top of the page: nothing a tile does to its
280
+ * size or to the page's scroll moves it.
281
+ * - The link does nothing for `armMs` after the dialog appears, and any press
282
+ * or key in that time starts the wait again: a press that was already on
283
+ * its way when the dialog came up opens nothing, nor does the third of a
284
+ * run of them. A press is judged by when it was made, not by when a page
285
+ * that was busy got to hear of it. Focus starts on the button that
286
+ * dismisses, which always works, as does Escape. A press beside the dialog
287
+ * does nothing.
288
+ * - The link also waits until the pointer has really moved (`travel`
289
+ * pixels), or the keyboard has been taken to it (Tab, a screen reader):
290
+ * a pointer that rests where the link came up opens nothing, however
291
+ * long the tile has its user wait.
292
+ * - It keeps clear of the tile that asked, when `tileLinks` was told its
293
+ * frame: the dialog goes above or below the frame, where there is room.
294
+ * That is not somewhere the pointer cannot be: a tile can move itself, and
295
+ * the page, between the press and the prompt.
296
+ * - Where it was takes no press for a moment once a press has dismissed it:
297
+ * the second click of a double click does not go through to the page.
137
298
  *
138
- * The prompt is plain elements with a few class names (`tile-link-prompt`,
139
- * `tile-link-url`, `tile-link-dismiss`) for a host to style.
299
+ * The dialog element is put in `container` (so it is styled with that part
300
+ * of the page, and goes with it), wherever in the page that is. It is plain
301
+ * elements with a few class names for a host to style: `tile-link-dialog`,
302
+ * `tile-link-host`, `tile-link-note`, `tile-link-url`, `tile-link-open`,
303
+ * `tile-link-dismiss`.
140
304
  */
141
305
  export function linkPrompt (container: HTMLElement, options: LinkPromptOptions = {}): LinkHandler {
142
- let settle: ((opened: boolean) => void) | undefined;
143
- return (url, { activated }) => {
144
- if (!activated) return false;
145
- settle?.(false);
306
+ const armMs = options.armMs ?? LINK_PROMPT.armMs;
307
+ const travel = options.travel ?? LINK_PROMPT.travel;
308
+ const restMs = options.restMs ?? LINK_PROMPT.restMs;
309
+ const maxShown = options.maxShown ?? LINK_PROMPT.maxShown;
310
+ const notes = { ...NOTES, ...options.notes };
311
+ const now = () => performance.now();
312
+ // When a press or a key was made. A page that was busy hears of it later,
313
+ // and what it hears of late was no less early. (Where a browser does not
314
+ // say when on the page's own clock, it is when the page heard of it.)
315
+ const madeAt = (e: Event) => {
316
+ const t = now();
317
+ return e.timeStamp > 0 && e.timeStamp < t ? e.timeStamp : t;
318
+ };
319
+ return (url, request) => {
320
+ if (!request.activated) return false;
146
321
  const doc = container.ownerDocument;
147
- const box = doc.createElement('div');
148
- box.className = 'tile-link-prompt';
149
- box.setAttribute('role', 'group');
150
- box.style.cssText = 'display: flex; gap: 0.5em; align-items: baseline; padding: 0.5em 0.75em; font: inherit; overflow-wrap: anywhere;';
151
- const label = doc.createElement('span');
152
- label.textContent = options.label ?? 'This tile wants to open';
153
- const link = doc.createElement('a');
154
- link.className = 'tile-link-url';
322
+ const win = doc.defaultView as Window;
323
+ const before = showing.get(doc);
324
+ if (before?.live()) return false;
325
+ if (now() < (resting.get(doc) ?? 0)) return false;
326
+ before?.finish(false); // it went with its part of the page, unanswered
327
+ const make = <K extends keyof HTMLElementTagNameMap>(name: K, className: string, style: string, text?: string): HTMLElementTagNameMap[K] => {
328
+ const node = doc.createElement(name);
329
+ if (className) node.className = className;
330
+ if (style) node.style.cssText = style;
331
+ if (text !== undefined) node.textContent = text;
332
+ return node;
333
+ };
334
+ const d = parts(url, options.registrableDomain);
335
+ // What a host's own rules for the place it gave us might take away is said again: a prompt nobody can see or press still holds the page.
336
+ const dialog = make('dialog', 'tile-link-dialog', 'position: fixed; box-sizing: border-box; max-width: min(32rem, 92vw); padding: 1.25rem; border: 1px solid #888; border-radius: 10px; font: inherit; visibility: visible; pointer-events: auto;');
337
+ dialog.append(make('p', '', 'margin: 0 0 0.25rem;', options.label ?? 'This tile wants to open a page on'));
338
+ const cut = (text: string, most: number) => (text.length > most ? `${text.slice(0, most / 2)} … (${text.length - most} more characters) … ${text.slice(-most / 2)}` : text);
339
+ const where = make('p', 'tile-link-host', 'margin: 0 0 0.75rem; font-size: 1.5em; font-weight: 700; overflow-wrap: anywhere; direction: ltr; unicode-bidi: isolate;');
340
+ if (d.sub) where.append(make('span', '', 'font-weight: 400; opacity: 0.65;', d.sub));
341
+ // An address with no host in it (a host may let `mailto:` through): what it names is all there is to show.
342
+ where.append(make('span', '', '', d.host ? d.site : cut(`${d.scheme}${url.pathname}`, 80)));
343
+ if (d.port) where.append(make('span', '', 'font-weight: 400; opacity: 0.65;', `:${d.port}`));
344
+ dialog.append(where);
345
+ for (const said of [d.insecure && notes.insecure, d.userinfo && notes.userinfo, d.encoded && notes.encoded]) {
346
+ if (said) dialog.append(make('p', 'tile-link-note', 'margin: 0 0 0.5rem; padding-left: 0.5rem; border-left: 3px solid #c00;', said));
347
+ }
348
+ // The whole address, with the host marked: this is where a tile would put what it wants to send out.
349
+ const address = make('p', 'tile-link-url', 'margin: 0 0 1rem; font: 12px/1.4 ui-monospace, monospace; overflow-wrap: anywhere; max-height: 7.5em; overflow: auto; opacity: 0.8; direction: ltr; unicode-bidi: isolate;');
350
+ if (d.host) {
351
+ address.append(make('span', '', '', `${d.scheme}//`));
352
+ if (d.userinfo) address.append(make('span', '', 'text-decoration: line-through;', `${d.userinfo}@`));
353
+ address.append(make('strong', '', '', url.host), make('span', '', '', cut(d.rest, maxShown)));
354
+ }
355
+ else address.append(make('span', '', '', cut(url.href, maxShown)));
356
+ dialog.append(address);
357
+ const row = make('div', '', 'display: flex; gap: 0.75rem; justify-content: flex-end; align-items: baseline;');
358
+ const dismiss = make('button', 'tile-link-dismiss', 'font: inherit; padding: 0.5rem 1rem;', options.dismiss ?? 'Dismiss');
359
+ dismiss.type = 'button';
360
+ const link = make('a', 'tile-link-open', 'font: inherit; padding: 0.5rem 1rem; border: 1px solid currentColor; border-radius: 6px; text-decoration: none;', `${options.open ?? 'Open'} ${d.host}`.trim());
155
361
  link.href = url.href;
156
362
  link.target = '_blank';
157
363
  link.rel = 'noopener noreferrer';
158
- link.textContent = url.href;
159
- link.style.cssText = 'flex: 1; min-width: 0;';
160
- const dismiss = doc.createElement('button');
161
- dismiss.type = 'button';
162
- dismiss.className = 'tile-link-dismiss';
163
- dismiss.textContent = options.dismiss ?? 'Dismiss';
164
- box.append(label, link, dismiss);
364
+ row.append(dismiss, link);
365
+ dialog.append(row);
366
+
165
367
  return new Promise<boolean>((resolve) => {
166
- const done = (opened: boolean) => {
167
- if (settle !== done) return;
168
- settle = undefined;
169
- box.remove();
368
+ let armAt = now() + armMs;
369
+ let timer: ReturnType<typeof setTimeout> | undefined;
370
+ let done = false;
371
+ let needsMove = false;
372
+ let moved = false;
373
+ let finger = false; // the last press on the dialog was a finger's
374
+ let from: { x: number; y: number } | undefined;
375
+ const armed = (at = now()) => at >= armAt && (!needsMove || moved || finger);
376
+ const show = () => {
377
+ const on = armed();
378
+ link.setAttribute('aria-disabled', on ? 'false' : 'true');
379
+ link.style.opacity = on ? '1' : '0.4';
380
+ };
381
+ const wait = () => {
382
+ clearTimeout(timer);
383
+ timer = setTimeout(show, Math.max(0, armAt - now()) + 5);
384
+ show();
385
+ };
386
+ const onMove = (ev: Event) => {
387
+ const e = ev as PointerEvent;
388
+ if (!e.isTrusted || moved || e.pointerType === 'touch') return;
389
+ if (!from) { from = { x: e.clientX, y: e.clientY }; return; }
390
+ if (Math.hypot(e.clientX - from.x, e.clientY - from.y) >= travel) { moved = true; show(); }
391
+ };
392
+ // Above or below the tile that asked, wherever there is room for the whole dialog.
393
+ const keepClear = () => {
394
+ // Wherever it goes, a pointer parked where the link comes up opens
395
+ // nothing, however long the tile has its user wait: the tile may
396
+ // have moved itself, or the page, since the press that asked, and
397
+ // "clear of the tile" is then where the pointer is. (A finger is not
398
+ // parked anywhere: for one, the wait is all there is.)
399
+ needsMove = win.matchMedia?.('(hover: hover)').matches ?? true;
400
+ const room = dialog.getBoundingClientRect().height + 16;
401
+ const f = request.frame?.getBoundingClientRect?.();
402
+ let top: number | undefined;
403
+ if (f) {
404
+ const vh = win.innerHeight;
405
+ const above = Math.max(0, Math.min(f.top, vh));
406
+ const below = vh - Math.max(0, Math.min(f.bottom, vh));
407
+ if (below >= room && (below >= above || above < room)) top = vh - below + 8;
408
+ else if (above >= room) top = above - room + 8;
409
+ }
410
+ if (top === undefined) return; // in the middle, which may be over the tile
411
+ dialog.style.top = `${top}px`;
412
+ dialog.style.bottom = 'auto';
413
+ dialog.style.marginTop = '0';
414
+ dialog.style.marginBottom = '0';
415
+ };
416
+ const early = (ev: Event) => {
417
+ const e = ev as KeyboardEvent;
418
+ if (!e.isTrusted) return;
419
+ if (e.type === 'pointerdown') finger = (ev as PointerEvent).pointerType === 'touch';
420
+ // Tabbing to the link is the user going to it, as moving the pointer there is.
421
+ if (e.type === 'keydown' && e.key === 'Tab') { moved = true; show(); }
422
+ if (armed(madeAt(e))) return;
423
+ // Refusing is always the user's to do.
424
+ if (dismiss.contains(e.target as Node) || (e.type === 'keydown' && e.key === 'Escape')) return;
425
+ // Too soon to be an answer to what the dialog says: it counts for nothing, and the wait starts over.
426
+ armAt = now() + armMs;
427
+ wait();
428
+ if (e.type !== 'keydown' || e.key !== 'Tab') { e.preventDefault(); e.stopPropagation(); }
429
+ };
430
+ const EARLY = ['pointerdown', 'mousedown', 'click', 'auxclick', 'keydown'];
431
+ // `press`: the press on the dialog that dismissed it, when it was one.
432
+ const finish = (opened: boolean, press?: Event) => {
433
+ if (done) return;
434
+ done = true;
435
+ if (showing.get(doc) === mine) showing.delete(doc);
436
+ clearTimeout(timer);
437
+ doc.removeEventListener('pointermove', onMove, true);
438
+ for (const type of EARLY) dialog.removeEventListener(type, early, true);
439
+ if (press) {
440
+ // The dialog goes at once, and the page is there again where it
441
+ // was: a second press on its way to the same spot would land on
442
+ // whatever the tile has put there meanwhile.
443
+ const r = dialog.getBoundingClientRect();
444
+ const where = { left: r.left, top: r.top, width: r.width, height: r.height };
445
+ shield(doc, () => where, { ms: armMs, dwellMs: armMs });
446
+ }
447
+ try { dialog.close(); }
448
+ catch { /* not open */ }
449
+ dialog.remove();
170
450
  resolve(opened);
171
451
  };
172
- settle = done;
173
- // The link is a real one: following it is the user's own navigation.
174
- link.addEventListener('click', () => setTimeout(() => done(true)));
175
- dismiss.addEventListener('click', () => done(false));
176
- container.append(box);
452
+ // The user said no: nothing asks again for a moment.
453
+ const refuse = (press?: Event) => {
454
+ if (done) return;
455
+ resting.set(doc, now() + restMs);
456
+ finish(false, press);
457
+ };
458
+ // (By the attribute: a browser that knows no dialog element shows ours as a plain box, which serves.)
459
+ const mine = { live: () => !done && dialog.isConnected && dialog.hasAttribute('open'), finish };
460
+ showing.set(doc, mine);
461
+ for (const type of EARLY) dialog.addEventListener(type, early, true);
462
+ const follow = (ev: Event) => {
463
+ const e = ev as MouseEvent;
464
+ if (e.type === 'auxclick' && e.button !== 1) return;
465
+ if (!e.isTrusted || !armed(madeAt(e))) return e.preventDefault();
466
+ // The link is a real one: following it is the user's own navigation.
467
+ setTimeout(() => finish(true));
468
+ };
469
+ link.addEventListener('click', follow);
470
+ link.addEventListener('auxclick', follow);
471
+ // The keyboard arriving on the link is the user going to it, however
472
+ // they got there: with Tab, or with a screen reader's own cursor,
473
+ // which presses no key the page sees. (A press on the link that came
474
+ // too soon does not bring the keyboard there: it is stopped above.)
475
+ link.addEventListener('focus', () => { moved = true; show(); });
476
+ // (A click the keyboard made has no press behind it: `detail` is 0.)
477
+ dismiss.addEventListener('click', (ev) => refuse(ev.isTrusted && ev.detail > 0 ? ev : undefined));
478
+ dialog.addEventListener('cancel', (ev) => { ev.preventDefault(); refuse(); });
479
+ dialog.addEventListener('close', () => finish(false));
480
+ container.append(dialog);
481
+ const modal = typeof dialog.showModal === 'function';
482
+ try {
483
+ if (modal) dialog.showModal();
484
+ else dialog.setAttribute('open', '');
485
+ }
486
+ catch { /* not in a document that can show it: refused below */ }
487
+ // A modal dialog holds the whole page. One that did not come to be
488
+ // shown (its container is not displayed, or not in the page) must not.
489
+ if (!dialog.hasAttribute('open') || (modal && !dialog.getClientRects().length)) return finish(false);
490
+ keepClear();
491
+ doc.addEventListener('pointermove', onMove, { capture: true, passive: true });
492
+ dismiss.focus({ preventScroll: true });
493
+ wait();
177
494
  });
178
495
  };
179
496
  }
package/src/memory.ts CHANGED
@@ -13,6 +13,11 @@ export class MemoryTileLoader {
13
13
  addTile (id: string, manifest: InMemoryMasl) {
14
14
  this.#tiles[id] = manifest;
15
15
  }
16
+ // Forgets a tile, by the id it was added under. A Tile that was loaded
17
+ // from it before keeps what it has.
18
+ removeTile (id: string) {
19
+ delete this.#tiles[id];
20
+ }
16
21
  async load (url: string, mothership: TileMothership): Promise<Tile | false> {
17
22
  let u: URL;
18
23
  try { u = new URL(url); }