squiffy-runtime 7.0.0-beta.6 → 7.0.0-beta.8

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 (80) hide show
  1. package/dist/assets.d.ts +1 -0
  2. package/dist/classes.test.d.ts +1 -0
  3. package/dist/confirmDialog.d.ts +8 -0
  4. package/dist/events.d.ts +11 -0
  5. package/dist/every.d.ts +12 -0
  6. package/dist/every.test.d.ts +1 -0
  7. package/dist/paths.d.ts +15 -0
  8. package/dist/paths.test.d.ts +1 -0
  9. package/dist/playerSettings.d.ts +17 -0
  10. package/dist/preview-host.d.ts +2 -0
  11. package/dist/preview-host.js +10 -0
  12. package/dist/preview-host.js.map +2 -2
  13. package/dist/preview-html.js +1 -1
  14. package/dist/preview-protocol.d.ts +6 -0
  15. package/dist/settings.test.d.ts +1 -0
  16. package/dist/settingsDialog.d.ts +17 -0
  17. package/dist/skill.test.d.ts +1 -0
  18. package/dist/sound.d.ts +35 -0
  19. package/dist/sound.test.d.ts +1 -0
  20. package/dist/squiffy.page.css +14 -3
  21. package/dist/squiffy.preview.html +680 -82
  22. package/dist/squiffy.runtime.css +531 -1
  23. package/dist/squiffy.runtime.d.ts +5 -1
  24. package/dist/squiffy.runtime.global.js +117 -96
  25. package/dist/squiffy.runtime.global.js.map +1 -1
  26. package/dist/squiffy.runtime.js +5728 -4520
  27. package/dist/squiffy.runtime.js.map +1 -1
  28. package/dist/state.d.ts +4 -1
  29. package/dist/style.test.d.ts +1 -0
  30. package/dist/textProcessor.d.ts +16 -0
  31. package/dist/transitions.test.d.ts +1 -0
  32. package/dist/types.d.ts +54 -0
  33. package/dist/uiLinks.test.d.ts +1 -0
  34. package/dist/utils.d.ts +1 -0
  35. package/dist/utils.test.d.ts +1 -0
  36. package/package.json +3 -3
  37. package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
  38. package/src/animation.test.ts +44 -0
  39. package/src/animation.ts +9 -5
  40. package/src/assets.test.ts +1 -3
  41. package/src/assets.ts +1 -1
  42. package/src/classes.test.ts +201 -0
  43. package/src/confirmDialog.ts +66 -0
  44. package/src/events.ts +18 -0
  45. package/src/every.test.ts +25 -0
  46. package/src/every.ts +94 -0
  47. package/src/panels.test.ts +24 -0
  48. package/src/paths.test.ts +66 -0
  49. package/src/paths.ts +155 -0
  50. package/src/playerSettings.ts +128 -0
  51. package/src/plugins/animate.ts +16 -3
  52. package/src/plugins/live.ts +10 -4
  53. package/src/plugins/plugins.test.ts +51 -6
  54. package/src/preview-host.test.ts +22 -0
  55. package/src/preview-host.ts +15 -0
  56. package/src/preview-protocol.ts +9 -1
  57. package/src/preview.test.ts +114 -3
  58. package/src/preview.ts +97 -3
  59. package/src/settings.test.ts +233 -0
  60. package/src/settingsDialog.ts +160 -0
  61. package/src/skill.test.ts +67 -0
  62. package/src/sound.test.ts +273 -0
  63. package/src/sound.ts +207 -0
  64. package/src/squiffy.page.css +14 -3
  65. package/src/squiffy.runtime.css +531 -1
  66. package/src/squiffy.runtime.test.ts +1130 -17
  67. package/src/squiffy.runtime.ts +600 -38
  68. package/src/state.ts +45 -10
  69. package/src/style.test.ts +89 -0
  70. package/src/textProcessor.ts +484 -35
  71. package/src/transitions.test.ts +302 -0
  72. package/src/types.ts +79 -0
  73. package/src/uiLinks.test.ts +156 -0
  74. package/src/updater.ts +26 -8
  75. package/src/utils.test.ts +60 -0
  76. package/src/utils.ts +44 -14
  77. package/dist/infixExpressions.d.ts +0 -6
  78. package/src/infixExpressions.test.ts +0 -379
  79. package/src/infixExpressions.ts +0 -488
  80. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -2,6 +2,7 @@ import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
