squiffy-runtime 6.0.1 → 7.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.d.ts CHANGED
@@ -6,14 +6,25 @@ export interface SquiffyInitOptions {
6
6
  persist?: boolean;
7
7
  storyId?: string;
8
8
  onSet?: (attribute: string, value: any) => void;
9
+ /**
10
+ * Maps an asset path used in the story (e.g. "cat.png" in an img src) to the URL it should be
11
+ * loaded from. Applied to src, srcset and poster attributes, and url() in inline styles, of
12
+ * rendered output. Absolute URLs (http:, https:, data:, blob: etc. and protocol-relative) are
13
+ * left alone. When not provided, paths are used as they are.
14
+ */
15
+ resolveAssetUrl?: (path: string) => string;
9
16
  }
10
17
  export interface SquiffySettings {
11
18
  scroll: string;
12
19
  persist: boolean;
13
20
  onSet: (attribute: string, value: any) => void;
14
21
  }
22
+ export interface StartAt {
23
+ section: string;
24
+ passage?: string;
25
+ }
15
26
  export interface SquiffyApi {
16
- begin: () => Promise<void>;
27
+ begin: (startAt?: StartAt) => Promise<void>;
17
28
  restart: () => void;
18
29
  get: (attribute: string) => any;
19
30
  set: (attribute: string, value: any) => void;
@@ -19,6 +19,7 @@ export interface PluginHost {
19
19
  getSectionText(name: string): string | null;
20
20
  getPassageText(name: string): string | null;
21
21
  processText: (text: string, inline: boolean) => string;
22
+ resolveAssetsInHtml: (html: string) => string;
22
23
  addTransition: (fn: () => Promise<void>) => void;
23
24
  animation: Animation;
24
25
  on<E extends keyof SquiffyEventMap>(event: E, handler: SquiffyEventHandler<E>): () => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squiffy-runtime",
3
- "version": "6.0.1",
3
+ "version": "7.0.0-beta.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/textadventures/squiffy.git",
@@ -8,20 +8,29 @@
8
8
  },
9
9
  "type": "module",
10
10
  "main": "dist/squiffy.runtime.js",
11
- "types": "dist/src/squiffy.runtime.d.ts",
11
+ "types": "dist/squiffy.runtime.d.ts",
12
12
  "exports": {
13
13
  ".": {
14
- "types": "./dist/src/squiffy.runtime.d.ts",
14
+ "types": "./dist/squiffy.runtime.d.ts",
15
15
  "default": "./dist/squiffy.runtime.js"
16
16
  },
17
17
  "./squiffy.runtime.css": "./dist/squiffy.runtime.css",
18
18
  "./dist/squiffy.runtime.global.js": "./dist/squiffy.runtime.global.js",
19
- "./dist/squiffy.runtime.css": "./dist/squiffy.runtime.css"
19
+ "./dist/squiffy.runtime.css": "./dist/squiffy.runtime.css",
20
+ "./preview-host": {
21
+ "types": "./dist/preview-host.d.ts",
22
+ "default": "./dist/preview-host.js"
23
+ },
24
+ "./preview-html": {
25
+ "types": "./dist/preview-html.d.ts",
26
+ "default": "./dist/preview-html.js"
27
+ },
28
+ "./squiffy.preview.html": "./dist/squiffy.preview.html"
20
29
  },
21
30
  "scripts": {
22
31
  "dev": "vitest",
23
32
  "test": "vitest --run",
24
- "build": "vite build",
33
+ "build": "vite build && vite build -c vite.preview.config.ts",
25
34
  "prepublishOnly": "npm run build && npm run test"
26
35
  },
27
36
  "author": "Alex Warren",
@@ -36,17 +45,17 @@
36
45
  "@types/jsdom": "^30.0.0",
37
46
  "css.escape": "^1.5.1",
38
47
  "esbuild": "^0.28.2",
39
- "global-jsdom": "^30.0.0",
40
- "jsdom": "^30.0.1",
41
- "squiffy-compiler": "^6.0.1",
48
+ "global-jsdom": "^31.0.0",
49
+ "jsdom": "^31.0.0",
50
+ "squiffy-compiler": "^7.0.0-beta.1",
42
51
  "typescript": "^6.0.3",
43
- "vite": "^8.3.4",
52
+ "vite": "^8.3.5",
44
53
  "vite-plugin-dts": "^5.1.2"
45
54
  },
