squiffy-runtime 6.0.1 → 7.0.0-beta.11

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 (117) hide show
  1. package/dist/assets.d.ts +3 -0
  2. package/dist/assets.test.d.ts +1 -0
  3. package/dist/classes.test.d.ts +1 -0
  4. package/dist/confirmDialog.d.ts +8 -0
  5. package/dist/events.d.ts +16 -0
  6. package/dist/every.d.ts +12 -0
  7. package/dist/every.test.d.ts +1 -0
  8. package/dist/helpers.test.d.ts +1 -0
  9. package/dist/numbers.d.ts +3 -0
  10. package/dist/panels.d.ts +14 -0
  11. package/dist/panels.test.d.ts +1 -0
  12. package/dist/paths.d.ts +15 -0
  13. package/dist/paths.test.d.ts +1 -0
  14. package/dist/persistent.test.d.ts +1 -0
  15. package/dist/playerSettings.d.ts +17 -0
  16. package/dist/pluginManager.d.ts +2 -1
  17. package/dist/preview-host.d.ts +33 -0
  18. package/dist/preview-host.js +125 -0
  19. package/dist/preview-host.js.map +7 -0
  20. package/dist/preview-host.test.d.ts +1 -0
  21. package/dist/preview-html.d.ts +2 -0
  22. package/dist/preview-html.js +2 -0
  23. package/dist/preview-protocol.d.ts +69 -0
  24. package/dist/preview.d.ts +15 -0
  25. package/dist/preview.main.d.ts +1 -0
  26. package/dist/preview.test.d.ts +1 -0
  27. package/dist/saveSlots.d.ts +16 -0
  28. package/dist/saves.test.d.ts +1 -0
  29. package/dist/savesDialog.d.ts +43 -0
  30. package/dist/savesDialog.test.d.ts +1 -0
  31. package/dist/scripts.test.d.ts +1 -0
  32. package/dist/settings.test.d.ts +1 -0
  33. package/dist/settingsDialog.d.ts +17 -0
  34. package/dist/skill.test.d.ts +1 -0
  35. package/dist/sound.d.ts +35 -0
  36. package/dist/sound.test.d.ts +1 -0
  37. package/dist/squiffy.page.css +155 -0
  38. package/dist/squiffy.preview.html +1631 -0
  39. package/dist/squiffy.runtime.css +1123 -20
  40. package/dist/squiffy.runtime.d.ts +13 -1
  41. package/dist/squiffy.runtime.global.js +146 -76
  42. package/dist/squiffy.runtime.global.js.map +1 -1
  43. package/dist/squiffy.runtime.js +7105 -4681
  44. package/dist/squiffy.runtime.js.map +1 -1
  45. package/dist/state.d.ts +17 -0
  46. package/dist/storyLists.d.ts +4 -0
  47. package/dist/storyLists.test.d.ts +1 -0
  48. package/dist/style.test.d.ts +1 -0
  49. package/dist/textProcessor.d.ts +27 -0
  50. package/dist/transitions.test.d.ts +1 -0
  51. package/dist/types.d.ts +137 -1
  52. package/dist/types.plugins.d.ts +2 -0
  53. package/dist/uiLinks.test.d.ts +1 -0
  54. package/dist/utils.d.ts +2 -1
  55. package/dist/utils.test.d.ts +1 -0
  56. package/package.json +25 -11
  57. package/src/__snapshots__/squiffy.runtime.test.ts.snap +22 -22
  58. package/src/animation.test.ts +44 -0
  59. package/src/animation.ts +9 -5
  60. package/src/assets.test.ts +225 -0
  61. package/src/assets.ts +92 -0
  62. package/src/classes.test.ts +201 -0
  63. package/src/confirmDialog.ts +66 -0
  64. package/src/events.ts +20 -0
  65. package/src/every.test.ts +25 -0
  66. package/src/every.ts +94 -0
  67. package/src/helpers.test.ts +34 -0
  68. package/src/numbers.ts +21 -0
  69. package/src/panels.test.ts +225 -0
  70. package/src/panels.ts +187 -0
  71. package/src/paths.test.ts +66 -0
  72. package/src/paths.ts +155 -0
  73. package/src/persistent.test.ts +155 -0
  74. package/src/playerSettings.ts +128 -0
  75. package/src/pluginManager.ts +6 -1
  76. package/src/plugins/animate.ts +34 -9
  77. package/src/plugins/live.ts +18 -5
  78. package/src/plugins/plugins.test.ts +93 -6
  79. package/src/plugins/replaceLabel.ts +7 -3
  80. package/src/preview-host.test.ts +171 -0
  81. package/src/preview-host.ts +190 -0
  82. package/src/preview-protocol.ts +79 -0
  83. package/src/preview.main.ts +34 -0
  84. package/src/preview.test.ts +367 -0
  85. package/src/preview.ts +331 -0
  86. package/src/saveSlots.ts +159 -0
  87. package/src/saves.test.ts +199 -0
  88. package/src/savesDialog.test.ts +290 -0
  89. package/src/savesDialog.ts +499 -0
  90. package/src/scripts.test.ts +130 -0
  91. package/src/settings.test.ts +233 -0
  92. package/src/settingsDialog.ts +160 -0
  93. package/src/skill.test.ts +67 -0
  94. package/src/sound.test.ts +273 -0
  95. package/src/sound.ts +207 -0
  96. package/src/squiffy.page.css +155 -0
  97. package/src/squiffy.runtime.css +1123 -20
  98. package/src/squiffy.runtime.test.ts +2806 -44
  99. package/src/squiffy.runtime.ts +1130 -64
  100. package/src/state.ts +172 -11
  101. package/src/storyLists.test.ts +134 -0
  102. package/src/storyLists.ts +57 -0
  103. package/src/style.test.ts +89 -0
  104. package/src/textProcessor.ts +739 -58
  105. package/src/transitions.test.ts +343 -0
  106. package/src/types.plugins.ts +7 -0
  107. package/src/types.ts +226 -2
  108. package/src/uiLinks.test.ts +156 -0
  109. package/src/updater.ts +26 -8
  110. package/src/utils.test.ts +60 -0
  111. package/src/utils.ts +46 -14
  112. package/vite.config.ts +3 -4
  113. package/vite.preview.config.ts +83 -0
  114. package/dist/infixExpressions.d.ts +0 -2
  115. package/src/infixExpressions.test.ts +0 -187
  116. package/src/infixExpressions.ts +0 -323
  117. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -10,9 +10,7 @@ vi.mock("animejs", () => ({
10
10
  setTimeout(() => params.onComplete?.());
11
11
  },
12
12
  stagger: () => 0,
13
- text: {
14
- split: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
15
- },
13
+ splitText: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
16
14
  }));
