squiffy-runtime 7.0.0-beta.7 → 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 (56) hide show
  1. package/dist/confirmDialog.d.ts +8 -0
  2. package/dist/events.d.ts +10 -0
  3. package/dist/every.d.ts +12 -0
  4. package/dist/every.test.d.ts +1 -0
  5. package/dist/playerSettings.d.ts +17 -0
  6. package/dist/preview-html.js +1 -1
  7. package/dist/settings.test.d.ts +1 -0
  8. package/dist/settingsDialog.d.ts +17 -0
  9. package/dist/squiffy.page.css +4 -1
  10. package/dist/squiffy.preview.html +673 -83
  11. package/dist/squiffy.runtime.css +531 -1
  12. package/dist/squiffy.runtime.d.ts +5 -1
  13. package/dist/squiffy.runtime.global.js +106 -85
  14. package/dist/squiffy.runtime.global.js.map +1 -1
  15. package/dist/squiffy.runtime.js +4743 -4157
  16. package/dist/squiffy.runtime.js.map +1 -1
  17. package/dist/state.d.ts +1 -0
  18. package/dist/style.test.d.ts +1 -0
  19. package/dist/textProcessor.d.ts +8 -0
  20. package/dist/transitions.test.d.ts +1 -0
  21. package/dist/types.d.ts +43 -0
  22. package/dist/uiLinks.test.d.ts +1 -0
  23. package/dist/utils.d.ts +1 -0
  24. package/dist/utils.test.d.ts +1 -0
  25. package/package.json +3 -3
  26. package/src/animation.test.ts +44 -0
  27. package/src/animation.ts +7 -3
  28. package/src/confirmDialog.ts +66 -0
  29. package/src/events.ts +17 -0
  30. package/src/every.test.ts +25 -0
  31. package/src/every.ts +94 -0
  32. package/src/panels.test.ts +24 -0
  33. package/src/playerSettings.ts +128 -0
  34. package/src/plugins/animate.ts +9 -0
  35. package/src/plugins/live.ts +3 -1
  36. package/src/plugins/plugins.test.ts +17 -0
  37. package/src/preview.test.ts +53 -3
  38. package/src/preview.ts +60 -1
  39. package/src/settings.test.ts +233 -0
  40. package/src/settingsDialog.ts +160 -0
  41. package/src/squiffy.page.css +4 -1
  42. package/src/squiffy.runtime.css +531 -1
  43. package/src/squiffy.runtime.test.ts +613 -16
  44. package/src/squiffy.runtime.ts +372 -19
  45. package/src/state.ts +16 -1
  46. package/src/style.test.ts +89 -0
  47. package/src/textProcessor.ts +141 -6
  48. package/src/transitions.test.ts +302 -0
  49. package/src/types.ts +56 -0
  50. package/src/uiLinks.test.ts +156 -0
  51. package/src/utils.test.ts +60 -0
  52. package/src/utils.ts +44 -14
  53. package/dist/infixExpressions.d.ts +0 -7
  54. package/src/infixExpressions.test.ts +0 -516
  55. package/src/infixExpressions.ts +0 -672
  56. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