2
2
  import Handlebars from "handlebars";
3
3
  import { fadeReplace } from "../utils.js";
4
4
  import { SquiffyEventMap } from "../events.js";
5
+ import { parsePath } from "../paths.js";
5
6
 
6
7
  export function LivePlugin(): SquiffyPlugin {
7
8
  let squiffy: PluginHost;
@@ -29,8 +30,11 @@ export function LivePlugin(): SquiffyPlugin {
29
30
 
30
31
  const onSet = async (e: SquiffyEventMap["set"]) => {
31
32
  const promises: Promise<void>[] = [];
32
- const selector = `.squiffy-live[data-attribute="${CSS.escape(e.attribute)}"]`;
33
- for (const el of squiffy.outputElement.querySelectorAll<HTMLElement>(selector)) {
33
+ // The "set" event names the attribute that changed, so {{live "hero.hp"}} is
34
+ // updated when hero is set (#442)
35
+ const elements = [...squiffy.outputElement.querySelectorAll<HTMLElement>(".squiffy-live[data-attribute]")]
36
+ .filter(el => parsePath(el.dataset.attribute!)[0] === e.attribute);
37
+ for (const el of elements) {
34
38
  const oldContent = el.innerHTML;
35
39
  let newContent = "";
36
40
  if (el.dataset.section) {
@@ -44,9 +48,11 @@ export function LivePlugin(): SquiffyPlugin {
44
48
  newContent = squiffy.processText(passageText, true);
45
49
  }
46
50
  } else {
47
- newContent = e.value;
51
+ newContent = el.dataset.attribute == e.attribute ? e.value : squiffy.get(el.dataset.attribute!);
48
52
  }
49
- if (oldContent !== newContent) {
53
+ // A value that's a number is the same as the text on screen, e.g. when another
54
+ // part of the same attribute changes, such as another setting
55
+ if (oldContent !== String(newContent)) {
50
56
  promises.push(fadeReplace(el, newContent));
51
57
  }
52
58
  }
@@ -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,
@@ -388,6 +387,35 @@ Score: {{live "score"}}.
388
387
  });
389
388
  });
390
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
+
391
419
  test("Live plugin: embed section content", async () => {
392
420
  const script = `
393
421
  [[start]]:
@@ -478,6 +506,23 @@ You clicked!
478
506
  expect(animateSpan?.getAttribute("data-interval")).toBe("50");
479
507
  });
480
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
+
481
526
  test("Animate plugin: trigger on link", async () => {
482
527
  const script = `
483
528
  {{#animate "typewriter" trigger="link"}}[Click me]{{/animate}}
@@ -59,6 +59,28 @@ describe("preview host", () => {
59
59
  expect(sent.slice(2)).toEqual([{ channel: PREVIEW_CHANNEL, type: "theme", theme: "system" }]);
60
60
  });
61
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
+
62
84
  test("passes messages from the page to handlers, ignoring anything else", () => {
63
85
  const { channel, receive } = fakeChannel();
64
86
  const handlers = {
@@ -33,6 +33,8 @@ export interface PreviewHandlers {
33
33
  onNavigated?(section: string, passage?: string): void;
34
34
  // Whether the story's own CSS sets its color-scheme, so setTheme() makes no difference
35
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;
36
38
  onRuntimeError?(message: string, stack?: string): void;
37
39
  }
38
40
 
@@ -50,6 +52,8 @@ export interface PreviewHost {
50
52
  setAssets(assets: PreviewAssets): void;
51
53
  // Shows the story in light or dark mode. It's kept if the page reloads.
52
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;
53
57
  dispose(): void;
54
58
  }
55
59
 
@@ -57,6 +61,8 @@ export interface PreviewHost {
57
61
  // story runs with an opaque origin: it can't reach the host page, its storage or its cookies.
58
62
  export function setUpPreviewFrame(iframe: HTMLIFrameElement, previewHtml: string) {
59
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");
60
66
  iframe.srcdoc = previewHtml;
61
67
  }
62
68
 
@@ -79,6 +85,7 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
79
85
  let isReady = false;
80
86
  let queue: HostMessage[] = [];
81
87
  let theme: PreviewTheme | undefined;
88
+ let muted = false;
82
89
  let resolveReady: () => void;
83
90
  const ready = new Promise<void>(resolve => { resolveReady = resolve; });
84
91
 
@@ -96,6 +103,7 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
96
103
  // where a host can load it again
97
104
  isReady = true;
98
105
  if (theme) send({ type: "theme", theme });
106
+ if (muted) send({ type: "muted", muted });
99
107
  const queued = queue;
100
108
  queue = [];
101
109
  for (const m of queued) send(m);
@@ -118,6 +126,9 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
118
126
  case "themeFixed":
119
127
  handlers.onThemeFixed?.(message.fixed);
120
128
  break;
129
+ case "usesSound":
130
+ handlers.onUsesSound?.(message.usesSound);
131
+ break;
121
132
  case "runtimeError":
122
133
  handlers.onRuntimeError?.(message.message, message.stack);
123
134
  break;
@@ -136,6 +147,10 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
136
147
  // Sent when the page is ready, and again if it reloads
137
148
  if (isReady) send({ type: "theme", theme });
138
149
  },
150
+ setMuted: value => {
151
+ muted = value;
152
+ if (isReady) send({ type: "muted", muted });
153
+ },
139
154
  dispose: () => {
140
155
  stop();
141
156
  queue = [];
@@ -14,6 +14,9 @@ export interface PreviewStory {
14
14
  // starts "export const story".
15
15
  js: string;
16
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.
17
20
  css?: string[];
18
21
  scripts?: string[];
19
22
  }
@@ -42,7 +45,9 @@ export type HostMessage =
42
45
  | { type: "assets"; assets: PreviewAssets }
43
46
  // Shows the story in light or dark mode, e.g. to match the host's own theme. A story's own
44
47
  // CSS can still override it, e.g. with ":root { color-scheme: light; }".
45
- | { type: "theme"; theme: PreviewTheme };
48
+ | { type: "theme"; theme: PreviewTheme }
49
+ // Mutes or unmutes the story's music and sounds (#444)
50
+ | { type: "muted"; muted: boolean };
46
51
 
47
52
  export type PreviewMessage =
48
53
  // The page has loaded and is listening
@@ -55,6 +60,9 @@ export type PreviewMessage =
55
60
  // An attribute was set. Internal attributes, whose names start with "_", aren't sent.
56
61
  | { type: "attributeSet"; name: string; value: unknown }
57
62
  | { type: "canGoBackChanged"; canGoBack: boolean }
63
+ // Whether the story plays music or sounds (#444), so the host can show a mute button. Sent
64
+ // each time a story is loaded, before "loaded", and when a sound plays.
65
+ | { type: "usesSound"; usesSound: boolean }
58
66
  // A section or passage was shown, or Back went to one
59
67
  | { type: "navigated"; section: string; passage?: string }
60
68
  // An error from the story's JavaScript or the runtime
@@ -3,7 +3,7 @@ import globalJsdom from "global-jsdom";
3
3
  import { compile } from "squiffy-compiler";
4
4
  import { createPreview } from "./preview.js";
5
5
  import type { PreviewMessage } from "./preview-protocol.js";
6
- import type { Panel, Story } from "./types.js";
6
+ import type { Panel, PlayerSetting, Story } from "./types.js";
7
7
 
8
8
  beforeAll(() => {
9
9
  vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
@@ -31,8 +31,8 @@ afterEach(() => {
31
31
  });
32
32
 
33
33
  // The compiled story module, as a host would send it
34
- const compileJs = async (script: string, panels?: Panel[]) => {
35
- const result = await compile({ script, panels });
34
+ const compileJs = async (script: string, panels?: Panel[], settings?: PlayerSetting[]) => {
35
+ const result = await compile({ script, panels, settings });
36
36
  if (!result.success) throw new Error("Compile failed");
37
37
  return result.getJs();
38
38
  };
@@ -71,6 +71,7 @@ describe("preview", () => {
71
71
  expect(element.textContent).toContain("Welcome.");
72
72
  expect(messages).toEqual([
73
73
  { type: "themeFixed", fixed: false },
74
+ { type: "usesSound", usesSound: false },
74
75
  { type: "canGoBackChanged", canGoBack: false },
75
76
  // The story-wide turn count (#377), which isn't internal, so it's reported
76
77
  { type: "attributeSet", name: "turns", value: 0 },
@@ -98,6 +99,46 @@ describe("preview", () => {
98
99
  expect(messages).toContainEqual({ type: "canGoBackChanged", canGoBack: false });
99
100
  });
100
101
 
102
+ test("reports a story with sound, mutes it, and stops it when another story is loaded (#444)", async () => {
103
+ const played: { src: string; muted: boolean; paused: boolean }[] = [];
104
+ vi.stubGlobal("Audio", class {
105
+ muted = false;
106
+ paused = true;
107
+ volume = 1;
108
+ loop = false;
109
+ preload = "";
110
+ constructor(public src = "") {
111
+ played.push(this);
112
+ }
113
+ play() {
114
+ this.paused = false;
115
+ return Promise.resolve();
116
+ }
117
+ pause() {
118
+ this.paused = true;
119
+ }
120
+ addEventListener() {}
121
+ });
122
+ try {
123
+ const { preview, messages } = setUp();
124
+ await preview.receive({ type: "muted", muted: true });
125
+ await preview.receive({ type: "load", story: { js: await compileJs("@music theme.mp3\nHello.") } });
126
+ expect(messages).toContainEqual({ type: "usesSound", usesSound: true });
127
+ const music = played.filter(a => !a.paused);
128
+ expect(music.map(a => a.muted)).toEqual([true]);
129
+
130
+ await preview.receive({ type: "muted", muted: false });
131
+ expect(music[0].muted).toBe(false);
132
+
133
+ await preview.receive({ type: "load", story: { js: await compileJs("Hello.") } });
134
+ expect(played.filter(a => !a.paused)).toEqual([]);
135
+ }
136
+ finally {
137
+ vi.unstubAllGlobals();
138
+ vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
139
+ }
140
+ });
141
+
101
142
  test("starts at a section or a passage", async () => {
102
143
  const { preview, messages, element } = setUp();
103
144
  const js = await compileJs(script);
@@ -174,6 +215,26 @@ describe("preview", () => {
174
215
  expect(fixed()).toEqual([]);
175
216
  });
176
217
 
218
+ test("swaps the url()s in the story's stylesheets for its assets' URLs", async () => {
219
+ const { preview } = setUp();
220
+ const js = await compileJs(script);
221
+ const css = `@font-face { src: url("fonts/a.woff2") format("woff2"), url(missing.woff); }
222
+ body { background: url('./bg.png'), url(https://example.com/x.png); }`;
223
+ const style = () => [...document.head.querySelectorAll("style")][1].textContent;
224
+ await preview.receive({ type: "assets", assets: { files: { "fonts/a.woff2": new Uint8Array([1]), "bg.png": new Uint8Array([2]) } } });
225
+ await preview.receive({ type: "load", story: { js, css: [css] } });
226
+ expect(style()).toBe(`@font-face { src: url("blob:preview/0") format("woff2"), url(missing.woff); }
227
+ body { background: url("blob:preview/1"), url(https://example.com/x.png); }`);
228
+
229
+ // New assets go to the stylesheets that are already there
230
+ await preview.receive({ type: "assets", assets: { files: { "fonts/a.woff2": new Uint8Array([3]) } } });
231
+ expect(style()).toContain("src: url(\"blob:preview/2\")");
232
+ expect(style()).toContain("url('./bg.png')");
233
+ // The same stylesheet again changes nothing
234
+ await preview.receive({ type: "update", js, css: [css] });
235
+ expect(style()).toContain("src: url(\"blob:preview/2\")");
236
+ });
237
+
177
238
  test("adds the story's stylesheets, replacing the previous story's", async () => {
178
239
  const { preview } = setUp();
179
240
  const js = await compileJs(script);
@@ -228,6 +289,56 @@ describe("preview", () => {
228
289
  expect(document.querySelectorAll("dialog.squiffy-panel-dialog")).toHaveLength(0);
229
290
  });
230
291
 
292
+ test("shows a Settings button for a story with settings, which opens the Settings dialog", async () => {
293
+ const { preview, element } = setUp();
294
+ const settings: PlayerSetting[] = [{ name: "warnings", label: "Content warnings", type: "toggle" }];
295
+ const panels: Panel[] = [{ passage: "status", label: "Status" }];
296
+ const panelScript = "[[]]:\n\n[status]:\nScore: {{score}}\n\n" + script;
297
+ await preview.receive({ type: "load", story: { js: await compileJs(panelScript, panels, settings) } });
298
+ const buttons = () => [...element.querySelectorAll<HTMLButtonElement>(".squiffy-preview-header button")];
299
+ expect(buttons().map(b => b.title || b.textContent)).toEqual(["Status", "Settings"]);
300
+ buttons()[1].click();
301
+ expect(document.querySelector("dialog.squiffy-settings label")!.textContent).toBe("Content warnings");
302
+
303
+ // Still after the panels' buttons when they change
304
+ await preview.receive({ type: "update", js: await compileJs(panelScript, [{ passage: "status", label: "Score" }], settings) });
305
+ expect(buttons().map(b => b.title || b.textContent)).toEqual(["Score", "Settings"]);
306
+
307
+ await preview.receive({ type: "update", js: await compileJs(panelScript, panels) });
308
+ expect(buttons().map(b => b.title || b.textContent)).toEqual(["Status"]);
309
+
310
+ await preview.receive({ type: "load", story: { js: await compileJs(script) } });
311
+ expect(document.querySelectorAll("dialog.squiffy-settings")).toHaveLength(0);
312
+ });
313
+
314
+ test("puts the story's classes on #squiffy, as a published story does", async () => {
315
+ const { preview, element } = setUp();
316
+ const settings: PlayerSetting[] = [{ name: "warnings", label: "Content warnings", type: "toggle" }];
317
+ const classScript = "[[start]]:\n@class dark\nIn the [[cellar]].\n\n[[cellar]]:\nDown here.\n";
318
+ await preview.receive({ type: "load", story: { js: await compileJs(classScript, undefined, settings) } });
319
+ expect(element.id).toBe("squiffy");
320
+ expect(element.classList.contains("dark")).toBe(true);
321
+ expect(document.querySelector("div#squiffy.dark")).toBe(element);
322
+
323
+ // A setting's class, when the player changes it
324
+ element.querySelector<HTMLButtonElement>(".squiffy-settings-button")!.click();
325
+ const toggle = document.querySelector<HTMLInputElement>("dialog.squiffy-settings input[type=checkbox]")!;
326
+ toggle.checked = true;
327
+ toggle.dispatchEvent(new window.Event("change"));
328
+ await Promise.resolve();
329
+ expect(element.classList.contains("setting-warnings")).toBe(true);
330
+
331
+ // A section's class goes when the player leaves it
332
+ element.querySelector<HTMLAnchorElement>("a.squiffy-link")!.click();
333
+ await new Promise(resolve => setTimeout(resolve, 0));
334
+ expect(element.classList.contains("dark")).toBe(false);
335
+ expect(element.classList.contains("setting-warnings")).toBe(true);
336
+
337
+ // And a new story starts with none
338
+ await preview.receive({ type: "load", story: { js: await compileJs(script) } });
339
+ expect([...element.classList]).toEqual([]);
340
+ });
341
+
231
342
  test("reports errors", async () => {
232
343
  const messages: PreviewMessage[] = [];
233
344
  const preview = createPreview({
package/src/preview.ts CHANGED
@@ -3,8 +3,9 @@
3
3
 
4
4
  import { init } from "./squiffy.runtime.js";
5
5
  import { createPanels, type Panels } from "./panels.js";
6
+ import { createSettingsDialog, SETTINGS_ICON, type SettingsDialog } from "./settingsDialog.js";
6
7
  import type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory } from "./preview-protocol.js";
7
- import type { Panel, SquiffyApi, Story } from "./types.js";
8
+ import type { Panel, PlayerSetting, SquiffyApi, Story } from "./types.js";
8
9
 
9
10
  export interface PreviewOptions {
10
11
  // Where to show the story
@@ -28,6 +29,10 @@ const mimeType = (path: string) => mimeTypes[path.substring(path.lastIndexOf("."
28
29
 
29
30
  const normalisePath = (path: string) => path.replace(/^(\.\/)+/, "");
30
31
 
32
+ // The url()s in a story's stylesheet that are paths, rather than web addresses, data: URIs and the like
33
+ const CSS_URL = /url\(\s*(?:"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|([^)"'\s]*))\s*\)/gi;
34
+ const isRelativeUrl = (url: string) => url != "" && !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url);
35
+
31
36
  async function importFromBlob(js: string): Promise<{ story: Story }> {
32
37
  const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
33
38
  try {
@@ -53,13 +58,27 @@ export function createPreview(options: PreviewOptions) {
53
58
  let panels: Panels | undefined;
54
59
  let panelsJson = "";
55
60
  let panelButtons: HTMLElement | undefined;
61
+ // The Settings button (#452), after the panels' buttons, for a story with "settings"
62
+ let settingsButton: HTMLButtonElement | undefined;
63
+ let settingsDialog: SettingsDialog | undefined;
56
64
  let panelSide: HTMLElement | undefined;
65
+ // The runtime puts the story's classes (@class, {{addclass}}, settings such as
66
+ // setting-textSize-Large) on the element it's given, which here is inside the header and side
67
+ // panels' layout. They're copied to the preview's own element, which is #squiffy as on a
68
+ // published page, so stylesheets with rules such as div#squiffy.dark work here too.
69
+ let classObserver: MutationObserver | undefined;
70
+ let mirroredClasses: string[] = [];
71
+ // The host's mute button (#444), which carries on to the next story loaded
72
+ let muted = false;
73
+ let usesSound = false;
57
74
  // Each load gets a new number, so a slow load that's been replaced doesn't start
58
75
  let loadCount = 0;
59
76
  const assetUrls = new Map<string, string>();
60
77
  const objectUrls: string[] = [];
61
78
  // The story's own stylesheets and scripts
62
79
  let styles: HTMLStyleElement[] = [];
80
+ // Their text as the host sent it, before withAssetUrls
81
+ let styleTexts: string[] = [];
63
82
  let scripts: HTMLScriptElement[] = [];
64
83
  // Sets the theme. It's added before any of the story's own stylesheets, so they can override it.
65
84
  const themeStyle = document.createElement("style");
@@ -102,27 +121,39 @@ export function createPreview(options: PreviewOptions) {
102
121
  objectUrls.push(url);
103
122
  assetUrls.set(normalisePath(path), url);
104
123
  }
124
+ // The stylesheets' url()s, such as their fonts, may now be different files
125
+ styles.forEach((style, i) => { style.textContent = withAssetUrls(styleTexts[i]); });
105
126
  }
106
127
 
128
+ // A stylesheet with its url()s, which are paths from the story's folder, swapped for the
129
+ // assets' URLs. One that isn't an asset is left as it is.
130
+ const withAssetUrls = (css: string) => css.replace(CSS_URL, (match, double?: string, single?: string, bare?: string) => {
131
+ const url = (double ?? single ?? bare ?? "").trim();
132
+ const resolved = isRelativeUrl(url) ? assetUrls.get(normalisePath(url)) : undefined;
133
+ return resolved ? `url("${resolved}")` : match;
134
+ });
135
+
107
136
  // Replaces the story's stylesheets, where the old ones were, so they stay before its scripts
108
137
  // (which may add styles of their own). Returns false if they haven't changed.
109
138
  function setStyles(css: string[]): boolean {
110
- if (css.length == styles.length && css.every((text, i) => styles[i].textContent == text)) return false;
139
+ if (css.length == styleTexts.length && css.every((text, i) => styleTexts[i] == text)) return false;
111
140
  const before = styles[0] ?? scripts[0] ?? null;
112
141
  const added = css.map(text => {
113
142
  const style = document.createElement("style");
114
- style.textContent = text;
143
+ style.textContent = withAssetUrls(text);
115
144
  document.head.insertBefore(style, before);
116
145
  return style;
117
146
  });
118
147
  for (const style of styles) style.remove();
119
148
  styles = added;
149
+ styleTexts = [...css];
120
150
  return true;
121
151
  }
122
152
 
123
153
  async function addStoryFiles(story: PreviewStory) {
124
154
  for (const element of [...styles, ...scripts]) element.remove();
125
155
  styles = [];
156
+ styleTexts = [];
126
157
  scripts = [];
127
158
  setStyles(story.css ?? []);
128
159
  for (const js of story.scripts ?? []) {
@@ -138,9 +169,22 @@ export function createPreview(options: PreviewOptions) {
138
169
  }
139
170
  }
140
171
 
172
+ function mirrorClasses(from: HTMLElement | undefined) {
173
+ const classes = from ? [...from.classList].filter(c => c != "squiffy-preview-story") : [];
174
+ for (const c of mirroredClasses) {
175
+ if (!classes.includes(c)) options.element.classList.remove(c);
176
+ }
177
+ for (const c of classes) options.element.classList.add(c);
178
+ mirroredClasses = classes;
179
+ }
180
+
141
181
  async function load(message: Extract<HostMessage, { type: "load" }>) {
142
182
  const thisLoad = ++loadCount;
183
+ api?.dispose();
143
184
  api = undefined;
185
+ classObserver?.disconnect();
186
+ classObserver = undefined;
187
+ mirrorClasses(undefined);
144
188
  options.element.innerHTML = "";
145
189
  await addStoryFiles(message.story);
146
190
  const { story } = await loadModule(message.story.js);
@@ -150,6 +194,9 @@ export function createPreview(options: PreviewOptions) {
150
194
  panels?.dispose();
151
195
  panels = undefined;
152
196
  panelsJson = "";
197
+ settingsDialog?.element.remove();
198
+ settingsDialog = undefined;
199
+ settingsButton = undefined;
153
200
  panelButtons = document.createElement("div");
154
201
  panelButtons.className = "squiffy-preview-header";
155
202
  panelSide = document.createElement("div");
@@ -158,6 +205,8 @@ export function createPreview(options: PreviewOptions) {
158
205
  container.className = "squiffy-preview-story";
159
206
  panelSide.appendChild(container);
160
207
  options.element.append(panelButtons, panelSide);
208
+ classObserver = new MutationObserver(() => mirrorClasses(container));
209
+ classObserver.observe(container, { attributes: true, attributeFilter: ["class"] });
161
210
 
162
211
  const newApi = await init({
163
212
  element: container,
@@ -175,10 +224,22 @@ export function createPreview(options: PreviewOptions) {
175
224
  newApi.on("navigated", e => {
176
225
  if (thisLoad == loadCount) send({ type: "navigated", ...e });
177
226
  });
227
+ newApi.on("sound", () => {
228
+ if (thisLoad == loadCount && !usesSound) {
229
+ usesSound = true;
230
+ send({ type: "usesSound", usesSound });
231
+ }
232
+ });
233
+ newApi.setMuted(muted);
234
+ usesSound = newApi.usesSound();
235
+ send({ type: "usesSound", usesSound });
178
236
  api = newApi;
179
237
  setPanels(story.panels);
238
+ setSettingsButton(story.settings);
180
239
  send({ type: "canGoBackChanged", canGoBack: false });
181
240
  await newApi.begin(message.startAt);
241
+ // Now, rather than waiting for the observer, so they're there when the host hears it's loaded
242
+ if (thisLoad == loadCount) mirrorClasses(container);
182
243
  if (thisLoad == loadCount) send({ type: "loaded" });
183
244
  }
184
245
 
@@ -191,6 +252,34 @@ export function createPreview(options: PreviewOptions) {
191
252
  panels = list?.length ? createPanels(api, { panels: list, buttons: panelButtons, side: panelSide }) : undefined;
192
253
  }
193
254
 
255
+ // Shows the Settings button if the story has settings
256
+ function setSettingsButton(list: PlayerSetting[] | undefined) {
257
+ if (!api || !panelButtons) return;
258
+ if (!list?.length) {
259
+ settingsButton?.remove();
260
+ settingsButton = undefined;
261
+ return;
262
+ }
263
+ if (settingsButton) {
264
+ panelButtons.appendChild(settingsButton);
265
+ return;
266
+ }
267
+ const button = document.createElement("button");
268
+ button.type = "button";
269
+ button.className = "squiffy-header-button squiffy-settings-button";
270
+ button.title = "Settings";
271
+ button.setAttribute("aria-label", "Settings");
272
+ button.setAttribute("aria-haspopup", "dialog");
273
+ button.innerHTML = SETTINGS_ICON;
274
+ button.addEventListener("click", () => {
275
+ if (!api) return;
276
+ settingsDialog ??= createSettingsDialog(api);
277
+ settingsDialog.open();
278
+ });
279
+ panelButtons.appendChild(button);
280
+ settingsButton = button;
281
+ }
282
+
194
283
  async function receive(message: HostMessage) {
195
284
  try {
196
285
  switch (message.type) {
@@ -205,6 +294,7 @@ export function createPreview(options: PreviewOptions) {
205
294
  const { story } = await loadModule(message.js);
206
295
  api.update(story);
207
296
  setPanels(story.panels);
297
+ setSettingsButton(story.settings);
208
298
  }
209
299
  break;
210
300
  case "restart":
@@ -216,6 +306,10 @@ export function createPreview(options: PreviewOptions) {
216
306
  case "assets":
217
307
  setAssets(message.assets);
218
308
  break;
309
+ case "muted":
310
+ muted = message.muted;
311
+ api?.setMuted(muted);
312
+ break;
219
313
  case "theme":
220
314
  themeStyle.textContent = message.theme == "system" ? "" : `:root { color-scheme: ${message.theme}; }`;
221
315
  break;