46
55
  "dependencies": {
47
56
  "animejs": "^4.5.0",
48
57
  "handlebars": "^4.7.10",
49
- "marked": "^18.1.1"
58
+ "marked": "^18.1.2"
50
59
  },
51
- "gitHead": "e5186d77e730d0f055091299197c13edfe08c92e"
60
+ "gitHead": "558b8c3c0a4ce8d7a2e4eb0e9a439ecfc4c53a62"
52
61
  }
@@ -0,0 +1,227 @@
1
+ import { expect, test, beforeEach, afterEach, vi } from "vitest";
2
+ import globalJsdom from "global-jsdom";
3
+ import { init } from "./squiffy.runtime.js";
4
+ import { compile as squiffyCompile } from "squiffy-compiler";
5
+ import { SquiffyInitOptions } from "./types.js";
6
+
7
+ // anime.js captures the global document when it's imported, which is before each test
8
+ // sets up jsdom, so it can't run here. Replace it with a stub that completes immediately.
9
+ vi.mock("animejs", () => ({
10
+ animate: (_targets: unknown, params: { onComplete?: () => void }) => {
11
+ setTimeout(() => params.onComplete?.());
12
+ },
13
+ stagger: () => 0,
14
+ text: {
15
+ split: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
16
+ },
17
+ }));
18
+
19
+ const html = `
20
+ <!DOCTYPE html>
21
+ <html>
22
+ <body>
23
+ <div id="squiffy"></div>
24
+ </body>
25
+ </html>
26
+ `;
27
+
28
+ const compile = async (script: string) => {
29
+ const compileResult = await squiffyCompile({ script });
30
+ if (!compileResult.success) {
31
+ throw new Error("Compile failed");
32
+ }
33
+ const js = compileResult.output.js.map(jsLines => new Function("squiffy", "get", "set", jsLines.join("\n")));
34
+ return { js: js as any, ...compileResult.output.story };
35
+ };
36
+
37
+ const resolveAssetUrl = (path: string) => `blob:test/${path}`;
38
+
39
+ const initScript = async (script: string, options: Partial<SquiffyInitOptions> = {}) => {
40
+ const element = document.getElementById("squiffy")!;
41
+ const squiffyApi = await init({
42
+ element,
43
+ story: await compile(script),
44
+ persist: false,
45
+ ...options,
46
+ });
47
+ await squiffyApi.begin();
48
+ return { squiffyApi, element };
49
+ };
50
+
51
+ let cleanup: () => void;
52
+
53
+ beforeEach(() => {
54
+ cleanup = globalJsdom(html, { url: "http://localhost/" });
55
+ });
56
+
57
+ afterEach(() => {
58
+ localStorage.clear();
59
+ cleanup();
60
+ });
61
+
62
+ test("Asset paths are unchanged without resolveAssetUrl", async () => {
63
+ const { element } = await initScript(`![A cat](cat.png)
64
+
65
+ <img src="dog.png">`);
66
+ const images = element.querySelectorAll("img");
67
+ expect(images[0].getAttribute("src")).toBe("cat.png");
68
+ expect(images[1].getAttribute("src")).toBe("dog.png");
69
+ expect(element.innerHTML).not.toContain("data-squiffy-asset");
70
+ });
71
+
72
+ test("resolveAssetUrl is applied to img src from Markdown and HTML", async () => {
73
+ const { element } = await initScript(`![A cat](cat.png)
74
+
75
+ <img src="images/dog.png">`, { resolveAssetUrl });
76
+ const images = element.querySelectorAll("img");
77
+ expect(images[0].getAttribute("src")).toBe("blob:test/cat.png");
78
+ expect(images[0].getAttribute("alt")).toBe("A cat");
79
+ expect(images[1].getAttribute("src")).toBe("blob:test/images/dog.png");
80
+ });
81
+
82
+ test("resolveAssetUrl is applied to audio, video, source, poster and srcset", async () => {
83
+ const { element } = await initScript(`<audio src="music.mp3"></audio>
84
+ <video poster="poster.jpg"><source src="clip.webm" type="video/webm"></video>
85
+ <img srcset="small.png 1x, large.png 2x, https://example.com/x.png 3x">`, { resolveAssetUrl });
86
+ expect(element.querySelector("audio")!.getAttribute("src")).toBe("blob:test/music.mp3");
87
+ expect(element.querySelector("video")!.getAttribute("poster")).toBe("blob:test/poster.jpg");
88
+ expect(element.querySelector("source")!.getAttribute("src")).toBe("blob:test/clip.webm");
89
+ expect(element.querySelector("img")!.getAttribute("srcset"))
90
+ .toBe("blob:test/small.png 1x, blob:test/large.png 2x, https://example.com/x.png 3x");
91
+ });
92
+
93
+ test("resolveAssetUrl is applied to url() in inline styles", async () => {
94
+ const { element } = await initScript("<div id=\"bg\" style=\"background-image: url('bg.png'); color: red\"></div>", { resolveAssetUrl });
95
+ const style = element.querySelector("#bg")!.getAttribute("style");
96
+ expect(style).toBe("background-image: url(\"blob:test/bg.png\"); color: red");
97
+ });
98
+
99
+ test("Absolute URLs are not passed to resolveAssetUrl", async () => {
100
+ const paths: string[] = [];
101
+ const { element } = await initScript(`<img src="http://example.com/a.png">
102
+ <img src="https://example.com/b.png">
103
+ <img src="data:image/png;base64,AAAA">
104
+ <img src="blob:http://localhost/1234">
105
+ <img src="//example.com/c.png">
106
+ <img src="local.png">`, {
107
+ resolveAssetUrl: path => {
108
+ paths.push(path);
109
+ return resolveAssetUrl(path);
110
+ }
111
+ });
112
+ expect(paths).toEqual(["local.png"]);
113
+ const srcs = [...element.querySelectorAll("img")].map(img => img.getAttribute("src"));
114
+ expect(srcs).toEqual([
115
+ "http://example.com/a.png",
116
+ "https://example.com/b.png",
117
+ "data:image/png;base64,AAAA",
118
+ "blob:http://localhost/1234",
119
+ "//example.com/c.png",
120
+ "blob:test/local.png",
121
+ ]);
122
+ });
123
+
124
+ test("Percent-encoded paths are decoded before being passed to resolveAssetUrl", async () => {
125
+ const { element } = await initScript("<img src=\"my%20cat.png\">", { resolveAssetUrl });
126
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/my cat.png");
127
+ });
128
+
129
+ test("Links are not passed to resolveAssetUrl", async () => {
130
+ const { element } = await initScript(`<a href="page.html">link</a> [[next]]
131
+
132
+ [[next]]:
133
+ Next`, { resolveAssetUrl });
134
+ expect(element.querySelector("a[href]")!.getAttribute("href")).toBe("page.html");
135
+ });
136
+
137
+ test("resolveAssetUrl is applied to passages", async () => {
138
+ const { squiffyApi, element } = await initScript(`Click [here].
139
+
140
+ [here]:
141
+ ![A cat](cat.png)`, { resolveAssetUrl });
142
+ const link = [...element.querySelectorAll<HTMLElement>("a.link-passage")].find(a => a.textContent === "here")!;
143
+ await squiffyApi.clickLink(link);
144
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/cat.png");
145
+ });
146
+
147
+ test("resolveAssetUrl is applied when the story is updated", async () => {
148
+ const { squiffyApi, element } = await initScript("Hello", { resolveAssetUrl });
149
+ squiffyApi.update(await compile("Hello ![A cat](cat.png)"));
150
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/cat.png");
151
+ });
152
+
153
+ test("Saved output is resolved again when it's loaded", async () => {
154
+ const script = "![A cat](cat.png)";
155
+ const story = await compile(script);
156
+
157
+ // First run, e.g. in a previous editor session, where cat.png was a different blob URL
158
+ let element = document.getElementById("squiffy")!;
159
+ let api = await init({ element, story, persist: true, storyId: "assets-test", resolveAssetUrl: p => `blob:old/${p}` });
160
+ await api.begin();
161
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:old/cat.png");
162
+
163
+ // Load the saved output into a fresh element
164
+ element.innerHTML = "";
165
+ element = document.getElementById("squiffy")!;
166
+ api = await init({ element, story, persist: true, storyId: "assets-test", resolveAssetUrl: p => `blob:new/${p}` });
167
+ await api.begin();
168
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:new/cat.png");
169
+ });
170
+
171
+ test("Asset paths in animate blocks are unchanged without resolveAssetUrl", async () => {
172
+ const { element } = await initScript("{{#animate \"typewriter\"}}![A cat](cat.png){{/animate}}");
173
+ await vi.waitFor(() => expect(element.querySelector(".squiffy-animate")).toBeNull());
174
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("cat.png");
175
+ expect(element.innerHTML).not.toContain("data-squiffy-asset");
176
+ });
177
+
178
+ test("resolveAssetUrl is applied to inline animate content", async () => {
179
+ const { element } = await initScript("{{#animate \"typewriter\"}}![A cat](cat.png){{/animate}}", { resolveAssetUrl });
180
+ await vi.waitFor(() => expect(element.querySelector(".squiffy-animate")).toBeNull());
181
+ // The content is restored after the animation completes, so check it's still resolved
182
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/cat.png");
183
+ });
184
+
185
+ test("resolveAssetUrl is applied to block animate content", async () => {
186
+ const { element } = await initScript(`{{#animate "typewriter"}}
187
+ ![A cat](cat.png)
188
+
189
+ <img src="dog.png">
190
+ {{/animate}}`, { resolveAssetUrl });
191
+ await vi.waitFor(() => expect(element.querySelector(".squiffy-animate")).toBeNull());
192
+ const srcs = [...element.querySelectorAll("img")].map(img => img.getAttribute("src"));
193
+ expect(srcs).toEqual(["blob:test/cat.png", "blob:test/dog.png"]);
194
+ });
195
+
196
+ test("resolveAssetUrl is applied to animate content waiting for a link trigger", async () => {
197
+ const { element } = await initScript(`{{#animate "typewriter" trigger="link"}}![A cat](cat.png) [next]{{/animate}}
198
+
199
+ [next]:
200
+ Next`, { resolveAssetUrl });
201
+ expect(element.querySelector(".squiffy-animate img")!.getAttribute("src")).toBe("blob:test/cat.png");
202
+ });
203
+
204
+ test("Saved animate content is resolved again when it's loaded", async () => {
205
+ const script = `{{#animate "typewriter" trigger="link"}}![A cat](cat.png) [next]{{/animate}}
206
+
207
+ {{#animate "typewriter"}}![A dog](dog.png){{/animate}}
208
+
209
+ [next]:
210
+ Next`;
211
+ const story = await compile(script);
212
+ const srcs = (element: HTMLElement) => [...element.querySelectorAll("img")].map(img => img.getAttribute("src"));
213
+
214
+ let element = document.getElementById("squiffy")!;
215
+ let api = await init({ element, story, persist: true, storyId: "assets-animate-test", resolveAssetUrl: p => `blob:old/${p}` });
216
+ await api.begin();
217
+ await vi.waitFor(() => expect(element.querySelectorAll(".squiffy-animate").length).toBe(1));
218
+ expect(srcs(element)).toEqual(["blob:old/cat.png", "blob:old/dog.png"]);
219
+
220
+ // Load the saved output: the pending (link-triggered) animation is rendered again from
221
+ // its stored content, and the completed one is re-resolved with the rest of the output.
222
+ element.innerHTML = "";
223
+ element = document.getElementById("squiffy")!;
224
+ api = await init({ element, story, persist: true, storyId: "assets-animate-test", resolveAssetUrl: p => `blob:new/${p}` });
225
+ await api.begin();
226
+ expect(srcs(element)).toEqual(["blob:new/cat.png", "blob:new/dog.png"]);
227
+ });
package/src/assets.ts ADDED
@@ -0,0 +1,92 @@
1
+ // Support for the resolveAssetUrl init option, which maps asset paths in story output (e.g. "cat.png")
2
+ // to the URLs they should load from (e.g. a blob: URL in the editor preview, or a data: URI in a
3
+ // single-file export).
4
+ //
5
+ // We rewrite the HTML string before it's inserted into the page, so the browser never requests the
6
+ // unresolved path. The original value is kept in a data-squiffy-asset-* attribute, so that output
7
+ // saved to localStorage (which will contain resolved URLs that may no longer be valid, e.g. blob: URLs)
8
+ // can be resolved again when it's restored.
9
+
10
+ export type AssetUrlResolver = (path: string) => string;
11
+
12
+ // Attributes that contain a single URL.
13
+ const urlAttributes = ["src", "poster"];
14
+
15
+ const originalPrefix = "data-squiffy-asset-";
16
+
17
+ const selector = [...urlAttributes, "srcset", "style"].map(a => `[${a}]`).join(",");
18
+
19
+ // Anything with a scheme (http:, https:, data:, blob:, mailto: etc.), protocol-relative URLs,
20
+ // and fragment-only references are left alone.
21
+ const isAbsolute = (url: string) => /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//") || url.startsWith("#");
22
+
23
+ const resolveUrl = (url: string, resolve: AssetUrlResolver): string => {
24
+ const trimmed = url.trim();
25
+ if (!trimmed || isAbsolute(trimmed)) return url;
26
+ let path = trimmed;
27
+ try {
28
+ // Markdown (and authors) may percent-encode paths, e.g. "my%20cat.png". The resolver
29
+ // works with file paths, so give it "my cat.png".
30
+ path = decodeURI(trimmed);
31
+ } catch {
32
+ // Not valid percent-encoding - pass it through as it is
33
+ }
34
+ return resolve(path);
35
+ };
36
+
37
+ // srcset is a comma-separated list of "url [descriptor]" candidates.
38
+ const resolveSrcset = (srcset: string, resolve: AssetUrlResolver) =>
39
+ srcset.split(",").map(candidate => {
40
+ const match = candidate.match(/^(\s*)(\S+)(.*)$/s);
41
+ if (!match) return candidate;
42
+ return match[1] + resolveUrl(match[2], resolve) + match[3];
43
+ }).join(",");
44
+
45
+ // CSS url(...) references in inline style attributes.
46
+ const resolveCssUrls = (css: string, resolve: AssetUrlResolver) =>
47
+ css.replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (whole, _quote: string, url: string) => {
48
+ const resolved = resolveUrl(url, resolve);
49
+ if (resolved === url) return whole;
50
+ return `url("${resolved.replace(/["\\\n]/g, c => "\\" + (c === "\n" ? "a " : c))}")`;
51
+ });
52
+
53
+ const resolveAttribute = (el: Element, attribute: string, resolve: AssetUrlResolver) => {
54
+ const originalAttribute = originalPrefix + attribute;
55
+ const original = el.getAttribute(originalAttribute) ?? el.getAttribute(attribute);
56
+ if (original === null) return;
57
+
58
+ let resolved: string;
59
+ if (attribute === "srcset") {
60
+ resolved = resolveSrcset(original, resolve);
61
+ } else if (attribute === "style") {
62
+ resolved = resolveCssUrls(original, resolve);
63
+ } else {
64
+ resolved = resolveUrl(original, resolve);
65
+ }
66
+
67
+ if (resolved === original) {
68
+ el.removeAttribute(originalAttribute);
69
+ } else {
70
+ el.setAttribute(originalAttribute, original);
71
+ }
72
+ el.setAttribute(attribute, resolved);
73
+ };
74
+
75
+ // Returns a function that rewrites asset URLs in an HTML string. With no resolver, HTML is returned unchanged.
76
+ export const createAssetHtmlResolver = (resolve: AssetUrlResolver | undefined) => (html: string): string => {
77
+ if (!resolve) return html;
78
+ // Quick check to avoid parsing HTML that can't contain anything to resolve.
79
+ if (!/\b(src|srcset|poster|style)\s*=/i.test(html)) return html;
80
+
81
+ // A <template>'s content is inert, so parsing into it doesn't start loading any images.
82
+ const template = document.createElement("template");
83
+ template.innerHTML = html;
84
+ for (const el of template.content.querySelectorAll(selector)) {
85
+ for (const attribute of [...urlAttributes, "srcset", "style"]) {
86
+ if (el.hasAttribute(attribute)) {
87
+ resolveAttribute(el, attribute, resolve);
88
+ }
89
+ }
90
+ }
91
+ return template.innerHTML;
92
+ };
package/src/events.ts CHANGED
@@ -4,6 +4,7 @@ export type SquiffyEventMap = {
4
4
  linkClick: { linkType: string }; // a story link was clicked
5
5
  set: { attribute: string, value: any }; // an attribute was set
6
6
  canGoBackChanged: { canGoBack: boolean }; // whether the "back" button should be enabled
7
+ navigated: { section: string, passage?: string }; // a section or passage was shown, or Back went to one
7
8
  };