17
15
 
18
16
  const html = `
@@ -35,8 +33,9 @@ class ResizeObserverMock {
35
33
  }
36
34
  global.ResizeObserver = ResizeObserverMock as any;
37
35
 
38
- const compile = async (script: string) => {
36
+ const compile = async (script: string, expressions = false) => {
39
37
  const compileResult = await squiffyCompile({
38
+ expressions,
40
39
  script: script,
41
40
  });
42
41
 
@@ -55,14 +54,14 @@ const compile = async (script: string) => {
55
54
  };
56
55
  };
57
56
 
58
- const initScript = async (script: string) => {
57
+ const initScript = async (script: string, expressions = false) => {
59
58
  const element = document.getElementById("squiffy");
60
59
 
61
60
  if (!element) {
62
61
  throw new Error("Element not found");
63
62
  }
64
63
 
65
- const compileResult = await compile(script);
64
+ const compileResult = await compile(script, expressions);
66
65
 
67
66
  const squiffyApi = await init({
68
67
  element: element,
@@ -220,6 +219,48 @@ Your score is {{#label "score"}}0{{/label}}.
220
219
  expect(labelSpans[0].classList.contains("fade-in")).toBe(false);
221
220
  });
222
221
 
222
+ test("Replace plugin: replaces the latest label, in a section visited again after the screen is cleared", async () => {
223
+ const script = `
224
+ [[]]:
225
+ @clear
226
+
227
+ [[room]]:
228
+ The box is {{#label "box"}}closed{{/label}}. [Open it](open) or [[go out]](outside).
229
+
230
+ [open]:
231
+ {{#replace "box"}}open{{/replace}}
232
+
233
+ [[outside]]:
234
+ You're outside. [[Go back in]](room)
235
+ `;
236
+
237
+ const { squiffyApi, element } = await initScript(script);
238
+ await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='outside']")!);
239
+ await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='room']")!);
240
+
241
+ expect(element.querySelectorAll(".squiffy-label-box").length).toBe(2);
242
+ const links = element.querySelectorAll<HTMLElement>("a.squiffy-link[data-passage='open']");
243
+ await squiffyApi.clickLink(links[links.length - 1]);
244
+ const labels = element.querySelectorAll(".squiffy-label-box");
245
+ expect(labels[0].textContent).toBe("closed");
246
+ expect(labels[1].textContent).toBe("open");
247
+ });
248
+
249
+ test("Replace plugin: replace with only a label in it", async () => {
250
+ const script = `
251
+ The box is {{#label "box"}}closed{{/label}}. [Open it](open)
252
+
253
+ [open]:
254
+ {{#replace "box"}}{{#label "lid"}}open{{/label}}{{/replace}}
255
+ `;
256
+
257
+ const { squiffyApi, element } = await initScript(script);
258
+ await squiffyApi.clickLink(findPassageLink(element, "open")!);
259
+
260
+ expect(element.querySelector(".squiffy-label-box")?.innerHTML).toBe("<span class=\"squiffy-label-lid\">open</span>");
261
+ expect(element.querySelector(".squiffy-error")).toBeNull();
262
+ });
263
+
223
264
  // ===== RotateSequencePlugin Tests =====
224
265
 
225
266
  test("Sequence plugin: click through sequence", async () => {
@@ -346,6 +387,35 @@ Score: {{live "score"}}.
346
387
  });
347
388
  });
348
389
 
390
+ test("Live plugin: a value inside an object updates when the object changes (#442)", async () => {
391
+ const script = `
392
+ @set hero = { hp: 10 }
393
+
394
+ HP: {{live "hero.hp"}}
395
+
396
+ [Hurt], [Heal]
397
+
398
+ [Hurt]:
399
+ @set hero.hp -= 6
400
+
401
+ [Heal]:
402
+ @set hero = { hp: 7 }
403
+ `;
404
+
405
+ const { squiffyApi, element } = await initScript(script, true);
406
+ const liveSpan = () => element.querySelector(".squiffy-live");
407
+ expect(liveSpan()?.textContent).toBe("10");
408
+
409
+ await squiffyApi.clickLink(findPassageLink(element, "Hurt")!);
410
+ await vi.waitFor(() => {
411
+ expect(liveSpan()?.textContent).toBe("4");
412
+ expect(liveSpan()?.classList.contains("fade-in")).toBe(false);
413
+ });
414
+
415
+ await squiffyApi.clickLink(findPassageLink(element, "Heal")!);
416
+ await vi.waitFor(() => expect(liveSpan()?.textContent).toBe("7"));
417
+ });
418
+
349
419
  test("Live plugin: embed section content", async () => {
350
420
  const script = `
351
421
  [[start]]:
@@ -436,6 +506,23 @@ You clicked!
436
506
  expect(animateSpan?.getAttribute("data-interval")).toBe("50");
437
507
  });
438
508
 
509
+ test("Animate plugin: times can be expressions or written in seconds (#451)", async () => {
510
+ const script = `
511
+ @set n = 3
512
+ {{#animate "typewriter" trigger="link" start="1.5s" interval=n * 10 duration="200ms"}}[Click me]{{/animate}}
513
+
514
+ [Click me]:
515
+ You clicked!
516
+ `;
517
+
518
+ const { element } = await initScript(script);
519
+
520
+ const animateSpan = element.querySelector<HTMLElement>(".squiffy-animate");
521
+ expect(animateSpan?.getAttribute("data-start")).toBe("1500");
522
+ expect(animateSpan?.getAttribute("data-interval")).toBe("30");
523
+ expect(animateSpan?.getAttribute("data-duration")).toBe("200");
524
+ });
525
+
439
526
  test("Animate plugin: trigger on link", async () => {
440
527
  const script = `
441
528
  {{#animate "typewriter" trigger="link"}}[Click me]{{/animate}}
@@ -11,14 +11,18 @@ export function ReplaceLabel() : SquiffyPlugin {
11
11
  return new Handlebars.SafeString(`<span class="squiffy-label-${name}">${options.fn(this)}</span>`);
12
12
  });
13
13
  squiffy.registerHelper("replace", function(this: any, name: string, options) {
14
- const result = options.fn(this);
15
- const element = squiffy.outputElement.querySelector<HTMLElement>(`.squiffy-label-${name}`);
14
+ // A block that's only another helper, such as {{#label}}, gives that helper's SafeString
15
+ const result = String(options.fn(this));
16
+ // The latest label with the name: when a section is visited again, or the screen's been
17
+ // cleared, earlier ones can still be in the output (in the clear stack, hidden)
18
+ const labels = squiffy.outputElement.querySelectorAll<HTMLElement>(`.squiffy-label-${name}`);
19
+ const element = labels[labels.length - 1];
16
20
  if (element) {
17
21
  const isBlock = result.includes("\n\n");
18
22
  const html = isBlock
19
23
  ? marked.parse(result, { async: false }).trim()
20
24
  : marked.parseInline(result, { async: false }).trim();
21
- squiffy.addTransition(() => fadeReplace(element, html as string));
25
+ squiffy.addTransition(() => fadeReplace(element, html as string, squiffy.written));
22
26
  }
23
27
  return "";
24
28
  });
@@ -0,0 +1,171 @@
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.update("y", ["body { color: red; }"]);
35
+ host.restart();
36
+ host.back();
37
+ expect(sent.slice(2)).toEqual([
38
+ { channel: PREVIEW_CHANNEL, type: "update", js: "x" },
39
+ { channel: PREVIEW_CHANNEL, type: "update", js: "y", css: ["body { color: red; }"] },
40
+ { channel: PREVIEW_CHANNEL, type: "restart" },
41
+ { channel: PREVIEW_CHANNEL, type: "back" },
42
+ ]);
43
+ });
44
+
45
+ test("sends the theme when the page is ready, and again if it reloads", () => {
46
+ const { channel, sent, receive } = fakeChannel();
47
+ const host = createPreviewHost(channel);
48
+ host.setTheme("light");
49
+ host.setTheme("dark");
50
+ expect(sent).toEqual([]);
51
+
52
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
53
+ expect(sent).toEqual([{ channel: PREVIEW_CHANNEL, type: "theme", theme: "dark" }]);
54
+
55
+ host.setTheme("system");
56
+ expect(sent.slice(1)).toEqual([{ channel: PREVIEW_CHANNEL, type: "theme", theme: "system" }]);
57
+
58
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
59
+ expect(sent.slice(2)).toEqual([{ channel: PREVIEW_CHANNEL, type: "theme", theme: "system" }]);
60
+ });
61
+
62
+ test("sends mute when the page is ready, and again if it reloads (#444)", () => {
63
+ const { channel, sent, receive } = fakeChannel();
64
+ const host = createPreviewHost(channel, { onUsesSound: vi.fn() });
65
+ host.setMuted(true);
66
+ expect(sent).toEqual([]);
67
+
68
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
69
+ expect(sent).toEqual([{ channel: PREVIEW_CHANNEL, type: "muted", muted: true }]);
70
+
71
+ host.setMuted(false);
72
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
73
+ expect(sent.slice(1)).toEqual([{ channel: PREVIEW_CHANNEL, type: "muted", muted: false }]);
74
+ });
75
+
76
+ test("tells the host whether the story uses sound (#444)", () => {
77
+ const { channel, receive } = fakeChannel();
78
+ const onUsesSound = vi.fn();
79
+ createPreviewHost(channel, { onUsesSound });
80
+ receive({ channel: PREVIEW_CHANNEL, type: "usesSound", usesSound: true });
81
+ expect(onUsesSound).toHaveBeenCalledWith(true);
82
+ });
83
+
84
+ test("reloads the page before loading a story after one with scripts, sending the assets again (#528)", () => {
85
+ const { channel, sent, receive } = fakeChannel();
86
+ const onReady = vi.fn();
87
+ const host = createPreviewHost(channel, { onReady });
88
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
89
+ expect(onReady).toHaveBeenCalledOnce();
90
+ const assets = { urls: { "a.png": "https://example.com/a.png" } };
91
+ host.setAssets(assets);
92
+ host.load({ js: "one", scripts: ["document.addEventListener('squiffy:ready', () => {});"] });
93
+ sent.length = 0;
94
+
95
+ // Its scripts could have left things behind, so the page reloads first
96
+ host.setAssets(assets);
97
+ host.load({ js: "two" });
98
+ expect(sent).toEqual([
99
+ { channel: PREVIEW_CHANNEL, type: "assets", assets },
100
+ { channel: PREVIEW_CHANNEL, type: "reload" },
101
+ ]);
102
+ sent.length = 0;
103
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
104
+ expect(sent).toEqual([
105
+ { channel: PREVIEW_CHANNEL, type: "assets", assets },
106
+ { channel: PREVIEW_CHANNEL, type: "load", story: { js: "two" } },
107
+ ]);
108
+ // The host asked for it, so it isn't a reload that lost the story
109
+ expect(onReady).toHaveBeenCalledOnce();
110
+
111
+ // That story had no scripts, so the next one loads without a reload
112
+ sent.length = 0;
113
+ host.load({ js: "three" });
114
+ expect(sent).toEqual([{ channel: PREVIEW_CHANNEL, type: "load", story: { js: "three" } }]);
115
+ });
116
+
117
+ test("a page that reloads by itself is new, so the next story doesn't reload it (#528)", () => {
118
+ const { channel, sent, receive } = fakeChannel();
119
+ const host = createPreviewHost(channel);
120
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
121
+ host.load({ js: "one", scripts: ["x"] });
122
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
123
+ sent.length = 0;
124
+ host.load({ js: "two" });
125
+ expect(sent).toEqual([{ channel: PREVIEW_CHANNEL, type: "load", story: { js: "two" } }]);
126
+ });
127
+
128
+ test("only the last of the loads sent before the page is ready is sent", () => {
129
+ const { channel, sent, receive } = fakeChannel();
130
+ const host = createPreviewHost(channel);
131
+ host.load({ js: "one", scripts: ["x"] });
132
+ host.load({ js: "two" });
133
+ receive({ channel: PREVIEW_CHANNEL, type: "ready" });
134
+ expect(sent).toEqual([{ channel: PREVIEW_CHANNEL, type: "load", story: { js: "two" } }]);
135
+ });
136
+
137
+ test("passes messages from the page to handlers, ignoring anything else", () => {
138
+ const { channel, receive } = fakeChannel();
139
+ const handlers = {
140
+ onReady: vi.fn(), onLoaded: vi.fn(), onAttributeSet: vi.fn(), onCanGoBackChanged: vi.fn(),
141
+ onNavigated: vi.fn(), onThemeFixed: vi.fn(), onRuntimeError: vi.fn(),
142
+ };
143
+ const host = createPreviewHost(channel, handlers);
144
+ receive({ type: "navigated", section: "not ours" });
145
+ receive("hello");
146
+ receive(null);
147
+ for (const message of [
148
+ { type: "ready" },
149
+ { type: "loaded" },
150
+ { type: "attributeSet", name: "score", value: 2 },
151
+ { type: "canGoBackChanged", canGoBack: true },
152
+ { type: "navigated", section: "s", passage: "p" },
153
+ { type: "themeFixed", fixed: true },
154
+ { type: "runtimeError", message: "oops", stack: "at x" },
155
+ ]) {
156
+ receive({ channel: PREVIEW_CHANNEL, ...message });
157
+ }
158
+ expect(handlers.onReady).toHaveBeenCalledOnce();
159
+ expect(handlers.onLoaded).toHaveBeenCalledOnce();
160
+ expect(handlers.onAttributeSet).toHaveBeenCalledWith("score", 2);
161
+ expect(handlers.onCanGoBackChanged).toHaveBeenCalledWith(true);
162
+ expect(handlers.onNavigated).toHaveBeenCalledOnce();
163
+ expect(handlers.onNavigated).toHaveBeenCalledWith("s", "p");
164
+ expect(handlers.onThemeFixed).toHaveBeenCalledWith(true);
165
+ expect(handlers.onRuntimeError).toHaveBeenCalledWith("oops", "at x");
166
+
167
+ host.dispose();
168
+ receive({ channel: PREVIEW_CHANNEL, type: "loaded" });
169
+ expect(handlers.onLoaded).toHaveBeenCalledOnce();
170
+ });
171
+ });
@@ -0,0 +1,190 @@
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
+ // Whether the story's own CSS sets its color-scheme, so setTheme() makes no difference
35
+ onThemeFixed?(fixed: boolean): void;
36
+ // Whether the story plays music or sounds, so a mute button is worth showing
37
+ onUsesSound?(usesSound: boolean): void;
38
+ onRuntimeError?(message: string, stack?: string): void;
39
+ }
40
+
41
+ export interface PreviewHost {
42
+ // Resolves when the page has loaded. Messages sent before that are queued.
43
+ readonly ready: Promise<void>;
44
+ // Starts a story, replacing any that's running
45
+ load(story: PreviewStory, options?: { startAt?: StartAt }): void;
46
+ // Hot-updates the running story, keeping its state. css, if given, replaces the story's own
47
+ // stylesheets; its scripts only change with load().
48
+ update(js: string, css?: string[]): void;
49
+ restart(): void;
50
+ back(): void;
51
+ // Sets the assets the story can use. Send these before load().
52
+ setAssets(assets: PreviewAssets): void;
53
+ // Shows the story in light or dark mode. It's kept if the page reloads.
54
+ setTheme(theme: PreviewTheme): void;
55
+ // Mutes the story's music and sounds. It's kept for the next story loaded, and if the page reloads.
56
+ setMuted(muted: boolean): void;
57
+ dispose(): void;
58
+ }
59
+
60
+ // Sandboxes an iframe and loads the preview page into it. The sandbox allows scripts only, so the
61
+ // story runs with an opaque origin: it can't reach the host page, its storage or its cookies.
62
+ export function setUpPreviewFrame(iframe: HTMLIFrameElement, previewHtml: string) {
63
+ iframe.setAttribute("sandbox", "allow-scripts");
64
+ // So a story's music can start when the author starts it from the host page (#444)
65
+ iframe.setAttribute("allow", "autoplay");
66
+ iframe.srcdoc = previewHtml;
67
+ }
68
+
69
+ // A channel to a preview page in an iframe
70
+ export function iframeChannel(iframe: HTMLIFrameElement): PreviewChannel {
71
+ return {
72
+ // The page has an opaque origin, so there's no origin to target
73
+ send: message => iframe.contentWindow?.postMessage(message, "*"),
74
+ onMessage(handler) {
75
+ const listener = (event: MessageEvent) => {
76
+ if (event.source === iframe.contentWindow) handler(event.data);
77
+ };
78
+ window.addEventListener("message", listener);
79
+ return () => window.removeEventListener("message", listener);
80
+ },
81
+ };
82
+ }
83
+
84
+ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHandlers = {}): PreviewHost {
85
+ let isReady = false;
86
+ let queue: HostMessage[] = [];
87
+ let theme: PreviewTheme | undefined;
88
+ let muted = false;
89
+ // The assets last sent, to send again after the host has reloaded the page
90
+ let assets: PreviewAssets | undefined;
91
+ // Whether the story last loaded had scripts of its own, so the page needs reloading before
92
+ // the next one: what they did, such as listening for squiffy:ready, can't be undone (#528)
93
+ let hadScripts = false;
94
+ // Whether the host is waiting for the page to reload, which it asked for
95
+ let reloading = false;
96
+ let resolveReady: () => void;
97
+ const ready = new Promise<void>(resolve => { resolveReady = resolve; });
98
+
99
+ const send = (message: HostMessage) => {
100
+ if (isReady) channel.send({ channel: PREVIEW_CHANNEL, ...message });
101
+ else queue.push(message);
102
+ };
103
+
104
+ const stop = channel.onMessage(data => {
105
+ if (!isEnvelope<PreviewMessage>(data)) return;
106
+ const message = data as Envelope<PreviewMessage>;
107
+ switch (message.type) {
108
+ case "ready": {
109
+ // Sent again if the page reloads, which loses its story, so onReady is
110
+ // where a host can load it again. A reload the host asked for, to load a
111
+ // story, already has the story to send, with the assets that the page lost.
112
+ const requested = reloading;
113
+ reloading = false;
114
+ isReady = true;
115
+ if (theme) send({ type: "theme", theme });
116
+ if (muted) send({ type: "muted", muted });
117
+ let queued = queue;
118
+ queue = [];
119
+ if (requested && assets) {
120
+ queued = queued.filter(m => m.type != "assets");
121
+ send({ type: "assets", assets });
122
+ }
123
+ // The page is new, so only a story about to be loaded can have left anything behind
124
+ hadScripts = queued.some(m => m.type == "load" && !!m.story.scripts?.length);
125
+ for (const m of queued) send(m);
126
+ resolveReady();
127
+ if (!requested) handlers.onReady?.();
128
+ break;
129
+ }
130
+ case "loaded":
131
+ handlers.onLoaded?.();
132
+ break;
133
+ case "attributeSet":
134
+ handlers.onAttributeSet?.(message.name, message.value);
135
+ break;
136
+ case "canGoBackChanged":
137
+ handlers.onCanGoBackChanged?.(message.canGoBack);
138
+ break;
139
+ case "navigated":
140
+ handlers.onNavigated?.(message.section, message.passage);
141
+ break;
142
+ case "themeFixed":
143
+ handlers.onThemeFixed?.(message.fixed);
144
+ break;
145
+ case "usesSound":
146
+ handlers.onUsesSound?.(message.usesSound);
147
+ break;
148
+ case "runtimeError":
149
+ handlers.onRuntimeError?.(message.message, message.stack);
150
+ break;
151
+ }
152
+ });
153
+
154
+ return {
155
+ ready,
156
+ load: (story, options = {}) => {
157
+ if (!isReady) {
158
+ // A load that hasn't been sent yet is replaced by this one, and the page it goes to is new
159
+ queue = queue.filter(m => m.type != "load");
160
+ }
161
+ else if (hadScripts) {
162
+ channel.send({ channel: PREVIEW_CHANNEL, type: "reload" });
163
+ isReady = false;
164
+ reloading = true;
165
+ }
166
+ hadScripts = !!story.scripts?.length;
167
+ send({ type: "load", story, ...(options.startAt ? { startAt: options.startAt } : {}) });
168
+ },
169
+ update: (js, css) => send({ type: "update", js, ...(css ? { css } : {}) }),
170
+ restart: () => send({ type: "restart" }),
171
+ back: () => send({ type: "back" }),
172
+ setAssets: value => {
173
+ assets = value;
174
+ send({ type: "assets", assets });
175
+ },
176
+ setTheme: value => {
177
+ theme = value;
178
+ // Sent when the page is ready, and again if it reloads
179
+ if (isReady) send({ type: "theme", theme });
180
+ },
181
+ setMuted: value => {
182
+ muted = value;
183
+ if (isReady) send({ type: "muted", muted });
184
+ },
185
+ dispose: () => {
186
+ stop();
187
+ queue = [];
188
+ },
189
+ };
190
+ }
@@ -0,0 +1,79 @@
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
+ // A stylesheet's url()s that are paths, such as its fonts' files, are paths from the story's
18
+ // folder, like the assets', so a host should change any that are from the stylesheet's own
19
+ // folder. The preview swaps them for the assets' URLs.
20
+ css?: string[];
21
+ scripts?: string[];
22
+ }
23
+
24
+ export interface PreviewAssets {
25
+ // Asset contents by path, as the story refers to them (relative to the main .squiffy file).
26
+ // The preview makes its own object URLs for these: a sandboxed frame can't load the host's
27
+ // blob URLs.
28
+ files?: Record<string, Blob | ArrayBuffer | Uint8Array>;
29
+ // Or URLs the preview can load as they are, e.g. from VS Code's asWebviewUri.
30
+ urls?: Record<string, string>;
31
+ }
32
+
33
+ // "system" follows the reader's system setting, like an exported story
34
+ export type PreviewTheme = "light" | "dark" | "system";
35
+
36
+ export type HostMessage =
37
+ // Starts a story, replacing any that's running. Send assets first.
38
+ | { type: "load"; story: PreviewStory; startAt?: StartAt }
39
+ // Hot-updates the running story, keeping its state. css, if given, replaces the story's own
40
+ // stylesheets. Its scripts can't be replaced in a running story: that needs a load.
41
+ | { type: "update"; js: string; css?: string[] }
42
+ | { type: "restart" }
43
+ | { type: "back" }
44
+ // Replaces the assets the story can use
45
+ | { type: "assets"; assets: PreviewAssets }
46
+ // Shows the story in light or dark mode, e.g. to match the host's own theme. A story's own
47
+ // CSS can still override it, e.g. with ":root { color-scheme: light; }".
48
+ | { type: "theme"; theme: PreviewTheme }
49
+ // Mutes or unmutes the story's music and sounds (#444)
50
+ | { type: "muted"; muted: boolean }
51
+ // Reloads the page, which then sends "ready" again. The host sends this before loading a story
52
+ // after one that had scripts, which can leave things behind, such as a squiffy:ready listener
53
+ // that would hear about the next story too (#528).
54
+ | { type: "reload" };
55
+
56
+ export type PreviewMessage =
57
+ // The page has loaded and is listening
58
+ | { type: "ready" }
59
+ // A story from a load message has started
60
+ | { type: "loaded" }
61
+ // Whether the story's own CSS sets its color-scheme, e.g. ":root { color-scheme: light; }",
62
+ // so the theme message makes no difference. Sent each time a story is loaded, before "loaded".
63
+ | { type: "themeFixed"; fixed: boolean }
64
+ // An attribute was set. Internal attributes, whose names start with "_", aren't sent.
65
+ | { type: "attributeSet"; name: string; value: unknown }
66
+ | { type: "canGoBackChanged"; canGoBack: boolean }
67
+ // Whether the story plays music or sounds (#444), so the host can show a mute button. Sent
68
+ // each time a story is loaded, before "loaded", and when a sound plays.
69
+ | { type: "usesSound"; usesSound: boolean }
70
+ // A section or passage was shown, or Back went to one
71
+ | { type: "navigated"; section: string; passage?: string }
72
+ // An error from the story's JavaScript or the runtime
73
+ | { type: "runtimeError"; message: string; stack?: string };
74
+
75
+ export type Envelope<T> = T & { channel: typeof PREVIEW_CHANNEL };
76
+
77
+ export const isEnvelope = <T extends { type: string }>(data: unknown): data is Envelope<T> =>
78
+ typeof data == "object" && data !== null && (data as { channel?: unknown }).channel === PREVIEW_CHANNEL
79
+ && typeof (data as { type?: unknown }).type == "string";
@@ -0,0 +1,34 @@
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
+ reload: () => location.reload(),
22
+ });
23
+
24
+ window.addEventListener("message", event => {
25
+ // In an iframe, only the parent can drive the preview
26
+ if (!vscode && event.source !== window.parent) return;
27
+ if (!isEnvelope<HostMessage>(event.data)) return;
28
+ preview.receive(event.data);
29
+ });
30
+
31
+ window.addEventListener("error", event => post(errorMessage(event.error ?? event.message)));
32
+ window.addEventListener("unhandledrejection", event => post(errorMessage(event.reason)));
33
+
34
+ post({ type: "ready" });