squiffy-runtime 6.0.1 → 7.0.0-beta.2

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 (42) hide show
  1. package/dist/assets.d.ts +2 -0
  2. package/dist/assets.test.d.ts +1 -0
  3. package/dist/events.d.ts +4 -0
  4. package/dist/pluginManager.d.ts +2 -1
  5. package/dist/preview-host.d.ts +30 -0
  6. package/dist/preview-host.js +89 -0
  7. package/dist/preview-host.js.map +7 -0
  8. package/dist/preview-host.test.d.ts +1 -0
  9. package/dist/preview-html.d.ts +2 -0
  10. package/dist/preview-html.js +2 -0
  11. package/dist/preview-protocol.d.ts +57 -0
  12. package/dist/preview.d.ts +14 -0
  13. package/dist/preview.main.d.ts +1 -0
  14. package/dist/preview.test.d.ts +1 -0
  15. package/dist/squiffy.page.css +120 -0
  16. package/dist/squiffy.preview.html +477 -0
  17. package/dist/squiffy.runtime.css +76 -20
  18. package/dist/squiffy.runtime.global.js +62 -57
  19. package/dist/squiffy.runtime.global.js.map +1 -1
  20. package/dist/squiffy.runtime.js +3146 -3069
  21. package/dist/squiffy.runtime.js.map +1 -1
  22. package/dist/types.d.ts +12 -1
  23. package/dist/types.plugins.d.ts +1 -0
  24. package/package.json +22 -11
  25. package/src/assets.test.ts +227 -0
  26. package/src/assets.ts +92 -0
  27. package/src/events.ts +1 -0
  28. package/src/pluginManager.ts +5 -1
  29. package/src/plugins/animate.ts +6 -5
  30. package/src/preview-host.test.ts +92 -0
  31. package/src/preview-host.ts +138 -0
  32. package/src/preview-protocol.ts +63 -0
  33. package/src/preview.main.ts +33 -0
  34. package/src/preview.test.ts +181 -0
  35. package/src/preview.ts +171 -0
  36. package/src/squiffy.page.css +120 -0
  37. package/src/squiffy.runtime.css +76 -20
  38. package/src/squiffy.runtime.ts +25 -6
  39. package/src/types.plugins.ts +4 -0
  40. package/src/types.ts +17 -1
  41. package/vite.config.ts +3 -4
  42. package/vite.preview.config.ts +76 -0
