@dasl/tile-loader 2.5.0 → 3.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/README.md +53 -8
- package/dist/at.d.ts +18 -0
- package/dist/at.d.ts.map +1 -1
- package/dist/at.js +86 -3
- package/dist/at.js.map +1 -1
- package/dist/content-scheme.d.ts +6 -0
- package/dist/content-scheme.d.ts.map +1 -1
- package/dist/content-scheme.js.map +1 -1
- package/dist/data.js +2 -2
- package/dist/data.js.map +1 -1
- package/dist/index.d.ts +23 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +67 -43
- package/dist/index.js.map +1 -1
- package/dist/link.d.ts +61 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +142 -0
- package/dist/link.js.map +1 -0
- package/dist/size.d.ts.map +1 -1
- package/dist/size.js +29 -10
- package/dist/size.js.map +1 -1
- package/package.json +7 -2
- package/src/at.ts +76 -3
- package/src/content-scheme.ts +6 -0
- package/src/data.ts +2 -2
- package/src/index.ts +81 -48
- package/src/link.ts +179 -0
- package/src/size.ts +27 -9
package/src/index.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝
|
|
9
9
|
•--~~~## MOTHERSHIP ##~~~--•
|
|
10
10
|
|
|
11
|
-
The tile-loading architecture has
|
|
11
|
+
The tile-loading architecture has four levels that all communicate together:
|
|
12
12
|
|
|
13
13
|
- At the top, the MOTHERSHIP. This has access to things in the real world like
|
|
14
14
|
fetching from the internet or reading from the file system. It's the interface
|
|
@@ -18,7 +18,14 @@ The tile-loading architecture has three levels that all communicate together:
|
|
|
18
18
|
the configurability so that the other components can be deployed in entirely
|
|
19
19
|
generic ways.
|
|
20
20
|
- The mothership instantiates tiles by creating insulated contexts (a sandboxed
|
|
21
|
-
iframe, an incognito window…) and loading
|
|
21
|
+
iframe, an incognito window…) and loading the DOCK in it: a page on the
|
|
22
|
+
loading server's own origin, which frames the shuttle on the tile's origin
|
|
23
|
+
and keeps it there. The tile can script its shuttle but not the dock, so
|
|
24
|
+
the dock is what holds the frame in place (it can be navigated nowhere),
|
|
25
|
+
keeps everything below it from opening windows, and passes messages only
|
|
26
|
+
between the mothership and that one shuttle. The mothership only ever
|
|
27
|
+
talks to the dock.
|
|
28
|
+
- In the dock, the SHUTTLE. The role of the
|
|
22
29
|
shuttle is to set up a service worker and an iframe to load the root of the
|
|
23
30
|
tile into. It only exists because you need something to carry a service worker
|
|
24
31
|
in. The only other thing that it does is (*drumroll*) shuttle messages back
|
|
@@ -29,12 +36,20 @@ The tile-loading architecture has three levels that all communicate together:
|
|
|
29
36
|
*/
|
|
30
37
|
|
|
31
38
|
import { el } from "./lib/el.js";
|
|
32
|
-
import { tileResponseHeaders } from "@dasl/tile-lexicon";
|
|
39
|
+
import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
|
|
33
40
|
import type { AnyMasl, MaslHeaders, MaslResponse } from "@dasl/tile-lexicon";
|
|
34
41
|
|
|
35
42
|
export interface MothershipConfig {
|
|
36
43
|
/** Host of the loading server (`load.webtil.es`), with a scheme and port when not https://. */
|
|
37
44
|
loadDomain?: string;
|
|
45
|
+
/**
|
|
46
|
+
* The tile origin to run tiles on, as a host (`notes.tiles.example`, with
|
|
47
|
+
* the port if there is one), instead of a fresh random one for every load.
|
|
48
|
+
* For a deployment that means tiles to share an origin or to find their
|
|
49
|
+
* storage again; the loading server has to know the name as one of its tile
|
|
50
|
+
* origins. Leave it out and every tile gets an origin of its own.
|
|
51
|
+
*/
|
|
52
|
+
tileHost?: string;
|
|
38
53
|
/**
|
|
39
54
|
* Whether the shuttle spends the renderer's WebRTC budget before the tile
|
|
40
55
|
* loads (the default). A host that blocks WebRTC itself (an Electron app with
|
|
@@ -62,12 +77,25 @@ const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
|
|
|
62
77
|
const RCV_WORKER_REQUEST = `${WORKER_PFX}request`; // worker requested something
|
|
63
78
|
const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
|
|
64
79
|
const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
|
|
65
|
-
const TILES_ERROR = `${
|
|
80
|
+
const TILES_ERROR = `${SHUTTLE_PFX}error`; // shuttle errors
|
|
81
|
+
const RCV_DOCK_STOPPED = 'tiles-dock-stopped'; // the dock stopped the tile
|
|
66
82
|
// Tiles protocols (https://dasl.ing/tp-data.html and friends): the shuttle
|
|
67
83
|
// relays `tiles-protocol-up-<protocol>-<kind>` from the tile to us, and
|
|
68
84
|
// `tiles-protocol-down-<protocol>-<kind>` from us to the tile.
|
|
69
85
|
const PROTOCOL_UP = 'tiles-protocol-up-';
|
|
70
86
|
const PROTOCOL_DOWN = 'tiles-protocol-down-';
|
|
87
|
+
// Warnings and errors come as a list; anything else is logged as it is.
|
|
88
|
+
const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg : [msg]);
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The dock stopped a tile, because its runtime tried to leave the frame it
|
|
92
|
+
* runs in: `blocked` when the navigation was refused, `navigated` when the
|
|
93
|
+
* frame loaded something else all the same. The tile is gone either way; a
|
|
94
|
+
* host that wants it back renders it again.
|
|
95
|
+
*/
|
|
96
|
+
export interface StoppedEvent extends Event {
|
|
97
|
+
reason: 'blocked' | 'navigated';
|
|
98
|
+
}
|
|
71
99
|
|
|
72
100
|
/** A tiles-protocol message from a tile: `protocol` ("data"), `kind` ("payload", "ready"), and its `payload`. The mothership attaches no meaning to any of them. */
|
|
73
101
|
export interface ProtocolEvent extends Event {
|
|
@@ -75,14 +103,6 @@ export interface ProtocolEvent extends Event {
|
|
|
75
103
|
kind: string;
|
|
76
104
|
payload: unknown;
|
|
77
105
|
}
|
|
78
|
-
/**
|
|
79
|
-
* A tp-data message from a tile; `payload` is what the tile sent.
|
|
80
|
-
* @deprecated The `data` and `data-ready` events go in the next major
|
|
81
|
-
* version. Use `tileData()` from `@dasl/tile-loader/data`, or the `protocol` event.
|
|
82
|
-
*/
|
|
83
|
-
export interface DataEvent extends Event {
|
|
84
|
-
payload: unknown;
|
|
85
|
-
}
|
|
86
106
|
|
|
87
107
|
export class TileMothership {
|
|
88
108
|
#loaders: TileLoader[] = [];
|
|
@@ -95,31 +115,45 @@ export class TileMothership {
|
|
|
95
115
|
init () {
|
|
96
116
|
window.addEventListener('message', async (ev: MessageEvent) => {
|
|
97
117
|
const { action } = ev.data || {};
|
|
118
|
+
if (typeof action !== 'string') return;
|
|
119
|
+
// Any frame can post a message, and say anything in it: the window
|
|
120
|
+
// it comes from says which tile is talking. That window is the tile's
|
|
121
|
+
// dock, on the loading server's origin, and it stays there; a message
|
|
122
|
+
// from one of our frames that is somewhere else is not from a dock.
|
|
123
|
+
// Messages still carry an id; we don't read it.
|
|
124
|
+
const id = this.#idForWindow(ev.source);
|
|
125
|
+
if (!id || ev.origin !== this.getLoadOrigin()) return;
|
|
126
|
+
const tile = this.#id2tile.get(id)!;
|
|
98
127
|
if (action === TILES_WARNING) {
|
|
99
|
-
|
|
100
|
-
console.warn(`[W:${id}]`, ...msg);
|
|
128
|
+
console.warn(`[W:${id}]`, ...asList(ev.data.msg));
|
|
101
129
|
}
|
|
102
|
-
if (action === TILES_ERROR) {
|
|
103
|
-
|
|
104
|
-
|
|
130
|
+
else if (action === TILES_ERROR) {
|
|
131
|
+
console.error(`[S:${id}]`, ...asList(ev.data.msg));
|
|
132
|
+
}
|
|
133
|
+
else if (action === RCV_DOCK_STOPPED) {
|
|
134
|
+
const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
|
|
135
|
+
console.error(`[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
|
|
136
|
+
tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
|
|
105
137
|
}
|
|
106
138
|
else if (action === RCV_SHUTTLE_READY) {
|
|
107
|
-
const { id } = ev.data;
|
|
108
139
|
this.sendToShuttle(id, SND_WORKER_LOAD, { id });
|
|
109
140
|
}
|
|
110
141
|
else if (action === RCV_WORKER_READY) {
|
|
111
|
-
const { id } = ev.data;
|
|
112
|
-
const tile = this.#id2tile.get(id);
|
|
113
|
-
if (!tile) throw new Error(`No tile shuttle with ID ${id}`);
|
|
114
142
|
tile.dispatchEvent(new Event('load'));
|
|
115
143
|
}
|
|
116
144
|
else if (action === RCV_WORKER_REQUEST) {
|
|
117
|
-
const { type,
|
|
145
|
+
const { type, payload } = ev.data;
|
|
118
146
|
if (type === 'resolve-path') {
|
|
119
147
|
const { path, requestId } = payload;
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
148
|
+
let res: MaslResponse;
|
|
149
|
+
try {
|
|
150
|
+
res = await tile.resolvePath(path);
|
|
151
|
+
}
|
|
152
|
+
catch (err) {
|
|
153
|
+
// Answer all the same, or the worker waits for ever.
|
|
154
|
+
console.error(`Could not resolve ${path}:`, err);
|
|
155
|
+
res = { ok: false, status: 502, statusText: 'Bad Gateway' };
|
|
156
|
+
}
|
|
123
157
|
// Every document the worker serves, 404s included, carries the
|
|
124
158
|
// policy: the tile can script anything on its origin, so nothing
|
|
125
159
|
// on it may be unconfined.
|
|
@@ -129,11 +163,7 @@ export class TileMothership {
|
|
|
129
163
|
this.sendToShuttle(id, SND_WORKER_RESPONSE, { requestId, response });
|
|
130
164
|
}
|
|
131
165
|
}
|
|
132
|
-
else if (
|
|
133
|
-
// Protocol messages carry no id: the shuttle window they come from
|
|
134
|
-
// says which tile is talking, and nothing else gets to pretend.
|
|
135
|
-
const tile = this.tileForWindow(ev.source);
|
|
136
|
-
if (!tile) return;
|
|
166
|
+
else if (action.startsWith(PROTOCOL_UP)) {
|
|
137
167
|
const rest = action.slice(PROTOCOL_UP.length);
|
|
138
168
|
const dash = rest.indexOf('-');
|
|
139
169
|
if (dash < 1) return;
|
|
@@ -141,11 +171,6 @@ export class TileMothership {
|
|
|
141
171
|
const kind = rest.slice(dash + 1);
|
|
142
172
|
const { payload } = ev.data;
|
|
143
173
|
tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload }));
|
|
144
|
-
// Deprecated: tp-data also raised as events of its own, until the
|
|
145
|
-
// next major version (see @dasl/tile-loader/data).
|
|
146
|
-
if (protocol === 'data') {
|
|
147
|
-
tile.dispatchEvent(Object.assign(new Event(kind === 'payload' ? 'data' : `data-${kind}`), { payload }));
|
|
148
|
-
}
|
|
149
174
|
}
|
|
150
175
|
});
|
|
151
176
|
}
|
|
@@ -158,15 +183,22 @@ export class TileMothership {
|
|
|
158
183
|
return tileResponseHeaders(headers);
|
|
159
184
|
}
|
|
160
185
|
tileForWindow (source: MessageEventSource | null): Tile | undefined {
|
|
186
|
+
const id = this.#idForWindow(source);
|
|
187
|
+
if (id) return this.#id2tile.get(id);
|
|
188
|
+
}
|
|
189
|
+
#idForWindow (source: MessageEventSource | null): string | undefined {
|
|
161
190
|
if (!source) return;
|
|
162
191
|
for (const [id, ifr] of this.#id2shuttle) {
|
|
163
|
-
if (ifr.contentWindow === source) return
|
|
192
|
+
if (ifr.contentWindow === source) return id;
|
|
164
193
|
}
|
|
165
194
|
}
|
|
166
195
|
sendToShuttle (id: string, action: string, payload: unknown) {
|
|
167
196
|
const ifr = this.#id2shuttle.get(id);
|
|
168
197
|
if (!ifr) return console.error(`No shuttle for ID ${id}`);
|
|
169
|
-
|
|
198
|
+
// To the dock and no one else: should the frame ever be anywhere but on
|
|
199
|
+
// the loading server, what we say (the tile's documents, the host's
|
|
200
|
+
// data) does not go with it.
|
|
201
|
+
ifr.contentWindow?.postMessage({ id, action, payload }, this.getLoadOrigin());
|
|
170
202
|
}
|
|
171
203
|
registerShuttleFrame (ifr: HTMLIFrameElement, tile: Tile) {
|
|
172
204
|
const id = crypto.randomUUID(); // we might want to make that pluggable
|
|
@@ -190,10 +222,19 @@ export class TileMothership {
|
|
|
190
222
|
removeLoader (loader: TileLoader) {
|
|
191
223
|
this.#loaders = this.#loaders.filter(ldr => ldr !== loader);
|
|
192
224
|
}
|
|
193
|
-
|
|
225
|
+
/** The origin of the loading server: where the dock is, and so who we talk to. */
|
|
226
|
+
getLoadOrigin (): string {
|
|
194
227
|
const domain = this.#conf.loadDomain || 'load.webtil.es';
|
|
195
|
-
|
|
196
|
-
|
|
228
|
+
return new URL(/^https?:\/\//.test(domain) ? domain : `https://${domain}`).origin;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* What a tile's frame loads: the dock, on the loading server. Asked like
|
|
232
|
+
* this it picks a fresh origin for the tile and frames the runtime there.
|
|
233
|
+
*/
|
|
234
|
+
getLoadSource (): string {
|
|
235
|
+
const url = new URL(dockPath, this.getLoadOrigin());
|
|
236
|
+
if (this.#conf.tileHost) url.searchParams.set('tile', this.#conf.tileHost);
|
|
237
|
+
return url.href;
|
|
197
238
|
}
|
|
198
239
|
// Load a tile.
|
|
199
240
|
async loadTile (url: string): Promise<Tile | false> {
|
|
@@ -301,14 +342,6 @@ export class Tile extends EventTarget {
|
|
|
301
342
|
if (!this.#shuttleId) throw new Error('The tile is not rendered yet.');
|
|
302
343
|
this.#mothership.sendToShuttle(this.#shuttleId, `${PROTOCOL_DOWN}${protocol}-${kind}`, payload);
|
|
303
344
|
}
|
|
304
|
-
/**
|
|
305
|
-
* Sends a tp-data payload to the tile (https://dasl.ing/tp-data.html).
|
|
306
|
-
* @deprecated Goes in the next major version. Use `tileData(tile).send()`
|
|
307
|
-
* from `@dasl/tile-loader/data`, or `sendProtocol('data', 'payload', payload)`.
|
|
308
|
-
*/
|
|
309
|
-
sendData (payload: unknown) {
|
|
310
|
-
this.sendProtocol('data', 'payload', payload);
|
|
311
|
-
}
|
|
312
345
|
attachIframe (ifr: HTMLIFrameElement) {
|
|
313
346
|
this.#shuttleId = this.#mothership.registerShuttleFrame(ifr, this);
|
|
314
347
|
ifr.addEventListener('load', () => this.#mothership.startShuttle(this.#shuttleId!));
|
package/src/link.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The context side of the link protocol (https://dasl.ing/tp-link.html): a
|
|
2
|
+
// tile asks for a link to be opened, the context that frames it decides.
|
|
3
|
+
//
|
|
4
|
+
// A tile cannot open a window, and its frame only ever shows the tile's own
|
|
5
|
+
// documents. When the user follows a link out of a tile, or the tile asks
|
|
6
|
+
// from script, the request arrives here, and nothing happens unless the host
|
|
7
|
+
// says so:
|
|
8
|
+
//
|
|
9
|
+
// import { tileLinks, linkPrompt } from '@dasl/tile-loader/link';
|
|
10
|
+
// tileLinks(tile); // links out of the tile do nothing
|
|
11
|
+
// tileLinks(tile, { open: linkPrompt(container) }); // the user is shown where, and opens it
|
|
12
|
+
// tileLinks(tile, { open: (url) => myApp.confirmAndOpen(url) });
|
|
13
|
+
//
|
|
14
|
+
// The URL is the tile's to choose, and whatever it wants to say can be in it:
|
|
15
|
+
// a link opened without the user seeing where it goes is the tile sending
|
|
16
|
+
// data out. So the default opens nothing, `linkPrompt` has the user follow a
|
|
17
|
+
// link of the host's own making with the destination in plain sight, and a
|
|
18
|
+
// host with a handler of its own should do no less. Whatever the host does,
|
|
19
|
+
// it does somewhere of its own: the tile's frame is never navigated.
|
|
20
|
+
|
|
21
|
+
import type { ProtocolEvent, Tile } from './index.js';
|
|
22
|
+
|
|
23
|
+
/** The tiles protocol this module speaks. */
|
|
24
|
+
export const LINK_PROTOCOL = 'link';
|
|
25
|
+
|
|
26
|
+
// Longer than any link a person follows; a tile has no call to send more.
|
|
27
|
+
const MAX_URL_LENGTH = 8192;
|
|
28
|
+
|
|
29
|
+
export interface LinkRequest {
|
|
30
|
+
/**
|
|
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.
|
|
34
|
+
*/
|
|
35
|
+
activated: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Set when the tile asked from script and waits for an answer. A handler
|
|
38
|
+
* that returns nothing answers later itself, with
|
|
39
|
+
* `tile.sendProtocol('link', 'result', { id, opened })`.
|
|
40
|
+
*/
|
|
41
|
+
id?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Decides about one link: `true` if the host opened it, `false` if it did
|
|
46
|
+
* not. A host that answers the tile itself, later, returns nothing.
|
|
47
|
+
*/
|
|
48
|
+
export type LinkHandler = (url: URL, request: LinkRequest) => boolean | void | Promise<boolean | void>;
|
|
49
|
+
|
|
50
|
+
export interface TileLinksOptions {
|
|
51
|
+
/** What to do with a link the tile asks for. Without one, nothing opens. */
|
|
52
|
+
open?: LinkHandler;
|
|
53
|
+
/** The URL schemes that reach `open`; any other is refused. Default: `http:` and `https:`. */
|
|
54
|
+
schemes?: string[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface TileLinksControl {
|
|
58
|
+
/** Stops listening. Links out of the tile then do nothing, and go unanswered. */
|
|
59
|
+
stop (): void;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Hears a rendered tile's requests to open links, and answers them. */
|
|
63
|
+
export function tileLinks (tile: Tile, options: TileLinksOptions = {}): TileLinksControl {
|
|
64
|
+
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.
|
|
67
|
+
let deciding = false;
|
|
68
|
+
|
|
69
|
+
const answer = (id: unknown, opened: boolean) => {
|
|
70
|
+
if (typeof id !== 'string' || !id) return; // a followed link carries no id, and gets no answer
|
|
71
|
+
try { tile.sendProtocol(LINK_PROTOCOL, 'result', { id, opened }); }
|
|
72
|
+
catch { /* gone */ }
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const onProtocol = async (ev: Event) => {
|
|
76
|
+
const { protocol, kind, payload } = ev as ProtocolEvent;
|
|
77
|
+
if (protocol !== LINK_PROTOCOL || kind !== 'open') return;
|
|
78
|
+
const { id, url: asked } = (payload && typeof payload === 'object' ? payload : {}) as { id?: unknown; url?: unknown };
|
|
79
|
+
let url: URL | undefined;
|
|
80
|
+
if (typeof asked === 'string' && asked.length <= MAX_URL_LENGTH) {
|
|
81
|
+
try { url = new URL(asked); }
|
|
82
|
+
catch { /* not a URL */ }
|
|
83
|
+
}
|
|
84
|
+
if (!url || !schemes.includes(url.protocol) || !options.open || deciding) return answer(id, false);
|
|
85
|
+
deciding = true;
|
|
86
|
+
let opened: boolean | void;
|
|
87
|
+
try {
|
|
88
|
+
opened = await options.open(url, {
|
|
89
|
+
activated: globalThis.navigator?.userActivation?.isActive ?? false,
|
|
90
|
+
...(typeof id === 'string' && id ? { id } : {}),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
console.error('Could not open a link for a tile:', err);
|
|
95
|
+
opened = false;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
deciding = false;
|
|
99
|
+
}
|
|
100
|
+
if (typeof opened === 'boolean') answer(id, opened);
|
|
101
|
+
};
|
|
102
|
+
tile.addEventListener('protocol', onProtocol);
|
|
103
|
+
return {
|
|
104
|
+
stop () {
|
|
105
|
+
tile.removeEventListener('protocol', onProtocol);
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Opens `url` in a new tab or window, cut off from the page that opens it (no
|
|
112
|
+
* opener, no referrer). Only `http:` and `https:`. Browsers only allow it
|
|
113
|
+
* right after the user did something, so call it from a click of theirs.
|
|
114
|
+
*/
|
|
115
|
+
export function openInNewTab (url: URL): boolean {
|
|
116
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
117
|
+
window.open(url.href, '_blank', 'noopener,noreferrer');
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface LinkPromptOptions {
|
|
122
|
+
/** The words before the destination. Default: "This tile wants to open". */
|
|
123
|
+
label?: string;
|
|
124
|
+
/** The word on the button that refuses. Default: "Dismiss". */
|
|
125
|
+
dismiss?: string;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
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.
|
|
134
|
+
*
|
|
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.
|
|
137
|
+
*
|
|
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.
|
|
140
|
+
*/
|
|
141
|
+
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);
|
|
146
|
+
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';
|
|
155
|
+
link.href = url.href;
|
|
156
|
+
link.target = '_blank';
|
|
157
|
+
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);
|
|
165
|
+
return new Promise<boolean>((resolve) => {
|
|
166
|
+
const done = (opened: boolean) => {
|
|
167
|
+
if (settle !== done) return;
|
|
168
|
+
settle = undefined;
|
|
169
|
+
box.remove();
|
|
170
|
+
resolve(opened);
|
|
171
|
+
};
|
|
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);
|
|
177
|
+
});
|
|
178
|
+
};
|
|
179
|
+
}
|
package/src/size.ts
CHANGED
|
@@ -77,7 +77,9 @@ export function tileSize (tile: Tile, frame: HTMLElement, options: TileSizeOptio
|
|
|
77
77
|
let reported = ''; // the last size the host was told of
|
|
78
78
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
79
79
|
let lastApplied = 0;
|
|
80
|
-
|
|
80
|
+
let stopped = false;
|
|
81
|
+
const waiting: string[] = []; // request ids whose move is still to come
|
|
82
|
+
const moved: string[] = []; // request ids whose move the host is still to apply
|
|
81
83
|
|
|
82
84
|
// The frame's real box, when it has one.
|
|
83
85
|
const box = (): TileSize | undefined => {
|
|
@@ -92,6 +94,7 @@ export function tileSize (tile: Tile, frame: HTMLElement, options: TileSizeOptio
|
|
|
92
94
|
});
|
|
93
95
|
|
|
94
96
|
const grant = (id?: string) => {
|
|
97
|
+
if (stopped) return; // a move's timer can still fire after stop()
|
|
95
98
|
const size = box() ?? current;
|
|
96
99
|
current = size;
|
|
97
100
|
const dims = `${size.width}x${size.height}`;
|
|
@@ -106,11 +109,16 @@ export function tileSize (tile: Tile, frame: HTMLElement, options: TileSizeOptio
|
|
|
106
109
|
}
|
|
107
110
|
catch { /* not rendered yet: it asks when it is */ }
|
|
108
111
|
};
|
|
109
|
-
const answer = () => {
|
|
110
|
-
const ids = waiting.splice(0);
|
|
112
|
+
const answer = (ids: string[]) => {
|
|
111
113
|
if (ids.length) ids.forEach(id => grant(id));
|
|
112
114
|
else grant();
|
|
113
115
|
};
|
|
116
|
+
// The ids of `ids` that are still in `moved`, taken out of it.
|
|
117
|
+
const take = (ids: string[]) => ids.filter(id => {
|
|
118
|
+
const i = moved.indexOf(id);
|
|
119
|
+
if (i >= 0) moved.splice(i, 1);
|
|
120
|
+
return i >= 0;
|
|
121
|
+
});
|
|
114
122
|
|
|
115
123
|
const put = (size: TileSize) => {
|
|
116
124
|
current = size;
|
|
@@ -118,16 +126,24 @@ export function tileSize (tile: Tile, frame: HTMLElement, options: TileSizeOptio
|
|
|
118
126
|
frame.style.height = `${size.height}px`;
|
|
119
127
|
if (tileWidth) frame.style.width = `${size.width}px`;
|
|
120
128
|
};
|
|
121
|
-
// At most one move per SETTLE_MS: the first at once, the rest together.
|
|
129
|
+
// At most one move per SETTLE_MS: the first at once, the rest together. The
|
|
130
|
+
// requests gathered into one move are applied as one (for each dimension the
|
|
131
|
+
// last value asked for, which is what `wish` holds), and every one of them
|
|
132
|
+
// is answered, by its own id, with the size that came of it: no request is
|
|
133
|
+
// left waiting because a later one overtook it.
|
|
122
134
|
const move = () => {
|
|
123
135
|
const go = () => {
|
|
124
136
|
timer = undefined;
|
|
125
137
|
lastApplied = Date.now();
|
|
126
138
|
put(settle());
|
|
127
|
-
|
|
128
|
-
|
|
139
|
+
const ids = waiting.splice(0);
|
|
140
|
+
if (apply) return answer(ids);
|
|
141
|
+
// The host resizes its box. Each move's requests get their own time
|
|
142
|
+
// for that; the observer may answer them sooner.
|
|
143
|
+
moved.push(...ids);
|
|
144
|
+
setTimeout(() => answer(take(ids)), HOST_APPLIES_MS);
|
|
129
145
|
};
|
|
130
|
-
if (timer) return;
|
|
146
|
+
if (timer || stopped) return;
|
|
131
147
|
const since = Date.now() - lastApplied;
|
|
132
148
|
if (since >= SETTLE_MS) go();
|
|
133
149
|
else timer = setTimeout(go, SETTLE_MS - since);
|
|
@@ -153,8 +169,9 @@ export function tileSize (tile: Tile, frame: HTMLElement, options: TileSizeOptio
|
|
|
153
169
|
tile.addEventListener('protocol', onProtocol);
|
|
154
170
|
|
|
155
171
|
// The context's layout changes the box too (a narrower column, a rotated
|
|
156
|
-
// phone): the tile is told its new size.
|
|
157
|
-
|
|
172
|
+
// phone): the tile is told its new size. Requests still waiting for their
|
|
173
|
+
// move are left to it.
|
|
174
|
+
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(() => answer(moved.splice(0))) : undefined;
|
|
158
175
|
observer?.observe(frame);
|
|
159
176
|
|
|
160
177
|
put(settle());
|
|
@@ -175,6 +192,7 @@ export function tileSize (tile: Tile, frame: HTMLElement, options: TileSizeOptio
|
|
|
175
192
|
return resolved;
|
|
176
193
|
},
|
|
177
194
|
stop () {
|
|
195
|
+
stopped = true;
|
|
178
196
|
tile.removeEventListener('protocol', onProtocol);
|
|
179
197
|
observer?.disconnect();
|
|
180
198
|
if (timer) clearTimeout(timer);
|