squiffy-runtime 6.0.1 → 7.0.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets.d.ts +3 -0
- package/dist/assets.test.d.ts +1 -0
- package/dist/classes.test.d.ts +1 -0
- package/dist/confirmDialog.d.ts +8 -0
- package/dist/events.d.ts +16 -0
- package/dist/every.d.ts +12 -0
- package/dist/every.test.d.ts +1 -0
- package/dist/helpers.test.d.ts +1 -0
- package/dist/numbers.d.ts +3 -0
- package/dist/panels.d.ts +14 -0
- package/dist/panels.test.d.ts +1 -0
- package/dist/paths.d.ts +15 -0
- package/dist/paths.test.d.ts +1 -0
- package/dist/persistent.test.d.ts +1 -0
- package/dist/playerSettings.d.ts +17 -0
- package/dist/pluginManager.d.ts +2 -1
- package/dist/preview-host.d.ts +33 -0
- package/dist/preview-host.js +125 -0
- package/dist/preview-host.js.map +7 -0
- package/dist/preview-host.test.d.ts +1 -0
- package/dist/preview-html.d.ts +2 -0
- package/dist/preview-html.js +2 -0
- package/dist/preview-protocol.d.ts +69 -0
- package/dist/preview.d.ts +15 -0
- package/dist/preview.main.d.ts +1 -0
- package/dist/preview.test.d.ts +1 -0
- package/dist/saveSlots.d.ts +16 -0
- package/dist/saves.test.d.ts +1 -0
- package/dist/savesDialog.d.ts +43 -0
- package/dist/savesDialog.test.d.ts +1 -0
- package/dist/scripts.test.d.ts +1 -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 +155 -0
- package/dist/squiffy.preview.html +1631 -0
- package/dist/squiffy.runtime.css +1123 -20
- package/dist/squiffy.runtime.d.ts +13 -1
- package/dist/squiffy.runtime.global.js +146 -76
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +7105 -4681
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +17 -0
- package/dist/storyLists.d.ts +4 -0
- package/dist/storyLists.test.d.ts +1 -0
- package/dist/style.test.d.ts +1 -0
- package/dist/textProcessor.d.ts +27 -0
- package/dist/transitions.test.d.ts +1 -0
- package/dist/types.d.ts +137 -1
- package/dist/types.plugins.d.ts +2 -0
- package/dist/uiLinks.test.d.ts +1 -0
- package/dist/utils.d.ts +2 -1
- package/dist/utils.test.d.ts +1 -0
- package/package.json +25 -11
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +22 -22
- package/src/animation.test.ts +44 -0
- package/src/animation.ts +9 -5
- package/src/assets.test.ts +225 -0
- package/src/assets.ts +92 -0
- package/src/classes.test.ts +201 -0
- package/src/confirmDialog.ts +66 -0
- package/src/events.ts +20 -0
- package/src/every.test.ts +25 -0
- package/src/every.ts +94 -0
- package/src/helpers.test.ts +34 -0
- package/src/numbers.ts +21 -0
- package/src/panels.test.ts +225 -0
- package/src/panels.ts +187 -0
- package/src/paths.test.ts +66 -0
- package/src/paths.ts +155 -0
- package/src/persistent.test.ts +155 -0
- package/src/playerSettings.ts +128 -0
- package/src/pluginManager.ts +6 -1
- package/src/plugins/animate.ts +34 -9
- package/src/plugins/live.ts +18 -5
- package/src/plugins/plugins.test.ts +93 -6
- package/src/plugins/replaceLabel.ts +7 -3
- package/src/preview-host.test.ts +171 -0
- package/src/preview-host.ts +190 -0
- package/src/preview-protocol.ts +79 -0
- package/src/preview.main.ts +34 -0
- package/src/preview.test.ts +367 -0
- package/src/preview.ts +331 -0
- package/src/saveSlots.ts +159 -0
- package/src/saves.test.ts +199 -0
- package/src/savesDialog.test.ts +290 -0
- package/src/savesDialog.ts +499 -0
- package/src/scripts.test.ts +130 -0
- 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 +155 -0
- package/src/squiffy.runtime.css +1123 -20
- package/src/squiffy.runtime.test.ts +2806 -44
- package/src/squiffy.runtime.ts +1130 -64
- package/src/state.ts +172 -11
- package/src/storyLists.test.ts +134 -0
- package/src/storyLists.ts +57 -0
- package/src/style.test.ts +89 -0
- package/src/textProcessor.ts +739 -58
- package/src/transitions.test.ts +343 -0
- package/src/types.plugins.ts +7 -0
- package/src/types.ts +226 -2
- package/src/uiLinks.test.ts +156 -0
- package/src/updater.ts +26 -8
- package/src/utils.test.ts +60 -0
- package/src/utils.ts +46 -14
- package/vite.config.ts +3 -4
- package/vite.preview.config.ts +83 -0
- package/dist/infixExpressions.d.ts +0 -2
- package/src/infixExpressions.test.ts +0 -187
- package/src/infixExpressions.ts +0 -323
- /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
package/src/squiffy.runtime.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage } from "./types.js";
|
|
2
|
-
import {
|
|
1
|
+
import { SquiffyApi, SquiffyInitOptions, SquiffyScriptApi, SquiffyScriptEvent, Story, Section, Passage, StartAt, SavedGame, LoadSaveResult, TagFilter } from "./types.js";
|
|
2
|
+
import { listPassages, listSections, tagsOf } from "./storyLists.js";
|
|
3
|
+
import { TextProcessor, afterClear, errorHtml } from "./textProcessor.js";
|
|
4
|
+
import { toNumber } from "./numbers.js";
|
|
3
5
|
import { Emitter, SquiffyEventMap } from "./events.js";
|
|
4
6
|
import { State } from "./state.js";
|
|
7
|
+
import { checkSegment, readTarget, Target } from "./paths.js";
|
|
5
8
|
import { updateStory } from "./updater.js";
|
|
6
9
|
import { PluginManager } from "./pluginManager.js";
|
|
7
10
|
import { Plugins } from "./plugins/index.js";
|
|
@@ -9,9 +12,28 @@ import { LinkHandler } from "./linkHandler.js";
|
|
|
9
12
|
import { Animation } from "./animation.js";
|
|
10
13
|
import { imports } from "./import.js";
|
|
11
14
|
import { areInputsValid, setupInputValidation } from "./inputValidation.js";
|
|
12
|
-
|
|
13
|
-
|
|
15
|
+
import { createAssetHtmlResolver, isAbsolute } from "./assets.js";
|
|
16
|
+
import { Sound, DEFAULT_FADE } from "./sound.js";
|
|
17
|
+
import { EveryTimers } from "./every.js";
|
|
18
|
+
import { confirmDialog } from "./confirmDialog.js";
|
|
19
|
+
import { createSavesDialog, type SavesDialog } from "./savesDialog.js";
|
|
20
|
+
import { createSettingsDialog, type SettingsDialog } from "./settingsDialog.js";
|
|
21
|
+
import { PlayerSettings } from "./playerSettings.js";
|
|
22
|
+
|
|
23
|
+
export type { SquiffyApi, SquiffyScriptApi, SquiffyScriptEvent, SavedGame, LoadSaveResult, PlayerSetting, PlayerSettingOption, SettingValue } from "./types.js";
|
|
14
24
|
export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
|
|
25
|
+
export { createSavesDialog, formatSaveTime, SAVES_STRINGS, SAVE_FILE_EXTENSION } from "./savesDialog.js";
|
|
26
|
+
export type { SavesDialog, SavesDialogOptions, SavesStringName } from "./savesDialog.js";
|
|
27
|
+
export { confirmDialog } from "./confirmDialog.js";
|
|
28
|
+
export { createSettingsDialog, SETTINGS_STRINGS } from "./settingsDialog.js";
|
|
29
|
+
export type { SettingsDialog, SettingsDialogOptions } from "./settingsDialog.js";
|
|
30
|
+
export type { ConfirmDialogOptions } from "./confirmDialog.js";
|
|
31
|
+
export { indexedDbSaveSlots, memorySaveSlots } from "./saveSlots.js";
|
|
32
|
+
export { createPanels } from "./panels.js";
|
|
33
|
+
export type { Panels, PanelsOptions } from "./panels.js";
|
|
34
|
+
export { PANEL_ICONS } from "./types.js";
|
|
35
|
+
export type { Panel, PanelIcon } from "./types.js";
|
|
36
|
+
export type { SaveSlot, SaveSlots } from "./saveSlots.js";
|
|
15
37
|
|
|
16
38
|
export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> => {
|
|
17
39
|
let story: Story;
|
|
@@ -20,9 +42,27 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
20
42
|
let currentPassageElement: HTMLElement | null;
|
|
21
43
|
let currentBlockOutputElement: HTMLElement | null;
|
|
22
44
|
let scrollPosition = 0;
|
|
45
|
+
// Set when the screen is cleared, so the next scroll goes up to the top of the new screen (#54)
|
|
46
|
+
let scrollToTop = false;
|
|
47
|
+
// The section or passage being shown, and the ones it takes its @transition and @leave from,
|
|
48
|
+
// for a {{clear}} in its text (#524)
|
|
49
|
+
let shownFrom: (Section | Passage | undefined)[] = [];
|
|
50
|
+
// Errors from setting attributes (e.g. @set gold += abc), shown at the start of the next text
|
|
51
|
+
// written. A link's setters run before the next section has anywhere to show them.
|
|
52
|
+
const pendingErrors: string[] = [];
|
|
23
53
|
const emitter = new Emitter<SquiffyEventMap>();
|
|
24
54
|
const transitions: (() => Promise<void>)[] = [];
|
|
25
55
|
let runningTransitions = false;
|
|
56
|
+
// A {{goto ... after=}} waiting to happen (#375)
|
|
57
|
+
let gotoTimer: ReturnType<typeof setTimeout> | undefined;
|
|
58
|
+
// {{goto}}s followed one after another without the player doing anything, so a loop can't hang
|
|
59
|
+
// the browser
|
|
60
|
+
let gotoHops = 0;
|
|
61
|
+
const MAX_GOTO_HOPS = 100;
|
|
62
|
+
// The {{#every}}s showing their text again and again (#451), and how many sections or passages
|
|
63
|
+
// are being shown, which they wait for
|
|
64
|
+
const everyTimers = new EveryTimers(() => currentSectionElement, tickEvery);
|
|
65
|
+
let navigating = 0;
|
|
26
66
|
|
|
27
67
|
async function handleLink(link: HTMLElement): Promise<boolean> {
|
|
28
68
|
if (runningTransitions) return false;
|
|
@@ -39,13 +79,31 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
39
79
|
const passage = link.getAttribute("data-passage");
|
|
40
80
|
const section = link.getAttribute("data-section");
|
|
41
81
|
|
|
82
|
+
if (passage !== null || section !== null) {
|
|
83
|
+
gotoHops = 0;
|
|
84
|
+
// A text box that goes somewhere when Enter is pressed (#454) keeps what was typed
|
|
85
|
+
// first, so the section or passage it goes to can use it. Other text boxes are only
|
|
86
|
+
// kept when the player leaves the section.
|
|
87
|
+
if (link instanceof window.HTMLInputElement) {
|
|
88
|
+
const attribute = link.getAttribute("data-attribute") || link.id;
|
|
89
|
+
if (attribute) set(attribute, link.value);
|
|
90
|
+
}
|
|
91
|
+
// The story-wide turn count (#377). A {{goto}} isn't a turn, as the player didn't click it.
|
|
92
|
+
set("turns", (get("turns") || 0) + 1);
|
|
93
|
+
}
|
|
94
|
+
|
|
42
95
|
if (passage !== null) {
|
|
43
|
-
|
|
44
|
-
|
|
96
|
+
// A passage with @repeat can be clicked again, and doesn't count towards @1, @2... and @last
|
|
97
|
+
let clicked: string | undefined;
|
|
98
|
+
if (!isRepeatPassage(passage)) {
|
|
99
|
+
disableLink(link);
|
|
100
|
+
clicked = markClicked(link);
|
|
101
|
+
set("_turncount", get("_turncount") + 1);
|
|
102
|
+
}
|
|
45
103
|
await processLink(link);
|
|
46
104
|
if (passage) {
|
|
47
105
|
currentBlockOutputElement = null;
|
|
48
|
-
await showPassage(passage);
|
|
106
|
+
await showPassage(passage, clicked);
|
|
49
107
|
}
|
|
50
108
|
|
|
51
109
|
emitter.emit("linkClick", { linkType: "passage" });
|
|
@@ -85,21 +143,146 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
85
143
|
}
|
|
86
144
|
}
|
|
87
145
|
|
|
146
|
+
function isRepeatPassage(passageName: string) {
|
|
147
|
+
if (!passageName) return false;
|
|
148
|
+
const sectionPassages = currentSection?.passages;
|
|
149
|
+
if (sectionPassages && passageName in sectionPassages) return !!sectionPassages[passageName].repeat;
|
|
150
|
+
const masterPassages = story.sections[""]?.passages;
|
|
151
|
+
return !!(masterPassages && passageName in masterPassages && masterPassages[passageName].repeat);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// A link, or a text box that goes to a passage when Enter is pressed (#454)
|
|
88
155
|
function disableLink(link: Element) {
|
|
156
|
+
if (link instanceof window.HTMLInputElement) {
|
|
157
|
+
link.disabled = true;
|
|
158
|
+
link.classList.add("disabled");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
89
161
|
link.classList.add("disabled");
|
|
90
162
|
link.setAttribute("tabindex", "-1");
|
|
91
163
|
}
|
|
92
164
|
|
|
93
165
|
function enableLink(link: Element) {
|
|
166
|
+
if (link instanceof window.HTMLInputElement) {
|
|
167
|
+
link.disabled = false;
|
|
168
|
+
link.classList.remove("disabled");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
94
171
|
link.classList.remove("disabled");
|
|
95
172
|
link.removeAttribute("tabindex");
|
|
96
173
|
}
|
|
174
|
+
|
|
175
|
+
// Numbers a passage link that was clicked, so that going back can enable just that link, and
|
|
176
|
+
// not the others to the same passage, such as the other items' links in an {{#each}} (#448)
|
|
177
|
+
function markClicked(link: Element) {
|
|
178
|
+
let max = 0;
|
|
179
|
+
for (const other of outputElement.querySelectorAll("[data-clicked]")) {
|
|
180
|
+
max = Math.max(max, Number(other.getAttribute("data-clicked")) || 0);
|
|
181
|
+
}
|
|
182
|
+
const id = String(max + 1);
|
|
183
|
+
link.setAttribute("data-clicked", id);
|
|
184
|
+
return id;
|
|
185
|
+
}
|
|
97
186
|
|
|
98
|
-
async function begin() {
|
|
187
|
+
async function begin(startAt?: StartAt) {
|
|
188
|
+
if (startAt && startAt.section in story.sections) {
|
|
189
|
+
// Start somewhere else in a fresh story, e.g. from the section being edited
|
|
190
|
+
runUiJs();
|
|
191
|
+
await go(startAt.section);
|
|
192
|
+
if (startAt.passage !== undefined && get("_section") == startAt.section) {
|
|
193
|
+
await showPassage(startAt.passage);
|
|
194
|
+
}
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
99
197
|
if (!load()) {
|
|
100
198
|
await go(story.start);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
// As when a saved game is loaded, so that panels show the attributes it has
|
|
202
|
+
const passage = get("_passage");
|
|
203
|
+
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
204
|
+
// Saved while waiting for a {{goto}}, so carry on waiting
|
|
205
|
+
await resumeGoto();
|
|
206
|
+
everyTimers.sync();
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function resumeGoto() {
|
|
210
|
+
const element = currentPassageElement ?? currentSectionElement;
|
|
211
|
+
const section = element?.getAttribute("data-goto");
|
|
212
|
+
if (section && section in story.sections) {
|
|
213
|
+
await followGoto({ section, after: Number(element.getAttribute("data-goto-after") || 0) });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function cancelGoto() {
|
|
218
|
+
clearTimeout(gotoTimer);
|
|
219
|
+
gotoTimer = undefined;
|
|
220
|
+
textProcessor.goto = null;
|
|
221
|
+
textProcessor.deactivate.clear();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Disables the links to the passages that a {{deactivate}} in the text just shown asked for
|
|
225
|
+
// (#13). The element that did it, and each link it disabled, get the same number, so that going
|
|
226
|
+
// back can enable just those links again. A link already disabled by a click is left alone.
|
|
227
|
+
function takeDeactivate(element: HTMLElement) {
|
|
228
|
+
const names = textProcessor.deactivate;
|
|
229
|
+
if (names.size == 0) return;
|
|
230
|
+
const id = String((get("_deactivations") || 0) + 1);
|
|
231
|
+
set("_deactivations", Number(id));
|
|
232
|
+
element.setAttribute("data-deactivates", id);
|
|
233
|
+
for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
|
|
234
|
+
if (names.has(link.getAttribute("data-passage")!) && !link.classList.contains("disabled")) {
|
|
235
|
+
disableLink(link);
|
|
236
|
+
link.setAttribute("data-deactivated-by", id);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
names.clear();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Going back: enables the links that the element's {{deactivate}} disabled
|
|
243
|
+
function undoDeactivate(element: HTMLElement) {
|
|
244
|
+
const id = element.getAttribute("data-deactivates");
|
|
245
|
+
if (!id) return;
|
|
246
|
+
for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-deactivated-by="${id}"]`)) {
|
|
247
|
+
enableLink(link);
|
|
248
|
+
link.removeAttribute("data-deactivated-by");
|
|
101
249
|
}
|
|
102
250
|
}
|
|
251
|
+
|
|
252
|
+
// Takes the {{goto}} from the text just shown, if there was one, and marks the section or
|
|
253
|
+
// passage element with it, so that going back skips it, and loading resumes it.
|
|
254
|
+
function takeGoto(element: HTMLElement) {
|
|
255
|
+
const pending = textProcessor.goto;
|
|
256
|
+
textProcessor.goto = null;
|
|
257
|
+
if (pending) {
|
|
258
|
+
element.setAttribute("data-goto", pending.section);
|
|
259
|
+
if (pending.after) element.setAttribute("data-goto-after", String(pending.after));
|
|
260
|
+
}
|
|
261
|
+
return pending;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function followGoto(pending: { section: string; after: number } | null) {
|
|
265
|
+
if (!pending) return;
|
|
266
|
+
if (pending.after > 0) {
|
|
267
|
+
gotoTimer = setTimeout(() => {
|
|
268
|
+
gotoTimer = undefined;
|
|
269
|
+
gotoHops = 0;
|
|
270
|
+
void go(pending.section);
|
|
271
|
+
}, pending.after);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (++gotoHops > MAX_GOTO_HOPS) {
|
|
275
|
+
gotoHops = 0;
|
|
276
|
+
const element = currentPassageElement ?? currentSectionElement;
|
|
277
|
+
element.removeAttribute("data-goto");
|
|
278
|
+
const message = `stopped after ${MAX_GOTO_HOPS} in a row without the player clicking anything, going to "${pending.section}". Is there a loop?`;
|
|
279
|
+
console.error("Squiffy error in {{goto}}:", message);
|
|
280
|
+
element.insertAdjacentHTML("beforeend", errorHtml("Error in {{goto}}:", message));
|
|
281
|
+
save();
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
await go(pending.section);
|
|
285
|
+
}
|
|
103
286
|
|
|
104
287
|
async function processLink(link: HTMLElement) {
|
|
105
288
|
animation.runLinkAnimation(link);
|
|
@@ -113,7 +296,87 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
113
296
|
}
|
|
114
297
|
}
|
|
115
298
|
|
|
299
|
+
// Runs a setter from @set or a link, e.g. gold += 5. An error leaves the attribute as it was,
|
|
300
|
+
// and is shown with the next text written.
|
|
116
301
|
function setAttribute(expr: string) {
|
|
302
|
+
try {
|
|
303
|
+
if (story.expressions) {
|
|
304
|
+
setWithExpression(expr);
|
|
305
|
+
}
|
|
306
|
+
else {
|
|
307
|
+
setWithoutExpression(expr);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
catch (e) {
|
|
311
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
312
|
+
console.error(`Squiffy error in "${expr}":`, message);
|
|
313
|
+
pendingErrors.push(errorHtml(`Error in "${expr}":`, message));
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// +=, -=, *= and /=, which only work on numbers (#374)
|
|
318
|
+
function operate(lhs: string | string[], op: string, amountValue: unknown) {
|
|
319
|
+
const what = op + "=";
|
|
320
|
+
const amount = toNumber(what, amountValue);
|
|
321
|
+
const path = typeof lhs == "string" ? [lhs] : lhs;
|
|
322
|
+
let value = toNumber(what, state.getAt(path));
|
|
323
|
+
if (op == "+") value += amount;
|
|
324
|
+
if (op == "-") value -= amount;
|
|
325
|
+
if (op == "*") value *= amount;
|
|
326
|
+
if (op == "/") value /= amount;
|
|
327
|
+
state.setAt(path, value);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// The path a setter's target names, with any [index] in it worked out, e.g. ["inventory", "2",
|
|
331
|
+
// "name"] for inventory[i].name when i is 2 (#442)
|
|
332
|
+
function targetPath(target: Target): string[] {
|
|
333
|
+
return [target.attribute, ...target.segments.map(segment => {
|
|
334
|
+
if ("name" in segment) return segment.name;
|
|
335
|
+
const index = textProcessor.evaluate(segment.index);
|
|
336
|
+
if (typeof index != "string" && typeof index != "number") {
|
|
337
|
+
throw new Error(`[${segment.index.trim()}] should be a number or text, to say which value to set`);
|
|
338
|
+
}
|
|
339
|
+
const name = String(index);
|
|
340
|
+
checkSegment(name);
|
|
341
|
+
return name;
|
|
342
|
+
})];
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// A story with a squiffy.json (#373): the right-hand side is an expression, with the same rules
|
|
346
|
+
// as {{#if}}, e.g. weapon = "sword", gold = gold + price * 2, rich = gold > 100. The left-hand
|
|
347
|
+
// side can be a value inside an object, e.g. hero.hp = 10 or inventory[i].name = "lamp" (#442).
|
|
348
|
+
function setWithExpression(expr: string) {
|
|
349
|
+
const target = readTarget(expr);
|
|
350
|
+
const textMatch = target && /^\s*:=(.*)$/.exec(target.rest);
|
|
351
|
+
if (target && textMatch) {
|
|
352
|
+
// Text with {{...}} processed, as before
|
|
353
|
+
state.setAt(targetPath(target), ui.processText(textMatch[1], true));
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
const match = target && /^\s*([+\-*/]?)=(?!=)(.*)$/.exec(target.rest);
|
|
357
|
+
if (target && match) {
|
|
358
|
+
const [, op, rhs] = match;
|
|
359
|
+
const path = targetPath(target);
|
|
360
|
+
const value = textProcessor.evaluate(rhs);
|
|
361
|
+
if (op) {
|
|
362
|
+
operate(path, op, value);
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
state.setAt(path, value);
|
|
366
|
+
}
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const not = /^\s*not\s+/.exec(expr);
|
|
370
|
+
const flag = readTarget(not ? expr.substring(not[0].length) : expr);
|
|
371
|
+
if (!flag || flag.rest.trim()) {
|
|
372
|
+
throw new Error("expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key");
|
|
373
|
+
}
|
|
374
|
+
state.setAt(targetPath(flag), !not);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// A story without a squiffy.json, as in Squiffy 6: the right-hand side is a number, true,
|
|
378
|
+
// false, @attribute, or else text
|
|
379
|
+
function setWithoutExpression(expr: string) {
|
|
117
380
|
expr = expr.replace(/^(\w*\s*):=(.*)$/, (_, name, value) => (name + "=" + ui.processText(value, true)));
|
|
118
381
|
const setRegex = /^([\w]*)\s*=\s*(.*)$/;
|
|
119
382
|
const setMatch = setRegex.exec(expr);
|
|
@@ -140,24 +403,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
140
403
|
if (incDecMatch) {
|
|
141
404
|
const lhs = incDecMatch[1];
|
|
142
405
|
const op = incDecMatch[2];
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const rhsNumeric = parseFloat(rhs);
|
|
146
|
-
let value = get(lhs);
|
|
147
|
-
if (value === null) value = 0;
|
|
148
|
-
if (op == "+") {
|
|
149
|
-
value += rhsNumeric;
|
|
150
|
-
}
|
|
151
|
-
if (op == "-") {
|
|
152
|
-
value -= rhsNumeric;
|
|
153
|
-
}
|
|
154
|
-
if (op == "*") {
|
|
155
|
-
value *= rhsNumeric;
|
|
156
|
-
}
|
|
157
|
-
if (op == "/") {
|
|
158
|
-
value /= rhsNumeric;
|
|
159
|
-
}
|
|
160
|
-
set(lhs, value);
|
|
406
|
+
const rhsText = incDecMatch[3].trim();
|
|
407
|
+
operate(lhs, op, rhsText.startsWith("@") ? get(rhsText.substring(1)) : rhsText);
|
|
161
408
|
}
|
|
162
409
|
else {
|
|
163
410
|
let value = true;
|
|
@@ -171,16 +418,45 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
171
418
|
}
|
|
172
419
|
|
|
173
420
|
async function go(sectionName: string) {
|
|
421
|
+
navigating++;
|
|
422
|
+
try {
|
|
423
|
+
await goNow(sectionName);
|
|
424
|
+
}
|
|
425
|
+
finally {
|
|
426
|
+
navigating--;
|
|
427
|
+
everyTimers.sync();
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async function goNow(sectionName: string) {
|
|
432
|
+
cancelGoto();
|
|
174
433
|
const oldCanGoBack = canGoBack();
|
|
175
434
|
currentSection = story.sections[sectionName];
|
|
176
435
|
if (!currentSection) return;
|
|
436
|
+
const sectionBefore = get("_section");
|
|
437
|
+
if (sectionBefore !== null) {
|
|
438
|
+
// Where the player was before this (#56): the section, or the passage in it shown last
|
|
439
|
+
set("previous", get("_passage") ?? sectionBefore);
|
|
440
|
+
set("previous_section", sectionBefore);
|
|
441
|
+
}
|
|
442
|
+
if (get("_passage") !== null) set("_passage", null);
|
|
177
443
|
set("_section", sectionName);
|
|
444
|
+
// The story-wide turn count starts at 0 (#377), in a new story or one saved before it existed.
|
|
445
|
+
// It isn't a change the player made, so it isn't undone.
|
|
446
|
+
if (get("turns") === null) state.setInternal("turns", 0, false);
|
|
178
447
|
state.setSeen(sectionName);
|
|
179
448
|
const master = story.sections[""];
|
|
180
|
-
|
|
449
|
+
const clear = master?.clear || currentSection.clear;
|
|
450
|
+
shownFrom = [currentSection, master];
|
|
451
|
+
// @leave: the old text goes before anything changes on the screen
|
|
452
|
+
if (clear) await leaveTransition(shownFrom);
|
|
453
|
+
// @class (#449): this section's classes replace the last one's
|
|
454
|
+
setSectionClasses([...(master?.classes ?? []), ...(currentSection.classes ?? [])]);
|
|
455
|
+
if (clear) {
|
|
181
456
|
clearScreen();
|
|
182
457
|
}
|
|
183
458
|
newSection(sectionName);
|
|
459
|
+
startTransition(currentSectionElement, [currentSection, master]);
|
|
184
460
|
const sectionElement = currentSectionElement;
|
|
185
461
|
if (master) {
|
|
186
462
|
await run(master, "[[]]");
|
|
@@ -202,6 +478,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
202
478
|
setupInputValidation(currentSectionElement);
|
|
203
479
|
|
|
204
480
|
set("_turncount", 0);
|
|
481
|
+
takeDeactivate(currentSectionElement);
|
|
482
|
+
const pending = takeGoto(currentSectionElement);
|
|
205
483
|
writeUndoLog();
|
|
206
484
|
save();
|
|
207
485
|
|
|
@@ -209,9 +487,14 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
209
487
|
if (newCanGoBack != oldCanGoBack) {
|
|
210
488
|
emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
|
|
211
489
|
}
|
|
490
|
+
emitter.emit("navigated", { section: sectionName });
|
|
491
|
+
await followGoto(pending);
|
|
212
492
|
}
|
|
213
493
|
|
|
214
|
-
|
|
494
|
+
let inAfterWrite = false;
|
|
495
|
+
|
|
496
|
+
// afterWrite: where squiffy.ui.afterWrite queues its functions, for a section or passage's JS (#106)
|
|
497
|
+
function runJs(index: number, extra: any = null, afterWrite?: (() => void)[]) {
|
|
215
498
|
const squiffy = {
|
|
216
499
|
get: get,
|
|
217
500
|
set: set,
|
|
@@ -219,10 +502,30 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
219
502
|
transition: addTransition,
|
|
220
503
|
write: ui.write,
|
|
221
504
|
scrollToEnd: ui.scrollToEnd,
|
|
505
|
+
afterWrite: (fn: () => void) => {
|
|
506
|
+
if (!afterWrite) {
|
|
507
|
+
throw new Error("squiffy.ui.afterWrite can only be used in a section or passage's JavaScript");
|
|
508
|
+
}
|
|
509
|
+
afterWrite.push(fn);
|
|
510
|
+
},
|
|
222
511
|
},
|
|
223
512
|
story: {
|
|
224
|
-
|
|
513
|
+
// In an afterWrite function, the section's text is already on the page, so going
|
|
514
|
+
// somewhere else waits until it has finished, like {{goto}} (#106)
|
|
515
|
+
go: (sectionName: string) => {
|
|
516
|
+
if (!inAfterWrite) return go(sectionName);
|
|
517
|
+
textProcessor.goto ??= { section: sectionName, after: 0 };
|
|
518
|
+
return Promise.resolve();
|
|
519
|
+
},
|
|
225
520
|
seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
|
|
521
|
+
visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
|
|
522
|
+
lastVisited: (sectionOrPassage: string) => state.getLastVisited(sectionOrPassage),
|
|
523
|
+
// As the passages, sections and tags helpers (#527)
|
|
524
|
+
passages: (section?: string, filter?: TagFilter) => listPassages(story, section, get("_section"), filter),
|
|
525
|
+
sections: (filter?: TagFilter) => listSections(story, filter),
|
|
526
|
+
tags: (name?: string) => name === undefined
|
|
527
|
+
? [...(story.sections[get("_section")]?.tags ?? [])]
|
|
528
|
+
: tagsOf(story, name, get("_section")),
|
|
226
529
|
},
|
|
227
530
|
element: outputElementContainer,
|
|
228
531
|
import: imports,
|
|
@@ -235,9 +538,16 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
235
538
|
if (section.attributes) {
|
|
236
539
|
await processAttributes(section.attributes);
|
|
237
540
|
}
|
|
541
|
+
// @music and @sound (#444)
|
|
542
|
+
if (section.music !== undefined) set("_music", section.music);
|
|
543
|
+
for (const file of section.sounds ?? []) {
|
|
544
|
+
if (file == "stop") sound.stopSounds();
|
|
545
|
+
else sound.play(file);
|
|
546
|
+
}
|
|
547
|
+
const afterWrite: (() => void)[] = [];
|
|
238
548
|
if (section.jsIndex !== undefined) {
|
|
239
549
|
const sectionBefore = get("_section");
|
|
240
|
-
runJs(section.jsIndex);
|
|
550
|
+
runJs(section.jsIndex, null, afterWrite);
|
|
241
551
|
if (get("_section") !== sectionBefore) {
|
|
242
552
|
// JS called squiffy.story.go() and navigated away; the destination
|
|
243
553
|
// section will handle rendering its own content.
|
|
@@ -245,7 +555,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
245
555
|
}
|
|
246
556
|
}
|
|
247
557
|
|
|
248
|
-
ui.
|
|
558
|
+
let html = ui.renderHtml(section.text || "", false);
|
|
559
|
+
const cleared = afterClear(html);
|
|
560
|
+
if (cleared !== null) {
|
|
561
|
+
html = cleared;
|
|
562
|
+
await clearPartWay();
|
|
563
|
+
}
|
|
564
|
+
ui.writeHtml(html, source);
|
|
565
|
+
|
|
566
|
+
// Functions from squiffy.ui.afterWrite run once the text and its {{...}} are on the page (#106)
|
|
567
|
+
inAfterWrite = true;
|
|
568
|
+
try {
|
|
569
|
+
for (const fn of afterWrite) fn();
|
|
570
|
+
}
|
|
571
|
+
finally {
|
|
572
|
+
inAfterWrite = false;
|
|
573
|
+
}
|
|
249
574
|
|
|
250
575
|
await runTransitions();
|
|
251
576
|
}
|
|
@@ -261,7 +586,20 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
261
586
|
currentSectionElement.classList.remove("links-disabled");
|
|
262
587
|
}
|
|
263
588
|
|
|
264
|
-
|
|
589
|
+
// clicked: the number markClicked gave the link that was clicked to get here, if any
|
|
590
|
+
async function showPassage(passageName: string, clicked?: string) {
|
|
591
|
+
navigating++;
|
|
592
|
+
try {
|
|
593
|
+
await showPassageNow(passageName, clicked);
|
|
594
|
+
}
|
|
595
|
+
finally {
|
|
596
|
+
navigating--;
|
|
597
|
+
everyTimers.sync();
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async function showPassageNow(passageName: string, clicked?: string) {
|
|
602
|
+
cancelGoto();
|
|
265
603
|
const oldCanGoBack = canGoBack();
|
|
266
604
|
let passage = currentSection.passages && currentSection.passages[passageName];
|
|
267
605
|
const masterSection = story.sections[""];
|
|
@@ -269,6 +607,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
269
607
|
if (!passage) {
|
|
270
608
|
throw `No passage named ${passageName} in the current section or master section`;
|
|
271
609
|
}
|
|
610
|
+
// The section or passage shown before this one (#56)
|
|
611
|
+
set("previous", get("_passage") ?? get("_section"));
|
|
612
|
+
set("_passage", passageName);
|
|
272
613
|
state.setSeen(passageName);
|
|
273
614
|
|
|
274
615
|
const passages: Passage[] = [];
|
|
@@ -291,8 +632,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
291
632
|
passages.push(passage);
|
|
292
633
|
runFns.push(() => run(passage, `[[${get("_section")}]][${passageName}]`));
|
|
293
634
|
|
|
635
|
+
// [@after] runs after every passage, including those with @repeat (#523): the section's,
|
|
636
|
+
// then the master section's, the other way round from [], so the master's wraps the section's
|
|
637
|
+
const after = currentSection.passages?.["@after"];
|
|
638
|
+
if (after) {
|
|
639
|
+
passages.push(after);
|
|
640
|
+
runFns.push(() => run(after, `[[${get("_section")}]][@after]`));
|
|
641
|
+
}
|
|
642
|
+
const masterAfter = masterSection?.passages?.["@after"];
|
|
643
|
+
if (masterAfter) {
|
|
644
|
+
passages.push(masterAfter);
|
|
645
|
+
runFns.push(() => run(masterAfter, "[[]][@after]"));
|
|
646
|
+
}
|
|
647
|
+
|
|
294
648
|
const turnPassageName = "@" + get("_turncount");
|
|
295
|
-
if
|
|
649
|
+
// A passage with @repeat doesn't count as a turn, so @1, @2... and @last ran already if they're due
|
|
650
|
+
if (currentSection.passages && !passage.repeat) {
|
|
296
651
|
if (turnPassageName in currentSection.passages) {
|
|
297
652
|
const turnPassage = currentSection.passages[turnPassageName];
|
|
298
653
|
passages.push(turnPassage);
|
|
@@ -301,11 +656,20 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
301
656
|
if ("@last" in currentSection.passages && get("_turncount") >= (currentSection.passageCount || 0)) {
|
|
302
657
|
const turnPassage = currentSection.passages["@last"];
|
|
303
658
|
passages.push(turnPassage);
|
|
304
|
-
runFns.push(() => run(turnPassage, `[[${get("_section")}]][
|
|
659
|
+
runFns.push(() => run(turnPassage, `[[${get("_section")}]][@last]`));
|
|
305
660
|
}
|
|
306
661
|
}
|
|
307
662
|
|
|
308
|
-
|
|
663
|
+
const clear = passages.some(p => p.clear);
|
|
664
|
+
shownFrom = [passage, master, masterSection?.passages?.[""], currentSection, masterSection];
|
|
665
|
+
// @leave: the passage's own, or else a master passage's, or else its section's, or the master section's
|
|
666
|
+
if (clear) await leaveTransition(shownFrom);
|
|
667
|
+
|
|
668
|
+
// @class in a passage (#449) adds to the section's classes
|
|
669
|
+
const passageClasses = passages.flatMap(p => p.classes ?? []);
|
|
670
|
+
if (passageClasses.length) setSectionClasses([...sectionClasses(), ...passageClasses]);
|
|
671
|
+
|
|
672
|
+
if (clear) {
|
|
309
673
|
clearScreen();
|
|
310
674
|
createSectionElement();
|
|
311
675
|
}
|
|
@@ -313,8 +677,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
313
677
|
currentPassageElement = document.createElement("div");
|
|
314
678
|
currentPassageElement.classList.add("squiffy-output-passage");
|
|
315
679
|
currentPassageElement.setAttribute("data-passage", `${passageName}`);
|
|
680
|
+
if (clicked) currentPassageElement.setAttribute("data-clicked-link", clicked);
|
|
316
681
|
|
|
317
682
|
currentSectionElement.appendChild(currentPassageElement);
|
|
683
|
+
// @transition (#489): the passage's own, or else a master passage's, or else its section's, or the master section's
|
|
684
|
+
startTransition(currentPassageElement, shownFrom);
|
|
318
685
|
|
|
319
686
|
for (const fn of runFns) {
|
|
320
687
|
await fn();
|
|
@@ -323,12 +690,16 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
323
690
|
// Setup validation for any inputs added by passages
|
|
324
691
|
setupInputValidation(currentSectionElement);
|
|
325
692
|
|
|
693
|
+
takeDeactivate(currentPassageElement!);
|
|
694
|
+
const pending = takeGoto(currentPassageElement!);
|
|
326
695
|
writeUndoLog();
|
|
327
696
|
save();
|
|
328
697
|
const newCanGoBack = canGoBack();
|
|
329
698
|
if (newCanGoBack != oldCanGoBack) {
|
|
330
699
|
emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
|
|
331
700
|
}
|
|
701
|
+
emitter.emit("navigated", { section: get("_section"), passage: passageName });
|
|
702
|
+
await followGoto(pending);
|
|
332
703
|
}
|
|
333
704
|
|
|
334
705
|
async function processAttributes(attributes: string[]) {
|
|
@@ -338,7 +709,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
338
709
|
}
|
|
339
710
|
|
|
340
711
|
function restart() {
|
|
712
|
+
cancelGoto();
|
|
713
|
+
everyTimers.stopAll();
|
|
341
714
|
state.reset();
|
|
715
|
+
uiJsRun = false;
|
|
716
|
+
sound.sync();
|
|
717
|
+
syncClasses();
|
|
342
718
|
// TODO: This feels like the wrong way of triggering location.reload()
|
|
343
719
|
// - should be a separate setting to the scroll setting.
|
|
344
720
|
if (settings.scroll === "element" || settings.scroll === "none") {
|
|
@@ -352,38 +728,156 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
352
728
|
|
|
353
729
|
function save() {
|
|
354
730
|
// TODO: Queue up all attribute changes and save them only when this is called
|
|
355
|
-
|
|
731
|
+
// A transition still playing isn't saved, so loading the game doesn't play it again (#489)
|
|
732
|
+
let output = outputElement;
|
|
733
|
+
if (output.querySelector(".squiffy-transition")) {
|
|
734
|
+
output = outputElement.cloneNode(true) as HTMLDivElement;
|
|
735
|
+
output.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
|
|
736
|
+
}
|
|
737
|
+
set("_output", output.innerHTML);
|
|
356
738
|
}
|
|
357
739
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
740
|
+
// The story's @ui JavaScript, which registers its helpers and animations. It runs once before
|
|
741
|
+
// any text is shown, however the story starts: from the beginning, from a section the author
|
|
742
|
+
// chose, or from a saved game. Restarting runs it again, as that resets the attributes.
|
|
743
|
+
let uiJsRun = false;
|
|
744
|
+
function runUiJs() {
|
|
745
|
+
if (uiJsRun) return;
|
|
746
|
+
uiJsRun = true;
|
|
747
|
+
if (story.uiJsIndex !== undefined) {
|
|
748
|
+
runJs(story.uiJsIndex, {
|
|
749
|
+
registerAnimation: animation.registerAnimation.bind(animation),
|
|
750
|
+
registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
|
|
751
|
+
SafeString: textProcessor.handlebars.SafeString,
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
}
|
|
368
755
|
|
|
756
|
+
function load() {
|
|
369
757
|
state.load();
|
|
758
|
+
sound.sync();
|
|
759
|
+
syncClasses();
|
|
370
760
|
const output = get("_output");
|
|
371
761
|
if (!output) {
|
|
372
762
|
runUiJs();
|
|
373
763
|
return false;
|
|
374
764
|
}
|
|
375
765
|
|
|
376
|
-
|
|
766
|
+
showSavedOutput(output);
|
|
767
|
+
runUiJs();
|
|
768
|
+
pluginManager.onLoad();
|
|
769
|
+
setupInputValidation(currentSectionElement);
|
|
770
|
+
return true;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// Puts a saved game's text back on screen, and carries on from the end of it
|
|
774
|
+
function showSavedOutput(output: string) {
|
|
775
|
+
// Saved output may contain asset URLs that are no longer valid (e.g. blob: URLs), so resolve them again
|
|
776
|
+
outputElement.innerHTML = resolveAssetsInHtml(output);
|
|
377
777
|
|
|
378
778
|
setCurrentSectionElement();
|
|
379
779
|
setCurrentPassageElement();
|
|
380
780
|
currentBlockOutputElement = outputElement.querySelector(".squiffy-output-block:last-child");
|
|
381
781
|
|
|
382
782
|
currentSection = story.sections[get("_section")];
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// The game as it is now. The attributes include the text on screen (_output), and the undo
|
|
786
|
+
// log is in that text, so a loaded game can go back too.
|
|
787
|
+
function getSave(): SavedGame {
|
|
788
|
+
return {
|
|
789
|
+
format: "squiffy-save",
|
|
790
|
+
version: 1,
|
|
791
|
+
storyId: story.projectId ?? null,
|
|
792
|
+
section: get("_section"),
|
|
793
|
+
passage: get("_passage"),
|
|
794
|
+
summary: getSummary(),
|
|
795
|
+
savedAt: new Date().toISOString(),
|
|
796
|
+
// Persistent attributes aren't part of the game (#539)
|
|
797
|
+
state: Object.fromEntries(Object.entries(structuredClone(state.store)).filter(([name]) => !state.isPersistent(name))),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// The start of the text in the current section, to tell saves apart by. If it starts with a
|
|
802
|
+
// heading, that's it, as it's likely to name where the player is.
|
|
803
|
+
function getSummary() {
|
|
804
|
+
const MAX_LENGTH = 100;
|
|
805
|
+
const blocks = currentSectionElement?.querySelectorAll(".squiffy-output-block") ?? [];
|
|
806
|
+
for (const block of blocks) {
|
|
807
|
+
const text = textOf(block);
|
|
808
|
+
if (!text) continue;
|
|
809
|
+
const first = [...block.querySelectorAll("h1, h2, h3, h4, h5, h6, p, li")].find(child => textOf(child));
|
|
810
|
+
if (first && /^H[1-6]$/.test(first.tagName) && textOf(block).startsWith(textOf(first))) {
|
|
811
|
+
return textOf(first).substring(0, MAX_LENGTH);
|
|
812
|
+
}
|
|
813
|
+
if (text.length <= MAX_LENGTH) return text;
|
|
814
|
+
const cut = text.substring(0, MAX_LENGTH);
|
|
815
|
+
const space = cut.lastIndexOf(" ");
|
|
816
|
+
return (space > MAX_LENGTH / 2 ? cut.substring(0, space) : cut) + "…";
|
|
817
|
+
}
|
|
818
|
+
return "";
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// An element's text, with a space between paragraphs, headings and lines
|
|
822
|
+
function textOf(element: Element) {
|
|
823
|
+
const clone = element.cloneNode(true) as Element;
|
|
824
|
+
clone.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, div, br, tr, blockquote").forEach(el => el.after(" "));
|
|
825
|
+
return (clone.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function isSavedGame(save: unknown): save is SavedGame {
|
|
829
|
+
if (!save || typeof save != "object") return false;
|
|
830
|
+
const s = save as Partial<SavedGame>;
|
|
831
|
+
return s.format === "squiffy-save" && s.version === 1 && !!s.state && typeof s.state == "object"
|
|
832
|
+
&& !Array.isArray(s.state) && typeof s.state._output == "string";
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
async function loadSave(save: SavedGame): Promise<LoadSaveResult> {
|
|
836
|
+
if (!isSavedGame(save)) return { success: false, error: "notASave" };
|
|
837
|
+
// A story without an id, or a save from one, can't be checked, so it's loaded
|
|
838
|
+
if (save.storyId && story.projectId && save.storyId !== story.projectId) {
|
|
839
|
+
return { success: false, error: "wrongStory" };
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// Wait for anything being shown to finish, so it doesn't carry on into the loaded game
|
|
843
|
+
while (runningTransitions) {
|
|
844
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
845
|
+
}
|
|
846
|
+
cancelGoto();
|
|
847
|
+
everyTimers.stopAll();
|
|
848
|
+
pendingErrors.length = 0;
|
|
849
|
+
state.reset();
|
|
850
|
+
for (const [attribute, value] of Object.entries(save.state)) {
|
|
851
|
+
state.setInternal(attribute, value, false);
|
|
852
|
+
}
|
|
853
|
+
sound.sync();
|
|
854
|
+
syncClasses();
|
|
855
|
+
undoLog = {};
|
|
856
|
+
scrollPosition = 0;
|
|
857
|
+
scrollToTop = false;
|
|
858
|
+
showSavedOutput(save.state._output as string);
|
|
859
|
+
// As load() does, for a game loaded before the story has begun
|
|
383
860
|
runUiJs();
|
|
861
|
+
|
|
862
|
+
if (!currentSection) {
|
|
863
|
+
// The section the game was saved in isn't in the story any more, so start again from
|
|
864
|
+
// the beginning, keeping the attributes
|
|
865
|
+
outputElement.innerHTML = "";
|
|
866
|
+
await go(story.start);
|
|
867
|
+
emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
|
|
868
|
+
return { success: true };
|
|
869
|
+
}
|
|
870
|
+
|
|
384
871
|
pluginManager.onLoad();
|
|
385
872
|
setupInputValidation(currentSectionElement);
|
|
386
|
-
|
|
873
|
+
emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
|
|
874
|
+
const passage = get("_passage");
|
|
875
|
+
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
876
|
+
|
|
877
|
+
// Saved while waiting for a {{goto}}, so carry on waiting
|
|
878
|
+
await resumeGoto();
|
|
879
|
+
everyTimers.sync();
|
|
880
|
+
return { success: true };
|
|
387
881
|
}
|
|
388
882
|
|
|
389
883
|
function newBlockOutputElement() {
|
|
@@ -435,7 +929,35 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
435
929
|
return outputElement.querySelector<HTMLElement>(".squiffy-clear-stack");
|
|
436
930
|
}
|
|
437
931
|
|
|
438
|
-
|
|
932
|
+
|
|
933
|
+
// For scroll: "element", scrolls the story's own scrolling box (its nearest ancestor that
|
|
934
|
+
// scrolls, or else its own window) so that the top or the bottom of el is at the top or the
|
|
935
|
+
// bottom of it. Unlike scrollIntoView, this never scrolls the page around that box, or the page
|
|
936
|
+
// the story is in a frame of, such as the docs' samples.
|
|
937
|
+
function scrollWithin(el: Element, block: "start" | "end") {
|
|
938
|
+
const rect = el.getBoundingClientRect();
|
|
939
|
+
const box = scrollingBox(el);
|
|
940
|
+
if (box) {
|
|
941
|
+
const bounds = box.getBoundingClientRect();
|
|
942
|
+
const by = block === "start" ? rect.top - bounds.top : rect.bottom - bounds.bottom;
|
|
943
|
+
box.scrollTo({ top: box.scrollTop + by, behavior: "smooth" });
|
|
944
|
+
}
|
|
945
|
+
else {
|
|
946
|
+
const by = block === "start" ? rect.top : rect.bottom - window.innerHeight;
|
|
947
|
+
window.scrollTo({ top: window.scrollY + by, behavior: "smooth" });
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
function scrollingBox(el: Element): HTMLElement | null {
|
|
952
|
+
for (let e = el.parentElement; e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
|
|
953
|
+
const overflow = getComputedStyle(e).overflowY;
|
|
954
|
+
if ((overflow === "auto" || overflow === "scroll") && e.scrollHeight > e.clientHeight) return e;
|
|
955
|
+
}
|
|
956
|
+
return null;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// keep: an element that stays on the screen, for {{clear}} part-way through a section
|
|
960
|
+
function clearScreen(keep?: Element) {
|
|
439
961
|
// Callers should call createSectionElement() after calling this function, so there's a place for new
|
|
440
962
|
// output to go. We don't call this automatically within this function, in case we're just about to create
|
|
441
963
|
// a new section anyway.
|
|
@@ -449,21 +971,137 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
449
971
|
|
|
450
972
|
const clearStackItem = document.createElement("div");
|
|
451
973
|
clearStack.appendChild(clearStackItem);
|
|
974
|
+
scrollToTop = true;
|
|
452
975
|
|
|
453
976
|
// Move everything in the outputElement (except the clearStack itself) into the new clearStackItem
|
|
454
977
|
for (const child of [...outputElement.children]) {
|
|
455
|
-
if (child !== clearStack) {
|
|
978
|
+
if (child !== clearStack && child !== keep) {
|
|
456
979
|
clearStackItem.appendChild(child);
|
|
457
980
|
}
|
|
458
981
|
}
|
|
982
|
+
// Without its transitions, so it's as it was if the player goes back to it
|
|
983
|
+
clearStackItem.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
|
|
459
984
|
|
|
460
985
|
// NOTE: If we offer an option to disable the "back" feature, all of the above can be replaced with:
|
|
461
986
|
// outputElement.innerHTML = '';
|
|
462
987
|
}
|
|
463
988
|
|
|
989
|
+
// {{clear}} (#524): clears the screen while a section or passage is being shown, as @clear
|
|
990
|
+
// would have before it, taking away what it has shown so far too
|
|
991
|
+
async function clearPartWay() {
|
|
992
|
+
if (currentPassageElement) {
|
|
993
|
+
await leaveTransition(shownFrom);
|
|
994
|
+
// The passage starts again on a screen of its own, as with @clear, so going back
|
|
995
|
+
// takes it away and brings back the screen as it was before it
|
|
996
|
+
const passageElement = currentPassageElement.cloneNode(false) as HTMLElement;
|
|
997
|
+
currentPassageElement.remove();
|
|
998
|
+
endTransition(passageElement);
|
|
999
|
+
clearScreen();
|
|
1000
|
+
createSectionElement();
|
|
1001
|
+
currentPassageElement = passageElement;
|
|
1002
|
+
currentSectionElement.appendChild(passageElement);
|
|
1003
|
+
startTransition(passageElement, shownFrom);
|
|
1004
|
+
}
|
|
1005
|
+
else {
|
|
1006
|
+
// The section element stays, playing its @transition, and what's in it so far goes,
|
|
1007
|
+
// such as the master section's text, along with what came before it
|
|
1008
|
+
const sectionElement = currentSectionElement;
|
|
1009
|
+
await leaveTransition(shownFrom, [...screenElements().filter(e => e !== sectionElement), ...sectionElement.children]);
|
|
1010
|
+
sectionElement.replaceChildren();
|
|
1011
|
+
clearScreen(sectionElement);
|
|
1012
|
+
}
|
|
1013
|
+
newBlockOutputElement();
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// @transition (#489): plays the first transition given, as a class that the stylesheet animates.
|
|
1017
|
+
// "none" (or Harlowe's "instant") plays none, so a section can turn off the master section's.
|
|
1018
|
+
function startTransition(element: HTMLElement, from: (Section | Passage | undefined)[]) {
|
|
1019
|
+
const source = from.find(s => s?.transition);
|
|
1020
|
+
const name = source?.transition;
|
|
1021
|
+
if (!name || name == "none" || name == "instant") return;
|
|
1022
|
+
element.classList.add("squiffy-transition", name);
|
|
1023
|
+
element.setAttribute("data-transition", name);
|
|
1024
|
+
if (source!.transitionTime !== undefined) {
|
|
1025
|
+
element.style.setProperty("--squiffy-transition-time", `${source!.transitionTime}ms`);
|
|
1026
|
+
}
|
|
1027
|
+
const end = (event: Event) => {
|
|
1028
|
+
// A @leave transition started before this one ended takes the element off the screen itself
|
|
1029
|
+
if (event.target !== element || element.classList.contains("squiffy-leave")) return;
|
|
1030
|
+
element.removeEventListener("animationend", end);
|
|
1031
|
+
element.removeEventListener("animationcancel", end);
|
|
1032
|
+
endTransition(element);
|
|
1033
|
+
};
|
|
1034
|
+
element.addEventListener("animationend", end);
|
|
1035
|
+
element.addEventListener("animationcancel", end);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// @leave: plays the first leave transition given on everything on the screen, the arrival
|
|
1039
|
+
// transitions backwards, and waits for it to finish, so that clearScreen() can take it away.
|
|
1040
|
+
// Links and Back wait too.
|
|
1041
|
+
async function leaveTransition(from: (Section | Passage | undefined)[], on: Element[] = screenElements()) {
|
|
1042
|
+
const source = from.find(s => s?.leave);
|
|
1043
|
+
const name = source?.leave;
|
|
1044
|
+
if (!name || name == "none" || name == "instant") return;
|
|
1045
|
+
const elements = on.filter((e): e is HTMLElement => e instanceof HTMLElement);
|
|
1046
|
+
if (!elements.length) return;
|
|
1047
|
+
for (const element of elements) {
|
|
1048
|
+
endTransition(element);
|
|
1049
|
+
element.classList.add("squiffy-transition", "squiffy-leave", name);
|
|
1050
|
+
element.setAttribute("data-transition", name);
|
|
1051
|
+
if (source!.leaveTime !== undefined) {
|
|
1052
|
+
element.style.setProperty("--squiffy-transition-time", `${source!.leaveTime}ms`);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
// Each element plays the same animation, so the first one finishing means they all have
|
|
1056
|
+
const first = elements[0];
|
|
1057
|
+
const style = getComputedStyle(first);
|
|
1058
|
+
if (!style.animationName || style.animationName == "none") return;
|
|
1059
|
+
// In case the animation never ends, such as in a page that isn't shown
|
|
1060
|
+
const seconds = (value: string) => Math.max(0, ...value.split(",").map(v => parseFloat(v) * (v.trim().endsWith("ms") ? 0.001 : 1) || 0));
|
|
1061
|
+
const timeout = (seconds(style.animationDuration) + seconds(style.animationDelay)) * 1000 + 1000;
|
|
1062
|
+
const wasRunning = runningTransitions;
|
|
1063
|
+
runningTransitions = true;
|
|
1064
|
+
try {
|
|
1065
|
+
await new Promise<void>(resolve => {
|
|
1066
|
+
const timer = setTimeout(done, timeout);
|
|
1067
|
+
function done(event?: Event) {
|
|
1068
|
+
if (event && event.target !== first) return;
|
|
1069
|
+
clearTimeout(timer);
|
|
1070
|
+
first.removeEventListener("animationend", done);
|
|
1071
|
+
first.removeEventListener("animationcancel", done);
|
|
1072
|
+
resolve();
|
|
1073
|
+
}
|
|
1074
|
+
first.addEventListener("animationend", done);
|
|
1075
|
+
first.addEventListener("animationcancel", done);
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
finally {
|
|
1079
|
+
runningTransitions = wasRunning;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// What's on the screen: the output, but not the clear stack hidden in it
|
|
1084
|
+
function screenElements() {
|
|
1085
|
+
const clearStack = getClearStack();
|
|
1086
|
+
return [...outputElement.children].filter(c => c !== clearStack);
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// Takes off a transition's class, so it doesn't play again when the element is shown again,
|
|
1090
|
+
// such as after going back past a @clear
|
|
1091
|
+
function endTransition(element: HTMLElement) {
|
|
1092
|
+
const name = element.getAttribute("data-transition");
|
|
1093
|
+
if (name) element.classList.remove(name);
|
|
1094
|
+
element.classList.remove("squiffy-transition", "squiffy-leave");
|
|
1095
|
+
if (!element.classList.length) element.removeAttribute("class");
|
|
1096
|
+
element.removeAttribute("data-transition");
|
|
1097
|
+
element.style.removeProperty("--squiffy-transition-time");
|
|
1098
|
+
if (!element.getAttribute("style")) element.removeAttribute("style");
|
|
1099
|
+
}
|
|
1100
|
+
|
|
464
1101
|
function unClearScreen() {
|
|
465
1102
|
const clearStack = getClearStack();
|
|
466
1103
|
if (!clearStack) return;
|
|
1104
|
+
clearStack.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
|
|
467
1105
|
for (const child of [...outputElement.children]) {
|
|
468
1106
|
if (child !== clearStack) {
|
|
469
1107
|
child.remove();
|
|
@@ -479,9 +1117,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
479
1117
|
|
|
480
1118
|
const ui = {
|
|
481
1119
|
write: (text: string, source: string) => {
|
|
1120
|
+
ui.writeHtml(ui.renderHtml(text, false), source);
|
|
1121
|
+
},
|
|
1122
|
+
writeHtml: (rendered: string, source: string) => {
|
|
482
1123
|
scrollPosition = outputElement.scrollHeight;
|
|
483
1124
|
|
|
484
|
-
const html =
|
|
1125
|
+
const html = pendingErrors.splice(0).join("") + rendered.trim();
|
|
485
1126
|
|
|
486
1127
|
// Previously, we skipped the rest of this if "html" came back as an empty string.
|
|
487
1128
|
// But, we _do_ always want the block to be created, in the editor at least - as the
|
|
@@ -516,8 +1157,24 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
516
1157
|
if (settings.scroll === "none") {
|
|
517
1158
|
// do nothing
|
|
518
1159
|
}
|
|
1160
|
+
else if (scrollToTop) {
|
|
1161
|
+
// The screen was cleared, so the new text starts at the top of the output, which may be
|
|
1162
|
+
// above where the reader has scrolled to.
|
|
1163
|
+
scrollToTop = false;
|
|
1164
|
+
if (settings.scroll === "element") {
|
|
1165
|
+
scrollWithin(currentSectionElement, "start");
|
|
1166
|
+
}
|
|
1167
|
+
else {
|
|
1168
|
+
const currentScrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
|
|
1169
|
+
const outputTop = outputElement.getBoundingClientRect().top + currentScrollTop;
|
|
1170
|
+
if (outputTop < currentScrollTop) {
|
|
1171
|
+
window.scrollTo({ top: outputTop, behavior: "smooth" });
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
519
1175
|
else if (settings.scroll === "element") {
|
|
520
|
-
outputElement.lastElementChild
|
|
1176
|
+
const last = outputElement.lastElementChild;
|
|
1177
|
+
if (last) scrollWithin(last, "end");
|
|
521
1178
|
}
|
|
522
1179
|
else {
|
|
523
1180
|
let scrollTo = scrollPosition;
|
|
@@ -532,12 +1189,19 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
532
1189
|
processText: (text: string, inline: boolean) => {
|
|
533
1190
|
return textProcessor.process(text, inline);
|
|
534
1191
|
},
|
|
1192
|
+
// processText, plus asset URL resolution - for text that's going to be displayed as HTML
|
|
1193
|
+
renderHtml: (text: string, inline: boolean) => {
|
|
1194
|
+
return resolveAssetsInHtml(ui.processText(text, inline));
|
|
1195
|
+
},
|
|
535
1196
|
};
|
|
536
1197
|
|
|
537
1198
|
function update(newStory: Story) {
|
|
538
1199
|
if (newStory.start != story.start) {
|
|
539
1200
|
story = newStory;
|
|
540
1201
|
state.reset();
|
|
1202
|
+
sound.sync();
|
|
1203
|
+
syncClasses();
|
|
1204
|
+
sound.preload(story.audio ?? []);
|
|
541
1205
|
outputElement.innerHTML = "";
|
|
542
1206
|
go(story.start);
|
|
543
1207
|
return;
|
|
@@ -547,16 +1211,24 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
547
1211
|
// sees sections that were added in this update.
|
|
548
1212
|
const oldStory = story;
|
|
549
1213
|
story = newStory;
|
|
1214
|
+
// Its settings may have changed
|
|
1215
|
+
syncClasses();
|
|
1216
|
+
sound.preload(story.audio ?? []);
|
|
550
1217
|
|
|
551
1218
|
// When re-rendering a section or passage, {{embed}} should look up passages in the
|
|
552
1219
|
// (new version of the) section being rendered.
|
|
553
1220
|
const processTextInSection = (text: string, section: Section) => {
|
|
554
1221
|
const previousSection = currentSection;
|
|
555
1222
|
currentSection = section;
|
|
1223
|
+
// Text shown again after an edit doesn't play its {{sound}}s again
|
|
1224
|
+
quiet = true;
|
|
556
1225
|
try {
|
|
557
|
-
|
|
1226
|
+
const html = ui.renderHtml(text, false);
|
|
1227
|
+
// Only what comes after a {{clear}} was shown (#524)
|
|
1228
|
+
return afterClear(html) ?? html;
|
|
558
1229
|
} finally {
|
|
559
1230
|
currentSection = previousSection;
|
|
1231
|
+
quiet = false;
|
|
560
1232
|
}
|
|
561
1233
|
};
|
|
562
1234
|
|
|
@@ -564,6 +1236,35 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
564
1236
|
|
|
565
1237
|
setCurrentSectionElement();
|
|
566
1238
|
setCurrentPassageElement();
|
|
1239
|
+
// The {{#every}}s shown again start again
|
|
1240
|
+
everyTimers.sync();
|
|
1241
|
+
emitter.emit("storyUpdated", {});
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// A master section passage for a panel or dialog (#14, #443): rendered with the attributes as
|
|
1245
|
+
// they are, changing nothing, with its links disabled
|
|
1246
|
+
function renderPassage(name: string): string {
|
|
1247
|
+
const passage = story.sections[""]?.passages?.[name];
|
|
1248
|
+
if (!passage) {
|
|
1249
|
+
return errorHtml("Error in panel:", `there is no passage called "${name}" in the master section [[]]`);
|
|
1250
|
+
}
|
|
1251
|
+
// Anything the story's own text has asked for, which this mustn't change
|
|
1252
|
+
const goto = textProcessor.goto;
|
|
1253
|
+
const deactivate = [...textProcessor.deactivate];
|
|
1254
|
+
state.readOnly = true;
|
|
1255
|
+
let html: string;
|
|
1256
|
+
try {
|
|
1257
|
+
html = ui.renderHtml(passage.text || "", false);
|
|
1258
|
+
}
|
|
1259
|
+
finally {
|
|
1260
|
+
state.readOnly = false;
|
|
1261
|
+
textProcessor.goto = goto;
|
|
1262
|
+
textProcessor.deactivate = new Set(deactivate);
|
|
1263
|
+
}
|
|
1264
|
+
const template = document.createElement("template");
|
|
1265
|
+
template.innerHTML = html;
|
|
1266
|
+
template.content.querySelectorAll("a.squiffy-link").forEach(disableLink);
|
|
1267
|
+
return template.innerHTML;
|
|
567
1268
|
}
|
|
568
1269
|
|
|
569
1270
|
function setCurrentSectionElement() {
|
|
@@ -604,7 +1305,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
604
1305
|
}
|
|
605
1306
|
|
|
606
1307
|
function canGoBack() {
|
|
607
|
-
|
|
1308
|
+
// Sections and passages that went somewhere else with {{goto}} are skipped by goBack(), so
|
|
1309
|
+
// they don't count, unless it's the current one, still waiting for its after= delay
|
|
1310
|
+
const current = currentPassageElement ?? currentSectionElement;
|
|
1311
|
+
const redirected = [...outputElement.querySelectorAll("[data-goto]")].filter(el => el !== current).length;
|
|
1312
|
+
return getHistoryCount() - redirected > 1;
|
|
608
1313
|
}
|
|
609
1314
|
|
|
610
1315
|
function goBack() {
|
|
@@ -614,11 +1319,36 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
614
1319
|
return;
|
|
615
1320
|
}
|
|
616
1321
|
|
|
1322
|
+
cancelGoto();
|
|
1323
|
+
// Undo back to the section or passage the player clicked through to, not one that went
|
|
1324
|
+
// somewhere else with {{goto}}
|
|
1325
|
+
do {
|
|
1326
|
+
undoLast();
|
|
1327
|
+
} while ((currentPassageElement ?? currentSectionElement).hasAttribute("data-goto") && getHistoryCount() > 1);
|
|
1328
|
+
// The music goes back to what it was, as _music was undone
|
|
1329
|
+
sound.sync();
|
|
1330
|
+
syncClasses();
|
|
1331
|
+
// The attributes were saved as they were undone, so save the output to match. Otherwise a saved
|
|
1332
|
+
// game would come back with the text that was undone.
|
|
1333
|
+
save();
|
|
1334
|
+
|
|
1335
|
+
if (!canGoBack()) {
|
|
1336
|
+
emitter.emit("canGoBackChanged", { canGoBack: false });
|
|
1337
|
+
}
|
|
1338
|
+
const passage = currentPassageElement?.getAttribute("data-passage");
|
|
1339
|
+
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
1340
|
+
// The {{#every}}s that were undone stop, and any in the section gone back to start again
|
|
1341
|
+
everyTimers.sync();
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
function undoLast() {
|
|
617
1345
|
const clearStack = getClearStack();
|
|
618
1346
|
|
|
619
1347
|
if (currentPassageElement) {
|
|
620
1348
|
const currentPassage = currentPassageElement.getAttribute("data-passage");
|
|
1349
|
+
const clicked = currentPassageElement.getAttribute("data-clicked-link");
|
|
621
1350
|
doUndo(currentPassageElement.getAttribute("data-undo"));
|
|
1351
|
+
undoDeactivate(currentPassageElement);
|
|
622
1352
|
currentPassageElement.remove();
|
|
623
1353
|
|
|
624
1354
|
// If there's nothing left in the outputElement except for an empty section element that
|
|
@@ -643,9 +1373,18 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
643
1373
|
setCurrentSectionElement();
|
|
644
1374
|
}
|
|
645
1375
|
|
|
646
|
-
|
|
647
|
-
|
|
1376
|
+
if (clicked) {
|
|
1377
|
+
for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-clicked="${clicked}"], input[data-clicked="${clicked}"]`)) {
|
|
648
1378
|
enableLink(link);
|
|
1379
|
+
link.removeAttribute("data-clicked");
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
else if (currentPassage && !isRepeatPassage(currentPassage)) {
|
|
1383
|
+
// Saved before links were numbered when clicked, so enable every link to the passage
|
|
1384
|
+
for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
|
|
1385
|
+
if (link.getAttribute("data-passage") == currentPassage) {
|
|
1386
|
+
enableLink(link);
|
|
1387
|
+
}
|
|
649
1388
|
}
|
|
650
1389
|
}
|
|
651
1390
|
|
|
@@ -673,10 +1412,6 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
673
1412
|
setCurrentPassageElement();
|
|
674
1413
|
enableInputs(currentSectionElement);
|
|
675
1414
|
}
|
|
676
|
-
|
|
677
|
-
if (!canGoBack()) {
|
|
678
|
-
emitter.emit("canGoBackChanged", { canGoBack: false });
|
|
679
|
-
}
|
|
680
1415
|
}
|
|
681
1416
|
|
|
682
1417
|
// We create a separate div inside the passed-in element. This allows us to clear the text output, but
|
|
@@ -685,6 +1420,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
685
1420
|
const outputElement = document.createElement("div");
|
|
686
1421
|
outputElementContainer.appendChild(outputElement);
|
|
687
1422
|
story = options.story;
|
|
1423
|
+
const resolveAssetsInHtml = createAssetHtmlResolver(options.resolveAssetUrl);
|
|
688
1424
|
|
|
689
1425
|
const settings = {
|
|
690
1426
|
scroll: options.scroll || "body",
|
|
@@ -720,6 +1456,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
720
1456
|
outputElement.addEventListener("click", handleClick);
|
|
721
1457
|
outputElement.addEventListener("keypress", async function (event) {
|
|
722
1458
|
if (event.key !== "Enter") return;
|
|
1459
|
+
const target = event.target;
|
|
1460
|
+
// A text box with data-section or data-passage goes there when Enter is pressed (#454),
|
|
1461
|
+
// like a link, once every text box in the section is filled in properly
|
|
1462
|
+
if (target instanceof window.HTMLInputElement && (target.hasAttribute("data-section") || target.hasAttribute("data-passage"))) {
|
|
1463
|
+
if (event.isComposing) return;
|
|
1464
|
+
event.preventDefault();
|
|
1465
|
+
if (!areInputsValid(currentSectionElement)) {
|
|
1466
|
+
// Shows which ones need filling in
|
|
1467
|
+
for (const input of currentSectionElement.querySelectorAll<HTMLInputElement>("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")) {
|
|
1468
|
+
input.reportValidity();
|
|
1469
|
+
}
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1472
|
+
await handleLink(target);
|
|
1473
|
+
return;
|
|
1474
|
+
}
|
|
723
1475
|
await handleClick(event);
|
|
724
1476
|
});
|
|
725
1477
|
|
|
@@ -736,6 +1488,66 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
736
1488
|
undoLog = {};
|
|
737
1489
|
};
|
|
738
1490
|
|
|
1491
|
+
// Adds what's changed since to the undo log of the section or passage already shown, keeping
|
|
1492
|
+
// the value from before it was shown, e.g. for an {{#every}}'s text (#451)
|
|
1493
|
+
const mergeUndoLog = function() {
|
|
1494
|
+
const element = currentPassageElement ?? currentSectionElement;
|
|
1495
|
+
const log = JSON.parse(element.getAttribute("data-undo") || "{}");
|
|
1496
|
+
for (const [attribute, value] of Object.entries(undoLog)) {
|
|
1497
|
+
if (!(attribute in log)) log[attribute] = value;
|
|
1498
|
+
}
|
|
1499
|
+
element.setAttribute("data-undo", JSON.stringify(log));
|
|
1500
|
+
undoLog = {};
|
|
1501
|
+
};
|
|
1502
|
+
|
|
1503
|
+
// Shows an {{#every}}'s text again (#451). Returns false if it has to wait, while a section or
|
|
1504
|
+
// passage is being shown.
|
|
1505
|
+
function tickEvery(el: HTMLElement): boolean {
|
|
1506
|
+
if (runningTransitions || navigating > 0) return false;
|
|
1507
|
+
const inline = el.tagName == "SPAN";
|
|
1508
|
+
const body = decodeURIComponent(el.getAttribute("data-every") || "");
|
|
1509
|
+
let html: string;
|
|
1510
|
+
textProcessor.stopEvery = false;
|
|
1511
|
+
try {
|
|
1512
|
+
html = ui.renderHtml(body, inline);
|
|
1513
|
+
// Text added after text keeps its spaces, e.g. {{#every 1000 append=true}}Drip. {{/every}}
|
|
1514
|
+
if (inline) html = (/^\s/.test(body) ? " " : "") + html + (/\s$/.test(body) ? " " : "");
|
|
1515
|
+
}
|
|
1516
|
+
catch (e) {
|
|
1517
|
+
html = errorHtml("Error in {{#every}}:", e instanceof Error ? e.message : String(e));
|
|
1518
|
+
textProcessor.stopEvery = true;
|
|
1519
|
+
}
|
|
1520
|
+
const text = document.createElement(inline ? "span" : "div");
|
|
1521
|
+
text.className = "squiffy-every-text";
|
|
1522
|
+
text.innerHTML = html;
|
|
1523
|
+
if (el.hasAttribute("data-every-append")) el.append(text);
|
|
1524
|
+
else el.replaceChildren(text);
|
|
1525
|
+
pluginManager.onWrite(text);
|
|
1526
|
+
// It's empty until its first tick, so when the text was written the page may not have been
|
|
1527
|
+
// tall enough to scroll down to where it starts. This finishes that scroll, as the text is
|
|
1528
|
+
// taller now. It never scrolls past where the new text starts, or up.
|
|
1529
|
+
ui.scrollToEnd();
|
|
1530
|
+
|
|
1531
|
+
const count = (Number(el.getAttribute("data-every-count")) || 0) + 1;
|
|
1532
|
+
el.setAttribute("data-every-count", String(count));
|
|
1533
|
+
const times = Number(el.getAttribute("data-every-times")) || 0;
|
|
1534
|
+
if (textProcessor.stopEvery || (times && count >= times)) el.setAttribute("data-every-stopped", "");
|
|
1535
|
+
textProcessor.stopEvery = false;
|
|
1536
|
+
|
|
1537
|
+
const element = currentPassageElement ?? currentSectionElement;
|
|
1538
|
+
takeDeactivate(element);
|
|
1539
|
+
const pending = takeGoto(element);
|
|
1540
|
+
mergeUndoLog();
|
|
1541
|
+
save();
|
|
1542
|
+
if (pending) {
|
|
1543
|
+
// It replaces any {{goto ... after=}} still waiting
|
|
1544
|
+
clearTimeout(gotoTimer);
|
|
1545
|
+
gotoHops = 0;
|
|
1546
|
+
void followGoto(pending);
|
|
1547
|
+
}
|
|
1548
|
+
return true;
|
|
1549
|
+
}
|
|
1550
|
+
|
|
739
1551
|
const doUndo = function(undosJson: string | null) {
|
|
740
1552
|
if (!undosJson) return;
|
|
741
1553
|
const undos = JSON.parse(undosJson) as Record<string, any>;
|
|
@@ -748,10 +1560,196 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
748
1560
|
const state = new State(settings.persist, storageKey, settings.onSet, emitter, onSet);
|
|
749
1561
|
const get = state.get.bind(state);
|
|
750
1562
|
const set = state.set.bind(state);
|
|
1563
|
+
// Persistent attributes (#539), kept for the story apart from the rest, like the player's settings
|
|
1564
|
+
state.persistentNames = () => story.persistent ?? [];
|
|
1565
|
+
state.initPersistent(settings.persist ? "squiffy-persistent:" + storageKey : undefined, options.persistent);
|
|
1566
|
+
|
|
1567
|
+
// The player's settings (#452), which the story reads as settings.name
|
|
1568
|
+
const playerSettings = new PlayerSettings(() => story.settings ?? [], settings.persist ? "squiffy-settings:" + storageKey : undefined);
|
|
1569
|
+
state.playerSettings = () => playerSettings.any() ? playerSettings.all() : null;
|
|
1570
|
+
// After a setting changes: its classes, and text that shows it, such as {{live "settings"}} and panels
|
|
1571
|
+
const settingChanged = (name: string, value: unknown) => {
|
|
1572
|
+
syncClasses();
|
|
1573
|
+
emitter.emit("settingChanged", { name, value });
|
|
1574
|
+
emitter.emit("set", { attribute: "settings", value: playerSettings.all() });
|
|
1575
|
+
};
|
|
751
1576
|
|
|
752
1577
|
const textProcessor = new TextProcessor(() => story, state, () => currentSection);
|
|
1578
|
+
const strings = options.strings ?? {};
|
|
1579
|
+
if (typeof strings.restart == "string") textProcessor.strings.restart = strings.restart;
|
|
1580
|
+
if (typeof strings.saves == "string") textProcessor.strings.saves = strings.saves;
|
|
1581
|
+
if (typeof strings.settings == "string") textProcessor.strings.settings = strings.settings;
|
|
1582
|
+
|
|
1583
|
+
// Music and sound effects (#444)
|
|
1584
|
+
let playedSound = false;
|
|
1585
|
+
// While text is shown again rather than for the first time, {{sound}} doesn't play
|
|
1586
|
+
let quiet = false;
|
|
1587
|
+
// How long the next change to _music fades for: fade= on {{music}} or {{stopmusic}}
|
|
1588
|
+
let musicFade = DEFAULT_FADE;
|
|
1589
|
+
const sound = new Sound({
|
|
1590
|
+
resolveUrl: path => isAbsolute(path) || !options.resolveAssetUrl
|
|
1591
|
+
? path
|
|
1592
|
+
: options.resolveAssetUrl(path.replace(/^(\.\/)+/, "")),
|
|
1593
|
+
getMusic: () => get("_music"),
|
|
1594
|
+
mutedKey: settings.persist ? "squiffy-muted:" + storageKey : undefined,
|
|
1595
|
+
onPlay: () => {
|
|
1596
|
+
playedSound = true;
|
|
1597
|
+
emitter.emit("sound", {});
|
|
1598
|
+
},
|
|
1599
|
+
});
|
|
1600
|
+
sound.preload(story.audio ?? []);
|
|
1601
|
+
emitter.on("set", ({ attribute }) => {
|
|
1602
|
+
if (attribute != "_music") return;
|
|
1603
|
+
const fade = musicFade;
|
|
1604
|
+
musicFade = DEFAULT_FADE;
|
|
1605
|
+
sound.sync(fade);
|
|
1606
|
+
});
|
|
1607
|
+
const fadeOption = (options: { hash?: Record<string, unknown> } | undefined) => {
|
|
1608
|
+
const fade = Number(options?.hash?.fade);
|
|
1609
|
+
return options?.hash && "fade" in options.hash && Number.isFinite(fade) && fade >= 0 ? fade : DEFAULT_FADE;
|
|
1610
|
+
};
|
|
1611
|
+
// {{music}} and {{sound}} with nothing after them are still an attribute called music or
|
|
1612
|
+
// sound, as they were before these helpers
|
|
1613
|
+
const isHelperOptions = (value: unknown) => typeof value == "object" && value !== null && "hash" in value;
|
|
1614
|
+
textProcessor.handlebars.registerHelper("music", (file: unknown, options?: { hash?: Record<string, unknown> }) => {
|
|
1615
|
+
if (isHelperOptions(file)) return get("music");
|
|
1616
|
+
if (state.readOnly || typeof file != "string") return "";
|
|
1617
|
+
musicFade = fadeOption(options);
|
|
1618
|
+
set("_music", file || null);
|
|
1619
|
+
musicFade = DEFAULT_FADE;
|
|
1620
|
+
return "";
|
|
1621
|
+
});
|
|
1622
|
+
textProcessor.handlebars.registerHelper("stopmusic", (options?: { hash?: Record<string, unknown> }) => {
|
|
1623
|
+
if (state.readOnly) return "";
|
|
1624
|
+
musicFade = fadeOption(options);
|
|
1625
|
+
set("_music", null);
|
|
1626
|
+
musicFade = DEFAULT_FADE;
|
|
1627
|
+
return "";
|
|
1628
|
+
});
|
|
1629
|
+
textProcessor.handlebars.registerHelper("sound", (file: unknown, options?: { hash?: Record<string, unknown> }) => {
|
|
1630
|
+
if (isHelperOptions(file)) return get("sound");
|
|
1631
|
+
if (state.readOnly || quiet || typeof file != "string" || !file) return "";
|
|
1632
|
+
const volume = Number(options?.hash?.volume ?? 1);
|
|
1633
|
+
sound.play(file, volume);
|
|
1634
|
+
return "";
|
|
1635
|
+
});
|
|
1636
|
+
textProcessor.handlebars.registerHelper("stopsounds", () => {
|
|
1637
|
+
if (!state.readOnly && !quiet) sound.stopSounds();
|
|
1638
|
+
return "";
|
|
1639
|
+
});
|
|
1640
|
+
|
|
1641
|
+
// Classes on the story's element (#449): the current section's, from @class, which change with
|
|
1642
|
+
// the section, and ones from {{addclass}}, which stay until they're removed. They're attributes,
|
|
1643
|
+
// so they come back with Back and saved games.
|
|
1644
|
+
const SECTION_CLASSES = "_sectionclasses";
|
|
1645
|
+
const CLASSES = "_classes";
|
|
1646
|
+
// The classes this put on the element, so it leaves any others alone
|
|
1647
|
+
let appliedClasses: string[] = [];
|
|
1648
|
+
const classList = (attribute: string): string[] => {
|
|
1649
|
+
const value = get(attribute);
|
|
1650
|
+
return Array.isArray(value) ? value.filter((c): c is string => typeof c == "string" && c.length > 0) : [];
|
|
1651
|
+
};
|
|
1652
|
+
const sectionClasses = () => classList(SECTION_CLASSES);
|
|
1653
|
+
// Class names from helper arguments, which can each hold several separated by spaces
|
|
1654
|
+
const classNames = (values: unknown[]) => values
|
|
1655
|
+
.filter(v => !isHelperOptions(v))
|
|
1656
|
+
.flatMap(v => String(v ?? "").split(/\s+/))
|
|
1657
|
+
.filter(c => c.length > 0);
|
|
1658
|
+
function setSectionClasses(classes: string[]) {
|
|
1659
|
+
const unique = [...new Set(classes)];
|
|
1660
|
+
const current = sectionClasses();
|
|
1661
|
+
if (unique.length == current.length && unique.every((c, i) => c == current[i])) return;
|
|
1662
|
+
set(SECTION_CLASSES, unique);
|
|
1663
|
+
}
|
|
1664
|
+
function applyClasses(classes: string[]) {
|
|
1665
|
+
for (const c of appliedClasses) {
|
|
1666
|
+
if (!classes.includes(c)) outputElementContainer.classList.remove(c);
|
|
1667
|
+
}
|
|
1668
|
+
for (const c of classes) outputElementContainer.classList.add(c);
|
|
1669
|
+
appliedClasses = classes;
|
|
1670
|
+
}
|
|
1671
|
+
// With the classes from the player's settings, such as setting-textSize-Large
|
|
1672
|
+
function syncClasses() {
|
|
1673
|
+
applyClasses([...new Set([...sectionClasses(), ...classList(CLASSES), ...playerSettings.classes()])]);
|
|
1674
|
+
}
|
|
1675
|
+
emitter.on("set", ({ attribute }) => {
|
|
1676
|
+
if (attribute == SECTION_CLASSES || attribute == CLASSES) syncClasses();
|
|
1677
|
+
});
|
|
1678
|
+
textProcessor.handlebars.registerHelper("addclass", (...args: unknown[]) => {
|
|
1679
|
+
if (state.readOnly) return "";
|
|
1680
|
+
const classes = classList(CLASSES);
|
|
1681
|
+
const added = classNames(args).filter(c => !classes.includes(c));
|
|
1682
|
+
if (added.length) set(CLASSES, [...classes, ...added]);
|
|
1683
|
+
return "";
|
|
1684
|
+
});
|
|
1685
|
+
textProcessor.handlebars.registerHelper("removeclass", (...args: unknown[]) => {
|
|
1686
|
+
if (state.readOnly) return "";
|
|
1687
|
+
const removed = classNames(args);
|
|
1688
|
+
const classes = classList(CLASSES);
|
|
1689
|
+
if (classes.some(c => removed.includes(c))) set(CLASSES, classes.filter(c => !removed.includes(c)));
|
|
1690
|
+
return "";
|
|
1691
|
+
});
|
|
1692
|
+
textProcessor.handlebars.registerHelper("toggleclass", (...args: unknown[]) => {
|
|
1693
|
+
if (state.readOnly) return "";
|
|
1694
|
+
let classes = classList(CLASSES);
|
|
1695
|
+
for (const c of new Set(classNames(args))) {
|
|
1696
|
+
classes = classes.includes(c) ? classes.filter(x => x != c) : [...classes, c];
|
|
1697
|
+
}
|
|
1698
|
+
set(CLASSES, classes);
|
|
1699
|
+
return "";
|
|
1700
|
+
});
|
|
1701
|
+
// Whether the story's element has all these classes, from @class or {{addclass}}
|
|
1702
|
+
textProcessor.handlebars.registerHelper("hasclass", (...args: unknown[]) => {
|
|
1703
|
+
const names = classNames(args);
|
|
1704
|
+
const classes = [...sectionClasses(), ...classList(CLASSES)];
|
|
1705
|
+
return names.length > 0 && names.every(c => classes.includes(c));
|
|
1706
|
+
});
|
|
1707
|
+
|
|
753
1708
|
const linkHandler = new LinkHandler();
|
|
754
1709
|
|
|
1710
|
+
// {{restart}} and {{saves}} links (#452). The page can handle them itself, with its own
|
|
1711
|
+
// dialogs, by listening for restartRequested and savesRequested. Otherwise the runtime asks
|
|
1712
|
+
// before restarting, and opens a Saved games dialog of its own.
|
|
1713
|
+
let savesDialog: SavesDialog | null = null;
|
|
1714
|
+
linkHandler.registerLinkHandler("restart", link => {
|
|
1715
|
+
const confirm = link.getAttribute("data-confirm") !== "false";
|
|
1716
|
+
// After the click has been handled, which saves the game as it is
|
|
1717
|
+
queueMicrotask(async () => {
|
|
1718
|
+
if (emitter.has("restartRequested")) {
|
|
1719
|
+
emitter.emit("restartRequested", { confirm });
|
|
1720
|
+
return;
|
|
1721
|
+
}
|
|
1722
|
+
if (confirm && !await confirmDialog({
|
|
1723
|
+
message: strings.restartConfirm ?? "Are you sure you want to restart?",
|
|
1724
|
+
confirm: strings.restart ?? "Restart",
|
|
1725
|
+
cancel: strings.cancel,
|
|
1726
|
+
})) return;
|
|
1727
|
+
restart();
|
|
1728
|
+
});
|
|
1729
|
+
return {};
|
|
1730
|
+
});
|
|
1731
|
+
let settingsDialog: SettingsDialog | null = null;
|
|
1732
|
+
linkHandler.registerLinkHandler("settings", () => {
|
|
1733
|
+
if (emitter.has("settingsRequested")) {
|
|
1734
|
+
emitter.emit("settingsRequested", {});
|
|
1735
|
+
}
|
|
1736
|
+
else {
|
|
1737
|
+
settingsDialog ??= createSettingsDialog(api, { strings });
|
|
1738
|
+
settingsDialog.open();
|
|
1739
|
+
}
|
|
1740
|
+
return {};
|
|
1741
|
+
});
|
|
1742
|
+
linkHandler.registerLinkHandler("saves", () => {
|
|
1743
|
+
if (emitter.has("savesRequested")) {
|
|
1744
|
+
emitter.emit("savesRequested", {});
|
|
1745
|
+
}
|
|
1746
|
+
else {
|
|
1747
|
+
savesDialog ??= createSavesDialog(api, { strings });
|
|
1748
|
+
savesDialog.open();
|
|
1749
|
+
}
|
|
1750
|
+
return {};
|
|
1751
|
+
});
|
|
1752
|
+
|
|
755
1753
|
const getSectionText = (sectionName: string) => {
|
|
756
1754
|
if (sectionName in story.sections) {
|
|
757
1755
|
return story.sections[sectionName].text || null;
|
|
@@ -762,7 +1760,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
762
1760
|
const getPassageText = (name: string) => {
|
|
763
1761
|
if (currentSection.passages && name in currentSection.passages) {
|
|
764
1762
|
return currentSection.passages[name].text || null;
|
|
765
|
-
} else if (
|
|
1763
|
+
} else if (story.sections[""]?.passages && name in story.sections[""].passages) {
|
|
766
1764
|
return story.sections[""].passages![name].text || null;
|
|
767
1765
|
}
|
|
768
1766
|
return null;
|
|
@@ -775,14 +1773,14 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
775
1773
|
const animation = new Animation();
|
|
776
1774
|
|
|
777
1775
|
const pluginManager = new PluginManager(outputElement, textProcessor, state, linkHandler,
|
|
778
|
-
getSectionText, getPassageText, ui.
|
|
1776
|
+
getSectionText, getPassageText, ui.renderHtml, addTransition, animation, emitter, resolveAssetsInHtml);
|
|
779
1777
|
pluginManager.add(Plugins.ReplaceLabel());
|
|
780
1778
|
pluginManager.add(Plugins.RotateSequencePlugin());
|
|
781
1779
|
pluginManager.add(Plugins.RandomPlugin());
|
|
782
1780
|
pluginManager.add(Plugins.LivePlugin());
|
|
783
1781
|
pluginManager.add(Plugins.AnimatePlugin());
|
|
784
1782
|
|
|
785
|
-
|
|
1783
|
+
const api: SquiffyApi = {
|
|
786
1784
|
begin: begin,
|
|
787
1785
|
restart: restart,
|
|
788
1786
|
get: get,
|
|
@@ -790,8 +1788,76 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
790
1788
|
clickLink: handleLink,
|
|
791
1789
|
update: update,
|
|
792
1790
|
goBack: goBack,
|
|
1791
|
+
canGoBack: canGoBack,
|
|
1792
|
+
getSave: getSave,
|
|
1793
|
+
loadSave: loadSave,
|
|
1794
|
+
renderPassage: renderPassage,
|
|
1795
|
+
isMuted: () => sound.isMuted(),
|
|
1796
|
+
setMuted: (muted: boolean) => sound.setMuted(muted),
|
|
1797
|
+
usesSound: () => playedSound || !!story.audio?.length,
|
|
1798
|
+
getSettings: () => structuredClone(playerSettings.definitions()),
|
|
1799
|
+
getSetting: (name: string) => playerSettings.get(name),
|
|
1800
|
+
setSetting: (name, value) => {
|
|
1801
|
+
if (playerSettings.set(name, value)) settingChanged(name, playerSettings.get(name));
|
|
1802
|
+
},
|
|
1803
|
+
resetSettings: () => {
|
|
1804
|
+
const before = playerSettings.all();
|
|
1805
|
+
playerSettings.reset();
|
|
1806
|
+
for (const [name, value] of Object.entries(playerSettings.all())) {
|
|
1807
|
+
if (value !== before[name]) settingChanged(name, value);
|
|
1808
|
+
}
|
|
1809
|
+
},
|
|
1810
|
+
getPersistent: () => state.getPersistent(),
|
|
1811
|
+
forget: (names?: string[]) => state.forget(names),
|
|
1812
|
+
dispose: () => {
|
|
1813
|
+
cancelGoto();
|
|
1814
|
+
everyTimers.stopAll();
|
|
1815
|
+
sound.dispose();
|
|
1816
|
+
applyClasses([]);
|
|
1817
|
+
savesDialog?.element.remove();
|
|
1818
|
+
settingsDialog?.element.remove();
|
|
1819
|
+
},
|
|
793
1820
|
on: (e, h) => emitter.on(e, h),
|
|
794
1821
|
off: (e, h) => emitter.off(e, h),
|
|
795
1822
|
once: (e, h) => emitter.once(e, h),
|
|
796
1823
|
};
|
|
797
|
-
|
|
1824
|
+
|
|
1825
|
+
// For the story's own scripts (#528): the events that are about the story, and what a
|
|
1826
|
+
// section's JavaScript can do
|
|
1827
|
+
// Checked as well as typed, as the story's scripts aren't TypeScript
|
|
1828
|
+
const scriptEvent = <E extends SquiffyScriptEvent>(event: E): E => {
|
|
1829
|
+
if (!SCRIPT_EVENTS.includes(event)) {
|
|
1830
|
+
throw new Error(`A story's script can't listen for "${event}": it can listen for ${SCRIPT_EVENTS.map(e => `"${e}"`).join(", ")}`);
|
|
1831
|
+
}
|
|
1832
|
+
return event;
|
|
1833
|
+
};
|
|
1834
|
+
const scriptApi: SquiffyScriptApi = {
|
|
1835
|
+
get: get,
|
|
1836
|
+
set: set,
|
|
1837
|
+
story: {
|
|
1838
|
+
go: (sectionName: string) => go(sectionName),
|
|
1839
|
+
seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
|
|
1840
|
+
visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
|
|
1841
|
+
lastVisited: (sectionOrPassage: string) => state.getLastVisited(sectionOrPassage),
|
|
1842
|
+
passages: (section?: string, filter?: TagFilter) => listPassages(story, section, get("_section"), filter),
|
|
1843
|
+
sections: (filter?: TagFilter) => listSections(story, filter),
|
|
1844
|
+
tags: (name?: string) => name === undefined
|
|
1845
|
+
? [...(story.sections[get("_section")]?.tags ?? [])]
|
|
1846
|
+
: tagsOf(story, name, get("_section")),
|
|
1847
|
+
},
|
|
1848
|
+
getSetting: (name: string) => playerSettings.get(name),
|
|
1849
|
+
element: outputElementContainer,
|
|
1850
|
+
on: (e, h) => emitter.on(scriptEvent(e), h),
|
|
1851
|
+
off: (e, h) => emitter.off(scriptEvent(e), h),
|
|
1852
|
+
once: (e, h) => emitter.once(scriptEvent(e), h),
|
|
1853
|
+
};
|
|
1854
|
+
// Before begin(), so a script hears about the first section. It bubbles, so a script can
|
|
1855
|
+
// listen on document, as it runs before the story's element is there.
|
|
1856
|
+
const view = outputElementContainer.ownerDocument.defaultView;
|
|
1857
|
+
if (view) {
|
|
1858
|
+
outputElementContainer.dispatchEvent(new view.CustomEvent("squiffy:ready", { bubbles: true, detail: scriptApi }));
|
|
1859
|
+
}
|
|
1860
|
+
return api;
|
|
1861
|
+
};
|
|
1862
|
+
|
|
1863
|
+
const SCRIPT_EVENTS: SquiffyScriptEvent[] = ["navigated", "set", "settingChanged"];
|