squiffy-runtime 7.0.0-beta.5 → 7.0.0-beta.6
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/events.d.ts +1 -0
- package/dist/panels.d.ts +14 -0
- package/dist/panels.test.d.ts +1 -0
- package/dist/preview-host.d.ts +2 -1
- package/dist/preview-host.js +4 -1
- package/dist/preview-host.js.map +2 -2
- package/dist/preview-html.js +1 -1
- package/dist/preview-protocol.d.ts +4 -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/squiffy.page.css +46 -22
- package/dist/squiffy.preview.html +604 -108
- package/dist/squiffy.runtime.css +468 -8
- package/dist/squiffy.runtime.d.ts +9 -1
- package/dist/squiffy.runtime.global.js +113 -72
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +4154 -3534
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +2 -0
- package/dist/textProcessor.d.ts +1 -0
- package/dist/types.d.ts +30 -0
- package/package.json +3 -3
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
- package/src/events.ts +1 -0
- package/src/panels.test.ts +201 -0
- package/src/panels.ts +187 -0
- package/src/preview-host.test.ts +5 -1
- package/src/preview-host.ts +9 -3
- package/src/preview-protocol.ts +6 -2
- package/src/preview.test.ts +68 -3
- package/src/preview.ts +74 -13
- 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/squiffy.page.css +46 -22
- package/src/squiffy.runtime.css +468 -8
- package/src/squiffy.runtime.test.ts +375 -4
- package/src/squiffy.runtime.ts +227 -10
- package/src/state.ts +18 -4
- package/src/textProcessor.ts +50 -9
- package/src/types.ts +54 -1
- package/vite.preview.config.ts +7 -0
package/src/squiffy.runtime.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt } from "./types.js";
|
|
1
|
+
import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt, SavedGame, LoadSaveResult } from "./types.js";
|
|
2
2
|
import { TextProcessor, errorHtml } from "./textProcessor.js";
|
|
3
3
|
import { toNumber } from "./numbers.js";
|
|
4
4
|
import { Emitter, SquiffyEventMap } from "./events.js";
|
|
@@ -12,8 +12,16 @@ import { imports } from "./import.js";
|
|
|
12
12
|
import { areInputsValid, setupInputValidation } from "./inputValidation.js";
|
|
13
13
|
import { createAssetHtmlResolver } from "./assets.js";
|
|
14
14
|
|
|
15
|
-
export type { SquiffyApi } from "./types.js";
|
|
15
|
+
export type { SquiffyApi, SavedGame, LoadSaveResult } from "./types.js";
|
|
16
16
|
export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
|
|
17
|
+
export { createSavesDialog, formatSaveTime, SAVES_STRINGS, SAVE_FILE_EXTENSION } from "./savesDialog.js";
|
|
18
|
+
export type { SavesDialog, SavesDialogOptions, SavesStringName } from "./savesDialog.js";
|
|
19
|
+
export { indexedDbSaveSlots, memorySaveSlots } from "./saveSlots.js";
|
|
20
|
+
export { createPanels } from "./panels.js";
|
|
21
|
+
export type { Panels, PanelsOptions } from "./panels.js";
|
|
22
|
+
export { PANEL_ICONS } from "./types.js";
|
|
23
|
+
export type { Panel, PanelIcon } from "./types.js";
|
|
24
|
+
export type { SaveSlot, SaveSlots } from "./saveSlots.js";
|
|
17
25
|
|
|
18
26
|
export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> => {
|
|
19
27
|
let story: Story;
|
|
@@ -59,8 +67,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
59
67
|
}
|
|
60
68
|
|
|
61
69
|
if (passage !== null) {
|
|
62
|
-
|
|
63
|
-
|
|
70
|
+
// A passage with @repeat can be clicked again, and doesn't count towards @1, @2... and @last
|
|
71
|
+
if (!isRepeatPassage(passage)) {
|
|
72
|
+
disableLink(link);
|
|
73
|
+
set("_turncount", get("_turncount") + 1);
|
|
74
|
+
}
|
|
64
75
|
await processLink(link);
|
|
65
76
|
if (passage) {
|
|
66
77
|
currentBlockOutputElement = null;
|
|
@@ -104,6 +115,14 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
104
115
|
}
|
|
105
116
|
}
|
|
106
117
|
|
|
118
|
+
function isRepeatPassage(passageName: string) {
|
|
119
|
+
if (!passageName) return false;
|
|
120
|
+
const sectionPassages = currentSection?.passages;
|
|
121
|
+
if (sectionPassages && passageName in sectionPassages) return !!sectionPassages[passageName].repeat;
|
|
122
|
+
const masterPassages = story.sections[""]?.passages;
|
|
123
|
+
return !!(masterPassages && passageName in masterPassages && masterPassages[passageName].repeat);
|
|
124
|
+
}
|
|
125
|
+
|
|
107
126
|
function disableLink(link: Element) {
|
|
108
127
|
link.classList.add("disabled");
|
|
109
128
|
link.setAttribute("tabindex", "-1");
|
|
@@ -128,6 +147,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
128
147
|
return;
|
|
129
148
|
}
|
|
130
149
|
// Saved while waiting for a {{goto}}, so carry on waiting
|
|
150
|
+
await resumeGoto();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function resumeGoto() {
|
|
131
154
|
const element = currentPassageElement ?? currentSectionElement;
|
|
132
155
|
const section = element?.getAttribute("data-goto");
|
|
133
156
|
if (section && section in story.sections) {
|
|
@@ -139,6 +162,35 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
139
162
|
clearTimeout(gotoTimer);
|
|
140
163
|
gotoTimer = undefined;
|
|
141
164
|
textProcessor.goto = null;
|
|
165
|
+
textProcessor.deactivate.clear();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Disables the links to the passages that a {{deactivate}} in the text just shown asked for
|
|
169
|
+
// (#13). The element that did it, and each link it disabled, get the same number, so that going
|
|
170
|
+
// back can enable just those links again. A link already disabled by a click is left alone.
|
|
171
|
+
function takeDeactivate(element: HTMLElement) {
|
|
172
|
+
const names = textProcessor.deactivate;
|
|
173
|
+
if (names.size == 0) return;
|
|
174
|
+
const id = String((get("_deactivations") || 0) + 1);
|
|
175
|
+
set("_deactivations", Number(id));
|
|
176
|
+
element.setAttribute("data-deactivates", id);
|
|
177
|
+
for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
|
|
178
|
+
if (names.has(link.getAttribute("data-passage")!) && !link.classList.contains("disabled")) {
|
|
179
|
+
disableLink(link);
|
|
180
|
+
link.setAttribute("data-deactivated-by", id);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
names.clear();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Going back: enables the links that the element's {{deactivate}} disabled
|
|
187
|
+
function undoDeactivate(element: HTMLElement) {
|
|
188
|
+
const id = element.getAttribute("data-deactivates");
|
|
189
|
+
if (!id) return;
|
|
190
|
+
for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-deactivated-by="${id}"]`)) {
|
|
191
|
+
enableLink(link);
|
|
192
|
+
link.removeAttribute("data-deactivated-by");
|
|
193
|
+
}
|
|
142
194
|
}
|
|
143
195
|
|
|
144
196
|
// Takes the {{goto}} from the text just shown, if there was one, and marks the section or
|
|
@@ -294,6 +346,13 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
294
346
|
const oldCanGoBack = canGoBack();
|
|
295
347
|
currentSection = story.sections[sectionName];
|
|
296
348
|
if (!currentSection) return;
|
|
349
|
+
const sectionBefore = get("_section");
|
|
350
|
+
if (sectionBefore !== null) {
|
|
351
|
+
// Where the player was before this (#56): the section, or the passage in it shown last
|
|
352
|
+
set("previous", get("_passage") ?? sectionBefore);
|
|
353
|
+
set("previous_section", sectionBefore);
|
|
354
|
+
}
|
|
355
|
+
if (get("_passage") !== null) set("_passage", null);
|
|
297
356
|
set("_section", sectionName);
|
|
298
357
|
// The story-wide turn count starts at 0 (#377), in a new story or one saved before it existed.
|
|
299
358
|
// It isn't a change the player made, so it isn't undone.
|
|
@@ -325,6 +384,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
325
384
|
setupInputValidation(currentSectionElement);
|
|
326
385
|
|
|
327
386
|
set("_turncount", 0);
|
|
387
|
+
takeDeactivate(currentSectionElement);
|
|
328
388
|
const pending = takeGoto(currentSectionElement);
|
|
329
389
|
writeUndoLog();
|
|
330
390
|
save();
|
|
@@ -337,7 +397,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
337
397
|
await followGoto(pending);
|
|
338
398
|
}
|
|
339
399
|
|
|
340
|
-
|
|
400
|
+
let inAfterWrite = false;
|
|
401
|
+
|
|
402
|
+
// afterWrite: where squiffy.ui.afterWrite queues its functions, for a section or passage's JS (#106)
|
|
403
|
+
function runJs(index: number, extra: any = null, afterWrite?: (() => void)[]) {
|
|
341
404
|
const squiffy = {
|
|
342
405
|
get: get,
|
|
343
406
|
set: set,
|
|
@@ -345,9 +408,21 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
345
408
|
transition: addTransition,
|
|
346
409
|
write: ui.write,
|
|
347
410
|
scrollToEnd: ui.scrollToEnd,
|
|
411
|
+
afterWrite: (fn: () => void) => {
|
|
412
|
+
if (!afterWrite) {
|
|
413
|
+
throw new Error("squiffy.ui.afterWrite can only be used in a section or passage's JavaScript");
|
|
414
|
+
}
|
|
415
|
+
afterWrite.push(fn);
|
|
416
|
+
},
|
|
348
417
|
},
|
|
349
418
|
story: {
|
|
350
|
-
|
|
419
|
+
// In an afterWrite function, the section's text is already on the page, so going
|
|
420
|
+
// somewhere else waits until it has finished, like {{goto}} (#106)
|
|
421
|
+
go: (sectionName: string) => {
|
|
422
|
+
if (!inAfterWrite) return go(sectionName);
|
|
423
|
+
textProcessor.goto ??= { section: sectionName, after: 0 };
|
|
424
|
+
return Promise.resolve();
|
|
425
|
+
},
|
|
351
426
|
seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
|
|
352
427
|
visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
|
|
353
428
|
},
|
|
@@ -362,9 +437,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
362
437
|
if (section.attributes) {
|
|
363
438
|
await processAttributes(section.attributes);
|
|
364
439
|
}
|
|
440
|
+
const afterWrite: (() => void)[] = [];
|
|
365
441
|
if (section.jsIndex !== undefined) {
|
|
366
442
|
const sectionBefore = get("_section");
|
|
367
|
-
runJs(section.jsIndex);
|
|
443
|
+
runJs(section.jsIndex, null, afterWrite);
|
|
368
444
|
if (get("_section") !== sectionBefore) {
|
|
369
445
|
// JS called squiffy.story.go() and navigated away; the destination
|
|
370
446
|
// section will handle rendering its own content.
|
|
@@ -374,6 +450,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
374
450
|
|
|
375
451
|
ui.write(section.text || "", source);
|
|
376
452
|
|
|
453
|
+
// Functions from squiffy.ui.afterWrite run once the text and its {{...}} are on the page (#106)
|
|
454
|
+
inAfterWrite = true;
|
|
455
|
+
try {
|
|
456
|
+
for (const fn of afterWrite) fn();
|
|
457
|
+
}
|
|
458
|
+
finally {
|
|
459
|
+
inAfterWrite = false;
|
|
460
|
+
}
|
|
461
|
+
|
|
377
462
|
await runTransitions();
|
|
378
463
|
}
|
|
379
464
|
|
|
@@ -397,6 +482,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
397
482
|
if (!passage) {
|
|
398
483
|
throw `No passage named ${passageName} in the current section or master section`;
|
|
399
484
|
}
|
|
485
|
+
// The section or passage shown before this one (#56)
|
|
486
|
+
set("previous", get("_passage") ?? get("_section"));
|
|
487
|
+
set("_passage", passageName);
|
|
400
488
|
state.setSeen(passageName);
|
|
401
489
|
|
|
402
490
|
const passages: Passage[] = [];
|
|
@@ -420,7 +508,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
420
508
|
runFns.push(() => run(passage, `[[${get("_section")}]][${passageName}]`));
|
|
421
509
|
|
|
422
510
|
const turnPassageName = "@" + get("_turncount");
|
|
423
|
-
if
|
|
511
|
+
// A passage with @repeat doesn't count as a turn, so @1, @2... and @last ran already if they're due
|
|
512
|
+
if (currentSection.passages && !passage.repeat) {
|
|
424
513
|
if (turnPassageName in currentSection.passages) {
|
|
425
514
|
const turnPassage = currentSection.passages[turnPassageName];
|
|
426
515
|
passages.push(turnPassage);
|
|
@@ -451,6 +540,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
451
540
|
// Setup validation for any inputs added by passages
|
|
452
541
|
setupInputValidation(currentSectionElement);
|
|
453
542
|
|
|
543
|
+
takeDeactivate(currentPassageElement!);
|
|
454
544
|
const pending = takeGoto(currentPassageElement!);
|
|
455
545
|
writeUndoLog();
|
|
456
546
|
save();
|
|
@@ -505,6 +595,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
505
595
|
return false;
|
|
506
596
|
}
|
|
507
597
|
|
|
598
|
+
showSavedOutput(output);
|
|
599
|
+
runUiJs();
|
|
600
|
+
pluginManager.onLoad();
|
|
601
|
+
setupInputValidation(currentSectionElement);
|
|
602
|
+
return true;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// Puts a saved game's text back on screen, and carries on from the end of it
|
|
606
|
+
function showSavedOutput(output: string) {
|
|
508
607
|
// Saved output may contain asset URLs that are no longer valid (e.g. blob: URLs), so resolve them again
|
|
509
608
|
outputElement.innerHTML = resolveAssetsInHtml(output);
|
|
510
609
|
|
|
@@ -513,10 +612,97 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
513
612
|
currentBlockOutputElement = outputElement.querySelector(".squiffy-output-block:last-child");
|
|
514
613
|
|
|
515
614
|
currentSection = story.sections[get("_section")];
|
|
516
|
-
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// The game as it is now. The attributes include the text on screen (_output), and the undo
|
|
618
|
+
// log is in that text, so a loaded game can go back too.
|
|
619
|
+
function getSave(): SavedGame {
|
|
620
|
+
return {
|
|
621
|
+
format: "squiffy-save",
|
|
622
|
+
version: 1,
|
|
623
|
+
storyId: story.projectId ?? null,
|
|
624
|
+
section: get("_section"),
|
|
625
|
+
passage: get("_passage"),
|
|
626
|
+
summary: getSummary(),
|
|
627
|
+
savedAt: new Date().toISOString(),
|
|
628
|
+
state: structuredClone(state.store),
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// The start of the text in the current section, to tell saves apart by. If it starts with a
|
|
633
|
+
// heading, that's it, as it's likely to name where the player is.
|
|
634
|
+
function getSummary() {
|
|
635
|
+
const MAX_LENGTH = 100;
|
|
636
|
+
const blocks = currentSectionElement?.querySelectorAll(".squiffy-output-block") ?? [];
|
|
637
|
+
for (const block of blocks) {
|
|
638
|
+
const text = textOf(block);
|
|
639
|
+
if (!text) continue;
|
|
640
|
+
const first = [...block.querySelectorAll("h1, h2, h3, h4, h5, h6, p, li")].find(child => textOf(child));
|
|
641
|
+
if (first && /^H[1-6]$/.test(first.tagName) && textOf(block).startsWith(textOf(first))) {
|
|
642
|
+
return textOf(first).substring(0, MAX_LENGTH);
|
|
643
|
+
}
|
|
644
|
+
if (text.length <= MAX_LENGTH) return text;
|
|
645
|
+
const cut = text.substring(0, MAX_LENGTH);
|
|
646
|
+
const space = cut.lastIndexOf(" ");
|
|
647
|
+
return (space > MAX_LENGTH / 2 ? cut.substring(0, space) : cut) + "…";
|
|
648
|
+
}
|
|
649
|
+
return "";
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// An element's text, with a space between paragraphs, headings and lines
|
|
653
|
+
function textOf(element: Element) {
|
|
654
|
+
const clone = element.cloneNode(true) as Element;
|
|
655
|
+
clone.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, div, br, tr, blockquote").forEach(el => el.after(" "));
|
|
656
|
+
return (clone.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function isSavedGame(save: unknown): save is SavedGame {
|
|
660
|
+
if (!save || typeof save != "object") return false;
|
|
661
|
+
const s = save as Partial<SavedGame>;
|
|
662
|
+
return s.format === "squiffy-save" && s.version === 1 && !!s.state && typeof s.state == "object"
|
|
663
|
+
&& !Array.isArray(s.state) && typeof s.state._output == "string";
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async function loadSave(save: SavedGame): Promise<LoadSaveResult> {
|
|
667
|
+
if (!isSavedGame(save)) return { success: false, error: "notASave" };
|
|
668
|
+
// A story without an id, or a save from one, can't be checked, so it's loaded
|
|
669
|
+
if (save.storyId && story.projectId && save.storyId !== story.projectId) {
|
|
670
|
+
return { success: false, error: "wrongStory" };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Wait for anything being shown to finish, so it doesn't carry on into the loaded game
|
|
674
|
+
while (runningTransitions) {
|
|
675
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
676
|
+
}
|
|
677
|
+
cancelGoto();
|
|
678
|
+
pendingErrors.length = 0;
|
|
679
|
+
state.reset();
|
|
680
|
+
for (const [attribute, value] of Object.entries(save.state)) {
|
|
681
|
+
state.setInternal(attribute, value, false);
|
|
682
|
+
}
|
|
683
|
+
undoLog = {};
|
|
684
|
+
scrollPosition = 0;
|
|
685
|
+
scrollToTop = false;
|
|
686
|
+
showSavedOutput(save.state._output as string);
|
|
687
|
+
|
|
688
|
+
if (!currentSection) {
|
|
689
|
+
// The section the game was saved in isn't in the story any more, so start again from
|
|
690
|
+
// the beginning, keeping the attributes
|
|
691
|
+
outputElement.innerHTML = "";
|
|
692
|
+
await go(story.start);
|
|
693
|
+
emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
|
|
694
|
+
return { success: true };
|
|
695
|
+
}
|
|
696
|
+
|
|
517
697
|
pluginManager.onLoad();
|
|
518
698
|
setupInputValidation(currentSectionElement);
|
|
519
|
-
|
|
699
|
+
emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
|
|
700
|
+
const passage = get("_passage");
|
|
701
|
+
emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
|
|
702
|
+
|
|
703
|
+
// Saved while waiting for a {{goto}}, so carry on waiting
|
|
704
|
+
await resumeGoto();
|
|
705
|
+
return { success: true };
|
|
520
706
|
}
|
|
521
707
|
|
|
522
708
|
function newBlockOutputElement() {
|
|
@@ -717,6 +903,33 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
717
903
|
|
|
718
904
|
setCurrentSectionElement();
|
|
719
905
|
setCurrentPassageElement();
|
|
906
|
+
emitter.emit("storyUpdated", {});
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// A master section passage for a panel or dialog (#14, #443): rendered with the attributes as
|
|
910
|
+
// they are, changing nothing, with its links disabled
|
|
911
|
+
function renderPassage(name: string): string {
|
|
912
|
+
const passage = story.sections[""]?.passages?.[name];
|
|
913
|
+
if (!passage) {
|
|
914
|
+
return errorHtml("Error in panel:", `there is no passage called "${name}" in the master section [[]]`);
|
|
915
|
+
}
|
|
916
|
+
// Anything the story's own text has asked for, which this mustn't change
|
|
917
|
+
const goto = textProcessor.goto;
|
|
918
|
+
const deactivate = [...textProcessor.deactivate];
|
|
919
|
+
state.readOnly = true;
|
|
920
|
+
let html: string;
|
|
921
|
+
try {
|
|
922
|
+
html = ui.renderHtml(passage.text || "", false);
|
|
923
|
+
}
|
|
924
|
+
finally {
|
|
925
|
+
state.readOnly = false;
|
|
926
|
+
textProcessor.goto = goto;
|
|
927
|
+
textProcessor.deactivate = new Set(deactivate);
|
|
928
|
+
}
|
|
929
|
+
const template = document.createElement("template");
|
|
930
|
+
template.innerHTML = html;
|
|
931
|
+
template.content.querySelectorAll("a.squiffy-link").forEach(disableLink);
|
|
932
|
+
return template.innerHTML;
|
|
720
933
|
}
|
|
721
934
|
|
|
722
935
|
function setCurrentSectionElement() {
|
|
@@ -794,6 +1007,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
794
1007
|
if (currentPassageElement) {
|
|
795
1008
|
const currentPassage = currentPassageElement.getAttribute("data-passage");
|
|
796
1009
|
doUndo(currentPassageElement.getAttribute("data-undo"));
|
|
1010
|
+
undoDeactivate(currentPassageElement);
|
|
797
1011
|
currentPassageElement.remove();
|
|
798
1012
|
|
|
799
1013
|
// If there's nothing left in the outputElement except for an empty section element that
|
|
@@ -963,6 +1177,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
|
|
|
963
1177
|
update: update,
|
|
964
1178
|
goBack: goBack,
|
|
965
1179
|
canGoBack: canGoBack,
|
|
1180
|
+
getSave: getSave,
|
|
1181
|
+
loadSave: loadSave,
|
|
1182
|
+
renderPassage: renderPassage,
|
|
966
1183
|
on: (e, h) => emitter.on(e, h),
|
|
967
1184
|
off: (e, h) => emitter.off(e, h),
|
|
968
1185
|
once: (e, h) => emitter.once(e, h),
|
package/src/state.ts
CHANGED
|
@@ -24,7 +24,12 @@ export class State {
|
|
|
24
24
|
return this.persist && window.localStorage && this.storyId;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
// While this is true, set() does nothing: e.g. while a panel is rendered, so its {{set}}s
|
|
28
|
+
// don't change the story
|
|
29
|
+
readOnly = false;
|
|
30
|
+
|
|
27
31
|
set(attribute: string, value: any) {
|
|
32
|
+
if (this.readOnly) return;
|
|
28
33
|
this.setInternal(attribute, value, true);
|
|
29
34
|
}
|
|
30
35
|
|
|
@@ -48,8 +53,13 @@ export class State {
|
|
|
48
53
|
this.onSet(attribute, value);
|
|
49
54
|
}
|
|
50
55
|
|
|
56
|
+
// Only the store's own properties are attributes, not ones it inherits, such as valueOf
|
|
57
|
+
private has(attribute: string) {
|
|
58
|
+
return Object.prototype.hasOwnProperty.call(this.store, attribute);
|
|
59
|
+
}
|
|
60
|
+
|
|
51
61
|
get(attribute: string): any {
|
|
52
|
-
if (
|
|
62
|
+
if (this.has(attribute)) {
|
|
53
63
|
return structuredClone(this.store[attribute]);
|
|
54
64
|
}
|
|
55
65
|
|
|
@@ -61,12 +71,16 @@ export class State {
|
|
|
61
71
|
// This allows {{attribute}} in templates to reflect changes made
|
|
62
72
|
// by helpers like {{inc}} during the same render pass.
|
|
63
73
|
return new Proxy({} as Record<string, any>, {
|
|
64
|
-
|
|
65
|
-
|
|
74
|
+
// A name that isn't an attribute is null, unless it's one every object has, like
|
|
75
|
+
// valueOf, which Handlebars can use
|
|
76
|
+
get: (target, prop) => typeof prop == "string" && (this.has(prop) || !(prop in target))
|
|
77
|
+
? this.get(prop)
|
|
78
|
+
: Reflect.get(target, prop),
|
|
79
|
+
has: (_, prop) => this.has(String(prop)),
|
|
66
80
|
ownKeys: () => Object.keys(this.store),
|
|
67
81
|
getOwnPropertyDescriptor: (_, prop) => {
|
|
68
82
|
const key = String(prop);
|
|
69
|
-
if (
|
|
83
|
+
if (this.has(key)) {
|
|
70
84
|
return {
|
|
71
85
|
enumerable: true,
|
|
72
86
|
configurable: true,
|
package/src/textProcessor.ts
CHANGED
|
@@ -70,6 +70,27 @@ export class TextProcessor {
|
|
|
70
70
|
return "";
|
|
71
71
|
});
|
|
72
72
|
|
|
73
|
+
// {{deactivate "name"}} (#13): the runtime disables the links to that passage on the screen
|
|
74
|
+
// once the section or passage being shown has been written. With no name, it's the passage
|
|
75
|
+
// being shown, e.g. one with @repeat that the player is done with (#104).
|
|
76
|
+
this.handlebars.registerHelper("deactivate", (...args: any[]) => {
|
|
77
|
+
args.pop();
|
|
78
|
+
const names = args.length ? args.map(unwrapValue) : [this.state.get("_passage")];
|
|
79
|
+
for (const name of names) {
|
|
80
|
+
if (typeof name != "string" || !name) {
|
|
81
|
+
return new Handlebars.SafeString(errorHtml("Error in {{deactivate}}:",
|
|
82
|
+
args.length ? "expected a passage name, e.g. {{deactivate \"door\"}}" : "{{deactivate}} with no passage name only works in a passage"));
|
|
83
|
+
}
|
|
84
|
+
const sectionPassages = this.getCurrentSection()?.passages;
|
|
85
|
+
const masterPassages = this.getStory().sections[""]?.passages;
|
|
86
|
+
if (!(sectionPassages && name in sectionPassages) && !(masterPassages && name in masterPassages)) {
|
|
87
|
+
return new Handlebars.SafeString(errorHtml("Error in {{deactivate}}:", `there is no passage called "${name}" in this section`));
|
|
88
|
+
}
|
|
89
|
+
this.deactivate.add(name);
|
|
90
|
+
}
|
|
91
|
+
return "";
|
|
92
|
+
});
|
|
93
|
+
|
|
73
94
|
// State modification helpers (side effects, no output)
|
|
74
95
|
// These execute at render time, so they respect {{#if}} conditions
|
|
75
96
|
this.handlebars.registerHelper("set", (attribute: string, value: any) => {
|
|
@@ -240,9 +261,24 @@ export class TextProcessor {
|
|
|
240
261
|
|
|
241
262
|
const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&").replace(/"/g, """);
|
|
242
263
|
|
|
243
|
-
|
|
264
|
+
// A link's text and setters can have {{...}} in them, such as [[Drop the {{this}}]](drop,
|
|
265
|
+
// item = "{{this}}") inside an {{#each}}. They're filled in where the link is, so they see
|
|
266
|
+
// the loop's item. Setters aren't HTML, so their values aren't escaped.
|
|
267
|
+
const linkTemplates = new Map<string, HandlebarsTemplateDelegate>();
|
|
268
|
+
const fillIn = (text: unknown, context: unknown, options: any, escape: boolean) => {
|
|
269
|
+
if (typeof text != "string" || !text.includes("{{")) return text;
|
|
270
|
+
const key = (escape ? "h:" : "t:") + text;
|
|
271
|
+
let template = linkTemplates.get(key);
|
|
272
|
+
if (!template) {
|
|
273
|
+
template = this.handlebars.compile(rewriteInfixExpressions(text), { compat: true, noEscape: !escape });
|
|
274
|
+
linkTemplates.set(key, template);
|
|
275
|
+
}
|
|
276
|
+
return template(context, { data: options.data });
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
const addAdditionalParameters = (context: unknown, options: any) => {
|
|
244
280
|
let result = "";
|
|
245
|
-
const setters = options.hash.set as string || "";
|
|
281
|
+
const setters = fillIn(options.hash.set as string || "", context, options, false) as string;
|
|
246
282
|
if (setters) {
|
|
247
283
|
// With expressions, a setter can have commas inside quotes, e.g. greeting = "Hi, there"
|
|
248
284
|
const list = this.getStory().expressions ? splitSetters(setters) : setters.split(",").map(s => s.trim());
|
|
@@ -251,14 +287,15 @@ export class TextProcessor {
|
|
|
251
287
|
return result;
|
|
252
288
|
};
|
|
253
289
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
290
|
+
// Handlebars passes the context a helper is used in (inside an {{#each}}, the item) as this
|
|
291
|
+
this.handlebars.registerHelper("section", function (this: unknown, section: string, options) {
|
|
292
|
+
const text = fillIn(options.hash.text as string || section, this, options, true);
|
|
293
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-section" data-section="${escapeAttr(section)}"${addAdditionalParameters(this, options)} role="link" tabindex="0">${text}</a>`);
|
|
257
294
|
});
|
|
258
295
|
|
|
259
|
-
this.handlebars.registerHelper("passage", (passage: string, options)
|
|
260
|
-
const text = options.hash.text as string || passage;
|
|
261
|
-
return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${escapeAttr(passage)}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
|
|
296
|
+
this.handlebars.registerHelper("passage", function (this: unknown, passage: string, options) {
|
|
297
|
+
const text = fillIn(options.hash.text as string || passage, this, options, true);
|
|
298
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${escapeAttr(passage)}"${addAdditionalParameters(this, options)} role="link" tabindex="0">${text}</a>`);
|
|
262
299
|
});
|
|
263
300
|
}
|
|
264
301
|
|
|
@@ -278,6 +315,9 @@ export class TextProcessor {
|
|
|
278
315
|
// Where a {{goto}} asked to go. The runtime clears it before showing a section or passage, and
|
|
279
316
|
// follows it afterwards.
|
|
280
317
|
goto: { section: string; after: number } | null = null;
|
|
318
|
+
// The passages whose links a {{deactivate}} asked to disable. Like goto, the runtime clears it
|
|
319
|
+
// before showing a section or passage, and acts on it afterwards.
|
|
320
|
+
deactivate = new Set<string>();
|
|
281
321
|
|
|
282
322
|
private expressionCache = new Map<string, HandlebarsTemplateDelegate>();
|
|
283
323
|
// Where the __value helper puts the value of the expression being evaluated
|
|
@@ -285,7 +325,8 @@ export class TextProcessor {
|
|
|
285
325
|
|
|
286
326
|
process(text: string, inline: boolean) {
|
|
287
327
|
try {
|
|
288
|
-
|
|
328
|
+
// compat: inside an {{#each}}, a name that isn't one of the item's looks for an attribute
|
|
329
|
+
const template = this.handlebars.compile(rewriteInfixExpressions(text), { compat: true });
|
|
289
330
|
text = template(this.state.getStore());
|
|
290
331
|
|
|
291
332
|
if (inline) {
|
package/src/types.ts
CHANGED
|
@@ -41,6 +41,15 @@ export interface SquiffyApi {
|
|
|
41
41
|
goBack: () => void;
|
|
42
42
|
// Whether goBack() would go anywhere, e.g. to enable a Back button. canGoBackChanged says when it changes.
|
|
43
43
|
canGoBack: () => boolean;
|
|
44
|
+
// The game as it is now, to keep and load again later with loadSave()
|
|
45
|
+
getSave: () => SavedGame;
|
|
46
|
+
// Carries on from a saved game, in place of the game as it is now. A save from a different
|
|
47
|
+
// story (by its squiffy.json "id") isn't loaded.
|
|
48
|
+
loadSave: (save: SavedGame) => Promise<LoadSaveResult>;
|
|
49
|
+
// A passage in the master section [[]], rendered as HTML with the attributes as they are now,
|
|
50
|
+
// for a panel beside the story or a dialog (#14, #443). It changes nothing: {{set}} and the
|
|
51
|
+
// like are ignored, its @set and JavaScript don't run, and its links are disabled.
|
|
52
|
+
renderPassage: (name: string) => string;
|
|
44
53
|
|
|
45
54
|
on<E extends keyof SquiffyEventMap>(
|
|
46
55
|
event: E,
|
|
@@ -81,13 +90,33 @@ export interface Story {
|
|
|
81
90
|
) => void)[];
|
|
82
91
|
start: string;
|
|
83
92
|
id?: string | null;
|
|
93
|
+
// squiffy.json's "id", which a saved game is checked against
|
|
94
|
+
projectId?: string;
|
|
84
95
|
uiJsIndex?: number;
|
|
85
96
|
// Whether @set and link setters take expressions, with the same rules as {{#if}}: attributes
|
|
86
97
|
// by name, and text in quotes. True for a story with a squiffy.json (#373).
|
|
87
98
|
expressions?: boolean;
|
|
99
|
+
// squiffy.json's "panels": passages shown beside the story, or in a dialog from a button
|
|
100
|
+
panels?: Panel[];
|
|
88
101
|
sections: Record<string, Section>;
|
|
89
102
|
}
|
|
90
103
|
|
|
104
|
+
// The icons a panel's button can have, in place of its label
|
|
105
|
+
export const PANEL_ICONS = ["bag", "person", "map", "help", "info", "list", "book", "star", "heart"] as const;
|
|
106
|
+
export type PanelIcon = typeof PANEL_ICONS[number];
|
|
107
|
+
|
|
108
|
+
// A passage in the master section that's always on screen, rendered again as the story goes on:
|
|
109
|
+
// beside the story ("side"), or in a dialog that a button in the header opens ("button").
|
|
110
|
+
export interface Panel {
|
|
111
|
+
passage: string;
|
|
112
|
+
// The button's text, or its tooltip if it has an icon. A side panel's button only shows on
|
|
113
|
+
// screens too narrow for the panel.
|
|
114
|
+
label: string;
|
|
115
|
+
// "button" if it's left out
|
|
116
|
+
position?: "side" | "button";
|
|
117
|
+
icon?: PanelIcon;
|
|
118
|
+
}
|
|
119
|
+
|
|
91
120
|
export interface Section {
|
|
92
121
|
text?: string;
|
|
93
122
|
clear?: boolean;
|
|
@@ -100,6 +129,30 @@ export interface Section {
|
|
|
100
129
|
export interface Passage {
|
|
101
130
|
text?: string;
|
|
102
131
|
clear?: boolean;
|
|
132
|
+
// @repeat: its links stay clickable, and clicking one doesn't count towards @1, @2... and @last (#104)
|
|
133
|
+
repeat?: boolean;
|
|
103
134
|
attributes?: string[];
|
|
104
135
|
jsIndex?: number;
|
|
105
|
-
}
|
|
136
|
+
}
|
|
137
|
+
// A saved game, from SquiffyApi.getSave(). It's JSON, so it can be kept as text or in a file.
|
|
138
|
+
export interface SavedGame {
|
|
139
|
+
format: "squiffy-save";
|
|
140
|
+
version: 1;
|
|
141
|
+
// The story's squiffy.json "id", if it has one
|
|
142
|
+
storyId: string | null;
|
|
143
|
+
// Where the player was
|
|
144
|
+
section: string | null;
|
|
145
|
+
passage: string | null;
|
|
146
|
+
// The start of the text the player was reading, to tell saves apart by
|
|
147
|
+
summary: string;
|
|
148
|
+
// When it was saved, as an ISO date
|
|
149
|
+
savedAt: string;
|
|
150
|
+
// Every attribute, including the text on screen (_output)
|
|
151
|
+
state: Record<string, unknown>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type LoadSaveResult =
|
|
155
|
+
| { success: true }
|
|
156
|
+
// notASave: it isn't a saved game, or it's from a newer version of Squiffy.
|
|
157
|
+
// wrongStory: it's from a different story.
|
|
158
|
+
| { success: false; error: "notASave" | "wrongStory" };
|
package/vite.preview.config.ts
CHANGED
|
@@ -22,6 +22,13 @@ html, body { height: 100%; }
|
|
|
22
22
|
div#squiffy-container { max-width: none; height: 100%; padding: 0; }
|
|
23
23
|
#squiffy, .squiffy-preview-story, .squiffy-preview-story > div { height: 100%; box-sizing: border-box; }
|
|
24
24
|
.squiffy-preview-story > div { padding: 1em max(1.25rem, calc((100% - var(--squiffy-max-width)) / 2)); }
|
|
25
|
+
/* The story's panels: their buttons above the story, and side panels to its right */
|
|
26
|
+
#squiffy { display: flex; flex-direction: column; }
|
|
27
|
+
.squiffy-preview-header { flex: none; padding: 0.5rem 0.75rem 0; font-family: system-ui, sans-serif; font-size: 0.875rem; text-align: right; }
|
|
28
|
+
.squiffy-preview-header:empty { display: none; }
|
|
29
|
+
.squiffy-preview-body { flex: 1; min-height: 0; display: flex; }
|
|
30
|
+
#squiffy .squiffy-preview-body > .squiffy-preview-story { flex: 1; min-width: 0; height: 100%; }
|
|
31
|
+
.squiffy-preview-body > aside.squiffy-panels-side { flex: none; width: var(--squiffy-side-width); box-sizing: border-box; overflow-y: auto; padding: 1em 1.25rem 1em 0; }
|
|
25
32
|
</style>
|
|
26
33
|
</head>
|
|
27
34
|
<body>
|