package/dist/state.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare class State {
8
8
  emitter: Emitter<SquiffyEventMap>;
9
9
  constructor(persist: boolean, storyId: string, onSet: (attribute: string, value: any) => void, emitter: Emitter<SquiffyEventMap>, onSetInternal?: (attribute: string, oldValue: any, newValue: any) => void);
10
10
  private usePersistentStorage;
11
+ playerSettings: () => Record<string, unknown> | null;
11
12
  readOnly: boolean;
12
13
  set(attribute: string, value: any): void;
13
14
  setAt(segments: string[], value: any): void;
@@ -0,0 +1 @@
1
+ export {};
@@ -7,12 +7,18 @@ export declare class TextProcessor {
7
7
  getCurrentSection: () => Section;
8
8
  handlebars: typeof Handlebars;
9
9
  constructor(story: () => Story, state: State, currentSection: () => Section);
10
+ strings: {
11
+ restart: string;
12
+ saves: string;
13
+ settings: string;
14
+ };
10
15
  evaluate(expression: string): unknown;
11
16
  goto: {
12
17
  section: string;
13
18
  after: number;
14
19
  } | null;
15
20
  deactivate: Set<string>;
21
+ stopEvery: boolean;
16
22
  private scopes;
17
23
  private embeddedText;
18
24
  private get params();
@@ -21,6 +27,8 @@ export declare class TextProcessor {
21
27
  getAttribute(attribute: string): any;
22
28
  setAttribute(attribute: string, value: any): void;
23
29
  private context;
30
+ private processing;
31
+ private positionKey;
24
32
  private expressionCache;
25
33
  private evaluated;
26
34
  process(text: string, inline: boolean): string;
@@ -0,0 +1 @@
1
+ export {};
package/dist/types.d.ts CHANGED
@@ -13,6 +13,12 @@ export interface SquiffyInitOptions {
13
13
  * left alone. When not provided, paths are used as they are.
14
14
  */
15
15
  resolveAssetUrl?: (path: string) => string;
16
+ /**
17
+ * The page's text, for a story in another language: squiffy.json's "strings", by the same
18
+ * names. Used for the text of {{restart}} and {{saves}} links (#452), and the dialogs they
19
+ * open when the page doesn't handle them itself. Anything left out is in English.
20
+ */
21
+ strings?: Partial<Record<string, string>>;
16
22
  }
17
23
  export interface SquiffySettings {
18
24
  scroll: string;
@@ -38,6 +44,10 @@ export interface SquiffyApi {
38
44
  isMuted: () => boolean;
39
45
  setMuted: (muted: boolean) => void;
40
46
  usesSound: () => boolean;
47
+ getSettings: () => PlayerSetting[];
48
+ getSetting: (name: string) => SettingValue | null;
49
+ setSetting: (name: string, value: SettingValue) => void;
50
+ resetSettings: () => void;
41
51
  dispose: () => void;
42
52
  on<E extends keyof SquiffyEventMap>(event: E, handler: SquiffyEventHandler<E>): () => void;
43
53
  off<E extends keyof SquiffyEventMap>(event: E, handler: SquiffyEventHandler<E>): void;
@@ -64,6 +74,7 @@ export interface Story {
64
74
  audio?: string[];
65
75
  expressions?: boolean;
66
76
  panels?: Panel[];
77
+ settings?: PlayerSetting[];
67
78
  sections: Record<string, Section>;
68
79
  }
69
80
  export declare const PANEL_ICONS: readonly ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"];
@@ -74,12 +85,40 @@ export interface Panel {
74
85
  position?: "side" | "button";
75
86
  icon?: PanelIcon;
76
87
  }
88
+ export type PlayerSetting = PlayerSettingBase & {
89
+ type: "toggle";
90
+ default?: boolean;
91
+ } | PlayerSettingBase & {
92
+ type: "list";
93
+ options: PlayerSettingOption[];
94
+ default?: string;
95
+ } | PlayerSettingBase & {
96
+ type: "range";
97
+ min: number;
98
+ max: number;
99
+ step?: number;
100
+ default?: number;
101
+ };
102
+ interface PlayerSettingBase {
103
+ name: string;
104
+ label: string;
105
+ description?: string;
106
+ }
107
+ export interface PlayerSettingOption {
108
+ value: string;
109
+ label: string;
110
+ }
111
+ export type SettingValue = boolean | string | number;
77
112
  export interface Section {
78
113
  text?: string;
79
114
  clear?: boolean;
80
115
  music?: string | null;
81
116
  sounds?: string[];
82
117
  classes?: string[];
118
+ transition?: string;
119
+ transitionTime?: number;
120
+ leave?: string;
121
+ leaveTime?: number;
83
122
  attributes?: string[];
84
123
  jsIndex?: number;
85
124
  passages?: Record<string, Passage>;
@@ -91,6 +130,10 @@ export interface Passage {
91
130
  music?: string | null;
92
131
  sounds?: string[];
93
132
  classes?: string[];
133
+ transition?: string;
134
+ transitionTime?: number;
135
+ leave?: string;
136
+ leaveTime?: number;
94
137
  repeat?: boolean;
95
138
  attributes?: string[];
96
139
  jsIndex?: number;
@@ -0,0 +1 @@
1
+ export {};
package/dist/utils.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export declare function fadeReplace(element: HTMLElement, text: string): Promise<void>;
2
+ export declare function parseDelay(value: unknown): number | null;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squiffy-runtime",
3
- "version": "7.0.0-beta.7",
3
+ "version": "7.0.0-beta.8",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/textadventures/squiffy.git",
@@ -49,7 +49,7 @@
49
49
  "esbuild": "^0.28.2",
50
50
  "global-jsdom": "^31.0.0",
51
51
  "jsdom": "^31.0.1",
52
- "squiffy-compiler": "^7.0.0-beta.7",
52
+ "squiffy-compiler": "^7.0.0-beta.8",
53
53
  "typescript": "^6.0.3",
54
54
  "vite": "^8.3.8",
55
55
  "vite-plugin-dts": "^5.1.2"
@@ -59,5 +59,5 @@
59
59
  "handlebars": "^4.7.10",
60
60
  "marked": "^18.2.0"
61
61
  },
62
- "gitHead": "ce089d0f0d0901c10e5a148e38cb1fdbb5d5a2d2"
62
+ "gitHead": "385947977612d33f310c92ef6ed9e1a423d8cb19"
63
63
  }
@@ -0,0 +1,44 @@
1
+ // The built-in animations in animation.ts
2
+ import { afterAll, beforeAll, expect, test } from "vitest";
3
+ import globalJsdom from "global-jsdom";
4
+ import type { Animation as AnimationClass } from "./animation.js";
5
+
6
+ let cleanup: () => void;
7
+ let Animation: typeof AnimationClass;
8
+
9
+ // anime.js keeps the document it finds when it's first imported, so there's one DOM for the
10
+ // whole file, made before it's imported
11
+ beforeAll(async () => {
12
+ cleanup = globalJsdom("<!DOCTYPE html><html><body></body></html>");
13
+ // jsdom has no ResizeObserver or document.fonts, which anime.js's splitText uses to split text
14
+ // into lines again when it's resized, and once the fonts have loaded
15
+ (globalThis as any).ResizeObserver ??= class { observe() {} unobserve() {} disconnect() {} };
16
+ Object.defineProperty(document, "fonts", { value: { status: "loaded", ready: Promise.resolve() } });
17
+ ({ Animation } = await import("./animation.js"));
18
+ });
19
+
20
+ afterAll(() => {
21
+ cleanup();
22
+ });
23
+
24
+ // The characters the animation split the text into, grouped by the element that holds them
25
+ const charsByParent = (el: HTMLElement) => {
26
+ const groups = new Map<Element, string>();
27
+ for (const char of el.querySelectorAll("[data-char]")) {
28
+ groups.set(char.parentElement!, (groups.get(char.parentElement!) ?? "") + char.textContent);
29
+ }
30
+ return [...groups.values()];
31
+ };
32
+
33
+ test.each([
34
+ ["typewriter", {}],
35
+ ["continue", { style: "wave" }],
36
+ ])("%s keeps each word's characters together, so a line can't break inside a word", (name, params) => {
37
+ const el = document.createElement("span");
38
+ el.textContent = "Now, let's spin...";
39
+ document.body.appendChild(el);
40
+
41
+ new Animation().runAnimation(name, el, params, () => {}, false);
42
+
43
+ expect(charsByParent(el)).toEqual(["Now,", "let's", "spin..."]);
44
+ });
package/src/animation.ts CHANGED
@@ -50,7 +50,10 @@ export class Animation {
50
50
 
51
51
  constructor() {
52
52
  this.registerAnimation("typewriter", function(el, params, onComplete, loop) {
53
- const { chars } = splitText(el, { words: false, chars: true });
53
+ // Each character in a span, inside a span for its word, so a line only breaks
54
+ // between words: without the words, it could break anywhere, e.g. at the
55
+ // apostrophe in "let's"
56
+ const { chars } = splitText(el, { words: true, chars: true });
54
57
 
55
58
  const fadeDuration = params.fadeDuration || 100; // ms fade-in per character
56
59
  const interval = params.interval || 100; // ms between each character appearing
@@ -106,9 +109,10 @@ export class Animation {
106
109
  let chars: HTMLElement[] | null = null;
107
110
 
108
111
  if (style === "wave") {
109
- // Wave style needs JS animation - split into chars and animate opacity
112
+ // Wave style needs JS animation - split into chars and animate opacity. Words too,
113
+ // so a line only breaks between words, as with typewriter.
110
114
  el.classList.add("squiffy-continue-wave");
111
- const split = splitText(el, { words: false, chars: true });
115
+ const split = splitText(el, { words: true, chars: true });
112
116
  chars = split.chars as HTMLElement[];
113
117
 
114
118
  waveAnimation = animate(chars, {
@@ -0,0 +1,66 @@
1
+ // A question for the player, such as "Are you sure you want to restart?", in a dialog that looks
2
+ // like the rest of the page, in place of the browser's confirm()
3
+
4
+ export interface ConfirmDialogOptions {
5
+ message: string;
6
+ // The button that goes ahead, e.g. "Restart"
7
+ confirm: string;
8
+ // "Cancel" by default
9
+ cancel?: string;
10
+ // Whether going ahead loses something, which colours its button as a warning
11
+ danger?: boolean;
12
+ // Where the dialog goes in the page: the end of the body by default
13
+ container?: HTMLElement;
14
+ }
15
+
16
+ let dialogCount = 0;
17
+
18
+ // Shows the question, and resolves true if the player goes ahead. Escape, Cancel and clicking
19
+ // outside the dialog all resolve false. The dialog is taken off the page once it's answered.
20
+ export function confirmDialog(options: ConfirmDialogOptions): Promise<boolean> {
21
+ const id = `squiffy-confirm-${++dialogCount}`;
22
+ const dialog = document.createElement("dialog");
23
+ dialog.className = "squiffy-confirm";
24
+ dialog.setAttribute("role", "alertdialog");
25
+ dialog.setAttribute("aria-labelledby", `${id}-message`);
26
+ dialog.innerHTML = `
27
+ <p id="${id}-message"></p>
28
+ <div class="squiffy-confirm-buttons">
29
+ <button type="button" class="squiffy-confirm-button" data-answer="no"></button>
30
+ <button type="button" class="squiffy-confirm-button ${options.danger ? "squiffy-confirm-danger" : "squiffy-confirm-primary"}" data-answer="yes"></button>
31
+ </div>`;
32
+ dialog.querySelector("p")!.textContent = options.message;
33
+ const no = dialog.querySelector<HTMLButtonElement>("[data-answer=no]")!;
34
+ const yes = dialog.querySelector<HTMLButtonElement>("[data-answer=yes]")!;
35
+ no.textContent = options.cancel ?? "Cancel";
36
+ yes.textContent = options.confirm;
37
+ (options.container ?? document.body).appendChild(dialog);
38
+
39
+ return new Promise<boolean>(resolve => {
40
+ let answered = false;
41
+ const finish = (answer: boolean) => {
42
+ if (answered) return;
43
+ answered = true;
44
+ if (dialog.open) dialog.close();
45
+ dialog.remove();
46
+ resolve(answer);
47
+ };
48
+ no.addEventListener("click", () => finish(false));
49
+ yes.addEventListener("click", () => finish(true));
50
+ // Escape
51
+ dialog.addEventListener("cancel", e => {
52
+ e.preventDefault();
53
+ finish(false);
54
+ });
55
+ dialog.addEventListener("close", () => finish(false));
56
+ // A click on the backdrop is on the dialog itself, outside its content
57
+ dialog.addEventListener("click", e => {
58
+ if (e.target !== dialog) return;
59
+ const rect = dialog.getBoundingClientRect();
60
+ const inside = e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom;
61
+ if (!inside) finish(false);
62
+ });
63
+ dialog.showModal();
64
+ yes.focus();
65
+ });
66
+ }
package/src/events.ts CHANGED
@@ -7,6 +7,18 @@ export type SquiffyEventMap = {
7
7
  navigated: { section: string, passage?: string }; // a section or passage was shown, or Back went to one
8
8
  sound: Record<string, never>; // music or a sound started playing (#444), even if it's muted
9
9
  storyUpdated: Record<string, never>; // update() changed the story, e.g. after an edit in the editor
10
+ // A {{restart}} link was clicked (#452). With a handler, the page does the restarting, asking
11
+ // first if confirm is true. Without one, the runtime asks in its own dialog.
12
+ restartRequested: { confirm: boolean };
13
+ // A {{saves}} link was clicked (#452). With a handler, the page opens its Saved games dialog.
14
+ // Without one, the runtime opens one of its own.
15
+ savesRequested: Record<string, never>;
16
+ // A {{settings}} link was clicked (#452). With a handler, the page opens its Settings dialog.
17
+ // Without one, the runtime opens one of its own.
18
+ settingsRequested: Record<string, never>;
19
+ // The player changed a setting (#452). Putting them back to their defaults raises it for each
20
+ // one that changes.
21
+ settingChanged: { name: string, value: unknown };
10
22
  };
11
23
 
12
24
  export type SquiffyEventHandler<E extends keyof SquiffyEventMap> =
@@ -33,6 +45,11 @@ export class Emitter<Events extends Record<string, any>> {
33
45
  return off;
34
46
  }
35
47
 
48
+ // Whether anything is listening for the event
49
+ has<E extends keyof Events>(event: E) {
50
+ return (this.listeners.get(event)?.size ?? 0) > 0;
51
+ }
52
+
36
53
  emit<E extends keyof Events>(event: E, payload: Events[E]) {
37
54
  this.listeners.get(event)?.forEach(h => {
38
55
  try { (h as any)(payload); } catch (err) {
@@ -0,0 +1,25 @@
1
+ import { expect, test } from "vitest";
2
+ import { captureEveryBodies } from "./every.js";
3
+
4
+ const body = (text: string) => `__body="${encodeURIComponent(text)}"`;
5
+
6
+ test("captureEveryBodies copies each {{#every}}'s text into it (#451)", () => {
7
+ expect(captureEveryBodies("A {{#every 1000}}Tick {{n}}{{/every}} B"))
8
+ .toBe(`A {{#every 1000 ${body("Tick {{n}}")}}}Tick {{n}}{{/every}} B`);
9
+ expect(captureEveryBodies("{{~#every 1000 times=2~}}x{{~/every~}}"))
10
+ .toBe(`{{~#every 1000 times=2 ${body("x")}~}}x{{~/every~}}`);
11
+ expect(captureEveryBodies("{{#every \"1s\"}}\"quoted}}\"{{/every}}"))
12
+ .toBe(`{{#every "1s" ${body("\"quoted}}\"")}}}"quoted}}"{{/every}}`);
13
+ });
14
+
15
+ test("captureEveryBodies handles {{#every}} inside {{#every}}", () => {
16
+ const inner = "{{#every 500}}in{{/every}}";
17
+ expect(captureEveryBodies(`{{#every 1000}}out ${inner}{{/every}}`))
18
+ .toBe(`{{#every 1000 ${body(`out ${inner}`)}}}out {{#every 500 ${body("in")}}}in{{/every}}{{/every}}`);
19
+ });
20
+
21
+ test("captureEveryBodies leaves other text alone", () => {
22
+ for (const text of ["no tags", "{{#if a}}x{{/if}}", "\\{{#every 1000}}x{{/every}}", "{{#everything}}x{{/everything}}"]) {
23
+ expect(captureEveryBodies(text)).toBe(text);
24
+ }
25
+ });
package/src/every.ts ADDED
@@ -0,0 +1,94 @@
1
+ // {{#every 1000}}...{{/every}} (#451): text shown again and again, every so often, while the
2
+ // player is in the section. Each time, its text is worked out again and replaces what it showed
3
+ // before (or, with append=true, is added after it), until a {{stop}} inside it, times= ticks, or
4
+ // the player moving on to another section.
5
+ //
6
+ // The text is kept in the page, so a saved game, going back and the editor's preview can start
7
+ // it again: before the text is compiled, captureEveryBodies() copies each {{#every}}'s text into a
8
+ // hidden __body= parameter, which the helper puts in the element it writes.
9
+
10
+ import { findTagEnd } from "squiffy-compiler/infix-expressions";
11
+
12
+ const everyTag = /(\\*)\{\{~?\s*(?:(#every)(?=[\s}~])|(\/every)\s*~?\}\})/g;
13
+
14
+ // Adds __body="..." to each {{#every}}, with the text between it and its {{/every}}, encoded so
15
+ // that it can't end the string or the tag
16
+ export function captureEveryBodies(text: string): string {
17
+ if (!text.includes("#every")) return text;
18
+ const insertions: { at: number; text: string }[] = [];
19
+ const open: { tagEnd: number; bodyStart: number }[] = [];
20
+ everyTag.lastIndex = 0;
21
+ let match: RegExpExecArray | null;
22
+ while ((match = everyTag.exec(text)) !== null) {
23
+ // An odd number of backslashes escapes the mustache
24
+ if (match[1].length % 2 === 1) continue;
25
+ if (match[2]) {
26
+ const tagEnd = findTagEnd(text, match.index + match[0].length);
27
+ if (tagEnd === -1) break;
28
+ const bodyStart = text.indexOf("}}", tagEnd) + 2;
29
+ // With no delay, it's left for the helper to report, as __body= would be the delay
30
+ const hasDelay = text.slice(match.index + match[0].length, tagEnd).trim() !== "";
31
+ open.push({ tagEnd: hasDelay ? tagEnd : -1, bodyStart });
32
+ everyTag.lastIndex = bodyStart;
33
+ } else {
34
+ const start = open.pop();
35
+ if (!start) continue;
36
+ if (start.tagEnd === -1) continue;
37
+ const body = text.slice(start.bodyStart, match.index + match[1].length);
38
+ insertions.push({ at: start.tagEnd, text: ` __body="${encodeURIComponent(body)}"` });
39
+ }
40
+ }
41
+ insertions.sort((a, b) => b.at - a.at);
42
+ for (const { at, text: insert } of insertions) {
43
+ text = text.slice(0, at) + insert + text.slice(at);
44
+ }
45
+ return text;
46
+ }
47
+
48
+ export const everySelector = ".squiffy-every:not([data-every-stopped])";
49
+
50
+ // A tick's timer function is marked, so that the CLI's --play can tell a story that's only
51
+ // repeating some text from one that's still moving on by itself
52
+ export const EVERY_TICK = "squiffyEvery";
53
+
54
+ // The timers for the {{#every}}s in the current section. sync() starts a timer for each one that
55
+ // hasn't got one, and stops those that aren't there any more.
56
+ export class EveryTimers {
57
+ private timers = new Map<HTMLElement, ReturnType<typeof setTimeout>>();
58
+
59
+ // tick: shows the text again. It returns false if it can't yet, e.g. while a transition is
60
+ // running, so it's tried again a little later.
61
+ constructor(private getRoot: () => HTMLElement | undefined, private tick: (el: HTMLElement) => boolean) {}
62
+
63
+ sync() {
64
+ const root = this.getRoot();
65
+ const active = new Set(root?.isConnected ? root.querySelectorAll<HTMLElement>(everySelector) : []);
66
+ for (const [el, timer] of this.timers) {
67
+ if (!active.has(el)) {
68
+ clearTimeout(timer);
69
+ this.timers.delete(el);
70
+ }
71
+ }
72
+ for (const el of active) {
73
+ if (!this.timers.has(el)) this.schedule(el, Number(el.getAttribute("data-every-delay")) || 0);
74
+ }
75
+ }
76
+
77
+ stopAll() {
78
+ for (const timer of this.timers.values()) clearTimeout(timer);
79
+ this.timers.clear();
80
+ }
81
+
82
+ private schedule(el: HTMLElement, ms: number) {
83
+ const fn = () => {
84
+ this.timers.delete(el);
85
+ if (!this.tick(el)) {
86
+ this.schedule(el, 50);
87
+ return;
88
+ }
89
+ this.sync();
90
+ };
91
+ (fn as unknown as Record<string, boolean>)[EVERY_TICK] = true;
92
+ this.timers.set(el, setTimeout(fn, ms));
93
+ }
94
+ }
@@ -199,3 +199,27 @@ test("a hot update renders the panels again", async () => {
199
199
  test("the compiler checks for the same icons the runtime has", () => {
200
200
  expect([...COMPILER_PANEL_ICONS]).toEqual([...PANEL_ICONS]);
201
201
  });
202
+
203
+ test("shows the attributes of a game restored when the page loads", async () => {
204
+ const element = document.getElementById("squiffy")!;
205
+ const result = await squiffyCompile({ script });
206
+ if (!result.success) throw new Error("Compile failed");
207
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
208
+ const story = { js: js as any, ...result.output.story };
209
+
210
+ const first = await init({ element, story, persist: true, storyId: "panels-restore" });
211
+ await first.begin();
212
+ await click(first, element, "Get the lamp");
213
+ expect(first.get("gold")).toBe(15);
214
+
215
+ // The page again, as it does it: the panels first, then the story begins, from the saved game
216
+ document.getElementById("container")!.querySelector("aside")?.remove();
217
+ element.innerHTML = "";
218
+ const api = await init({ element, story, persist: true, storyId: "panels-restore" });
219
+ panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
220
+ await api.begin();
221
+ await settle();
222
+
223
+ expect(document.querySelector("aside.squiffy-panels-side")!.textContent).toContain("Gold: 15");
224
+ localStorage.clear();
225
+ });
@@ -0,0 +1,128 @@
1
+ // Player settings (#452): options from squiffy.json's "settings" that the player can change at any
2
+ // time, such as text size or content warnings. The story reads them as settings.name. They're the
3
+ // player's, not the game's, so they aren't attributes: going back, restarting and loading a saved
4
+ // game leave them as they are. They're kept for the story in localStorage, like Mute.
5
+
6
+ import type { PlayerSetting, SettingValue } from "./types.js";
7
+
8
+ export class PlayerSettings {
9
+ // The values the player has changed, by name. A setting that isn't here has its default.
10
+ private values: Record<string, SettingValue> = {};
11
+
12
+ constructor(private getDefinitions: () => PlayerSetting[], private storageKey?: string) {
13
+ if (!storageKey) return;
14
+ try {
15
+ const saved = JSON.parse(localStorage.getItem(storageKey) ?? "{}");
16
+ if (saved && typeof saved == "object" && !Array.isArray(saved)) this.values = saved;
17
+ }
18
+ catch {
19
+ // Nothing saved, or storage that can't be read: every setting has its default
20
+ }
21
+ }
22
+
23
+ definitions() {
24
+ return this.getDefinitions().filter(setting => setting && typeof setting.name == "string");
25
+ }
26
+
27
+ private find(name: string) {
28
+ return this.definitions().find(setting => setting.name == name);
29
+ }
30
+
31
+ // Whether the story has any settings, which is when it reads settings.name as a setting
32
+ any() {
33
+ return this.definitions().length > 0;
34
+ }
35
+
36
+ get(name: string): SettingValue | null {
37
+ const setting = this.find(name);
38
+ if (!setting) return null;
39
+ const value = Object.prototype.hasOwnProperty.call(this.values, name) ? this.values[name] : undefined;
40
+ return value !== undefined && isValid(setting, value) ? value : defaultValue(setting);
41
+ }
42
+
43
+ // Every setting's value, by name: the "settings" the story reads
44
+ all(): Record<string, SettingValue> {
45
+ return Object.fromEntries(this.definitions().map(setting => [setting.name, this.get(setting.name)!]));
46
+ }
47
+
48
+ // Returns whether the value changed. One the setting can't have is ignored.
49
+ set(name: string, value: SettingValue): boolean {
50
+ const setting = this.find(name);
51
+ if (!setting) return false;
52
+ const coerced = coerce(setting, value);
53
+ if (coerced === null || coerced === this.get(name)) return false;
54
+ this.values[name] = coerced;
55
+ this.store();
56
+ return true;
57
+ }
58
+
59
+ reset() {
60
+ this.values = {};
61
+ this.store();
62
+ }
63
+
64
+ // The classes the settings put on the story's element, so the story's CSS can use them: a
65
+ // toggle's name while it's on (setting-warnings), and a list's or range's name and value
66
+ // (setting-textSize-Large)
67
+ classes(): string[] {
68
+ const classes: string[] = [];
69
+ for (const setting of this.definitions()) {
70
+ const value = this.get(setting.name);
71
+ if (setting.type == "toggle") {
72
+ if (value === true) classes.push(`setting-${setting.name}`);
73
+ }
74
+ else if (value !== null) {
75
+ classes.push(`setting-${setting.name}-${String(value).replace(/[^A-Za-z0-9_-]+/g, "-")}`);
76
+ }
77
+ }
78
+ return classes;
79
+ }
80
+
81
+ private store() {
82
+ if (!this.storageKey) return;
83
+ try {
84
+ if (Object.keys(this.values).length) localStorage.setItem(this.storageKey, JSON.stringify(this.values));
85
+ else localStorage.removeItem(this.storageKey);
86
+ }
87
+ catch {
88
+ // Storage that's full or turned off: the setting lasts until the page is closed
89
+ }
90
+ }
91
+ }
92
+
93
+ export function defaultValue(setting: PlayerSetting): SettingValue {
94
+ switch (setting.type) {
95
+ case "toggle": return setting.default ?? false;
96
+ case "list": return setting.default ?? setting.options[0]?.value ?? "";
97
+ case "range": return setting.default ?? setting.min;
98
+ }
99
+ }
100
+
101
+ function isValid(setting: PlayerSetting, value: unknown) {
102
+ return coerce(setting, value) === value;
103
+ }
104
+
105
+ // The value as the setting has it, e.g. "true" for a toggle is true and "3" for a range is 3, or
106
+ // null if the setting can't have it. A range's value is kept within min and max, on a step.
107
+ function coerce(setting: PlayerSetting, value: unknown): SettingValue | null {
108
+ switch (setting.type) {
109
+ case "toggle":
110
+ if (typeof value == "boolean") return value;
111
+ if (value === "true") return true;
112
+ if (value === "false") return false;
113
+ return null;
114
+ case "list": {
115
+ const text = typeof value == "string" || typeof value == "number" || typeof value == "boolean" ? String(value) : null;
116
+ return text !== null && setting.options.some(option => option.value === text) ? text : null;
117
+ }
118
+ case "range": {
119
+ const n = typeof value == "number" ? value : typeof value == "string" && value.trim() ? Number(value) : NaN;
120
+ if (!Number.isFinite(n)) return null;
121
+ const clamped = Math.min(setting.max, Math.max(setting.min, n));
122
+ if (!setting.step) return clamped;
123
+ const stepped = setting.min + Math.round((clamped - setting.min) / setting.step) * setting.step;
124
+ // Without the rounding errors of adding up steps such as 0.1
125
+ return Number(Math.min(setting.max, stepped).toFixed(10));
126
+ }
127
+ }
128
+ }
@@ -1,6 +1,10 @@
1
1
  import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
2
2
  import Handlebars from "handlebars";
3
3
  import * as marked from "marked";
4
+ import { parseDelay } from "../utils.js";
5
+
6
+ // The parameters to the built-in animations that are times
7
+ const timeParameters = ["start", "interval", "duration", "fadeDuration"];
4
8
 
5
9
  export function AnimatePlugin(): SquiffyPlugin {
6
10
  let squiffy: PluginHost;
@@ -132,6 +136,11 @@ export function AnimatePlugin(): SquiffyPlugin {
132
136
  content,
133
137
  ...options.hash,
134
138
  };
139
+ // Times can be written like "1.5s" as well as in milliseconds (#451)
140
+ for (const key of timeParameters) {
141
+ const delay = parseDelay(dataset[key]);
142
+ if (delay !== null) dataset[key] = delay;
143
+ }
135
144
 
136
145
  const attrs = Object.entries(dataset)
137
146
  .map(([key, value]) =>
@@ -50,7 +50,9 @@ export function LivePlugin(): SquiffyPlugin {
50
50
  } else {
51
51
  newContent = el.dataset.attribute == e.attribute ? e.value : squiffy.get(el.dataset.attribute!);
52
52
  }
53
- 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)) {
54
56
  promises.push(fadeReplace(el, newContent));
55
57
  }
56
58
  }