@swell/apps-sdk 2.0.0-alpha.4 → 2.0.0-alpha.6
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 +77 -1
- package/dist/component-frame.html +13 -0
- package/dist/components-client.d.cts +31 -0
- package/dist/components-client.d.ts +31 -0
- package/dist/components-client.js +85 -0
- package/dist/components-focus.d.cts +2 -0
- package/dist/components-focus.d.ts +2 -0
- package/dist/components-focus.js +68 -0
- package/dist/components-frame.d.cts +18 -0
- package/dist/components-frame.d.ts +18 -0
- package/dist/components-frame.js +226 -0
- package/dist/components-host.d.cts +58 -0
- package/dist/components-host.d.ts +58 -0
- package/dist/components-host.js +294 -0
- package/dist/components-placement.d.cts +18 -0
- package/dist/components-placement.d.ts +18 -0
- package/dist/components-placement.js +131 -0
- package/dist/components-protocol.d.cts +78 -0
- package/dist/components-protocol.d.ts +78 -0
- package/dist/components-protocol.js +20 -0
- package/dist/components-types.d.cts +46 -0
- package/dist/components-types.d.ts +46 -0
- package/dist/components-types.js +1 -0
- package/dist/components.d.cts +6 -0
- package/dist/components.d.ts +6 -0
- package/dist/components.js +2 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/request-context.d.cts +4 -0
- package/dist/request-context.d.ts +4 -0
- package/dist/request-context.js +4 -0
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +13 -3
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ComponentInput, ComponentToken } from './components-types.js';
|
|
2
|
+
import type { WireProps } from './components-protocol.js';
|
|
3
|
+
/** Controls one mounted component. */
|
|
4
|
+
export interface ComponentHandle<TValue = unknown> {
|
|
5
|
+
/**
|
|
6
|
+
* Resolves when the component has mounted in its frame. Rejects when the component cannot be
|
|
7
|
+
* loaded or started; the `error` event fires as well. `unmount` also rejects it, without an
|
|
8
|
+
* `error` event. A frame `error` is final: a later `ready` from that frame does not revive the
|
|
9
|
+
* handle. A frame that only missed the 10 s start timeout can still start later and then serves `emit`.
|
|
10
|
+
*/
|
|
11
|
+
readonly ready: Promise<void>;
|
|
12
|
+
/**
|
|
13
|
+
* Listens to the component. Returns a function that removes the listener; unknown events are ignored.
|
|
14
|
+
* A listener that throws is caught and logged with `console.error`; the other listeners still run.
|
|
15
|
+
*/
|
|
16
|
+
on(event: 'change', handler: (value: TValue) => void): () => void;
|
|
17
|
+
on(event: 'validity', handler: (error: string | null) => void): () => void;
|
|
18
|
+
on(event: 'error', handler: (error: Error) => void): () => void;
|
|
19
|
+
/** Re-renders the component with new data. */
|
|
20
|
+
update(input: ComponentInput<TValue>): void;
|
|
21
|
+
/**
|
|
22
|
+
* Sends an event to the component and resolves with its handler's result. Rejects when the frame
|
|
23
|
+
* does not start in time, reports an error (final) or is unmounted.
|
|
24
|
+
*/
|
|
25
|
+
emit<T = unknown>(event: string, data?: unknown): Promise<T>;
|
|
26
|
+
/**
|
|
27
|
+
* Moves keyboard focus to the component's first control, as a form does for its first invalid field.
|
|
28
|
+
* During overlay, to the component's modal. A component without controls keeps focus on its frame.
|
|
29
|
+
*/
|
|
30
|
+
focus(): void;
|
|
31
|
+
unmount(): void;
|
|
32
|
+
}
|
|
33
|
+
export interface EmbedOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
|
|
34
|
+
/** Frame URL from the component metadata. */
|
|
35
|
+
src: string;
|
|
36
|
+
settings?: Record<string, unknown>;
|
|
37
|
+
title?: string;
|
|
38
|
+
getToken?: () => Promise<ComponentToken>;
|
|
39
|
+
}
|
|
40
|
+
type Listener = (value: never) => void;
|
|
41
|
+
type HandleEvent = 'change' | 'validity' | 'error';
|
|
42
|
+
export declare const toError: (error: unknown) => Error;
|
|
43
|
+
/** The props a handle update changes: only the keys the host passed. */
|
|
44
|
+
export declare function pickInput(input: ComponentInput<unknown, unknown>): Partial<WireProps>;
|
|
45
|
+
/** Handle event listeners. Unknown event names subscribe to nothing. */
|
|
46
|
+
export declare function createListeners(): {
|
|
47
|
+
on(event: string, handler: Listener): () => void;
|
|
48
|
+
notify(event: HandleEvent, value: unknown): void;
|
|
49
|
+
};
|
|
50
|
+
/** A promise with its settle functions. Rejections are handled, so an unobserved one is not reported. */
|
|
51
|
+
export declare function deferred(): {
|
|
52
|
+
promise: Promise<void>;
|
|
53
|
+
resolve: () => void;
|
|
54
|
+
reject: (error: Error) => void;
|
|
55
|
+
};
|
|
56
|
+
/** Embeds a component frame in `placeholder`. Internal: hosts use createComponents().mount(). */
|
|
57
|
+
export declare function embedComponent<TValue = unknown, TContext = Record<string, unknown>>(placeholder: HTMLElement, options: EmbedOptions<TValue, TContext>): ComponentHandle<TValue>;
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { placeFrame } from './components-placement.js';
|
|
2
|
+
import { unwrap, wrap } from './components-protocol.js';
|
|
3
|
+
const REFRESH_SECONDS = 60;
|
|
4
|
+
const MIN_REFRESH_MS = 5_000;
|
|
5
|
+
const RETRY_MS = 10_000;
|
|
6
|
+
const MAX_RETRY_MS = 5 * 60_000;
|
|
7
|
+
const MAX_TIMEOUT = 2 ** 31 - 1;
|
|
8
|
+
const START_MS = 10_000;
|
|
9
|
+
const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale'];
|
|
10
|
+
export const toError = (error) => (error instanceof Error ? error : new Error(String(error)));
|
|
11
|
+
/** The props a handle update changes: only the keys the host passed. */
|
|
12
|
+
export function pickInput(input) {
|
|
13
|
+
const changed = {};
|
|
14
|
+
for (const key of INPUT_KEYS) {
|
|
15
|
+
if (key in input)
|
|
16
|
+
Object.assign(changed, { [key]: input[key] });
|
|
17
|
+
}
|
|
18
|
+
return changed;
|
|
19
|
+
}
|
|
20
|
+
/** Handle event listeners. Unknown event names subscribe to nothing. */
|
|
21
|
+
export function createListeners() {
|
|
22
|
+
const sets = new Map([['change', new Set()], ['validity', new Set()], ['error', new Set()]]);
|
|
23
|
+
return {
|
|
24
|
+
on(event, handler) {
|
|
25
|
+
const set = sets.get(event);
|
|
26
|
+
set?.add(handler);
|
|
27
|
+
return () => {
|
|
28
|
+
set?.delete(handler);
|
|
29
|
+
};
|
|
30
|
+
},
|
|
31
|
+
notify(event, value) {
|
|
32
|
+
for (const handler of sets.get(event) ?? []) {
|
|
33
|
+
// A throwing listener must not stop the others or break the failure path that notified it
|
|
34
|
+
try {
|
|
35
|
+
handler(value);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
console.error(error);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** A promise with its settle functions. Rejections are handled, so an unobserved one is not reported. */
|
|
45
|
+
export function deferred() {
|
|
46
|
+
let resolve;
|
|
47
|
+
let reject;
|
|
48
|
+
const promise = new Promise((done, fail) => {
|
|
49
|
+
resolve = done;
|
|
50
|
+
reject = fail;
|
|
51
|
+
});
|
|
52
|
+
promise.catch(() => { });
|
|
53
|
+
return { promise, resolve, reject };
|
|
54
|
+
}
|
|
55
|
+
// randomUUID exists only in secure contexts; hosts served over plain http (local development) still get
|
|
56
|
+
// a random channel
|
|
57
|
+
function randomChannel() {
|
|
58
|
+
if (typeof crypto.randomUUID === 'function')
|
|
59
|
+
return crypto.randomUUID();
|
|
60
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
|
|
61
|
+
}
|
|
62
|
+
/** Embeds a component frame in `placeholder`. Internal: hosts use createComponents().mount(). */
|
|
63
|
+
export function embedComponent(placeholder, options) {
|
|
64
|
+
const window = placeholder.ownerDocument.defaultView;
|
|
65
|
+
if (!window)
|
|
66
|
+
throw new Error('Component placeholder must be attached to a window');
|
|
67
|
+
const channel = randomChannel();
|
|
68
|
+
const url = new URL(options.src);
|
|
69
|
+
url.searchParams.set('parent', window.location.origin);
|
|
70
|
+
url.searchParams.set('channel', channel);
|
|
71
|
+
const frameOrigin = url.origin;
|
|
72
|
+
const props = {
|
|
73
|
+
value: options.value, context: options.context ?? {}, params: options.params ?? {},
|
|
74
|
+
settings: options.settings ?? {}, locale: options.locale ?? 'en', readonly: options.readonly ?? false,
|
|
75
|
+
};
|
|
76
|
+
const { on, notify } = createListeners();
|
|
77
|
+
const pending = new Map();
|
|
78
|
+
let calls = 0;
|
|
79
|
+
let token = null;
|
|
80
|
+
let tokenTimer;
|
|
81
|
+
let tokenFailures = 0;
|
|
82
|
+
let startTimer;
|
|
83
|
+
let greeted = false;
|
|
84
|
+
let started = false;
|
|
85
|
+
let destroyed = false;
|
|
86
|
+
// The component has rendered once: a later frame error leaves it usable, and in the Tab order
|
|
87
|
+
let rendered = false;
|
|
88
|
+
const { promise: ready, resolve: markReady, reject: failReady } = deferred();
|
|
89
|
+
// Settles on the frame's own `ready` message, so a frame that starts after the start timeout still serves `emit`
|
|
90
|
+
const { promise: live, resolve: markLive, reject: failLive } = deferred();
|
|
91
|
+
// Rejects at the start timeout, so `emit` fails instead of waiting for a frame that never starts
|
|
92
|
+
const { promise: startFailed, reject: failStart } = deferred();
|
|
93
|
+
const stop = (error) => {
|
|
94
|
+
failReady(error);
|
|
95
|
+
failLive(error);
|
|
96
|
+
};
|
|
97
|
+
const fail = (error) => {
|
|
98
|
+
const reported = toError(error);
|
|
99
|
+
notify('error', reported);
|
|
100
|
+
return reported;
|
|
101
|
+
};
|
|
102
|
+
const rejectPending = (error) => {
|
|
103
|
+
for (const call of pending.values())
|
|
104
|
+
call.reject(error);
|
|
105
|
+
pending.clear();
|
|
106
|
+
};
|
|
107
|
+
const placed = placeFrame(placeholder, url.href, options.title ?? 'App component', rect => send({ type: 'rect', rect }));
|
|
108
|
+
// A Tab stop only while the frame runs: from its first hello until it fails to start, or reports an error
|
|
109
|
+
// before it rendered, so Tab skips a frame that shows an error page
|
|
110
|
+
placed.iframe.tabIndex = -1;
|
|
111
|
+
const skipInTabOrder = () => {
|
|
112
|
+
placed.iframe.tabIndex = -1;
|
|
113
|
+
};
|
|
114
|
+
const focusFrame = () => {
|
|
115
|
+
placed.iframe.focus();
|
|
116
|
+
send({ type: 'focus' });
|
|
117
|
+
};
|
|
118
|
+
// Throws when the message cannot be cloned
|
|
119
|
+
function post(message) {
|
|
120
|
+
if (started && !destroyed)
|
|
121
|
+
placed.iframe.contentWindow?.postMessage(wrap(channel, message), frameOrigin);
|
|
122
|
+
}
|
|
123
|
+
function send(message) {
|
|
124
|
+
try {
|
|
125
|
+
post(message);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
fail(error);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// A failed refresh keeps the current token, which can still be valid, and retries with backoff
|
|
132
|
+
async function loadToken() {
|
|
133
|
+
if (!options.getToken || destroyed)
|
|
134
|
+
return;
|
|
135
|
+
let next;
|
|
136
|
+
let error;
|
|
137
|
+
try {
|
|
138
|
+
next = await options.getToken();
|
|
139
|
+
if (!next || typeof next.token !== 'string' || !Number.isFinite(next.expires)) {
|
|
140
|
+
throw new TypeError('getToken must resolve to { token: string, expires: number }');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch (caught) {
|
|
144
|
+
next = undefined;
|
|
145
|
+
error = caught;
|
|
146
|
+
}
|
|
147
|
+
if (destroyed)
|
|
148
|
+
return;
|
|
149
|
+
const delay = next
|
|
150
|
+
? Math.max(MIN_REFRESH_MS, (next.expires - REFRESH_SECONDS) * 1000 - Date.now())
|
|
151
|
+
: Math.min(MAX_RETRY_MS, RETRY_MS * 2 ** tokenFailures);
|
|
152
|
+
tokenFailures = next ? 0 : tokenFailures + 1;
|
|
153
|
+
tokenTimer = setTimeout(() => void loadToken(), Math.min(MAX_TIMEOUT, delay));
|
|
154
|
+
if (next) {
|
|
155
|
+
token = next.token;
|
|
156
|
+
send({ type: 'token', token });
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
fail(error);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// On a microtask, so listeners added right after mount see a getToken that throws at once
|
|
163
|
+
const tokenLoaded = Promise.resolve().then(loadToken);
|
|
164
|
+
// A frame page that never says hello (404, CSP, frame-ancestors) fails ready instead of leaving it pending
|
|
165
|
+
placed.iframe.addEventListener('load', () => {
|
|
166
|
+
if (greeted || destroyed)
|
|
167
|
+
return;
|
|
168
|
+
clearTimeout(startTimer);
|
|
169
|
+
startTimer = setTimeout(() => {
|
|
170
|
+
if (greeted || destroyed)
|
|
171
|
+
return;
|
|
172
|
+
const error = new Error('Component frame did not start');
|
|
173
|
+
skipInTabOrder();
|
|
174
|
+
failReady(error);
|
|
175
|
+
failStart(error);
|
|
176
|
+
fail(error);
|
|
177
|
+
}, START_MS);
|
|
178
|
+
});
|
|
179
|
+
async function onMessage(event) {
|
|
180
|
+
if (event.origin !== frameOrigin || event.source !== placed.iframe.contentWindow)
|
|
181
|
+
return;
|
|
182
|
+
const message = unwrap(event.data, channel);
|
|
183
|
+
if (!message)
|
|
184
|
+
return;
|
|
185
|
+
switch (message.type) {
|
|
186
|
+
case 'hello':
|
|
187
|
+
clearTimeout(startTimer);
|
|
188
|
+
if (greeted) {
|
|
189
|
+
// The frame reloaded: its new runtime starts without overlay and cannot answer earlier events
|
|
190
|
+
placed.setOverlay(false);
|
|
191
|
+
rejectPending(new Error('Component reloaded'));
|
|
192
|
+
}
|
|
193
|
+
if (!greeted)
|
|
194
|
+
placed.iframe.removeAttribute('tabindex');
|
|
195
|
+
greeted = true;
|
|
196
|
+
await tokenLoaded;
|
|
197
|
+
started = true;
|
|
198
|
+
try {
|
|
199
|
+
post({ type: 'init', props, token });
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
const reported = toError(error);
|
|
203
|
+
skipInTabOrder();
|
|
204
|
+
stop(reported);
|
|
205
|
+
fail(reported);
|
|
206
|
+
}
|
|
207
|
+
return;
|
|
208
|
+
case 'ready':
|
|
209
|
+
rendered = true;
|
|
210
|
+
markReady();
|
|
211
|
+
markLive();
|
|
212
|
+
return;
|
|
213
|
+
case 'change':
|
|
214
|
+
notify('change', message.value);
|
|
215
|
+
return;
|
|
216
|
+
case 'validity':
|
|
217
|
+
notify('validity', typeof message.error === 'string' ? message.error : null);
|
|
218
|
+
return;
|
|
219
|
+
case 'resize':
|
|
220
|
+
if (Number.isFinite(message.height))
|
|
221
|
+
placed.setHeight(Math.max(0, Math.ceil(message.height)));
|
|
222
|
+
return;
|
|
223
|
+
case 'overlay': {
|
|
224
|
+
const on = message.on === true;
|
|
225
|
+
send({ type: 'rect', rect: placed.setOverlay(on) });
|
|
226
|
+
// The component's modal takes focus, unless focus is already in its frame
|
|
227
|
+
if (on && placeholder.ownerDocument.activeElement !== placed.iframe)
|
|
228
|
+
focusFrame();
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
case 'result': {
|
|
232
|
+
const call = pending.get(message.call);
|
|
233
|
+
if (!call)
|
|
234
|
+
return;
|
|
235
|
+
pending.delete(message.call);
|
|
236
|
+
if (typeof message.error === 'string')
|
|
237
|
+
call.reject(new Error(message.error));
|
|
238
|
+
else
|
|
239
|
+
call.resolve(message.result);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
case 'error': {
|
|
243
|
+
const error = new Error(String(message.message));
|
|
244
|
+
if (!rendered)
|
|
245
|
+
skipInTabOrder();
|
|
246
|
+
stop(error);
|
|
247
|
+
fail(error);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
window.addEventListener('message', onMessage);
|
|
253
|
+
return {
|
|
254
|
+
ready,
|
|
255
|
+
on,
|
|
256
|
+
update(input) {
|
|
257
|
+
const changed = pickInput(input);
|
|
258
|
+
Object.assign(props, changed);
|
|
259
|
+
send({ type: 'update', props: changed });
|
|
260
|
+
},
|
|
261
|
+
async emit(name, data) {
|
|
262
|
+
await Promise.race([live, startFailed]);
|
|
263
|
+
if (destroyed)
|
|
264
|
+
throw new Error('Component unmounted');
|
|
265
|
+
const call = ++calls;
|
|
266
|
+
const result = new Promise((resolve, reject) => {
|
|
267
|
+
pending.set(call, { resolve: resolve, reject });
|
|
268
|
+
});
|
|
269
|
+
try {
|
|
270
|
+
post({ type: 'event', call, name, data });
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
pending.delete(call);
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
return result;
|
|
277
|
+
},
|
|
278
|
+
focus() {
|
|
279
|
+
if (!destroyed)
|
|
280
|
+
focusFrame();
|
|
281
|
+
},
|
|
282
|
+
unmount() {
|
|
283
|
+
if (destroyed)
|
|
284
|
+
return;
|
|
285
|
+
destroyed = true;
|
|
286
|
+
window.removeEventListener('message', onMessage);
|
|
287
|
+
clearTimeout(tokenTimer);
|
|
288
|
+
clearTimeout(startTimer);
|
|
289
|
+
rejectPending(new Error('Component unmounted'));
|
|
290
|
+
stop(new Error('Component unmounted'));
|
|
291
|
+
placed.destroy();
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Rect } from './components-protocol.cjs';
|
|
2
|
+
export interface PlacedFrame {
|
|
3
|
+
readonly iframe: HTMLIFrameElement;
|
|
4
|
+
/** Sizes the placeholder, which the iframe fills, to the component's height. */
|
|
5
|
+
setHeight(height: number): void;
|
|
6
|
+
/** Covers the viewport while the component shows a modal. Returns the placeholder position. */
|
|
7
|
+
setOverlay(on: boolean): Rect;
|
|
8
|
+
destroy(): void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Puts the component iframe in the placeholder, so it lays out, stacks, clips and takes focus like any other
|
|
12
|
+
* element of the host page. For overlay the iframe enters the top layer as a manual popover: it covers the
|
|
13
|
+
* viewport above everything else and escapes its ancestors' opacity, transform, filter and overflow, without
|
|
14
|
+
* moving in the DOM (a moved iframe reloads). Without the Popover API it is a fixed box with the top z-index,
|
|
15
|
+
* which a transformed or filtered ancestor still confines. During overlay the rest of the page is inert and
|
|
16
|
+
* does not scroll.
|
|
17
|
+
*/
|
|
18
|
+
export declare function placeFrame(placeholder: HTMLElement, src: string, title: string, onOverlayRect: (rect: Rect) => void): PlacedFrame;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Rect } from './components-protocol.js';
|
|
2
|
+
export interface PlacedFrame {
|
|
3
|
+
readonly iframe: HTMLIFrameElement;
|
|
4
|
+
/** Sizes the placeholder, which the iframe fills, to the component's height. */
|
|
5
|
+
setHeight(height: number): void;
|
|
6
|
+
/** Covers the viewport while the component shows a modal. Returns the placeholder position. */
|
|
7
|
+
setOverlay(on: boolean): Rect;
|
|
8
|
+
destroy(): void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Puts the component iframe in the placeholder, so it lays out, stacks, clips and takes focus like any other
|
|
12
|
+
* element of the host page. For overlay the iframe enters the top layer as a manual popover: it covers the
|
|
13
|
+
* viewport above everything else and escapes its ancestors' opacity, transform, filter and overflow, without
|
|
14
|
+
* moving in the DOM (a moved iframe reloads). Without the Popover API it is a fixed box with the top z-index,
|
|
15
|
+
* which a transformed or filtered ancestor still confines. During overlay the rest of the page is inert and
|
|
16
|
+
* does not scroll.
|
|
17
|
+
*/
|
|
18
|
+
export declare function placeFrame(placeholder: HTMLElement, src: string, title: string, onOverlayRect: (rect: Rect) => void): PlacedFrame;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// A plain block that fills the placeholder. During overlay the iframe is also a popover: these inline styles keep
|
|
2
|
+
// the user agent's popover border, padding and colors off it
|
|
3
|
+
const IN_FLOW = {
|
|
4
|
+
display: 'block', position: 'static', inset: 'auto', margin: '0', padding: '0', border: '0',
|
|
5
|
+
width: '100%', height: '100%', 'max-width': 'none', 'max-height': 'none', overflow: 'visible',
|
|
6
|
+
background: 'transparent', 'color-scheme': 'normal', 'z-index': 'auto',
|
|
7
|
+
};
|
|
8
|
+
// The z-index only matters without the Popover API: the top layer is above every z-index
|
|
9
|
+
const COVER = { position: 'fixed', inset: '0px', width: '100vw', height: '100vh', 'z-index': '2147483647' };
|
|
10
|
+
function rectOf(element) {
|
|
11
|
+
const { top, left, width } = element.getBoundingClientRect();
|
|
12
|
+
return { top, left, width };
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Puts the component iframe in the placeholder, so it lays out, stacks, clips and takes focus like any other
|
|
16
|
+
* element of the host page. For overlay the iframe enters the top layer as a manual popover: it covers the
|
|
17
|
+
* viewport above everything else and escapes its ancestors' opacity, transform, filter and overflow, without
|
|
18
|
+
* moving in the DOM (a moved iframe reloads). Without the Popover API it is a fixed box with the top z-index,
|
|
19
|
+
* which a transformed or filtered ancestor still confines. During overlay the rest of the page is inert and
|
|
20
|
+
* does not scroll.
|
|
21
|
+
*/
|
|
22
|
+
export function placeFrame(placeholder, src, title, onOverlayRect) {
|
|
23
|
+
const document = placeholder.ownerDocument;
|
|
24
|
+
const window = document.defaultView;
|
|
25
|
+
if (!window)
|
|
26
|
+
throw new Error('Component placeholder must be attached to a window');
|
|
27
|
+
const iframe = document.createElement('iframe');
|
|
28
|
+
iframe.src = src;
|
|
29
|
+
iframe.title = title;
|
|
30
|
+
iframe.setAttribute('allow', 'payment *; publickey-credentials-get *');
|
|
31
|
+
const style = (styles) => {
|
|
32
|
+
for (const name in styles)
|
|
33
|
+
iframe.style.setProperty(name, styles[name]);
|
|
34
|
+
};
|
|
35
|
+
style(IN_FLOW);
|
|
36
|
+
// No height until the component reports one: an iframe without a height is 150px
|
|
37
|
+
placeholder.style.height = '0px';
|
|
38
|
+
placeholder.appendChild(iframe);
|
|
39
|
+
let overlay = false;
|
|
40
|
+
let frame = 0;
|
|
41
|
+
let lastRect = '';
|
|
42
|
+
let savedOverflow = null;
|
|
43
|
+
// Elements made inert for the overlay, restored after it; elements that were inert already are left alone
|
|
44
|
+
let inerted = [];
|
|
45
|
+
const keyOf = (rect) => `${rect.top}:${rect.left}:${rect.width}`;
|
|
46
|
+
const follow = () => {
|
|
47
|
+
const rect = rectOf(placeholder);
|
|
48
|
+
const key = keyOf(rect);
|
|
49
|
+
if (key !== lastRect) {
|
|
50
|
+
lastRect = key;
|
|
51
|
+
onOverlayRect(rect);
|
|
52
|
+
}
|
|
53
|
+
frame = window.requestAnimationFrame(follow);
|
|
54
|
+
};
|
|
55
|
+
// Everything beside the iframe's ancestors: focus and clicks cannot reach the page under the overlay
|
|
56
|
+
const inertRest = () => {
|
|
57
|
+
for (let node = iframe; node.parentElement && node !== document.body; node = node.parentElement) {
|
|
58
|
+
for (const sibling of Array.from(node.parentElement.children)) {
|
|
59
|
+
if (sibling === node || sibling.hasAttribute('inert'))
|
|
60
|
+
continue;
|
|
61
|
+
sibling.setAttribute('inert', '');
|
|
62
|
+
inerted.push(sibling);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const lockScroll = (lock) => {
|
|
67
|
+
const root = document.documentElement;
|
|
68
|
+
if (lock && savedOverflow === null) {
|
|
69
|
+
savedOverflow = root.style.overflow;
|
|
70
|
+
root.style.overflow = 'hidden';
|
|
71
|
+
}
|
|
72
|
+
if (!lock && savedOverflow !== null) {
|
|
73
|
+
root.style.overflow = savedOverflow;
|
|
74
|
+
savedOverflow = null;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
// The iframe is a popover only during overlay, so host styles for [popover] never reach it in the page.
|
|
78
|
+
// showPopover throws for an iframe out of the page or already shown; the overlay styles apply either way
|
|
79
|
+
const popover = (show) => {
|
|
80
|
+
if (show)
|
|
81
|
+
iframe.setAttribute('popover', 'manual');
|
|
82
|
+
const toggle = show ? iframe.showPopover : iframe.hidePopover;
|
|
83
|
+
try {
|
|
84
|
+
if (typeof toggle === 'function')
|
|
85
|
+
toggle.call(iframe);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Out of the page, or already in that state
|
|
89
|
+
}
|
|
90
|
+
if (!show)
|
|
91
|
+
iframe.removeAttribute('popover');
|
|
92
|
+
};
|
|
93
|
+
const release = () => {
|
|
94
|
+
window.cancelAnimationFrame(frame);
|
|
95
|
+
for (const element of inerted)
|
|
96
|
+
element.removeAttribute('inert');
|
|
97
|
+
inerted = [];
|
|
98
|
+
lockScroll(false);
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
iframe,
|
|
102
|
+
setHeight(height) {
|
|
103
|
+
placeholder.style.height = `${height}px`;
|
|
104
|
+
},
|
|
105
|
+
setOverlay(on) {
|
|
106
|
+
const rect = rectOf(placeholder);
|
|
107
|
+
if (on === overlay)
|
|
108
|
+
return rect;
|
|
109
|
+
overlay = on;
|
|
110
|
+
if (on) {
|
|
111
|
+
style(COVER);
|
|
112
|
+
popover(true);
|
|
113
|
+
lockScroll(true);
|
|
114
|
+
inertRest();
|
|
115
|
+
lastRect = keyOf(rect);
|
|
116
|
+
frame = window.requestAnimationFrame(follow);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
release();
|
|
120
|
+
popover(false);
|
|
121
|
+
style(IN_FLOW);
|
|
122
|
+
}
|
|
123
|
+
return rect;
|
|
124
|
+
},
|
|
125
|
+
destroy() {
|
|
126
|
+
release();
|
|
127
|
+
iframe.remove();
|
|
128
|
+
placeholder.style.height = '';
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export declare const PROTOCOL = "swell:component";
|
|
2
|
+
/**
|
|
3
|
+
* Protocol evolution: changes within version 1 are additive. Both sides ignore message types and
|
|
4
|
+
* fields they do not know, so new messages and fields need no version change. A breaking change
|
|
5
|
+
* (a removed or renamed message or field, or a changed meaning) needs a new version.
|
|
6
|
+
*/
|
|
7
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
8
|
+
export declare const TOKEN_HEADER = "Swell-Component-Token";
|
|
9
|
+
/** Placeholder position in the host viewport. */
|
|
10
|
+
export interface Rect {
|
|
11
|
+
readonly top: number;
|
|
12
|
+
readonly left: number;
|
|
13
|
+
readonly width: number;
|
|
14
|
+
}
|
|
15
|
+
/** Component props as sent over postMessage: data only. */
|
|
16
|
+
export interface WireProps {
|
|
17
|
+
value: unknown;
|
|
18
|
+
context: unknown;
|
|
19
|
+
params: Record<string, unknown>;
|
|
20
|
+
settings: Record<string, unknown>;
|
|
21
|
+
locale: string;
|
|
22
|
+
readonly: boolean;
|
|
23
|
+
}
|
|
24
|
+
export type HostMessage = {
|
|
25
|
+
type: 'init';
|
|
26
|
+
props: WireProps;
|
|
27
|
+
token: string | null;
|
|
28
|
+
} | {
|
|
29
|
+
type: 'update';
|
|
30
|
+
props: Partial<WireProps>;
|
|
31
|
+
} | {
|
|
32
|
+
type: 'token';
|
|
33
|
+
token: string | null;
|
|
34
|
+
} | {
|
|
35
|
+
type: 'event';
|
|
36
|
+
call: number;
|
|
37
|
+
name: string;
|
|
38
|
+
data: unknown;
|
|
39
|
+
} | {
|
|
40
|
+
type: 'rect';
|
|
41
|
+
rect: Rect;
|
|
42
|
+
} | {
|
|
43
|
+
type: 'focus';
|
|
44
|
+
};
|
|
45
|
+
export type FrameMessage = {
|
|
46
|
+
type: 'hello';
|
|
47
|
+
} | {
|
|
48
|
+
type: 'ready';
|
|
49
|
+
} | {
|
|
50
|
+
type: 'change';
|
|
51
|
+
value: unknown;
|
|
52
|
+
} | {
|
|
53
|
+
type: 'validity';
|
|
54
|
+
error: string | null;
|
|
55
|
+
} | {
|
|
56
|
+
type: 'resize';
|
|
57
|
+
height: number;
|
|
58
|
+
} | {
|
|
59
|
+
type: 'overlay';
|
|
60
|
+
on: boolean;
|
|
61
|
+
} | {
|
|
62
|
+
type: 'result';
|
|
63
|
+
call: number;
|
|
64
|
+
result?: unknown;
|
|
65
|
+
error?: string;
|
|
66
|
+
} | {
|
|
67
|
+
type: 'error';
|
|
68
|
+
message: string;
|
|
69
|
+
};
|
|
70
|
+
interface Envelope {
|
|
71
|
+
$swell: typeof PROTOCOL;
|
|
72
|
+
v: number;
|
|
73
|
+
channel: string;
|
|
74
|
+
}
|
|
75
|
+
export declare function wrap<T extends HostMessage | FrameMessage>(channel: string, message: T): T & Envelope;
|
|
76
|
+
/** The message when it belongs to this protocol version and channel, otherwise null. */
|
|
77
|
+
export declare function unwrap<T extends HostMessage | FrameMessage>(data: unknown, channel: string): T | null;
|
|
78
|
+
export {};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export declare const PROTOCOL = "swell:component";
|
|
2
|
+
/**
|
|
3
|
+
* Protocol evolution: changes within version 1 are additive. Both sides ignore message types and
|
|
4
|
+
* fields they do not know, so new messages and fields need no version change. A breaking change
|
|
5
|
+
* (a removed or renamed message or field, or a changed meaning) needs a new version.
|
|
6
|
+
*/
|
|
7
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
8
|
+
export declare const TOKEN_HEADER = "Swell-Component-Token";
|
|
9
|
+
/** Placeholder position in the host viewport. */
|
|
10
|
+
export interface Rect {
|
|
11
|
+
readonly top: number;
|
|
12
|
+
readonly left: number;
|
|
13
|
+
readonly width: number;
|
|
14
|
+
}
|
|
15
|
+
/** Component props as sent over postMessage: data only. */
|
|
16
|
+
export interface WireProps {
|
|
17
|
+
value: unknown;
|
|
18
|
+
context: unknown;
|
|
19
|
+
params: Record<string, unknown>;
|
|
20
|
+
settings: Record<string, unknown>;
|
|
21
|
+
locale: string;
|
|
22
|
+
readonly: boolean;
|
|
23
|
+
}
|
|
24
|
+
export type HostMessage = {
|
|
25
|
+
type: 'init';
|
|
26
|
+
props: WireProps;
|
|
27
|
+
token: string | null;
|
|
28
|
+
} | {
|
|
29
|
+
type: 'update';
|
|
30
|
+
props: Partial<WireProps>;
|
|
31
|
+
} | {
|
|
32
|
+
type: 'token';
|
|
33
|
+
token: string | null;
|
|
34
|
+
} | {
|
|
35
|
+
type: 'event';
|
|
36
|
+
call: number;
|
|
37
|
+
name: string;
|
|
38
|
+
data: unknown;
|
|
39
|
+
} | {
|
|
40
|
+
type: 'rect';
|
|
41
|
+
rect: Rect;
|
|
42
|
+
} | {
|
|
43
|
+
type: 'focus';
|
|
44
|
+
};
|
|
45
|
+
export type FrameMessage = {
|
|
46
|
+
type: 'hello';
|
|
47
|
+
} | {
|
|
48
|
+
type: 'ready';
|
|
49
|
+
} | {
|
|
50
|
+
type: 'change';
|
|
51
|
+
value: unknown;
|
|
52
|
+
} | {
|
|
53
|
+
type: 'validity';
|
|
54
|
+
error: string | null;
|
|
55
|
+
} | {
|
|
56
|
+
type: 'resize';
|
|
57
|
+
height: number;
|
|
58
|
+
} | {
|
|
59
|
+
type: 'overlay';
|
|
60
|
+
on: boolean;
|
|
61
|
+
} | {
|
|
62
|
+
type: 'result';
|
|
63
|
+
call: number;
|
|
64
|
+
result?: unknown;
|
|
65
|
+
error?: string;
|
|
66
|
+
} | {
|
|
67
|
+
type: 'error';
|
|
68
|
+
message: string;
|
|
69
|
+
};
|
|
70
|
+
interface Envelope {
|
|
71
|
+
$swell: typeof PROTOCOL;
|
|
72
|
+
v: number;
|
|
73
|
+
channel: string;
|
|
74
|
+
}
|
|
75
|
+
export declare function wrap<T extends HostMessage | FrameMessage>(channel: string, message: T): T & Envelope;
|
|
76
|
+
/** The message when it belongs to this protocol version and channel, otherwise null. */
|
|
77
|
+
export declare function unwrap<T extends HostMessage | FrameMessage>(data: unknown, channel: string): T | null;
|
|
78
|
+
export {};
|