squiffy-runtime 6.0.0 → 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/assets.d.ts +2 -0
- package/dist/assets.test.d.ts +1 -0
- package/dist/events.d.ts +4 -0
- package/dist/pluginManager.d.ts +2 -1
- package/dist/preview-host.d.ts +29 -0
- package/dist/preview-host.js +83 -0
- package/dist/preview-host.js.map +7 -0
- package/dist/preview-host.test.d.ts +1 -0
- package/dist/preview-html.d.ts +2 -0
- package/dist/preview-html.js +2 -0
- package/dist/preview-protocol.d.ts +53 -0
- package/dist/preview.d.ts +14 -0
- package/dist/preview.main.d.ts +1 -0
- package/dist/preview.test.d.ts +1 -0
- package/dist/squiffy.preview.html +298 -0
- package/dist/squiffy.runtime.global.js +58 -53
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +2146 -1996
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/types.d.ts +12 -1
- package/dist/types.plugins.d.ts +1 -0
- package/package.json +21 -12
- package/src/assets.test.ts +227 -0
- package/src/assets.ts +92 -0
- package/src/events.ts +1 -0
- package/src/pluginManager.ts +5 -1
- package/src/plugins/animate.ts +6 -5
- package/src/preview-host.test.ts +75 -0
- package/src/preview-host.ts +129 -0
- package/src/preview-protocol.ts +57 -0
- package/src/preview.main.ts +33 -0
- package/src/preview.test.ts +168 -0
- package/src/preview.ts +165 -0
- package/src/squiffy.runtime.ts +25 -6
- package/src/types.plugins.ts +4 -0
- package/src/types.ts +17 -1
- package/vite.preview.config.ts +72 -0
|
@@ -0,0 +1,129 @@
|
|
|
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, StartAt,
|
|
16
|
+
} from "./preview-protocol.js";
|
|
17
|
+
|
|
18
|
+
export type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory, 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
|
+
dispose(): void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Sandboxes an iframe and loads the preview page into it. The sandbox allows scripts only, so the
|
|
52
|
+
// story runs with an opaque origin: it can't reach the host page, its storage or its cookies.
|
|
53
|
+
export function setUpPreviewFrame(iframe: HTMLIFrameElement, previewHtml: string) {
|
|
54
|
+
iframe.setAttribute("sandbox", "allow-scripts");
|
|
55
|
+
iframe.srcdoc = previewHtml;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A channel to a preview page in an iframe
|
|
59
|
+
export function iframeChannel(iframe: HTMLIFrameElement): PreviewChannel {
|
|
60
|
+
return {
|
|
61
|
+
// The page has an opaque origin, so there's no origin to target
|
|
62
|
+
send: message => iframe.contentWindow?.postMessage(message, "*"),
|
|
63
|
+
onMessage(handler) {
|
|
64
|
+
const listener = (event: MessageEvent) => {
|
|
65
|
+
if (event.source === iframe.contentWindow) handler(event.data);
|
|
66
|
+
};
|
|
67
|
+
window.addEventListener("message", listener);
|
|
68
|
+
return () => window.removeEventListener("message", listener);
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHandlers = {}): PreviewHost {
|
|
74
|
+
let isReady = false;
|
|
75
|
+
let queue: HostMessage[] = [];
|
|
76
|
+
let resolveReady: () => void;
|
|
77
|
+
const ready = new Promise<void>(resolve => { resolveReady = resolve; });
|
|
78
|
+
|
|
79
|
+
const send = (message: HostMessage) => {
|
|
80
|
+
if (isReady) channel.send({ channel: PREVIEW_CHANNEL, ...message });
|
|
81
|
+
else queue.push(message);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const stop = channel.onMessage(data => {
|
|
85
|
+
if (!isEnvelope<PreviewMessage>(data)) return;
|
|
86
|
+
const message = data as Envelope<PreviewMessage>;
|
|
87
|
+
switch (message.type) {
|
|
88
|
+
case "ready": {
|
|
89
|
+
// Sent again if the page reloads, which loses its story, so onReady is
|
|
90
|
+
// where a host can load it again
|
|
91
|
+
isReady = true;
|
|
92
|
+
const queued = queue;
|
|
93
|
+
queue = [];
|
|
94
|
+
for (const m of queued) send(m);
|
|
95
|
+
resolveReady();
|
|
96
|
+
handlers.onReady?.();
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
case "loaded":
|
|
100
|
+
handlers.onLoaded?.();
|
|
101
|
+
break;
|
|
102
|
+
case "attributeSet":
|
|
103
|
+
handlers.onAttributeSet?.(message.name, message.value);
|
|
104
|
+
break;
|
|
105
|
+
case "canGoBackChanged":
|
|
106
|
+
handlers.onCanGoBackChanged?.(message.canGoBack);
|
|
107
|
+
break;
|
|
108
|
+
case "navigated":
|
|
109
|
+
handlers.onNavigated?.(message.section, message.passage);
|
|
110
|
+
break;
|
|
111
|
+
case "runtimeError":
|
|
112
|
+
handlers.onRuntimeError?.(message.message, message.stack);
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
ready,
|
|
119
|
+
load: (story, options = {}) => send({ type: "load", story, ...(options.startAt ? { startAt: options.startAt } : {}) }),
|
|
120
|
+
update: js => send({ type: "update", js }),
|
|
121
|
+
restart: () => send({ type: "restart" }),
|
|
122
|
+
back: () => send({ type: "back" }),
|
|
123
|
+
setAssets: assets => send({ type: "assets", assets }),
|
|
124
|
+
dispose: () => {
|
|
125
|
+
stop();
|
|
126
|
+
queue = [];
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
export type HostMessage =
|
|
31
|
+
// Starts a story, replacing any that's running. Send assets first.
|
|
32
|
+
| { type: "load"; story: PreviewStory; startAt?: StartAt }
|
|
33
|
+
// Hot-updates the running story, keeping its state
|
|
34
|
+
| { type: "update"; js: string }
|
|
35
|
+
| { type: "restart" }
|
|
36
|
+
| { type: "back" }
|
|
37
|
+
// Replaces the assets the story can use
|
|
38
|
+
| { type: "assets"; assets: PreviewAssets };
|
|
39
|
+
|
|
40
|
+
export type PreviewMessage =
|
|
41
|
+
// The page has loaded and is listening
|
|
42
|
+
| { type: "ready" }
|
|
43
|
+
// A story from a load message has started
|
|
44
|
+
| { type: "loaded" }
|
|
45
|
+
// An attribute was set. Internal attributes, whose names start with "_", aren't sent.
|
|
46
|
+
| { type: "attributeSet"; name: string; value: unknown }
|
|
47
|
+
| { type: "canGoBackChanged"; canGoBack: boolean }
|
|
48
|
+
// A section or passage was shown, or Back went to one
|
|
49
|
+
| { type: "navigated"; section: string; passage?: string }
|
|
50
|
+
// An error from the story's JavaScript or the runtime
|
|
51
|
+
| { type: "runtimeError"; message: string; stack?: string };
|
|
52
|
+
|
|
53
|
+
export type Envelope<T> = T & { channel: typeof PREVIEW_CHANNEL };
|
|
54
|
+
|
|
55
|
+
export const isEnvelope = <T extends { type: string }>(data: unknown): data is Envelope<T> =>
|
|
56
|
+
typeof data == "object" && data !== null && (data as { channel?: unknown }).channel === PREVIEW_CHANNEL
|
|
57
|
+
&& 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,168 @@
|
|
|
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. 
|
|
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
|
+
expect([...document.head.querySelectorAll("style")].map(s => s.textContent)).toEqual(["body { color: blue; }"]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("reports errors", async () => {
|
|
151
|
+
const messages: PreviewMessage[] = [];
|
|
152
|
+
const preview = createPreview({
|
|
153
|
+
element: document.getElementById("squiffy")!,
|
|
154
|
+
send: m => messages.push(m),
|
|
155
|
+
loadModule: async () => { throw new Error("Bad story"); },
|
|
156
|
+
});
|
|
157
|
+
await preview.receive({ type: "load", story: { js: "" } });
|
|
158
|
+
expect(messages).toMatchObject([{ type: "runtimeError", message: "Bad story" }]);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test("ignores messages for a story that hasn't loaded", async () => {
|
|
162
|
+
const { preview, messages } = setUp();
|
|
163
|
+
await preview.receive({ type: "restart" });
|
|
164
|
+
await preview.receive({ type: "back" });
|
|
165
|
+
await preview.receive({ type: "update", js: await compileJs(script) });
|
|
166
|
+
expect(messages).toEqual([]);
|
|
167
|
+
});
|
|
168
|
+
});
|
package/src/preview.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
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
|
+
|
|
56
|
+
const send = (message: PreviewMessage) => {
|
|
57
|
+
try {
|
|
58
|
+
options.send(message);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// e.g. an attribute value that can't be cloned
|
|
62
|
+
if (message.type == "attributeSet") options.send({ ...message, value: String(message.value) });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const resolveAssetUrl = (path: string) => assetUrls.get(normalisePath(path)) ?? path;
|
|
67
|
+
|
|
68
|
+
function setAssets(assets: PreviewAssets) {
|
|
69
|
+
for (const url of objectUrls.splice(0)) URL.revokeObjectURL(url);
|
|
70
|
+
assetUrls.clear();
|
|
71
|
+
for (const [path, url] of Object.entries(assets.urls ?? {})) {
|
|
72
|
+
assetUrls.set(normalisePath(path), url);
|
|
73
|
+
}
|
|
74
|
+
for (const [path, data] of Object.entries(assets.files ?? {})) {
|
|
75
|
+
const blob = data instanceof Blob ? data : new Blob([data as BlobPart], { type: mimeType(path) });
|
|
76
|
+
const url = URL.createObjectURL(blob);
|
|
77
|
+
objectUrls.push(url);
|
|
78
|
+
assetUrls.set(normalisePath(path), url);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function addStoryFiles(story: PreviewStory) {
|
|
83
|
+
for (const element of injected.splice(0)) element.remove();
|
|
84
|
+
for (const css of story.css ?? []) {
|
|
85
|
+
const style = document.createElement("style");
|
|
86
|
+
style.textContent = css;
|
|
87
|
+
document.head.appendChild(style);
|
|
88
|
+
injected.push(style);
|
|
89
|
+
}
|
|
90
|
+
for (const js of story.scripts ?? []) {
|
|
91
|
+
const script = document.createElement("script");
|
|
92
|
+
const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
|
|
93
|
+
await new Promise<void>(resolve => {
|
|
94
|
+
script.onload = script.onerror = () => resolve();
|
|
95
|
+
script.src = url;
|
|
96
|
+
document.head.appendChild(script);
|
|
97
|
+
});
|
|
98
|
+
URL.revokeObjectURL(url);
|
|
99
|
+
injected.push(script);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function load(message: Extract<HostMessage, { type: "load" }>) {
|
|
104
|
+
const thisLoad = ++loadCount;
|
|
105
|
+
api = undefined;
|
|
106
|
+
options.element.innerHTML = "";
|
|
107
|
+
await addStoryFiles(message.story);
|
|
108
|
+
const { story } = await loadModule(message.story.js);
|
|
109
|
+
if (thisLoad != loadCount) return;
|
|
110
|
+
|
|
111
|
+
const container = document.createElement("div");
|
|
112
|
+
container.className = "squiffy-preview-story";
|
|
113
|
+
options.element.appendChild(container);
|
|
114
|
+
|
|
115
|
+
const newApi = await init({
|
|
116
|
+
element: container,
|
|
117
|
+
story,
|
|
118
|
+
persist: false,
|
|
119
|
+
scroll: "element",
|
|
120
|
+
resolveAssetUrl,
|
|
121
|
+
onSet: (name, value) => {
|
|
122
|
+
if (thisLoad == loadCount && !name.startsWith("_")) send({ type: "attributeSet", name, value });
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
newApi.on("canGoBackChanged", e => {
|
|
126
|
+
if (thisLoad == loadCount) send({ type: "canGoBackChanged", canGoBack: e.canGoBack });
|
|
127
|
+
});
|
|
128
|
+
newApi.on("navigated", e => {
|
|
129
|
+
if (thisLoad == loadCount) send({ type: "navigated", ...e });
|
|
130
|
+
});
|
|
131
|
+
api = newApi;
|
|
132
|
+
send({ type: "canGoBackChanged", canGoBack: false });
|
|
133
|
+
await newApi.begin(message.startAt);
|
|
134
|
+
if (thisLoad == loadCount) send({ type: "loaded" });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function receive(message: HostMessage) {
|
|
138
|
+
try {
|
|
139
|
+
switch (message.type) {
|
|
140
|
+
case "load":
|
|
141
|
+
await load(message);
|
|
142
|
+
break;
|
|
143
|
+
case "update":
|
|
144
|
+
if (api) api.update((await loadModule(message.js)).story);
|
|
145
|
+
break;
|
|
146
|
+
case "restart":
|
|
147
|
+
api?.restart();
|
|
148
|
+
break;
|
|
149
|
+
case "back":
|
|
150
|
+
api?.goBack();
|
|
151
|
+
break;
|
|
152
|
+
case "assets":
|
|
153
|
+
setAssets(message.assets);
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
send(errorMessage(error));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { receive };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export { errorMessage };
|
package/src/squiffy.runtime.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage } from "./types.js";
|
|
1
|
+
import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt } from "./types.js";
|
|
2
2
|
import { TextProcessor } from "./textProcessor.js";
|
|
3
3
|
import { Emitter, SquiffyEventMap } from "./events.js";
|
|
4
4
|
import { State } from "./state.js";
|
|
@@ -9,6 +9,7 @@ import { LinkHandler } from "./linkHandler.js";
|
|
|
9
9
|
import { Animation } from "./animation.js";
|
|
10
10
|
import { imports } from "./import.js";
|
|
11
11
|
import { areInputsValid, setupInputValidation } from "./inputValidation.js";
|
|
12
|
+
import { createAssetHtmlResolver } from "./assets.js";
|
|
12
13
|
|
|
13
14
|
export type { SquiffyApi } from "./types.js";
|
|
14
15
|
export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
|
|
@@ -95,7 +96,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
95
96
|
link.removeAttribute("tabindex");
|
|
96
97
|
}
|
|
97
98
|
|
|
98
|
-
async function begin() {
|
|
99
|
+
async function begin(startAt?: StartAt) {
|
|
100
|
+
if (startAt && startAt.section in story.sections) {
|
|
101
|
+
// Start somewhere else in a fresh story, e.g. from the section being edited
|
|
102
|
+
await go(startAt.section);
|
|
103
|
+
if (startAt.passage !== undefined && get("_section") == startAt.section) {
|
|
104
|
+
await showPassage(startAt.passage);
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
99
108
|
if (!load()) {
|
|
100
109
|
await go(story.start);
|
|
101
110
|
}
|
|
@@ -209,6 +218,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
209
218
|
if (newCanGoBack != oldCanGoBack) {
|
|
210
219
|
emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
|
|
211
220
|
}
|
|
221
|
+
emitter.emit("navigated", { section: sectionName });
|
|
212
222
|
}
|
|
213
223
|
|
|
214
224
|
function runJs(index: number, extra: any = null) {
|
|
@@ -329,6 +339,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
329
339
|
if (newCanGoBack != oldCanGoBack) {
|
|
330
340
|
emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
|
|
331
341
|
}
|
|
342
|
+
emitter.emit("navigated", { section: get("_section"), passage: passageName });
|
|
332
343
|
}
|
|
333
344
|
|
|
334
345
|
async function processAttributes(attributes: string[]) {
|
|
@@ -373,7 +384,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
373
384
|
return false;
|
|
374
385
|
}
|
|
375
386
|
|
|
376
|
-
|
|
387
|
+
// Saved output may contain asset URLs that are no longer valid (e.g. blob: URLs), so resolve them again
|
|
388
|
+
outputElement.innerHTML = resolveAssetsInHtml(output);
|
|
377
389
|
|
|
378
390
|
setCurrentSectionElement();
|
|
379
391
|
setCurrentPassageElement();
|
|
@@ -481,7 +493,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
481
493
|
write: (text: string, source: string) => {
|
|
482
494
|
scrollPosition = outputElement.scrollHeight;
|
|
483
495
|
|
|
484
|
-
const html = ui.
|
|
496
|
+
const html = ui.renderHtml(text, false).trim();
|
|
485
497
|
|
|
486
498
|
// Previously, we skipped the rest of this if "html" came back as an empty string.
|
|
487
499
|
// But, we _do_ always want the block to be created, in the editor at least - as the
|
|
@@ -532,6 +544,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
532
544
|
processText: (text: string, inline: boolean) => {
|
|
533
545
|
return textProcessor.process(text, inline);
|
|
534
546
|
},
|
|
547
|
+
// processText, plus asset URL resolution - for text that's going to be displayed as HTML
|
|
548
|
+
renderHtml: (text: string, inline: boolean) => {
|
|
549
|
+
return resolveAssetsInHtml(ui.processText(text, inline));
|
|
550
|
+
},
|
|
535
551
|
};
|
|
536
552
|
|
|
537
553
|
function update(newStory: Story) {
|
|
@@ -554,7 +570,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
554
570
|
const previousSection = currentSection;
|
|
555
571
|
currentSection = section;
|
|
556
572
|
try {
|
|
557
|
-
return ui.
|
|
573
|
+
return ui.renderHtml(text, false);
|
|
558
574
|
} finally {
|
|
559
575
|
currentSection = previousSection;
|
|
560
576
|
}
|
|
@@ -677,6 +693,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
677
693
|
if (!canGoBack()) {
|
|
678
694
|
emitter.emit("canGoBackChanged", { canGoBack: false });
|
|
679
695
|
}
|
|
696
|
+
const passage = currentPassageElement?.getAttribute("data-passage");
|
|
697
|
+
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
680
698
|
}
|
|
681
699
|
|
|
682
700
|
// We create a separate div inside the passed-in element. This allows us to clear the text output, but
|
|
@@ -685,6 +703,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
685
703
|
const outputElement = document.createElement("div");
|
|
686
704
|
outputElementContainer.appendChild(outputElement);
|
|
687
705
|
story = options.story;
|
|
706
|
+
const resolveAssetsInHtml = createAssetHtmlResolver(options.resolveAssetUrl);
|
|
688
707
|
|
|
689
708
|
const settings = {
|
|
690
709
|
scroll: options.scroll || "body",
|
|
@@ -775,7 +794,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
775
794
|
const animation = new Animation();
|
|
776
795
|
|
|
777
796
|
const pluginManager = new PluginManager(outputElement, textProcessor, state, linkHandler,
|
|
778
|
-
getSectionText, getPassageText, ui.
|
|
797
|
+
getSectionText, getPassageText, ui.renderHtml, addTransition, animation, emitter, resolveAssetsInHtml);
|
|
779
798
|
pluginManager.add(Plugins.ReplaceLabel());
|
|
780
799
|
pluginManager.add(Plugins.RotateSequencePlugin());
|
|
781
800
|
pluginManager.add(Plugins.RandomPlugin());
|
package/src/types.plugins.ts
CHANGED
|
@@ -22,6 +22,10 @@ export interface PluginHost {
|
|
|
22
22
|
getSectionText(name: string): string | null;
|
|
23
23
|
getPassageText(name: string): string | null;
|
|
24
24
|
processText: (text: string, inline: boolean) => string;
|
|
25
|
+
// Rewrites asset URLs (src, srcset, poster, style url()) in already-rendered HTML using the
|
|
26
|
+
// resolveAssetUrl init option. Use this for HTML a plugin inserts without going through
|
|
27
|
+
// processText. Returns the HTML unchanged if no resolveAssetUrl was given.
|
|
28
|
+
resolveAssetsInHtml: (html: string) => string;
|
|
25
29
|
addTransition: (fn: () => Promise<void>) => void;
|
|
26
30
|
animation: Animation;
|
|
27
31
|
on<E extends keyof SquiffyEventMap>(
|