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.
- package/dist/assets.d.ts +1 -0
- package/dist/classes.test.d.ts +1 -0
- package/dist/confirmDialog.d.ts +8 -0
- package/dist/events.d.ts +11 -0
- package/dist/every.d.ts +12 -0
- package/dist/every.test.d.ts +1 -0
- package/dist/paths.d.ts +15 -0
- package/dist/paths.test.d.ts +1 -0
- package/dist/playerSettings.d.ts +17 -0
- package/dist/preview-host.d.ts +2 -0
- package/dist/preview-host.js +10 -0
- package/dist/preview-host.js.map +2 -2
- package/dist/preview-html.js +1 -1
- package/dist/preview-protocol.d.ts +6 -0
- package/dist/settings.test.d.ts +1 -0
- package/dist/settingsDialog.d.ts +17 -0
- package/dist/skill.test.d.ts +1 -0
- package/dist/sound.d.ts +35 -0
- package/dist/sound.test.d.ts +1 -0
- package/dist/squiffy.page.css +14 -3
- package/dist/squiffy.preview.html +680 -82
- package/dist/squiffy.runtime.css +531 -1
- package/dist/squiffy.runtime.d.ts +5 -1
- package/dist/squiffy.runtime.global.js +117 -96
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +5728 -4520
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +4 -1
- package/dist/style.test.d.ts +1 -0
- package/dist/textProcessor.d.ts +16 -0
- package/dist/transitions.test.d.ts +1 -0
- package/dist/types.d.ts +54 -0
- package/dist/uiLinks.test.d.ts +1 -0
- package/dist/utils.d.ts +1 -0
- package/dist/utils.test.d.ts +1 -0
- package/package.json +3 -3
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
- package/src/animation.test.ts +44 -0
- package/src/animation.ts +9 -5
- package/src/assets.test.ts +1 -3
- package/src/assets.ts +1 -1
- package/src/classes.test.ts +201 -0
- package/src/confirmDialog.ts +66 -0
- package/src/events.ts +18 -0
- package/src/every.test.ts +25 -0
- package/src/every.ts +94 -0
- package/src/panels.test.ts +24 -0
- package/src/paths.test.ts +66 -0
- package/src/paths.ts +155 -0
- package/src/playerSettings.ts +128 -0
- package/src/plugins/animate.ts +16 -3
- package/src/plugins/live.ts +10 -4
- package/src/plugins/plugins.test.ts +51 -6
- package/src/preview-host.test.ts +22 -0
- package/src/preview-host.ts +15 -0
- package/src/preview-protocol.ts +9 -1
- package/src/preview.test.ts +114 -3
- package/src/preview.ts +97 -3
- package/src/settings.test.ts +233 -0
- package/src/settingsDialog.ts +160 -0
- package/src/skill.test.ts +67 -0
- package/src/sound.test.ts +273 -0
- package/src/sound.ts +207 -0
- package/src/squiffy.page.css +14 -3
- package/src/squiffy.runtime.css +531 -1
- package/src/squiffy.runtime.test.ts +1130 -17
- package/src/squiffy.runtime.ts +600 -38
- package/src/state.ts +45 -10
- package/src/style.test.ts +89 -0
- package/src/textProcessor.ts +484 -35
- package/src/transitions.test.ts +302 -0
- package/src/types.ts +79 -0
- package/src/uiLinks.test.ts +156 -0
- package/src/updater.ts +26 -8
- package/src/utils.test.ts +60 -0
- package/src/utils.ts +44 -14
- package/dist/infixExpressions.d.ts +0 -6
- package/src/infixExpressions.test.ts +0 -379
- package/src/infixExpressions.ts +0 -488
- /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
package/src/squiffy.runtime.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { TextProcessor, errorHtml } from "./textProcessor.js";
|
|
|
3
3
|
import { toNumber } from "./numbers.js";
|
|
4
4
|
import { Emitter, SquiffyEventMap } from "./events.js";
|
|
5
5
|
import { State } from "./state.js";
|
|
6
|
+
import { checkSegment, readTarget, Target } from "./paths.js";
|
|
6
7
|
import { updateStory } from "./updater.js";
|
|
7
8
|
import { PluginManager } from "./pluginManager.js";
|
|
8
9
|
import { Plugins } from "./plugins/index.js";
|
|
@@ -10,12 +11,22 @@ import { LinkHandler } from "./linkHandler.js";
|
|
|
10
11
|
import { Animation } from "./animation.js";
|
|
11
12
|
import { imports } from "./import.js";
|
|
12
13
|
import { areInputsValid, setupInputValidation } from "./inputValidation.js";
|
|
13
|
-
import { createAssetHtmlResolver } from "./assets.js";
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
import { createAssetHtmlResolver, isAbsolute } from "./assets.js";
|
|
15
|
+
import { Sound, DEFAULT_FADE } from "./sound.js";
|
|
16
|
+
import { EveryTimers } from "./every.js";
|
|
17
|
+
import { confirmDialog } from "./confirmDialog.js";
|
|
18
|
+
import { createSavesDialog, type SavesDialog } from "./savesDialog.js";
|
|
19
|
+
import { createSettingsDialog, type SettingsDialog } from "./settingsDialog.js";
|
|
20
|
+
import { PlayerSettings } from "./playerSettings.js";
|
|
21
|
+
|
|
22
|
+
export type { SquiffyApi, SavedGame, LoadSaveResult, PlayerSetting, PlayerSettingOption, SettingValue } from "./types.js";
|
|
16
23
|
export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
|
|
17
24
|
export { createSavesDialog, formatSaveTime, SAVES_STRINGS, SAVE_FILE_EXTENSION } from "./savesDialog.js";
|
|
18
25
|
export type { SavesDialog, SavesDialogOptions, SavesStringName } from "./savesDialog.js";
|
|
26
|
+
export { confirmDialog } from "./confirmDialog.js";
|
|
27
|
+
export { createSettingsDialog, SETTINGS_STRINGS } from "./settingsDialog.js";
|
|
28
|
+
export type { SettingsDialog, SettingsDialogOptions } from "./settingsDialog.js";
|
|
29
|
+
export type { ConfirmDialogOptions } from "./confirmDialog.js";
|
|
19
30
|
export { indexedDbSaveSlots, memorySaveSlots } from "./saveSlots.js";
|
|
20
31
|
export { createPanels } from "./panels.js";
|
|
21
32
|
export type { Panels, PanelsOptions } from "./panels.js";
|
|
@@ -44,6 +55,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
44
55
|
// the browser
|
|
45
56
|
let gotoHops = 0;
|
|
46
57
|
const MAX_GOTO_HOPS = 100;
|
|
58
|
+
// The {{#every}}s showing their text again and again (#451), and how many sections or passages
|
|
59
|
+
// are being shown, which they wait for
|
|
60
|
+
const everyTimers = new EveryTimers(() => currentSectionElement, tickEvery);
|
|
61
|
+
let navigating = 0;
|
|
47
62
|
|
|
48
63
|
async function handleLink(link: HTMLElement): Promise<boolean> {
|
|
49
64
|
if (runningTransitions) return false;
|
|
@@ -62,20 +77,29 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
62
77
|
|
|
63
78
|
if (passage !== null || section !== null) {
|
|
64
79
|
gotoHops = 0;
|
|
80
|
+
// A text box that goes somewhere when Enter is pressed (#454) keeps what was typed
|
|
81
|
+
// first, so the section or passage it goes to can use it. Other text boxes are only
|
|
82
|
+
// kept when the player leaves the section.
|
|
83
|
+
if (link instanceof window.HTMLInputElement) {
|
|
84
|
+
const attribute = link.getAttribute("data-attribute") || link.id;
|
|
85
|
+
if (attribute) set(attribute, link.value);
|
|
86
|
+
}
|
|
65
87
|
// The story-wide turn count (#377). A {{goto}} isn't a turn, as the player didn't click it.
|
|
66
88
|
set("turns", (get("turns") || 0) + 1);
|
|
67
89
|
}
|
|
68
90
|
|
|
69
91
|
if (passage !== null) {
|
|
70
92
|
// A passage with @repeat can be clicked again, and doesn't count towards @1, @2... and @last
|
|
93
|
+
let clicked: string | undefined;
|
|
71
94
|
if (!isRepeatPassage(passage)) {
|
|
72
95
|
disableLink(link);
|
|
96
|
+
clicked = markClicked(link);
|
|
73
97
|
set("_turncount", get("_turncount") + 1);
|
|
74
98
|
}
|
|
75
99
|
await processLink(link);
|
|
76
100
|
if (passage) {
|
|
77
101
|
currentBlockOutputElement = null;
|
|
78
|
-
await showPassage(passage);
|
|
102
|
+
await showPassage(passage, clicked);
|
|
79
103
|
}
|
|
80
104
|
|
|
81
105
|
emitter.emit("linkClick", { linkType: "passage" });
|
|
@@ -123,19 +147,43 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
123
147
|
return !!(masterPassages && passageName in masterPassages && masterPassages[passageName].repeat);
|
|
124
148
|
}
|
|
125
149
|
|
|
150
|
+
// A link, or a text box that goes to a passage when Enter is pressed (#454)
|
|
126
151
|
function disableLink(link: Element) {
|
|
152
|
+
if (link instanceof window.HTMLInputElement) {
|
|
153
|
+
link.disabled = true;
|
|
154
|
+
link.classList.add("disabled");
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
127
157
|
link.classList.add("disabled");
|
|
128
158
|
link.setAttribute("tabindex", "-1");
|
|
129
159
|
}
|
|
130
160
|
|
|
131
161
|
function enableLink(link: Element) {
|
|
162
|
+
if (link instanceof window.HTMLInputElement) {
|
|
163
|
+
link.disabled = false;
|
|
164
|
+
link.classList.remove("disabled");
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
132
167
|
link.classList.remove("disabled");
|
|
133
168
|
link.removeAttribute("tabindex");
|
|
134
169
|
}
|
|
170
|
+
|
|
171
|
+
// Numbers a passage link that was clicked, so that going back can enable just that link, and
|
|
172
|
+
// not the others to the same passage, such as the other items' links in an {{#each}} (#448)
|
|
173
|
+
function markClicked(link: Element) {
|
|
174
|
+
let max = 0;
|
|
175
|
+
for (const other of outputElement.querySelectorAll("[data-clicked]")) {
|
|
176
|
+
max = Math.max(max, Number(other.getAttribute("data-clicked")) || 0);
|
|
177
|
+
}
|
|
178
|
+
const id = String(max + 1);
|
|
179
|
+
link.setAttribute("data-clicked", id);
|
|
180
|
+
return id;
|
|
181
|
+
}
|
|
135
182
|
|
|
136
183
|
async function begin(startAt?: StartAt) {
|
|
137
184
|
if (startAt && startAt.section in story.sections) {
|
|
138
185
|
// Start somewhere else in a fresh story, e.g. from the section being edited
|
|
186
|
+
runUiJs();
|
|
139
187
|
await go(startAt.section);
|
|
140
188
|
if (startAt.passage !== undefined && get("_section") == startAt.section) {
|
|
141
189
|
await showPassage(startAt.passage);
|
|
@@ -146,8 +194,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
146
194
|
await go(story.start);
|
|
147
195
|
return;
|
|
148
196
|
}
|
|
197
|
+
// As when a saved game is loaded, so that panels show the attributes it has
|
|
198
|
+
const passage = get("_passage");
|
|
199
|
+
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
149
200
|
// Saved while waiting for a {{goto}}, so carry on waiting
|
|
150
201
|
await resumeGoto();
|
|
202
|
+
everyTimers.sync();
|
|
151
203
|
}
|
|
152
204
|
|
|
153
205
|
async function resumeGoto() {
|
|
@@ -259,43 +311,63 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
259
311
|
}
|
|
260
312
|
|
|
261
313
|
// +=, -=, *= and /=, which only work on numbers (#374)
|
|
262
|
-
function operate(lhs: string, op: string, amountValue: unknown) {
|
|
314
|
+
function operate(lhs: string | string[], op: string, amountValue: unknown) {
|
|
263
315
|
const what = op + "=";
|
|
264
316
|
const amount = toNumber(what, amountValue);
|
|
265
|
-
|
|
317
|
+
const path = typeof lhs == "string" ? [lhs] : lhs;
|
|
318
|
+
let value = toNumber(what, state.getAt(path));
|
|
266
319
|
if (op == "+") value += amount;
|
|
267
320
|
if (op == "-") value -= amount;
|
|
268
321
|
if (op == "*") value *= amount;
|
|
269
322
|
if (op == "/") value /= amount;
|
|
270
|
-
|
|
323
|
+
state.setAt(path, value);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// The path a setter's target names, with any [index] in it worked out, e.g. ["inventory", "2",
|
|
327
|
+
// "name"] for inventory[i].name when i is 2 (#442)
|
|
328
|
+
function targetPath(target: Target): string[] {
|
|
329
|
+
return [target.attribute, ...target.segments.map(segment => {
|
|
330
|
+
if ("name" in segment) return segment.name;
|
|
331
|
+
const index = textProcessor.evaluate(segment.index);
|
|
332
|
+
if (typeof index != "string" && typeof index != "number") {
|
|
333
|
+
throw new Error(`[${segment.index.trim()}] should be a number or text, to say which value to set`);
|
|
334
|
+
}
|
|
335
|
+
const name = String(index);
|
|
336
|
+
checkSegment(name);
|
|
337
|
+
return name;
|
|
338
|
+
})];
|
|
271
339
|
}
|
|
272
340
|
|
|
273
341
|
// A story with a squiffy.json (#373): the right-hand side is an expression, with the same rules
|
|
274
|
-
// as {{#if}}, e.g. weapon = "sword", gold = gold + price * 2, rich = gold > 100.
|
|
342
|
+
// as {{#if}}, e.g. weapon = "sword", gold = gold + price * 2, rich = gold > 100. The left-hand
|
|
343
|
+
// side can be a value inside an object, e.g. hero.hp = 10 or inventory[i].name = "lamp" (#442).
|
|
275
344
|
function setWithExpression(expr: string) {
|
|
276
|
-
const
|
|
277
|
-
|
|
345
|
+
const target = readTarget(expr);
|
|
346
|
+
const textMatch = target && /^\s*:=(.*)$/.exec(target.rest);
|
|
347
|
+
if (target && textMatch) {
|
|
278
348
|
// Text with {{...}} processed, as before
|
|
279
|
-
|
|
349
|
+
state.setAt(targetPath(target), ui.processText(textMatch[1], true));
|
|
280
350
|
return;
|
|
281
351
|
}
|
|
282
|
-
const match =
|
|
283
|
-
if (match) {
|
|
284
|
-
const [,
|
|
352
|
+
const match = target && /^\s*([+\-*/]?)=(?!=)(.*)$/.exec(target.rest);
|
|
353
|
+
if (target && match) {
|
|
354
|
+
const [, op, rhs] = match;
|
|
355
|
+
const path = targetPath(target);
|
|
285
356
|
const value = textProcessor.evaluate(rhs);
|
|
286
357
|
if (op) {
|
|
287
|
-
operate(
|
|
358
|
+
operate(path, op, value);
|
|
288
359
|
}
|
|
289
360
|
else {
|
|
290
|
-
|
|
361
|
+
state.setAt(path, value);
|
|
291
362
|
}
|
|
292
363
|
return;
|
|
293
364
|
}
|
|
294
|
-
const
|
|
295
|
-
|
|
365
|
+
const not = /^\s*not\s+/.exec(expr);
|
|
366
|
+
const flag = readTarget(not ? expr.substring(not[0].length) : expr);
|
|
367
|
+
if (!flag || flag.rest.trim()) {
|
|
296
368
|
throw new Error("expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key");
|
|
297
369
|
}
|
|
298
|
-
|
|
370
|
+
state.setAt(targetPath(flag), !not);
|
|
299
371
|
}
|
|
300
372
|
|
|
301
373
|
// A story without a squiffy.json, as in Squiffy 6: the right-hand side is a number, true,
|
|
@@ -342,6 +414,17 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
342
414
|
}
|
|
343
415
|
|
|
344
416
|
async function go(sectionName: string) {
|
|
417
|
+
navigating++;
|
|
418
|
+
try {
|
|
419
|
+
await goNow(sectionName);
|
|
420
|
+
}
|
|
421
|
+
finally {
|
|
422
|
+
navigating--;
|
|
423
|
+
everyTimers.sync();
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async function goNow(sectionName: string) {
|
|
345
428
|
cancelGoto();
|
|
346
429
|
const oldCanGoBack = canGoBack();
|
|
347
430
|
currentSection = story.sections[sectionName];
|
|
@@ -359,10 +442,16 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
359
442
|
if (get("turns") === null) state.setInternal("turns", 0, false);
|
|
360
443
|
state.setSeen(sectionName);
|
|
361
444
|
const master = story.sections[""];
|
|
362
|
-
|
|
445
|
+
const clear = master?.clear || currentSection.clear;
|
|
446
|
+
// @leave: the old text goes before anything changes on the screen
|
|
447
|
+
if (clear) await leaveTransition([currentSection, master]);
|
|
448
|
+
// @class (#449): this section's classes replace the last one's
|
|
449
|
+
setSectionClasses([...(master?.classes ?? []), ...(currentSection.classes ?? [])]);
|
|
450
|
+
if (clear) {
|
|
363
451
|
clearScreen();
|
|
364
452
|
}
|
|
365
453
|
newSection(sectionName);
|
|
454
|
+
startTransition(currentSectionElement, [currentSection, master]);
|
|
366
455
|
const sectionElement = currentSectionElement;
|
|
367
456
|
if (master) {
|
|
368
457
|
await run(master, "[[]]");
|
|
@@ -437,6 +526,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
437
526
|
if (section.attributes) {
|
|
438
527
|
await processAttributes(section.attributes);
|
|
439
528
|
}
|
|
529
|
+
// @music and @sound (#444)
|
|
530
|
+
if (section.music !== undefined) set("_music", section.music);
|
|
531
|
+
for (const file of section.sounds ?? []) {
|
|
532
|
+
if (file == "stop") sound.stopSounds();
|
|
533
|
+
else sound.play(file);
|
|
534
|
+
}
|
|
440
535
|
const afterWrite: (() => void)[] = [];
|
|
441
536
|
if (section.jsIndex !== undefined) {
|
|
442
537
|
const sectionBefore = get("_section");
|
|
@@ -473,7 +568,19 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
473
568
|
currentSectionElement.classList.remove("links-disabled");
|
|
474
569
|
}
|
|
475
570
|
|
|
476
|
-
|
|
571
|
+
// clicked: the number markClicked gave the link that was clicked to get here, if any
|
|
572
|
+
async function showPassage(passageName: string, clicked?: string) {
|
|
573
|
+
navigating++;
|
|
574
|
+
try {
|
|
575
|
+
await showPassageNow(passageName, clicked);
|
|
576
|
+
}
|
|
577
|
+
finally {
|
|
578
|
+
navigating--;
|
|
579
|
+
everyTimers.sync();
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
async function showPassageNow(passageName: string, clicked?: string) {
|
|
477
584
|
cancelGoto();
|
|
478
585
|
const oldCanGoBack = canGoBack();
|
|
479
586
|
let passage = currentSection.passages && currentSection.passages[passageName];
|
|
@@ -522,7 +629,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
522
629
|
}
|
|
523
630
|
}
|
|
524
631
|
|
|
525
|
-
|
|
632
|
+
const clear = passages.some(p => p.clear);
|
|
633
|
+
// @leave: the passage's own, or else a master passage's, or else its section's, or the master section's
|
|
634
|
+
if (clear) await leaveTransition([passage, master, masterSection?.passages?.[""], currentSection, masterSection]);
|
|
635
|
+
|
|
636
|
+
// @class in a passage (#449) adds to the section's classes
|
|
637
|
+
const passageClasses = passages.flatMap(p => p.classes ?? []);
|
|
638
|
+
if (passageClasses.length) setSectionClasses([...sectionClasses(), ...passageClasses]);
|
|
639
|
+
|
|
640
|
+
if (clear) {
|
|
526
641
|
clearScreen();
|
|
527
642
|
createSectionElement();
|
|
528
643
|
}
|
|
@@ -530,8 +645,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
530
645
|
currentPassageElement = document.createElement("div");
|
|
531
646
|
currentPassageElement.classList.add("squiffy-output-passage");
|
|
532
647
|
currentPassageElement.setAttribute("data-passage", `${passageName}`);
|
|
648
|
+
if (clicked) currentPassageElement.setAttribute("data-clicked-link", clicked);
|
|
533
649
|
|
|
534
650
|
currentSectionElement.appendChild(currentPassageElement);
|
|
651
|
+
// @transition (#489): the passage's own, or else a master passage's, or else its section's, or the master section's
|
|
652
|
+
startTransition(currentPassageElement, [passage, master, masterSection?.passages?.[""], currentSection, masterSection]);
|
|
535
653
|
|
|
536
654
|
for (const fn of runFns) {
|
|
537
655
|
await fn();
|
|
@@ -560,7 +678,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
560
678
|
|
|
561
679
|
function restart() {
|
|
562
680
|
cancelGoto();
|
|
681
|
+
everyTimers.stopAll();
|
|
563
682
|
state.reset();
|
|
683
|
+
uiJsRun = false;
|
|
684
|
+
sound.sync();
|
|
685
|
+
syncClasses();
|
|
564
686
|
// TODO: This feels like the wrong way of triggering location.reload()
|
|
565
687
|
// - should be a separate setting to the scroll setting.
|
|
566
688
|
if (settings.scroll === "element" || settings.scroll === "none") {
|
|
@@ -574,21 +696,35 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
574
696
|
|
|
575
697
|
function save() {
|
|
576
698
|
// TODO: Queue up all attribute changes and save them only when this is called
|
|
577
|
-
|
|
699
|
+
// A transition still playing isn't saved, so loading the game doesn't play it again (#489)
|
|
700
|
+
let output = outputElement;
|
|
701
|
+
if (output.querySelector(".squiffy-transition")) {
|
|
702
|
+
output = outputElement.cloneNode(true) as HTMLDivElement;
|
|
703
|
+
output.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
|
|
704
|
+
}
|
|
705
|
+
set("_output", output.innerHTML);
|
|
578
706
|
}
|
|
579
707
|
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
708
|
+
// The story's @ui JavaScript, which registers its helpers and animations. It runs once before
|
|
709
|
+
// any text is shown, however the story starts: from the beginning, from a section the author
|
|
710
|
+
// chose, or from a saved game. Restarting runs it again, as that resets the attributes.
|
|
711
|
+
let uiJsRun = false;
|
|
712
|
+
function runUiJs() {
|
|
713
|
+
if (uiJsRun) return;
|
|
714
|
+
uiJsRun = true;
|
|
715
|
+
if (story.uiJsIndex !== undefined) {
|
|
716
|
+
runJs(story.uiJsIndex, {
|
|
717
|
+
registerAnimation: animation.registerAnimation.bind(animation),
|
|
718
|
+
registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
|
|
719
|
+
SafeString: textProcessor.handlebars.SafeString,
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
}
|
|
590
723
|
|
|
724
|
+
function load() {
|
|
591
725
|
state.load();
|
|
726
|
+
sound.sync();
|
|
727
|
+
syncClasses();
|
|
592
728
|
const output = get("_output");
|
|
593
729
|
if (!output) {
|
|
594
730
|
runUiJs();
|
|
@@ -675,15 +811,20 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
675
811
|
await new Promise(resolve => setTimeout(resolve, 50));
|
|
676
812
|
}
|
|
677
813
|
cancelGoto();
|
|
814
|
+
everyTimers.stopAll();
|
|
678
815
|
pendingErrors.length = 0;
|
|
679
816
|
state.reset();
|
|
680
817
|
for (const [attribute, value] of Object.entries(save.state)) {
|
|
681
818
|
state.setInternal(attribute, value, false);
|
|
682
819
|
}
|
|
820
|
+
sound.sync();
|
|
821
|
+
syncClasses();
|
|
683
822
|
undoLog = {};
|
|
684
823
|
scrollPosition = 0;
|
|
685
824
|
scrollToTop = false;
|
|
686
825
|
showSavedOutput(save.state._output as string);
|
|
826
|
+
// As load() does, for a game loaded before the story has begun
|
|
827
|
+
runUiJs();
|
|
687
828
|
|
|
688
829
|
if (!currentSection) {
|
|
689
830
|
// The section the game was saved in isn't in the story any more, so start again from
|
|
@@ -702,6 +843,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
702
843
|
|
|
703
844
|
// Saved while waiting for a {{goto}}, so carry on waiting
|
|
704
845
|
await resumeGoto();
|
|
846
|
+
everyTimers.sync();
|
|
705
847
|
return { success: true };
|
|
706
848
|
}
|
|
707
849
|
|
|
@@ -754,6 +896,33 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
754
896
|
return outputElement.querySelector<HTMLElement>(".squiffy-clear-stack");
|
|
755
897
|
}
|
|
756
898
|
|
|
899
|
+
|
|
900
|
+
// For scroll: "element", scrolls the story's own scrolling box (its nearest ancestor that
|
|
901
|
+
// scrolls, or else its own window) so that the top or the bottom of el is at the top or the
|
|
902
|
+
// bottom of it. Unlike scrollIntoView, this never scrolls the page around that box, or the page
|
|
903
|
+
// the story is in a frame of, such as the docs' samples.
|
|
904
|
+
function scrollWithin(el: Element, block: "start" | "end") {
|
|
905
|
+
const rect = el.getBoundingClientRect();
|
|
906
|
+
const box = scrollingBox(el);
|
|
907
|
+
if (box) {
|
|
908
|
+
const bounds = box.getBoundingClientRect();
|
|
909
|
+
const by = block === "start" ? rect.top - bounds.top : rect.bottom - bounds.bottom;
|
|
910
|
+
box.scrollTo({ top: box.scrollTop + by, behavior: "smooth" });
|
|
911
|
+
}
|
|
912
|
+
else {
|
|
913
|
+
const by = block === "start" ? rect.top : rect.bottom - window.innerHeight;
|
|
914
|
+
window.scrollTo({ top: window.scrollY + by, behavior: "smooth" });
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
function scrollingBox(el: Element): HTMLElement | null {
|
|
919
|
+
for (let e = el.parentElement; e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
|
|
920
|
+
const overflow = getComputedStyle(e).overflowY;
|
|
921
|
+
if ((overflow === "auto" || overflow === "scroll") && e.scrollHeight > e.clientHeight) return e;
|
|
922
|
+
}
|
|
923
|
+
return null;
|
|
924
|
+
}
|
|
925
|
+
|
|
757
926
|
function clearScreen() {
|
|
758
927
|
// Callers should call createSectionElement() after calling this function, so there's a place for new
|
|
759
928
|
// output to go. We don't call this automatically within this function, in case we're just about to create
|
|
@@ -776,14 +945,97 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
776
945
|
clearStackItem.appendChild(child);
|
|
777
946
|
}
|
|
778
947
|
}
|
|
948
|
+
// Without its transitions, so it's as it was if the player goes back to it
|
|
949
|
+
clearStackItem.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
|
|
779
950
|
|
|
780
951
|
// NOTE: If we offer an option to disable the "back" feature, all of the above can be replaced with:
|
|
781
952
|
// outputElement.innerHTML = '';
|
|
782
953
|
}
|
|
783
954
|
|
|
955
|
+
// @transition (#489): plays the first transition given, as a class that the stylesheet animates.
|
|
956
|
+
// "none" (or Harlowe's "instant") plays none, so a section can turn off the master section's.
|
|
957
|
+
function startTransition(element: HTMLElement, from: (Section | Passage | undefined)[]) {
|
|
958
|
+
const source = from.find(s => s?.transition);
|
|
959
|
+
const name = source?.transition;
|
|
960
|
+
if (!name || name == "none" || name == "instant") return;
|
|
961
|
+
element.classList.add("squiffy-transition", name);
|
|
962
|
+
element.setAttribute("data-transition", name);
|
|
963
|
+
if (source!.transitionTime !== undefined) {
|
|
964
|
+
element.style.setProperty("--squiffy-transition-time", `${source!.transitionTime}ms`);
|
|
965
|
+
}
|
|
966
|
+
const end = (event: Event) => {
|
|
967
|
+
// A @leave transition started before this one ended takes the element off the screen itself
|
|
968
|
+
if (event.target !== element || element.classList.contains("squiffy-leave")) return;
|
|
969
|
+
element.removeEventListener("animationend", end);
|
|
970
|
+
element.removeEventListener("animationcancel", end);
|
|
971
|
+
endTransition(element);
|
|
972
|
+
};
|
|
973
|
+
element.addEventListener("animationend", end);
|
|
974
|
+
element.addEventListener("animationcancel", end);
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// @leave: plays the first leave transition given on everything on the screen, the arrival
|
|
978
|
+
// transitions backwards, and waits for it to finish, so that clearScreen() can take it away.
|
|
979
|
+
// Links and Back wait too.
|
|
980
|
+
async function leaveTransition(from: (Section | Passage | undefined)[]) {
|
|
981
|
+
const source = from.find(s => s?.leave);
|
|
982
|
+
const name = source?.leave;
|
|
983
|
+
if (!name || name == "none" || name == "instant") return;
|
|
984
|
+
const clearStack = getClearStack();
|
|
985
|
+
const elements = [...outputElement.children].filter((c): c is HTMLElement => c !== clearStack && c instanceof HTMLElement);
|
|
986
|
+
if (!elements.length) return;
|
|
987
|
+
for (const element of elements) {
|
|
988
|
+
endTransition(element);
|
|
989
|
+
element.classList.add("squiffy-transition", "squiffy-leave", name);
|
|
990
|
+
element.setAttribute("data-transition", name);
|
|
991
|
+
if (source!.leaveTime !== undefined) {
|
|
992
|
+
element.style.setProperty("--squiffy-transition-time", `${source!.leaveTime}ms`);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
// Each element plays the same animation, so the first one finishing means they all have
|
|
996
|
+
const first = elements[0];
|
|
997
|
+
const style = getComputedStyle(first);
|
|
998
|
+
if (!style.animationName || style.animationName == "none") return;
|
|
999
|
+
// In case the animation never ends, such as in a page that isn't shown
|
|
1000
|
+
const seconds = (value: string) => Math.max(0, ...value.split(",").map(v => parseFloat(v) * (v.trim().endsWith("ms") ? 0.001 : 1) || 0));
|
|
1001
|
+
const timeout = (seconds(style.animationDuration) + seconds(style.animationDelay)) * 1000 + 1000;
|
|
1002
|
+
const wasRunning = runningTransitions;
|
|
1003
|
+
runningTransitions = true;
|
|
1004
|
+
try {
|
|
1005
|
+
await new Promise<void>(resolve => {
|
|
1006
|
+
const timer = setTimeout(done, timeout);
|
|
1007
|
+
function done(event?: Event) {
|
|
1008
|
+
if (event && event.target !== first) return;
|
|
1009
|
+
clearTimeout(timer);
|
|
1010
|
+
first.removeEventListener("animationend", done);
|
|
1011
|
+
first.removeEventListener("animationcancel", done);
|
|
1012
|
+
resolve();
|
|
1013
|
+
}
|
|
1014
|
+
first.addEventListener("animationend", done);
|
|
1015
|
+
first.addEventListener("animationcancel", done);
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
finally {
|
|
1019
|
+
runningTransitions = wasRunning;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// Takes off a transition's class, so it doesn't play again when the element is shown again,
|
|
1024
|
+
// such as after going back past a @clear
|
|
1025
|
+
function endTransition(element: HTMLElement) {
|
|
1026
|
+
const name = element.getAttribute("data-transition");
|
|
1027
|
+
if (name) element.classList.remove(name);
|
|
1028
|
+
element.classList.remove("squiffy-transition", "squiffy-leave");
|
|
1029
|
+
if (!element.classList.length) element.removeAttribute("class");
|
|
1030
|
+
element.removeAttribute("data-transition");
|
|
1031
|
+
element.style.removeProperty("--squiffy-transition-time");
|
|
1032
|
+
if (!element.getAttribute("style")) element.removeAttribute("style");
|
|
1033
|
+
}
|
|
1034
|
+
|
|
784
1035
|
function unClearScreen() {
|
|
785
1036
|
const clearStack = getClearStack();
|
|
786
1037
|
if (!clearStack) return;
|
|
1038
|
+
clearStack.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
|
|
787
1039
|
for (const child of [...outputElement.children]) {
|
|
788
1040
|
if (child !== clearStack) {
|
|
789
1041
|
child.remove();
|
|
@@ -841,7 +1093,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
841
1093
|
// above where the reader has scrolled to.
|
|
842
1094
|
scrollToTop = false;
|
|
843
1095
|
if (settings.scroll === "element") {
|
|
844
|
-
currentSectionElement
|
|
1096
|
+
scrollWithin(currentSectionElement, "start");
|
|
845
1097
|
}
|
|
846
1098
|
else {
|
|
847
1099
|
const currentScrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
|
|
@@ -852,7 +1104,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
852
1104
|
}
|
|
853
1105
|
}
|
|
854
1106
|
else if (settings.scroll === "element") {
|
|
855
|
-
outputElement.lastElementChild
|
|
1107
|
+
const last = outputElement.lastElementChild;
|
|
1108
|
+
if (last) scrollWithin(last, "end");
|
|
856
1109
|
}
|
|
857
1110
|
else {
|
|
858
1111
|
let scrollTo = scrollPosition;
|
|
@@ -877,6 +1130,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
877
1130
|
if (newStory.start != story.start) {
|
|
878
1131
|
story = newStory;
|
|
879
1132
|
state.reset();
|
|
1133
|
+
sound.sync();
|
|
1134
|
+
syncClasses();
|
|
1135
|
+
sound.preload(story.audio ?? []);
|
|
880
1136
|
outputElement.innerHTML = "";
|
|
881
1137
|
go(story.start);
|
|
882
1138
|
return;
|
|
@@ -886,16 +1142,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
886
1142
|
// sees sections that were added in this update.
|
|
887
1143
|
const oldStory = story;
|
|
888
1144
|
story = newStory;
|
|
1145
|
+
// Its settings may have changed
|
|
1146
|
+
syncClasses();
|
|
1147
|
+
sound.preload(story.audio ?? []);
|
|
889
1148
|
|
|
890
1149
|
// When re-rendering a section or passage, {{embed}} should look up passages in the
|
|
891
1150
|
// (new version of the) section being rendered.
|
|
892
1151
|
const processTextInSection = (text: string, section: Section) => {
|
|
893
1152
|
const previousSection = currentSection;
|
|
894
1153
|
currentSection = section;
|
|
1154
|
+
// Text shown again after an edit doesn't play its {{sound}}s again
|
|
1155
|
+
quiet = true;
|
|
895
1156
|
try {
|
|
896
1157
|
return ui.renderHtml(text, false);
|
|
897
1158
|
} finally {
|
|
898
1159
|
currentSection = previousSection;
|
|
1160
|
+
quiet = false;
|
|
899
1161
|
}
|
|
900
1162
|
};
|
|
901
1163
|
|
|
@@ -903,6 +1165,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
903
1165
|
|
|
904
1166
|
setCurrentSectionElement();
|
|
905
1167
|
setCurrentPassageElement();
|
|
1168
|
+
// The {{#every}}s shown again start again
|
|
1169
|
+
everyTimers.sync();
|
|
906
1170
|
emitter.emit("storyUpdated", {});
|
|
907
1171
|
}
|
|
908
1172
|
|
|
@@ -990,6 +1254,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
990
1254
|
do {
|
|
991
1255
|
undoLast();
|
|
992
1256
|
} while ((currentPassageElement ?? currentSectionElement).hasAttribute("data-goto") && getHistoryCount() > 1);
|
|
1257
|
+
// The music goes back to what it was, as _music was undone
|
|
1258
|
+
sound.sync();
|
|
1259
|
+
syncClasses();
|
|
993
1260
|
// The attributes were saved as they were undone, so save the output to match. Otherwise a saved
|
|
994
1261
|
// game would come back with the text that was undone.
|
|
995
1262
|
save();
|
|
@@ -999,6 +1266,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
999
1266
|
}
|
|
1000
1267
|
const passage = currentPassageElement?.getAttribute("data-passage");
|
|
1001
1268
|
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
1269
|
+
// The {{#every}}s that were undone stop, and any in the section gone back to start again
|
|
1270
|
+
everyTimers.sync();
|
|
1002
1271
|
}
|
|
1003
1272
|
|
|
1004
1273
|
function undoLast() {
|
|
@@ -1006,6 +1275,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1006
1275
|
|
|
1007
1276
|
if (currentPassageElement) {
|
|
1008
1277
|
const currentPassage = currentPassageElement.getAttribute("data-passage");
|
|
1278
|
+
const clicked = currentPassageElement.getAttribute("data-clicked-link");
|
|
1009
1279
|
doUndo(currentPassageElement.getAttribute("data-undo"));
|
|
1010
1280
|
undoDeactivate(currentPassageElement);
|
|
1011
1281
|
currentPassageElement.remove();
|
|
@@ -1032,9 +1302,18 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1032
1302
|
setCurrentSectionElement();
|
|
1033
1303
|
}
|
|
1034
1304
|
|
|
1035
|
-
|
|
1036
|
-
|
|
1305
|
+
if (clicked) {
|
|
1306
|
+
for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-clicked="${clicked}"], input[data-clicked="${clicked}"]`)) {
|
|
1037
1307
|
enableLink(link);
|
|
1308
|
+
link.removeAttribute("data-clicked");
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
else if (currentPassage && !isRepeatPassage(currentPassage)) {
|
|
1312
|
+
// Saved before links were numbered when clicked, so enable every link to the passage
|
|
1313
|
+
for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
|
|
1314
|
+
if (link.getAttribute("data-passage") == currentPassage) {
|
|
1315
|
+
enableLink(link);
|
|
1316
|
+
}
|
|
1038
1317
|
}
|
|
1039
1318
|
}
|
|
1040
1319
|
|
|
@@ -1106,6 +1385,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1106
1385
|
outputElement.addEventListener("click", handleClick);
|
|
1107
1386
|
outputElement.addEventListener("keypress", async function (event) {
|
|
1108
1387
|
if (event.key !== "Enter") return;
|
|
1388
|
+
const target = event.target;
|
|
1389
|
+
// A text box with data-section or data-passage goes there when Enter is pressed (#454),
|
|
1390
|
+
// like a link, once every text box in the section is filled in properly
|
|
1391
|
+
if (target instanceof window.HTMLInputElement && (target.hasAttribute("data-section") || target.hasAttribute("data-passage"))) {
|
|
1392
|
+
if (event.isComposing) return;
|
|
1393
|
+
event.preventDefault();
|
|
1394
|
+
if (!areInputsValid(currentSectionElement)) {
|
|
1395
|
+
// Shows which ones need filling in
|
|
1396
|
+
for (const input of currentSectionElement.querySelectorAll<HTMLInputElement>("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")) {
|
|
1397
|
+
input.reportValidity();
|
|
1398
|
+
}
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
await handleLink(target);
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1109
1404
|
await handleClick(event);
|
|
1110
1405
|
});
|
|
1111
1406
|
|
|
@@ -1122,6 +1417,66 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1122
1417
|
undoLog = {};
|
|
1123
1418
|
};
|
|
1124
1419
|
|
|
1420
|
+
// Adds what's changed since to the undo log of the section or passage already shown, keeping
|
|
1421
|
+
// the value from before it was shown, e.g. for an {{#every}}'s text (#451)
|
|
1422
|
+
const mergeUndoLog = function() {
|
|
1423
|
+
const element = currentPassageElement ?? currentSectionElement;
|
|
1424
|
+
const log = JSON.parse(element.getAttribute("data-undo") || "{}");
|
|
1425
|
+
for (const [attribute, value] of Object.entries(undoLog)) {
|
|
1426
|
+
if (!(attribute in log)) log[attribute] = value;
|
|
1427
|
+
}
|
|
1428
|
+
element.setAttribute("data-undo", JSON.stringify(log));
|
|
1429
|
+
undoLog = {};
|
|
1430
|
+
};
|
|
1431
|
+
|
|
1432
|
+
// Shows an {{#every}}'s text again (#451). Returns false if it has to wait, while a section or
|
|
1433
|
+
// passage is being shown.
|
|
1434
|
+
function tickEvery(el: HTMLElement): boolean {
|
|
1435
|
+
if (runningTransitions || navigating > 0) return false;
|
|
1436
|
+
const inline = el.tagName == "SPAN";
|
|
1437
|
+
const body = decodeURIComponent(el.getAttribute("data-every") || "");
|
|
1438
|
+
let html: string;
|
|
1439
|
+
textProcessor.stopEvery = false;
|
|
1440
|
+
try {
|
|
1441
|
+
html = ui.renderHtml(body, inline);
|
|
1442
|
+
// Text added after text keeps its spaces, e.g. {{#every 1000 append=true}}Drip. {{/every}}
|
|
1443
|
+
if (inline) html = (/^\s/.test(body) ? " " : "") + html + (/\s$/.test(body) ? " " : "");
|
|
1444
|
+
}
|
|
1445
|
+
catch (e) {
|
|
1446
|
+
html = errorHtml("Error in {{#every}}:", e instanceof Error ? e.message : String(e));
|
|
1447
|
+
textProcessor.stopEvery = true;
|
|
1448
|
+
}
|
|
1449
|
+
const text = document.createElement(inline ? "span" : "div");
|
|
1450
|
+
text.className = "squiffy-every-text";
|
|
1451
|
+
text.innerHTML = html;
|
|
1452
|
+
if (el.hasAttribute("data-every-append")) el.append(text);
|
|
1453
|
+
else el.replaceChildren(text);
|
|
1454
|
+
pluginManager.onWrite(text);
|
|
1455
|
+
// It's empty until its first tick, so when the text was written the page may not have been
|
|
1456
|
+
// tall enough to scroll down to where it starts. This finishes that scroll, as the text is
|
|
1457
|
+
// taller now. It never scrolls past where the new text starts, or up.
|
|
1458
|
+
ui.scrollToEnd();
|
|
1459
|
+
|
|
1460
|
+
const count = (Number(el.getAttribute("data-every-count")) || 0) + 1;
|
|
1461
|
+
el.setAttribute("data-every-count", String(count));
|
|
1462
|
+
const times = Number(el.getAttribute("data-every-times")) || 0;
|
|
1463
|
+
if (textProcessor.stopEvery || (times && count >= times)) el.setAttribute("data-every-stopped", "");
|
|
1464
|
+
textProcessor.stopEvery = false;
|
|
1465
|
+
|
|
1466
|
+
const element = currentPassageElement ?? currentSectionElement;
|
|
1467
|
+
takeDeactivate(element);
|
|
1468
|
+
const pending = takeGoto(element);
|
|
1469
|
+
mergeUndoLog();
|
|
1470
|
+
save();
|
|
1471
|
+
if (pending) {
|
|
1472
|
+
// It replaces any {{goto ... after=}} still waiting
|
|
1473
|
+
clearTimeout(gotoTimer);
|
|
1474
|
+
gotoHops = 0;
|
|
1475
|
+
void followGoto(pending);
|
|
1476
|
+
}
|
|
1477
|
+
return true;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1125
1480
|
const doUndo = function(undosJson: string | null) {
|
|
1126
1481
|
if (!undosJson) return;
|
|
1127
1482
|
const undos = JSON.parse(undosJson) as Record<string, any>;
|
|
@@ -1135,9 +1490,192 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1135
1490
|
const get = state.get.bind(state);
|
|
1136
1491
|
const set = state.set.bind(state);
|
|
1137
1492
|
|
|
1493
|
+
// The player's settings (#452), which the story reads as settings.name
|
|
1494
|
+
const playerSettings = new PlayerSettings(() => story.settings ?? [], settings.persist ? "squiffy-settings:" + storageKey : undefined);
|
|
1495
|
+
state.playerSettings = () => playerSettings.any() ? playerSettings.all() : null;
|
|
1496
|
+
// After a setting changes: its classes, and text that shows it, such as {{live "settings"}} and panels
|
|
1497
|
+
const settingChanged = (name: string, value: unknown) => {
|
|
1498
|
+
syncClasses();
|
|
1499
|
+
emitter.emit("settingChanged", { name, value });
|
|
1500
|
+
emitter.emit("set", { attribute: "settings", value: playerSettings.all() });
|
|
1501
|
+
};
|
|
1502
|
+
|
|
1138
1503
|
const textProcessor = new TextProcessor(() => story, state, () => currentSection);
|
|
1504
|
+
const strings = options.strings ?? {};
|
|
1505
|
+
if (typeof strings.restart == "string") textProcessor.strings.restart = strings.restart;
|
|
1506
|
+
if (typeof strings.saves == "string") textProcessor.strings.saves = strings.saves;
|
|
1507
|
+
if (typeof strings.settings == "string") textProcessor.strings.settings = strings.settings;
|
|
1508
|
+
|
|
1509
|
+
// Music and sound effects (#444)
|
|
1510
|
+
let playedSound = false;
|
|
1511
|
+
// While text is shown again rather than for the first time, {{sound}} doesn't play
|
|
1512
|
+
let quiet = false;
|
|
1513
|
+
// How long the next change to _music fades for: fade= on {{music}} or {{stopmusic}}
|
|
1514
|
+
let musicFade = DEFAULT_FADE;
|
|
1515
|
+
const sound = new Sound({
|
|
1516
|
+
resolveUrl: path => isAbsolute(path) || !options.resolveAssetUrl
|
|
1517
|
+
? path
|
|
1518
|
+
: options.resolveAssetUrl(path.replace(/^(\.\/)+/, "")),
|
|
1519
|
+
getMusic: () => get("_music"),
|
|
1520
|
+
mutedKey: settings.persist ? "squiffy-muted:" + storageKey : undefined,
|
|
1521
|
+
onPlay: () => {
|
|
1522
|
+
playedSound = true;
|
|
1523
|
+
emitter.emit("sound", {});
|
|
1524
|
+
},
|
|
1525
|
+
});
|
|
1526
|
+
sound.preload(story.audio ?? []);
|
|
1527
|
+
emitter.on("set", ({ attribute }) => {
|
|
1528
|
+
if (attribute != "_music") return;
|
|
1529
|
+
const fade = musicFade;
|
|
1530
|
+
musicFade = DEFAULT_FADE;
|
|
1531
|
+
sound.sync(fade);
|
|
1532
|
+
});
|
|
1533
|
+
const fadeOption = (options: { hash?: Record<string, unknown> } | undefined) => {
|
|
1534
|
+
const fade = Number(options?.hash?.fade);
|
|
1535
|
+
return options?.hash && "fade" in options.hash && Number.isFinite(fade) && fade >= 0 ? fade : DEFAULT_FADE;
|
|
1536
|
+
};
|
|
1537
|
+
// {{music}} and {{sound}} with nothing after them are still an attribute called music or
|
|
1538
|
+
// sound, as they were before these helpers
|
|
1539
|
+
const isHelperOptions = (value: unknown) => typeof value == "object" && value !== null && "hash" in value;
|
|
1540
|
+
textProcessor.handlebars.registerHelper("music", (file: unknown, options?: { hash?: Record<string, unknown> }) => {
|
|
1541
|
+
if (isHelperOptions(file)) return get("music");
|
|
1542
|
+
if (state.readOnly || typeof file != "string") return "";
|
|
1543
|
+
musicFade = fadeOption(options);
|
|
1544
|
+
set("_music", file || null);
|
|
1545
|
+
musicFade = DEFAULT_FADE;
|
|
1546
|
+
return "";
|
|
1547
|
+
});
|
|
1548
|
+
textProcessor.handlebars.registerHelper("stopmusic", (options?: { hash?: Record<string, unknown> }) => {
|
|
1549
|
+
if (state.readOnly) return "";
|
|
1550
|
+
musicFade = fadeOption(options);
|
|
1551
|
+
set("_music", null);
|
|
1552
|
+
musicFade = DEFAULT_FADE;
|
|
1553
|
+
return "";
|
|
1554
|
+
});
|
|
1555
|
+
textProcessor.handlebars.registerHelper("sound", (file: unknown, options?: { hash?: Record<string, unknown> }) => {
|
|
1556
|
+
if (isHelperOptions(file)) return get("sound");
|
|
1557
|
+
if (state.readOnly || quiet || typeof file != "string" || !file) return "";
|
|
1558
|
+
const volume = Number(options?.hash?.volume ?? 1);
|
|
1559
|
+
sound.play(file, volume);
|
|
1560
|
+
return "";
|
|
1561
|
+
});
|
|
1562
|
+
textProcessor.handlebars.registerHelper("stopsounds", () => {
|
|
1563
|
+
if (!state.readOnly && !quiet) sound.stopSounds();
|
|
1564
|
+
return "";
|
|
1565
|
+
});
|
|
1566
|
+
|
|
1567
|
+
// Classes on the story's element (#449): the current section's, from @class, which change with
|
|
1568
|
+
// the section, and ones from {{addclass}}, which stay until they're removed. They're attributes,
|
|
1569
|
+
// so they come back with Back and saved games.
|
|
1570
|
+
const SECTION_CLASSES = "_sectionclasses";
|
|
1571
|
+
const CLASSES = "_classes";
|
|
1572
|
+
// The classes this put on the element, so it leaves any others alone
|
|
1573
|
+
let appliedClasses: string[] = [];
|
|
1574
|
+
const classList = (attribute: string): string[] => {
|
|
1575
|
+
const value = get(attribute);
|
|
1576
|
+
return Array.isArray(value) ? value.filter((c): c is string => typeof c == "string" && c.length > 0) : [];
|
|
1577
|
+
};
|
|
1578
|
+
const sectionClasses = () => classList(SECTION_CLASSES);
|
|
1579
|
+
// Class names from helper arguments, which can each hold several separated by spaces
|
|
1580
|
+
const classNames = (values: unknown[]) => values
|
|
1581
|
+
.filter(v => !isHelperOptions(v))
|
|
1582
|
+
.flatMap(v => String(v ?? "").split(/\s+/))
|
|
1583
|
+
.filter(c => c.length > 0);
|
|
1584
|
+
function setSectionClasses(classes: string[]) {
|
|
1585
|
+
const unique = [...new Set(classes)];
|
|
1586
|
+
const current = sectionClasses();
|
|
1587
|
+
if (unique.length == current.length && unique.every((c, i) => c == current[i])) return;
|
|
1588
|
+
set(SECTION_CLASSES, unique);
|
|
1589
|
+
}
|
|
1590
|
+
function applyClasses(classes: string[]) {
|
|
1591
|
+
for (const c of appliedClasses) {
|
|
1592
|
+
if (!classes.includes(c)) outputElementContainer.classList.remove(c);
|
|
1593
|
+
}
|
|
1594
|
+
for (const c of classes) outputElementContainer.classList.add(c);
|
|
1595
|
+
appliedClasses = classes;
|
|
1596
|
+
}
|
|
1597
|
+
// With the classes from the player's settings, such as setting-textSize-Large
|
|
1598
|
+
function syncClasses() {
|
|
1599
|
+
applyClasses([...new Set([...sectionClasses(), ...classList(CLASSES), ...playerSettings.classes()])]);
|
|
1600
|
+
}
|
|
1601
|
+
emitter.on("set", ({ attribute }) => {
|
|
1602
|
+
if (attribute == SECTION_CLASSES || attribute == CLASSES) syncClasses();
|
|
1603
|
+
});
|
|
1604
|
+
textProcessor.handlebars.registerHelper("addclass", (...args: unknown[]) => {
|
|
1605
|
+
if (state.readOnly) return "";
|
|
1606
|
+
const classes = classList(CLASSES);
|
|
1607
|
+
const added = classNames(args).filter(c => !classes.includes(c));
|
|
1608
|
+
if (added.length) set(CLASSES, [...classes, ...added]);
|
|
1609
|
+
return "";
|
|
1610
|
+
});
|
|
1611
|
+
textProcessor.handlebars.registerHelper("removeclass", (...args: unknown[]) => {
|
|
1612
|
+
if (state.readOnly) return "";
|
|
1613
|
+
const removed = classNames(args);
|
|
1614
|
+
const classes = classList(CLASSES);
|
|
1615
|
+
if (classes.some(c => removed.includes(c))) set(CLASSES, classes.filter(c => !removed.includes(c)));
|
|
1616
|
+
return "";
|
|
1617
|
+
});
|
|
1618
|
+
textProcessor.handlebars.registerHelper("toggleclass", (...args: unknown[]) => {
|
|
1619
|
+
if (state.readOnly) return "";
|
|
1620
|
+
let classes = classList(CLASSES);
|
|
1621
|
+
for (const c of new Set(classNames(args))) {
|
|
1622
|
+
classes = classes.includes(c) ? classes.filter(x => x != c) : [...classes, c];
|
|
1623
|
+
}
|
|
1624
|
+
set(CLASSES, classes);
|
|
1625
|
+
return "";
|
|
1626
|
+
});
|
|
1627
|
+
// Whether the story's element has all these classes, from @class or {{addclass}}
|
|
1628
|
+
textProcessor.handlebars.registerHelper("hasclass", (...args: unknown[]) => {
|
|
1629
|
+
const names = classNames(args);
|
|
1630
|
+
const classes = [...sectionClasses(), ...classList(CLASSES)];
|
|
1631
|
+
return names.length > 0 && names.every(c => classes.includes(c));
|
|
1632
|
+
});
|
|
1633
|
+
|
|
1139
1634
|
const linkHandler = new LinkHandler();
|
|
1140
1635
|
|
|
1636
|
+
// {{restart}} and {{saves}} links (#452). The page can handle them itself, with its own
|
|
1637
|
+
// dialogs, by listening for restartRequested and savesRequested. Otherwise the runtime asks
|
|
1638
|
+
// before restarting, and opens a Saved games dialog of its own.
|
|
1639
|
+
let savesDialog: SavesDialog | null = null;
|
|
1640
|
+
linkHandler.registerLinkHandler("restart", link => {
|
|
1641
|
+
const confirm = link.getAttribute("data-confirm") !== "false";
|
|
1642
|
+
// After the click has been handled, which saves the game as it is
|
|
1643
|
+
queueMicrotask(async () => {
|
|
1644
|
+
if (emitter.has("restartRequested")) {
|
|
1645
|
+
emitter.emit("restartRequested", { confirm });
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
if (confirm && !await confirmDialog({
|
|
1649
|
+
message: strings.restartConfirm ?? "Are you sure you want to restart?",
|
|
1650
|
+
confirm: strings.restart ?? "Restart",
|
|
1651
|
+
cancel: strings.cancel,
|
|
1652
|
+
})) return;
|
|
1653
|
+
restart();
|
|
1654
|
+
});
|
|
1655
|
+
return {};
|
|
1656
|
+
});
|
|
1657
|
+
let settingsDialog: SettingsDialog | null = null;
|
|
1658
|
+
linkHandler.registerLinkHandler("settings", () => {
|
|
1659
|
+
if (emitter.has("settingsRequested")) {
|
|
1660
|
+
emitter.emit("settingsRequested", {});
|
|
1661
|
+
}
|
|
1662
|
+
else {
|
|
1663
|
+
settingsDialog ??= createSettingsDialog(api, { strings });
|
|
1664
|
+
settingsDialog.open();
|
|
1665
|
+
}
|
|
1666
|
+
return {};
|
|
1667
|
+
});
|
|
1668
|
+
linkHandler.registerLinkHandler("saves", () => {
|
|
1669
|
+
if (emitter.has("savesRequested")) {
|
|
1670
|
+
emitter.emit("savesRequested", {});
|
|
1671
|
+
}
|
|
1672
|
+
else {
|
|
1673
|
+
savesDialog ??= createSavesDialog(api, { strings });
|
|
1674
|
+
savesDialog.open();
|
|
1675
|
+
}
|
|
1676
|
+
return {};
|
|
1677
|
+
});
|
|
1678
|
+
|
|
1141
1679
|
const getSectionText = (sectionName: string) => {
|
|
1142
1680
|
if (sectionName in story.sections) {
|
|
1143
1681
|
return story.sections[sectionName].text || null;
|
|
@@ -1168,7 +1706,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1168
1706
|
pluginManager.add(Plugins.LivePlugin());
|
|
1169
1707
|
pluginManager.add(Plugins.AnimatePlugin());
|
|
1170
1708
|
|
|
1171
|
-
|
|
1709
|
+
const api: SquiffyApi = {
|
|
1172
1710
|
begin: begin,
|
|
1173
1711
|
restart: restart,
|
|
1174
1712
|
get: get,
|
|
@@ -1180,8 +1718,32 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
1180
1718
|
getSave: getSave,
|
|
1181
1719
|
loadSave: loadSave,
|
|
1182
1720
|
renderPassage: renderPassage,
|
|
1721
|
+
isMuted: () => sound.isMuted(),
|
|
1722
|
+
setMuted: (muted: boolean) => sound.setMuted(muted),
|
|
1723
|
+
usesSound: () => playedSound || !!story.audio?.length,
|
|
1724
|
+
getSettings: () => structuredClone(playerSettings.definitions()),
|
|
1725
|
+
getSetting: (name: string) => playerSettings.get(name),
|
|
1726
|
+
setSetting: (name, value) => {
|
|
1727
|
+
if (playerSettings.set(name, value)) settingChanged(name, playerSettings.get(name));
|
|
1728
|
+
},
|
|
1729
|
+
resetSettings: () => {
|
|
1730
|
+
const before = playerSettings.all();
|
|
1731
|
+
playerSettings.reset();
|
|
1732
|
+
for (const [name, value] of Object.entries(playerSettings.all())) {
|
|
1733
|
+
if (value !== before[name]) settingChanged(name, value);
|
|
1734
|
+
}
|
|
1735
|
+
},
|
|
1736
|
+
dispose: () => {
|
|
1737
|
+
cancelGoto();
|
|
1738
|
+
everyTimers.stopAll();
|
|
1739
|
+
sound.dispose();
|
|
1740
|
+
applyClasses([]);
|
|
1741
|
+
savesDialog?.element.remove();
|
|
1742
|
+
settingsDialog?.element.remove();
|
|
1743
|
+
},
|
|
1183
1744
|
on: (e, h) => emitter.on(e, h),
|
|
1184
1745
|
off: (e, h) => emitter.off(e, h),
|
|
1185
1746
|
once: (e, h) => emitter.once(e, h),
|
|
1186
1747
|
};
|
|
1748
|
+
return api;
|
|
1187
1749
|
};
|