@@ -0,0 +1,138 @@
1
+ // The host side of the Squiffy preview: drives a preview page in a sandboxed iframe (the editor
2
+ // and desktop app) or a VS Code webview. It has no runtime code in it.
3
+ //
4
+ // import { previewHtml } from "squiffy-runtime/preview-html";
5
+ // import { createPreviewHost, iframeChannel, setUpPreviewFrame } from "squiffy-runtime/preview-host";
6
+ //
7
+ // setUpPreviewFrame(iframe, previewHtml);
8
+ // const preview = createPreviewHost(iframeChannel(iframe), {
9
+ // onNavigated: (section, passage) => ...,
10
+ // });
11
+ // await preview.setAssets({ files: { "cat.png": blob } });
12
+ // await preview.load({ js: await result.getJs() }, { startAt: { section: "kitchen" } });
13
+
14
+ import {
15
+ Envelope, HostMessage, isEnvelope, PREVIEW_CHANNEL, PreviewAssets, PreviewMessage, PreviewStory, PreviewTheme, StartAt,
16
+ } from "./preview-protocol.js";
17
+
18
+ export type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory, PreviewTheme, StartAt } from "./preview-protocol.js";
19
+ export { PREVIEW_CHANNEL } from "./preview-protocol.js";
20
+
21
+ // How the host talks to the preview page
22
+ export interface PreviewChannel {
23
+ send(message: Envelope<HostMessage>): void;
24
+ // Calls handler with each message from the page. Returns a function that stops listening.
25
+ onMessage(handler: (data: unknown) => void): () => void;
26
+ }
27
+
28
+ export interface PreviewHandlers {
29
+ onReady?(): void;
30
+ onLoaded?(): void;
31
+ onAttributeSet?(name: string, value: unknown): void;
32
+ onCanGoBackChanged?(canGoBack: boolean): void;
33
+ onNavigated?(section: string, passage?: string): void;
34
+ onRuntimeError?(message: string, stack?: string): void;
35
+ }
36
+
37
+ export interface PreviewHost {
38
+ // Resolves when the page has loaded. Messages sent before that are queued.
39
+ readonly ready: Promise<void>;
40
+ // Starts a story, replacing any that's running
41
+ load(story: PreviewStory, options?: { startAt?: StartAt }): void;
42
+ // Hot-updates the running story, keeping its state
43
+ update(js: string): void;
44
+ restart(): void;
45
+ back(): void;
46
+ // Sets the assets the story can use. Send these before load().
47
+ setAssets(assets: PreviewAssets): void;
48
+ // Shows the story in light or dark mode. It's kept if the page reloads.
49
+ setTheme(theme: PreviewTheme): void;
50
+ dispose(): void;
51
+ }
52
+
53
+ // Sandboxes an iframe and loads the preview page into it. The sandbox allows scripts only, so the
54
+ // story runs with an opaque origin: it can't reach the host page, its storage or its cookies.
55
+ export function setUpPreviewFrame(iframe: HTMLIFrameElement, previewHtml: string) {
56
+ iframe.setAttribute("sandbox", "allow-scripts");
57
+ iframe.srcdoc = previewHtml;
58
+ }
59
+
60
+ // A channel to a preview page in an iframe
61
+ export function iframeChannel(iframe: HTMLIFrameElement): PreviewChannel {
62
+ return {
63
+ // The page has an opaque origin, so there's no origin to target
64
+ send: message => iframe.contentWindow?.postMessage(message, "*"),
65
+ onMessage(handler) {
66
+ const listener = (event: MessageEvent) => {
67
+ if (event.source === iframe.contentWindow) handler(event.data);
68
+ };
69
+ window.addEventListener("message", listener);
70
+ return () => window.removeEventListener("message", listener);
71
+ },
72
+ };
73
+ }
74
+
75
+ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHandlers = {}): PreviewHost {
76
+ let isReady = false;
77
+ let queue: HostMessage[] = [];
78
+ let theme: PreviewTheme | undefined;
79
+ let resolveReady: () => void;
80
+ const ready = new Promise<void>(resolve => { resolveReady = resolve; });
81
+
82
+ const send = (message: HostMessage) => {
83
+ if (isReady) channel.send({ channel: PREVIEW_CHANNEL, ...message });
84
+ else queue.push(message);
85
+ };
86
+
87
+ const stop = channel.onMessage(data => {
88
+ if (!isEnvelope<PreviewMessage>(data)) return;
89
+ const message = data as Envelope<PreviewMessage>;
90
+ switch (message.type) {
91
+ case "ready": {
92
+ // Sent again if the page reloads, which loses its story, so onReady is
93
+ // where a host can load it again
94
+ isReady = true;
95
+ if (theme) send({ type: "theme", theme });
96
+ const queued = queue;
97
+ queue = [];
98
+ for (const m of queued) send(m);
99
+ resolveReady();
100
+ handlers.onReady?.();
101
+ break;
102
+ }
103
+ case "loaded":
104
+ handlers.onLoaded?.();
105
+ break;
106
+ case "attributeSet":
107
+ handlers.onAttributeSet?.(message.name, message.value);
108
+ break;
109
+ case "canGoBackChanged":
110
+ handlers.onCanGoBackChanged?.(message.canGoBack);
111
+ break;
112
+ case "navigated":
113
+ handlers.onNavigated?.(message.section, message.passage);
114
+ break;
115
+ case "runtimeError":
116
+ handlers.onRuntimeError?.(message.message, message.stack);
117
+ break;
118
+ }
119
+ });
120
+
121
+ return {
122
+ ready,
123
+ load: (story, options = {}) => send({ type: "load", story, ...(options.startAt ? { startAt: options.startAt } : {}) }),
124
+ update: js => send({ type: "update", js }),
125
+ restart: () => send({ type: "restart" }),
126
+ back: () => send({ type: "back" }),
127
+ setAssets: assets => send({ type: "assets", assets }),
128
+ setTheme: value => {
129
+ theme = value;
130
+ // Sent when the page is ready, and again if it reloads
131
+ if (isReady) send({ type: "theme", theme });
132
+ },
133
+ dispose: () => {
134
+ stop();
135
+ queue = [];
136
+ },
137
+ };
138
+ }
@@ -0,0 +1,63 @@
1
+ // The messages between a host (the editor, the desktop app or a VS Code extension) and the
2
+ // Squiffy preview page, which runs stories in a sandboxed frame or webview. See preview-host.ts
3
+ // for the host side and preview.ts for the page.
4
+
5
+ import type { StartAt } from "./types.js";
6
+
7
+ export type { StartAt } from "./types.js";
8
+
9
+ // Every message carries this, so each side can ignore unrelated messages.
10
+ export const PREVIEW_CHANNEL = "squiffy-preview";
11
+
12
+ export interface PreviewStory {
13
+ // The compiled story module: the output of the compiler's getJs() without globalJs, which
14
+ // starts "export const story".
15
+ js: string;
16
+ // The contents of the story's own stylesheets and scripts (from @import of .css and .js files).
17
+ css?: string[];
18
+ scripts?: string[];
19
+ }
20
+
21
+ export interface PreviewAssets {
22
+ // Asset contents by path, as the story refers to them (relative to the main .squiffy file).
23
+ // The preview makes its own object URLs for these: a sandboxed frame can't load the host's
24
+ // blob URLs.
25
+ files?: Record<string, Blob | ArrayBuffer | Uint8Array>;
26
+ // Or URLs the preview can load as they are, e.g. from VS Code's asWebviewUri.
27
+ urls?: Record<string, string>;
28
+ }
29
+
30
+ // "system" follows the reader's system setting, like an exported story
31
+ export type PreviewTheme = "light" | "dark" | "system";
32
+
33
+ export type HostMessage =
34
+ // Starts a story, replacing any that's running. Send assets first.
35
+ | { type: "load"; story: PreviewStory; startAt?: StartAt }
36
+ // Hot-updates the running story, keeping its state
37
+ | { type: "update"; js: string }
38
+ | { type: "restart" }
39
+ | { type: "back" }
40
+ // Replaces the assets the story can use
41
+ | { type: "assets"; assets: PreviewAssets }
42
+ // Shows the story in light or dark mode, e.g. to match the host's own theme. A story's own
43
+ // CSS can still override it, e.g. with ":root { color-scheme: light; }".
44
+ | { type: "theme"; theme: PreviewTheme };
45
+
46
+ export type PreviewMessage =
47
+ // The page has loaded and is listening
48
+ | { type: "ready" }
49
+ // A story from a load message has started
50
+ | { type: "loaded" }
51
+ // An attribute was set. Internal attributes, whose names start with "_", aren't sent.
52
+ | { type: "attributeSet"; name: string; value: unknown }
53
+ | { type: "canGoBackChanged"; canGoBack: boolean }
54
+ // A section or passage was shown, or Back went to one
55
+ | { type: "navigated"; section: string; passage?: string }
56
+ // An error from the story's JavaScript or the runtime
57
+ | { type: "runtimeError"; message: string; stack?: string };
58
+
59
+ export type Envelope<T> = T & { channel: typeof PREVIEW_CHANNEL };
60
+
61
+ export const isEnvelope = <T extends { type: string }>(data: unknown): data is Envelope<T> =>
62
+ typeof data == "object" && data !== null && (data as { channel?: unknown }).channel === PREVIEW_CHANNEL
63
+ && typeof (data as { type?: unknown }).type == "string";
@@ -0,0 +1,33 @@
1
+ // The entry point of the preview page (squiffy.preview.html), which is built as one
2
+ // self-contained file. It talks to its host with postMessage: to the parent window when it's in
3
+ // an iframe, or through acquireVsCodeApi() in a VS Code webview.
4
+
5
+ import { createPreview, errorMessage } from "./preview.js";
6
+ import { Envelope, HostMessage, isEnvelope, PREVIEW_CHANNEL, PreviewMessage } from "./preview-protocol.js";
7
+
8
+ declare const acquireVsCodeApi: undefined | (() => { postMessage(message: unknown): void });
9
+
10
+ const vscode = typeof acquireVsCodeApi == "function" ? acquireVsCodeApi() : undefined;
11
+
12
+ const post = (message: PreviewMessage) => {
13
+ const envelope: Envelope<PreviewMessage> = { channel: PREVIEW_CHANNEL, ...message };
14
+ if (vscode) vscode.postMessage(envelope);
15
+ else window.parent.postMessage(envelope, "*");
16
+ };
17
+
18
+ const preview = createPreview({
19
+ element: document.getElementById("squiffy")!,
20
+ send: post,
21
+ });
22
+
23
+ window.addEventListener("message", event => {
24
+ // In an iframe, only the parent can drive the preview
25
+ if (!vscode && event.source !== window.parent) return;
26
+ if (!isEnvelope<HostMessage>(event.data)) return;
27
+ preview.receive(event.data);
28
+ });
29
+
30
+ window.addEventListener("error", event => post(errorMessage(event.error ?? event.message)));
31
+ window.addEventListener("unhandledrejection", event => post(errorMessage(event.reason)));
32
+
33
+ post({ type: "ready" });
@@ -0,0 +1,181 @@
1
+ import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
2
+ import globalJsdom from "global-jsdom";
3
+ import { compile } from "squiffy-compiler";
4
+ import { createPreview } from "./preview.js";
5
+ import type { PreviewMessage } from "./preview-protocol.js";
6
+ import type { Story } from "./types.js";
7
+
8
+ beforeAll(() => {
9
+ vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
10
+ });
11
+
12
+ let cleanup: () => void;
13
+ let objectUrls: string[];
14
+
15
+ beforeEach(() => {
16
+ cleanup = globalJsdom("<!DOCTYPE html><html><head></head><body><div id=\"squiffy\"></div></body></html>");
17
+ objectUrls = [];
18
+ // jsdom has no object URLs
19
+ URL.createObjectURL = () => {
20
+ const url = `blob:preview/${objectUrls.length}`;
21
+ objectUrls.push(url);
22
+ return url;
23
+ };
24
+ URL.revokeObjectURL = () => {};
25
+ // Nor scrolling, which the preview's scroll: "element" uses
26
+ window.Element.prototype.scrollIntoView = () => {};
27
+ });
28
+
29
+ afterEach(() => {
30
+ cleanup();
31
+ });
32
+
33
+ // The compiled story module, as a host would send it
34
+ const compileJs = async (script: string) => {
35
+ const result = await compile({ script });
36
+ if (!result.success) throw new Error("Compile failed");
37
+ return result.getJs();
38
+ };
39
+
40
+ // Node can't import from blob URLs, so evaluate the module's one export here instead
41
+ const loadModule = async (js: string) => {
42
+ const body = js.replace("export const story = {};", "const story = {};") + "\nreturn story;";
43
+ return { story: new Function(body)() as Story };
44
+ };
45
+
46
+ const setUp = () => {
47
+ const messages: PreviewMessage[] = [];
48
+ const element = document.getElementById("squiffy")!;
49
+ const preview = createPreview({ element, send: m => messages.push(m), loadModule });
50
+ return { preview, messages, element };
51
+ };
52
+
53
+ const script = `@title Test
54
+ [[start]]:
55
+ @set score=1
56
+ Welcome. Go to the [[cellar]] or [look].
57
+
58
+ [look]:
59
+ @set looked
60
+ You look around. ![A cat](images/cat.png)
61
+
62
+ [[cellar]]:
63
+ It's dark down here.
64
+ `;
65
+
66
+ describe("preview", () => {
67
+ test("loads a story and reports what happens", async () => {
68
+ const { preview, messages, element } = setUp();
69
+ await preview.receive({ type: "load", story: { js: await compileJs(script) } });
70
+
71
+ expect(element.textContent).toContain("Welcome.");
72
+ expect(messages).toEqual([
73
+ { type: "canGoBackChanged", canGoBack: false },
74
+ { type: "attributeSet", name: "score", value: 1 },
75
+ { type: "navigated", section: "start" },
76
+ { type: "loaded" },
77
+ ]);
78
+
79
+ messages.length = 0;
80
+ element.querySelector<HTMLElement>("a[data-passage='look']")!.click();
81
+ await vi.waitFor(() => expect(messages.some(m => m.type == "navigated")).toBe(true));
82
+ expect(messages).toEqual([
83
+ { type: "attributeSet", name: "looked", value: true },
84
+ { type: "canGoBackChanged", canGoBack: true },
85
+ { type: "navigated", section: "start", passage: "look" },
86
+ ]);
87
+
88
+ messages.length = 0;
89
+ await preview.receive({ type: "back" });
90
+ expect(element.textContent).not.toContain("You look around");
91
+ expect(messages).toContainEqual({ type: "navigated", section: "start" });
92
+ expect(messages).toContainEqual({ type: "canGoBackChanged", canGoBack: false });
93
+ });
94
+
95
+ test("starts at a section or a passage", async () => {
96
+ const { preview, messages, element } = setUp();
97
+ const js = await compileJs(script);
98
+
99
+ await preview.receive({ type: "load", story: { js }, startAt: { section: "cellar" } });
100
+ expect(element.textContent).toContain("It's dark");
101
+ expect(element.textContent).not.toContain("Welcome");
102
+
103
+ messages.length = 0;
104
+ await preview.receive({ type: "load", story: { js }, startAt: { section: "start", passage: "look" } });
105
+ expect(element.textContent).toContain("Welcome.");
106
+ expect(element.textContent).toContain("You look around.");
107
+ expect(messages.filter(m => m.type == "navigated")).toEqual([
108
+ { type: "navigated", section: "start" },
109
+ { type: "navigated", section: "start", passage: "look" },
110
+ ]);
111
+
112
+ // An unknown section starts from the beginning
113
+ await preview.receive({ type: "load", story: { js }, startAt: { section: "nowhere" } });
114
+ expect(element.textContent).toContain("Welcome.");
115
+ });
116
+
117
+ test("resolves assets to object URLs it makes itself", async () => {
118
+ const { preview, element } = setUp();
119
+ await preview.receive({
120
+ type: "assets",
121
+ assets: { files: { "./images/cat.png": new Uint8Array([1, 2, 3]) }, urls: { "other.png": "https://example.com/other.png" } },
122
+ });
123
+ await preview.receive({ type: "load", story: { js: await compileJs(script) }, startAt: { section: "start", passage: "look" } });
124
+ expect(element.querySelector("img")!.getAttribute("src")).toBe(objectUrls[0]);
125
+ });
126
+
127
+ test("restart, and hot updates that keep the story's state", async () => {
128
+ const { preview, element } = setUp();
129
+ await preview.receive({ type: "load", story: { js: await compileJs(script) } });
130
+ element.querySelector<HTMLElement>("a[data-section='cellar']")!.click();
131
+ await vi.waitFor(() => expect(element.textContent).toContain("It's dark"));
132
+
133
+ await preview.receive({ type: "update", js: await compileJs(script.replace("It's dark", "It's pitch black")) });
134
+ expect(element.textContent).toContain("It's pitch black");
135
+ expect(element.textContent).toContain("Welcome.");
136
+
137
+ await preview.receive({ type: "restart" });
138
+ await vi.waitFor(() => expect(element.textContent).not.toContain("pitch black"));
139
+ expect(element.textContent).toContain("Welcome.");
140
+ });
141
+
142
+ test("adds the story's stylesheets, replacing the previous story's", async () => {
143
+ const { preview } = setUp();
144
+ const js = await compileJs(script);
145
+ await preview.receive({ type: "load", story: { js, css: ["body { color: red; }"] } });
146
+ await preview.receive({ type: "load", story: { js, css: ["body { color: blue; }"] } });
147
+ // After the preview's own (empty) theme style
148
+ expect([...document.head.querySelectorAll("style")].map(s => s.textContent)).toEqual(["", "body { color: blue; }"]);
149
+ });
150
+
151
+ test("sets the theme before the story's stylesheets, so they can override it", async () => {
152
+ const { preview } = setUp();
153
+ const js = await compileJs(script);
154
+ await preview.receive({ type: "load", story: { js, css: [":root { color-scheme: light; }"] } });
155
+ await preview.receive({ type: "theme", theme: "dark" });
156
+ const styles = () => [...document.head.querySelectorAll("style")].map(s => s.textContent);
157
+ expect(styles()).toEqual([":root { color-scheme: dark; }", ":root { color-scheme: light; }"]);
158
+
159
+ await preview.receive({ type: "theme", theme: "system" });
160
+ expect(styles()[0]).toBe("");
161
+ });
162
+
163
+ test("reports errors", async () => {
164
+ const messages: PreviewMessage[] = [];
165
+ const preview = createPreview({
166
+ element: document.getElementById("squiffy")!,
167
+ send: m => messages.push(m),
168
+ loadModule: async () => { throw new Error("Bad story"); },
169
+ });
170
+ await preview.receive({ type: "load", story: { js: "" } });
171
+ expect(messages).toMatchObject([{ type: "runtimeError", message: "Bad story" }]);
172
+ });
173
+
174
+ test("ignores messages for a story that hasn't loaded", async () => {
175
+ const { preview, messages } = setUp();
176
+ await preview.receive({ type: "restart" });
177
+ await preview.receive({ type: "back" });
178
+ await preview.receive({ type: "update", js: await compileJs(script) });
179
+ expect(messages).toEqual([]);
180
+ });
181
+ });
package/src/preview.ts ADDED
@@ -0,0 +1,171 @@
1
+ // The preview page's logic: runs stories sent by a host, and reports back what happens. The
2
+ // page itself (preview.main.ts) connects this to postMessage; it's separate so it can be tested.
3
+
4
+ import { init } from "./squiffy.runtime.js";
5
+ import type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory } from "./preview-protocol.js";
6
+ import type { SquiffyApi, Story } from "./types.js";
7
+
8
+ export interface PreviewOptions {
9
+ // Where to show the story
10
+ element: HTMLElement;
11
+ send(message: PreviewMessage): void;
12
+ // Loads a compiled story module. By default it's imported from a blob URL, so story
13
+ // JavaScript runs without new Function (and so without unsafe-eval in a CSP).
14
+ loadModule?(js: string): Promise<{ story: Story }>;
15
+ }
16
+
17
+ const mimeTypes: Record<string, string> = {
18
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp",
19
+ avif: "image/avif", svg: "image/svg+xml", ico: "image/x-icon", bmp: "image/bmp",
20
+ mp3: "audio/mpeg", ogg: "audio/ogg", oga: "audio/ogg", wav: "audio/wav", m4a: "audio/mp4", flac: "audio/flac",
21
+ mp4: "video/mp4", webm: "video/webm", ogv: "video/ogg",
22
+ woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",
23
+ pdf: "application/pdf", vtt: "text/vtt",
24
+ };
25
+
26
+ const mimeType = (path: string) => mimeTypes[path.substring(path.lastIndexOf(".") + 1).toLowerCase()] ?? "";
27
+
28
+ const normalisePath = (path: string) => path.replace(/^(\.\/)+/, "");
29
+
30
+ async function importFromBlob(js: string): Promise<{ story: Story }> {
31
+ const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
32
+ try {
33
+ return await import(/* @vite-ignore */ url);
34
+ }
35
+ finally {
36
+ URL.revokeObjectURL(url);
37
+ }
38
+ }
39
+
40
+ function errorMessage(error: unknown): PreviewMessage {
41
+ if (error instanceof Error) {
42
+ return { type: "runtimeError", message: error.message, ...(error.stack ? { stack: error.stack } : {}) };
43
+ }
44
+ return { type: "runtimeError", message: String(error) };
45
+ }
46
+
47
+ export function createPreview(options: PreviewOptions) {
48
+ const loadModule = options.loadModule ?? importFromBlob;
49
+ let api: SquiffyApi | undefined;
50
+ // Each load gets a new number, so a slow load that's been replaced doesn't start
51
+ let loadCount = 0;
52
+ const assetUrls = new Map<string, string>();
53
+ const objectUrls: string[] = [];
54
+ const injected: Element[] = [];
55
+ // Sets the theme. It's added before any of the story's own stylesheets, so they can override it.
56
+ const themeStyle = document.createElement("style");
57
+ document.head.appendChild(themeStyle);
58
+
59
+ const send = (message: PreviewMessage) => {
60
+ try {
61
+ options.send(message);
62
+ }
63
+ catch {
64
+ // e.g. an attribute value that can't be cloned
65
+ if (message.type == "attributeSet") options.send({ ...message, value: String(message.value) });
66
+ }
67
+ };
68
+
69
+ const resolveAssetUrl = (path: string) => assetUrls.get(normalisePath(path)) ?? path;
70
+
71
+ function setAssets(assets: PreviewAssets) {
72
+ for (const url of objectUrls.splice(0)) URL.revokeObjectURL(url);
73
+ assetUrls.clear();
74
+ for (const [path, url] of Object.entries(assets.urls ?? {})) {
75
+ assetUrls.set(normalisePath(path), url);
76
+ }
77
+ for (const [path, data] of Object.entries(assets.files ?? {})) {
78
+ const blob = data instanceof Blob ? data : new Blob([data as BlobPart], { type: mimeType(path) });
79
+ const url = URL.createObjectURL(blob);
80
+ objectUrls.push(url);
81
+ assetUrls.set(normalisePath(path), url);
82
+ }
83
+ }
84
+
85
+ async function addStoryFiles(story: PreviewStory) {
86
+ for (const element of injected.splice(0)) element.remove();
87
+ for (const css of story.css ?? []) {
88
+ const style = document.createElement("style");
89
+ style.textContent = css;
90
+ document.head.appendChild(style);
91
+ injected.push(style);
92
+ }
93
+ for (const js of story.scripts ?? []) {
94
+ const script = document.createElement("script");
95
+ const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
96
+ await new Promise<void>(resolve => {
97
+ script.onload = script.onerror = () => resolve();
98
+ script.src = url;
99
+ document.head.appendChild(script);
100
+ });
101
+ URL.revokeObjectURL(url);
102
+ injected.push(script);
103
+ }
104
+ }
105
+
106
+ async function load(message: Extract<HostMessage, { type: "load" }>) {
107
+ const thisLoad = ++loadCount;
108
+ api = undefined;
109
+ options.element.innerHTML = "";
110
+ await addStoryFiles(message.story);
111
+ const { story } = await loadModule(message.story.js);
112
+ if (thisLoad != loadCount) return;
113
+
114
+ const container = document.createElement("div");
115
+ container.className = "squiffy-preview-story";
116
+ options.element.appendChild(container);
117
+
118
+ const newApi = await init({
119
+ element: container,
120
+ story,
121
+ persist: false,
122
+ scroll: "element",
123
+ resolveAssetUrl,
124
+ onSet: (name, value) => {
125
+ if (thisLoad == loadCount && !name.startsWith("_")) send({ type: "attributeSet", name, value });
126
+ },
127
+ });
128
+ newApi.on("canGoBackChanged", e => {
129
+ if (thisLoad == loadCount) send({ type: "canGoBackChanged", canGoBack: e.canGoBack });
130
+ });
131
+ newApi.on("navigated", e => {
132
+ if (thisLoad == loadCount) send({ type: "navigated", ...e });
133
+ });
134
+ api = newApi;
135
+ send({ type: "canGoBackChanged", canGoBack: false });
136
+ await newApi.begin(message.startAt);
137
+ if (thisLoad == loadCount) send({ type: "loaded" });
138
+ }
139
+
140
+ async function receive(message: HostMessage) {
141
+ try {
142
+ switch (message.type) {
143
+ case "load":
144
+ await load(message);
145
+ break;
146
+ case "update":
147
+ if (api) api.update((await loadModule(message.js)).story);
148
+ break;
149
+ case "restart":
150
+ api?.restart();
151
+ break;
152
+ case "back":
153
+ api?.goBack();
154
+ break;
155
+ case "assets":
156
+ setAssets(message.assets);
157
+ break;
158
+ case "theme":
159
+ themeStyle.textContent = message.theme == "system" ? "" : `:root { color-scheme: ${message.theme}; }`;
160
+ break;
161
+ }
162
+ }
163
+ catch (error) {
164
+ send(errorMessage(error));
165
+ }
166
+ }
167
+
168
+ return { receive };
169
+ }
170
+
171
+ export { errorMessage };