8
9
 
9
10
  export type SquiffyEventHandler<E extends keyof SquiffyEventMap> =
@@ -13,6 +13,7 @@ export class PluginManager {
13
13
  getSectionText: (name: string) => string | null;
14
14
  getPassageText: (name: string) => string | null;
15
15
  processText: (text: string, inline: boolean) => string;
16
+ resolveAssetsInHtml: (html: string) => string;
16
17
  addTransition: (fn: () => Promise<void>) => void;
17
18
  emitter: Emitter<SquiffyEventMap>;
18
19
  plugins: SquiffyPlugin[] = [];
@@ -27,7 +28,8 @@ export class PluginManager {
27
28
  processText: (text: string, inline: boolean) => string,
28
29
  addTransition: (fn: () => Promise<void>) => void,
29
30
  animation: Animation,
30
- emitter: Emitter<SquiffyEventMap>) {
31
+ emitter: Emitter<SquiffyEventMap>,
32
+ resolveAssetsInHtml: (html: string) => string) {
31
33
  this.outputElement = outputElement;
32
34
  this.textProcessor = textProcessor;
33
35
  this.state = state;
@@ -38,6 +40,7 @@ export class PluginManager {
38
40
  this.addTransition = addTransition;
39
41
  this.animation = animation;
40
42
  this.emitter = emitter;
43
+ this.resolveAssetsInHtml = resolveAssetsInHtml;
41
44
  }
42
45
 
43
46
  add(plugin: SquiffyPlugin) {
@@ -54,6 +57,7 @@ export class PluginManager {
54
57
  getSectionText: this.getSectionText,
55
58
  getPassageText: this.getPassageText,
56
59
  processText: this.processText,
60
+ resolveAssetsInHtml: this.resolveAssetsInHtml,
57
61
  addTransition: this.addTransition,
58
62
  animation: this.animation,
59
63
  on: (e, h) => this.emitter.on(e, h),
@@ -32,12 +32,13 @@ export function AnimatePlugin(): SquiffyPlugin {
32
32
  if (!params.content) {
33
33
  continue;
34
34
  }
35
+ // The content is stored unrendered in data-content, so asset URLs in it haven't been
36
+ // resolved yet. On load it's rendered again, so it picks up the current resolver.
35
37
  const isBlock = params.content.includes("\n\n");
36
- if (isBlock) {
37
- el.innerHTML = marked.parse(params.content, { async: false }).trim();
38
- } else {
39
- el.innerHTML = marked.parseInline(params.content, { async: false }).trim();
40
- }
38
+ const html = isBlock
39
+ ? marked.parse(params.content, { async: false })
40
+ : marked.parseInline(params.content, { async: false });
41
+ el.innerHTML = squiffy.resolveAssetsInHtml(html.trim());
41
42
 
42
43
  if (!params.name) {
43
44
  continue;
@@ -0,0 +1,75 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import { createPreviewHost, PreviewChannel } from "./preview-host.js";
3
+ import { PREVIEW_CHANNEL } from "./preview-protocol.js";
4
+
5
+ const fakeChannel = () => {
6
+ const sent: unknown[] = [];
7
+ let handler: ((data: unknown) => void) | undefined;
8
+ const channel: PreviewChannel = {
9
+ send: m => sent.push(m),
10
+ onMessage: h => {
11
+ handler = h;
12
+ return () => { handler = undefined; };
13
+ },
14
+ };
15
+ return { channel, sent, receive: (data: unknown) => handler?.(data) };
16
+ };
17
+
18
+ describe("preview host", () => {
19
+ test("queues messages until the page is ready", async () => {
20
+ const { channel, sent, receive } = fakeChannel();
21
+ const host = createPreviewHost(channel);
22
+ host.setAssets({ urls: { "a.png": "https://example.com/a.png" } });
23
+ host.load({ js: "export const story = {};" }, { startAt: { section: "s", passage: "p" } });
24
+ expect(sent).toEqual([]);
25
+
26
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
27
+ await host.ready;
28
+ expect(sent).toEqual([
29
+ { channel: PREVIEW_CHANNEL, type: "assets", assets: { urls: { "a.png": "https://example.com/a.png" } } },
30
+ { channel: PREVIEW_CHANNEL, type: "load", story: { js: "export const story = {};" }, startAt: { section: "s", passage: "p" } },
31
+ ]);
32
+
33
+ host.update("x");
34
+ host.restart();
35
+ host.back();
36
+ expect(sent.slice(2)).toEqual([
37
+ { channel: PREVIEW_CHANNEL, type: "update", js: "x" },
38
+ { channel: PREVIEW_CHANNEL, type: "restart" },
39
+ { channel: PREVIEW_CHANNEL, type: "back" },
40
+ ]);
41
+ });
42
+
43
+ test("passes messages from the page to handlers, ignoring anything else", () => {
44
+ const { channel, receive } = fakeChannel();
45
+ const handlers = {
46
+ onReady: vi.fn(), onLoaded: vi.fn(), onAttributeSet: vi.fn(), onCanGoBackChanged: vi.fn(),
47
+ onNavigated: vi.fn(), onRuntimeError: vi.fn(),
48
+ };
49
+ const host = createPreviewHost(channel, handlers);
50
+ receive({ type: "navigated", section: "not ours" });
51
+ receive("hello");
52
+ receive(null);
53
+ for (const message of [
54
+ { type: "ready" },
55
+ { type: "loaded" },
56
+ { type: "attributeSet", name: "score", value: 2 },
57
+ { type: "canGoBackChanged", canGoBack: true },
58
+ { type: "navigated", section: "s", passage: "p" },
59
+ { type: "runtimeError", message: "oops", stack: "at x" },
60
+ ]) {
61
+ receive({ channel: PREVIEW_CHANNEL, ...message });
62
+ }
63
+ expect(handlers.onReady).toHaveBeenCalledOnce();
64
+ expect(handlers.onLoaded).toHaveBeenCalledOnce();
65
+ expect(handlers.onAttributeSet).toHaveBeenCalledWith("score", 2);
66
+ expect(handlers.onCanGoBackChanged).toHaveBeenCalledWith(true);
67
+ expect(handlers.onNavigated).toHaveBeenCalledOnce();
68
+ expect(handlers.onNavigated).toHaveBeenCalledWith("s", "p");
69
+ expect(handlers.onRuntimeError).toHaveBeenCalledWith("oops", "at x");
70
+
71
+ host.dispose();
72
+ receive({ channel: PREVIEW_CHANNEL, type: "loaded" });
73
+ expect(handlers.onLoaded).toHaveBeenCalledOnce();
74
+ });
75
+ });