@rohal12/spindle 0.64.18 → 0.64.20
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/pkg/format.js +1 -1
- package/dist/pkg/headless.js +115 -19
- package/package.json +1 -1
- package/src/components/PassageDialog.tsx +38 -4
- package/src/components/StoryInterface.tsx +25 -1
- package/src/event-emitter.ts +5 -3
- package/src/index.tsx +3 -2
- package/src/store.ts +115 -10
- package/src/story-api.ts +2 -0
- package/src/story-init.ts +17 -12
- package/types/index.d.ts +24 -0
package/dist/pkg/headless.js
CHANGED
|
@@ -9260,7 +9260,8 @@ var VALID_EVENTS = /* @__PURE__ */ new Set([
|
|
|
9260
9260
|
"beforenavigate",
|
|
9261
9261
|
"afternavigate",
|
|
9262
9262
|
"passagerender",
|
|
9263
|
-
"dialogrender"
|
|
9263
|
+
"dialogrender",
|
|
9264
|
+
"dialogclose"
|
|
9264
9265
|
]);
|
|
9265
9266
|
var listeners$2 = /* @__PURE__ */ new Map();
|
|
9266
9267
|
function on(event, cb) {
|
|
@@ -9285,9 +9286,9 @@ function emit(event, ...args) {
|
|
|
9285
9286
|
forEachListener(event, (cb) => cb(...args));
|
|
9286
9287
|
}
|
|
9287
9288
|
/**
|
|
9288
|
-
* Emit an event from inside a render commit (layout effect)
|
|
9289
|
-
* handler is logged instead of propagating
|
|
9290
|
-
* render; the remaining handlers still run.
|
|
9289
|
+
* Emit an event from inside a render commit (layout effect), or once one is
|
|
9290
|
+
* over (`dialogclose`). A throwing handler is logged instead of propagating
|
|
9291
|
+
* into Preact and breaking the render; the remaining handlers still run.
|
|
9291
9292
|
*/
|
|
9292
9293
|
function emitFromRender(event, ...args) {
|
|
9293
9294
|
forEachListener(event, (cb) => {
|
|
@@ -19267,7 +19268,7 @@ function executeStoryInit() {
|
|
|
19267
19268
|
container.style.display = "none";
|
|
19268
19269
|
document.body.appendChild(container);
|
|
19269
19270
|
storyInitContainer = container;
|
|
19270
|
-
render(h(ActionsDisabledContext.Provider, { value: true }, h(() => renderNodes(ast), null)), container);
|
|
19271
|
+
settingUpStart(() => render(h(ActionsDisabledContext.Provider, { value: true }, h(() => renderNodes(ast), null)), container));
|
|
19271
19272
|
recordStoryInitState();
|
|
19272
19273
|
}
|
|
19273
19274
|
const saveTitlePassage = state.storyData.passages.get("SaveTitle");
|
|
@@ -19287,9 +19288,13 @@ function initializeStory(session) {
|
|
|
19287
19288
|
console.warn(`spindle: discarding the saved session: the story no longer has the passage "${missing}"`);
|
|
19288
19289
|
session = void 0;
|
|
19289
19290
|
}
|
|
19290
|
-
if (session)
|
|
19291
|
-
|
|
19292
|
-
|
|
19291
|
+
if (session) {
|
|
19292
|
+
useStoryStore.getState().loadFromPayload(session);
|
|
19293
|
+
emit("storyinit");
|
|
19294
|
+
} else {
|
|
19295
|
+
settingUpStart(() => emit("storyinit"));
|
|
19296
|
+
recordStoryInitState();
|
|
19297
|
+
}
|
|
19293
19298
|
}
|
|
19294
19299
|
// src/passage-roles.ts
|
|
19295
19300
|
/** Runtime-owned passage roles, shared with stateless authoring tools. */
|
|
@@ -19624,6 +19629,22 @@ function moveInHistory(get, set, step) {
|
|
|
19624
19629
|
keepDrawsSoFar();
|
|
19625
19630
|
persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage, kind));
|
|
19626
19631
|
}
|
|
19632
|
+
/** How many runs of settingUpStart() are under way. */
|
|
19633
|
+
var startSetups = 0;
|
|
19634
|
+
/**
|
|
19635
|
+
* Run `fn`, which sets up the start moment of a new game: the StoryInit
|
|
19636
|
+
* passage, or the `storyinit` handlers at boot (unless a session was
|
|
19637
|
+
* restored) and on restart. recordStoryInitState() records what it leaves
|
|
19638
|
+
* behind, so recordMoment() has nothing to do meanwhile (see there).
|
|
19639
|
+
*/
|
|
19640
|
+
function settingUpStart(fn) {
|
|
19641
|
+
startSetups++;
|
|
19642
|
+
try {
|
|
19643
|
+
return fn();
|
|
19644
|
+
} finally {
|
|
19645
|
+
startSetups--;
|
|
19646
|
+
}
|
|
19647
|
+
}
|
|
19627
19648
|
/**
|
|
19628
19649
|
* Record the state StoryInit left behind as the start moment: its variable
|
|
19629
19650
|
* snapshot (the history base) and PRNG state. Called by executeStoryInit()
|
|
@@ -19644,6 +19665,32 @@ function recordStoryInitState() {
|
|
|
19644
19665
|
keepDrawsSoFar();
|
|
19645
19666
|
}
|
|
19646
19667
|
/**
|
|
19668
|
+
* Record the live variables as the state of the current moment (see
|
|
19669
|
+
* StoryState.recordMoment): what a navigation does for the moment it
|
|
19670
|
+
* enters, without the navigation.
|
|
19671
|
+
*/
|
|
19672
|
+
function recordCurrentMoment(get, set) {
|
|
19673
|
+
const { storyData, history, historyIndex, variables } = get();
|
|
19674
|
+
if (!storyData || historyIndex < 0) return;
|
|
19675
|
+
if (startSetups > 0 && history.length === 1) return;
|
|
19676
|
+
if (navigationTriggerPhase && enteredMoment?.navigationId === get().navigationId) return;
|
|
19677
|
+
const recorded = variables === lastNavigationVars || deepEqualStrict(reconstructVarsAt(historyIndex), variables);
|
|
19678
|
+
if (!recorded) {
|
|
19679
|
+
const entry = historyIndex > 0 ? computeVarPatches(reconstructVarsAt(historyIndex - 1), variables) : null;
|
|
19680
|
+
patchEntries.length = historyIndex;
|
|
19681
|
+
if (entry) patchEntries[historyIndex - 1] = entry;
|
|
19682
|
+
else variableBase = variables;
|
|
19683
|
+
if (sessionMoments.length > historyIndex) sessionMoments.length = historyIndex;
|
|
19684
|
+
lastNavigationVars = variables;
|
|
19685
|
+
if (historyIndex < history.length - 1) set((state) => {
|
|
19686
|
+
state.history = state.history.slice(0, historyIndex + 1);
|
|
19687
|
+
});
|
|
19688
|
+
clearReplayWatchers();
|
|
19689
|
+
}
|
|
19690
|
+
for (const capture of hookCaptures) capture.before = variables;
|
|
19691
|
+
if (!recorded) persistSessionThen(get);
|
|
19692
|
+
}
|
|
19693
|
+
/**
|
|
19647
19694
|
* Settles once the latest playthrough switch (init's lookup or creation, a
|
|
19648
19695
|
* restart's creation, the replacement of a deleted current playthrough, a
|
|
19649
19696
|
* load making the loaded save's playthrough current) is stored, with the
|
|
@@ -19847,11 +19894,10 @@ function loadedEntryMoment(payload) {
|
|
|
19847
19894
|
if (typeof moment.variables !== "object" || moment.variables === null) return;
|
|
19848
19895
|
return moment;
|
|
19849
19896
|
}
|
|
19850
|
-
|
|
19851
|
-
var hookWrites = /* @__PURE__ */ new Set();
|
|
19897
|
+
var hookCaptures = /* @__PURE__ */ new Set();
|
|
19852
19898
|
/** Note that `path` of the variables was written (see keepHookWrites). */
|
|
19853
19899
|
function recordHookWrite(path) {
|
|
19854
|
-
for (const writes of
|
|
19900
|
+
for (const { writes } of hookCaptures) writes.set(pathKey(path), path);
|
|
19855
19901
|
}
|
|
19856
19902
|
/**
|
|
19857
19903
|
* Write the changes between `before` and `after` (the live variables around
|
|
@@ -19986,6 +20032,7 @@ var PROGRAM_ORDER_ACTIONS = [
|
|
|
19986
20032
|
"navigate",
|
|
19987
20033
|
"goBack",
|
|
19988
20034
|
"goForward",
|
|
20035
|
+
"recordMoment",
|
|
19989
20036
|
"restart",
|
|
19990
20037
|
"save",
|
|
19991
20038
|
"load",
|
|
@@ -20222,6 +20269,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
|
|
|
20222
20269
|
},
|
|
20223
20270
|
goBack: () => moveInHistory(get, set, -1),
|
|
20224
20271
|
goForward: () => moveInHistory(get, set, 1),
|
|
20272
|
+
recordMoment: () => recordCurrentMoment(get, set),
|
|
20225
20273
|
setVariable: (name, value) => {
|
|
20226
20274
|
set((state) => {
|
|
20227
20275
|
checkVariableName(name, `$${name}`);
|
|
@@ -20294,7 +20342,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
|
|
|
20294
20342
|
enterRuntimePhase();
|
|
20295
20343
|
executeStoryInit();
|
|
20296
20344
|
clearSession(storyData.ifid);
|
|
20297
|
-
emit("storyinit");
|
|
20345
|
+
settingUpStart(() => emit("storyinit"));
|
|
20298
20346
|
recordStoryInitState();
|
|
20299
20347
|
},
|
|
20300
20348
|
save: (slot, custom) => {
|
|
@@ -20407,18 +20455,20 @@ var useStoryStore = create()(storyStore((set, get) => ({
|
|
|
20407
20455
|
};
|
|
20408
20456
|
},
|
|
20409
20457
|
beginSave: () => {
|
|
20410
|
-
const
|
|
20458
|
+
const capture = {
|
|
20459
|
+
before: get().variables,
|
|
20460
|
+
writes: /* @__PURE__ */ new Map()
|
|
20461
|
+
};
|
|
20411
20462
|
const replaced = latestStateApplied;
|
|
20412
|
-
|
|
20413
|
-
hookWrites.add(writes);
|
|
20463
|
+
hookCaptures.add(capture);
|
|
20414
20464
|
const dispose = () => {
|
|
20415
|
-
|
|
20465
|
+
hookCaptures.delete(capture);
|
|
20416
20466
|
};
|
|
20417
20467
|
return Object.assign(() => {
|
|
20418
20468
|
dispose();
|
|
20419
20469
|
if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
|
|
20420
20470
|
const payload = get().getSavePayload();
|
|
20421
|
-
keepHookWrites(payload, before, get().variables, [...writes.values()]);
|
|
20471
|
+
keepHookWrites(payload, capture.before, get().variables, [...capture.writes.values()]);
|
|
20422
20472
|
return payload;
|
|
20423
20473
|
}, { dispose });
|
|
20424
20474
|
},
|
|
@@ -20517,6 +20567,24 @@ var useStoryStore = create()(storyStore((set, get) => ({
|
|
|
20517
20567
|
})));
|
|
20518
20568
|
// src/components/StoryInterface.tsx
|
|
20519
20569
|
var DEFAULT_MARKUP = "<header class=\"story-menubar\">{story-title}{back}{forward}{restart}{quicksave}{quickload}{saves}{settings}</header>\n{passage}";
|
|
20570
|
+
/**
|
|
20571
|
+
* Whether interface markup uses the `{passage}` macro, however it is
|
|
20572
|
+
* written: with selectors (`{#story.main passage}`) and in any case
|
|
20573
|
+
* (`{Passage}`; macro names are case-insensitive). The text in an escaped
|
|
20574
|
+
* `\{passage}`, a comment, an attribute value, a label or code is no use
|
|
20575
|
+
* of the macro. Malformed markup counts as using it: the interface shows
|
|
20576
|
+
* its error then, which is the problem to report.
|
|
20577
|
+
*/
|
|
20578
|
+
function usesPassageMacro(markup) {
|
|
20579
|
+
let tokens;
|
|
20580
|
+
try {
|
|
20581
|
+
tokens = tokenizeMarkup(markup);
|
|
20582
|
+
} catch (err) {
|
|
20583
|
+
if (err instanceof MarkupError) return true;
|
|
20584
|
+
throw err;
|
|
20585
|
+
}
|
|
20586
|
+
return tokens.some((token) => token.type === "macro" && !token.isClose && token.name.toLowerCase() === "passage");
|
|
20587
|
+
}
|
|
20520
20588
|
function StoryInterface() {
|
|
20521
20589
|
const { storyData } = useStoryFields("storyData");
|
|
20522
20590
|
const overridePassage = storyData?.passages.get("StoryInterface");
|
|
@@ -20915,6 +20983,27 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
|
|
|
20915
20983
|
}, [dismissible, onClose]);
|
|
20916
20984
|
}
|
|
20917
20985
|
// src/components/PassageDialog.tsx
|
|
20986
|
+
/** How many dialogs have rendered: the place of the last in opening order. */
|
|
20987
|
+
var dialogsOpened = 0;
|
|
20988
|
+
/** The dialogs unmounted by the render pass under way, not announced yet. */
|
|
20989
|
+
var closedDialogs = [];
|
|
20990
|
+
/**
|
|
20991
|
+
* Emit `dialogclose` for a dialog that is unmounting, once the render pass
|
|
20992
|
+
* that unmounts it is over. The effect cleanups run before the dialog's DOM is
|
|
20993
|
+
* removed, and of dialogs closing together the lower one unmounts first,
|
|
20994
|
+
* while only the last restores focus (see useModalFocus): by the next
|
|
20995
|
+
* microtask the dialogs are gone, focus is back and `Story.isDialogOpen()`
|
|
20996
|
+
* tells the close. Dialogs that closed together are announced innermost
|
|
20997
|
+
* first.
|
|
20998
|
+
*/
|
|
20999
|
+
function announceDialogClose(closed) {
|
|
21000
|
+
if (closedDialogs.length === 0) queueMicrotask(() => {
|
|
21001
|
+
const dialogs = closedDialogs.sort((a, b) => b.opened - a.opened);
|
|
21002
|
+
closedDialogs = [];
|
|
21003
|
+
for (const { passage } of dialogs) emitFromRender("dialogclose", passage);
|
|
21004
|
+
});
|
|
21005
|
+
closedDialogs.push(closed);
|
|
21006
|
+
}
|
|
20918
21007
|
function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
|
|
20919
21008
|
const onCloseRef = useRef(onClose);
|
|
20920
21009
|
onCloseRef.current = onClose;
|
|
@@ -20956,7 +21045,13 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
|
|
|
20956
21045
|
return () => panel.removeAttribute("aria-labelledby");
|
|
20957
21046
|
}, [label, markup]);
|
|
20958
21047
|
useLayoutEffect(() => {
|
|
20959
|
-
if (panelRef.current)
|
|
21048
|
+
if (!panelRef.current) return;
|
|
21049
|
+
const closed = {
|
|
21050
|
+
passage: passageName ?? "",
|
|
21051
|
+
opened: ++dialogsOpened
|
|
21052
|
+
};
|
|
21053
|
+
emitFromRender("dialogrender", closed.passage, panelRef.current);
|
|
21054
|
+
return () => announceDialogClose(closed);
|
|
20960
21055
|
}, []);
|
|
20961
21056
|
const handleBackdrop = (e) => {
|
|
20962
21057
|
if (!dismissible) return;
|
|
@@ -22144,6 +22239,7 @@ function createStoryAPI() {
|
|
|
22144
22239
|
goto: storeAction("navigate"),
|
|
22145
22240
|
back: storeAction("goBack"),
|
|
22146
22241
|
forward: storeAction("goForward"),
|
|
22242
|
+
recordMoment: storeAction("recordMoment"),
|
|
22147
22243
|
restart: storeAction("restart"),
|
|
22148
22244
|
save: storeAction("save"),
|
|
22149
22245
|
load: storeAction("load"),
|
|
@@ -26375,7 +26471,7 @@ function boot() {
|
|
|
26375
26471
|
});
|
|
26376
26472
|
connectTriggersToStore();
|
|
26377
26473
|
const storyInterfacePassage = storyData.passages.get("StoryInterface");
|
|
26378
|
-
if (storyInterfacePassage && !storyInterfacePassage.content
|
|
26474
|
+
if (storyInterfacePassage && !usesPassageMacro(storyInterfacePassage.content)) console.warn("spindle: StoryInterface passage does not contain {passage}. The current passage will not be displayed.");
|
|
26379
26475
|
const root = document.getElementById("root");
|
|
26380
26476
|
if (!root) throw new Error("spindle: No <div id=\"root\"> element found.");
|
|
26381
26477
|
render(/* @__PURE__ */ jsx(App, {}), root);
|
package/package.json
CHANGED
|
@@ -24,6 +24,38 @@ import { DialogCloseContext, DialogPanelContext } from './dialog-close-context';
|
|
|
24
24
|
|
|
25
25
|
export { DialogCloseContext };
|
|
26
26
|
|
|
27
|
+
/** A dialog that closed, by its passage and its place in the opening order. */
|
|
28
|
+
interface ClosedDialog {
|
|
29
|
+
passage: string;
|
|
30
|
+
opened: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** How many dialogs have rendered: the place of the last in opening order. */
|
|
34
|
+
let dialogsOpened = 0;
|
|
35
|
+
|
|
36
|
+
/** The dialogs unmounted by the render pass under way, not announced yet. */
|
|
37
|
+
let closedDialogs: ClosedDialog[] = [];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Emit `dialogclose` for a dialog that is unmounting, once the render pass
|
|
41
|
+
* that unmounts it is over. The effect cleanups run before the dialog's DOM is
|
|
42
|
+
* removed, and of dialogs closing together the lower one unmounts first,
|
|
43
|
+
* while only the last restores focus (see useModalFocus): by the next
|
|
44
|
+
* microtask the dialogs are gone, focus is back and `Story.isDialogOpen()`
|
|
45
|
+
* tells the close. Dialogs that closed together are announced innermost
|
|
46
|
+
* first.
|
|
47
|
+
*/
|
|
48
|
+
function announceDialogClose(closed: ClosedDialog): void {
|
|
49
|
+
if (closedDialogs.length === 0) {
|
|
50
|
+
queueMicrotask(() => {
|
|
51
|
+
const dialogs = closedDialogs.sort((a, b) => b.opened - a.opened);
|
|
52
|
+
closedDialogs = [];
|
|
53
|
+
for (const { passage } of dialogs) emitFromRender('dialogclose', passage);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
closedDialogs.push(closed);
|
|
57
|
+
}
|
|
58
|
+
|
|
27
59
|
interface PassageDialogProps {
|
|
28
60
|
passageName?: string;
|
|
29
61
|
fallbackMarkup?: string;
|
|
@@ -112,11 +144,13 @@ export function PassageDialog({
|
|
|
112
144
|
return () => panel.removeAttribute('aria-labelledby');
|
|
113
145
|
}, [label, markup]);
|
|
114
146
|
|
|
115
|
-
// Signal that the dialog's DOM is committed (once per open)
|
|
147
|
+
// Signal that the dialog's DOM is committed (once per open), and that the
|
|
148
|
+
// dialog has closed (once for each dialogrender, with the same passage).
|
|
116
149
|
useLayoutEffect(() => {
|
|
117
|
-
if (panelRef.current)
|
|
118
|
-
|
|
119
|
-
|
|
150
|
+
if (!panelRef.current) return;
|
|
151
|
+
const closed = { passage: passageName ?? '', opened: ++dialogsOpened };
|
|
152
|
+
emitFromRender('dialogrender', closed.passage, panelRef.current);
|
|
153
|
+
return () => announceDialogClose(closed);
|
|
120
154
|
}, []);
|
|
121
155
|
|
|
122
156
|
const handleBackdrop = (e: MouseEvent) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useLayoutEffect, useMemo } from 'preact/hooks';
|
|
2
2
|
import { useStoryFields } from '../hooks/use-story-fields';
|
|
3
|
-
import { parseMarkup } from '../markup/parse';
|
|
3
|
+
import { MarkupError, parseMarkup, tokenizeMarkup } from '../markup/parse';
|
|
4
4
|
import {
|
|
5
5
|
renderInlineNodes,
|
|
6
6
|
InterfaceContext,
|
|
@@ -12,6 +12,30 @@ import { errorMessage } from '../utils/error-message';
|
|
|
12
12
|
const DEFAULT_MARKUP =
|
|
13
13
|
'<header class="story-menubar">{story-title}{back}{forward}{restart}{quicksave}{quickload}{saves}{settings}</header>\n{passage}';
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Whether interface markup uses the `{passage}` macro, however it is
|
|
17
|
+
* written: with selectors (`{#story.main passage}`) and in any case
|
|
18
|
+
* (`{Passage}`; macro names are case-insensitive). The text in an escaped
|
|
19
|
+
* `\{passage}`, a comment, an attribute value, a label or code is no use
|
|
20
|
+
* of the macro. Malformed markup counts as using it: the interface shows
|
|
21
|
+
* its error then, which is the problem to report.
|
|
22
|
+
*/
|
|
23
|
+
export function usesPassageMacro(markup: string): boolean {
|
|
24
|
+
let tokens;
|
|
25
|
+
try {
|
|
26
|
+
tokens = tokenizeMarkup(markup);
|
|
27
|
+
} catch (err) {
|
|
28
|
+
if (err instanceof MarkupError) return true;
|
|
29
|
+
throw err;
|
|
30
|
+
}
|
|
31
|
+
return tokens.some(
|
|
32
|
+
(token) =>
|
|
33
|
+
token.type === 'macro' &&
|
|
34
|
+
!token.isClose &&
|
|
35
|
+
token.name.toLowerCase() === 'passage',
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
15
39
|
export function StoryInterface() {
|
|
16
40
|
const { storyData } = useStoryFields('storyData');
|
|
17
41
|
|
package/src/event-emitter.ts
CHANGED
|
@@ -23,6 +23,7 @@ type EventMap = {
|
|
|
23
23
|
afternavigate: (to: string, from: string, kind: NavigationKind) => void;
|
|
24
24
|
passagerender: (passage: string, element: HTMLElement) => void;
|
|
25
25
|
dialogrender: (passage: string, element: HTMLElement) => void;
|
|
26
|
+
dialogclose: (passage: string) => void;
|
|
26
27
|
};
|
|
27
28
|
|
|
28
29
|
export type StoryEvent = keyof EventMap;
|
|
@@ -41,6 +42,7 @@ const VALID_EVENTS = new Set<string>([
|
|
|
41
42
|
'afternavigate',
|
|
42
43
|
'passagerender',
|
|
43
44
|
'dialogrender',
|
|
45
|
+
'dialogclose',
|
|
44
46
|
]);
|
|
45
47
|
|
|
46
48
|
// Each event key maps to a Set of callbacks.
|
|
@@ -83,9 +85,9 @@ export function emit<E extends StoryEvent>(
|
|
|
83
85
|
}
|
|
84
86
|
|
|
85
87
|
/**
|
|
86
|
-
* Emit an event from inside a render commit (layout effect)
|
|
87
|
-
* handler is logged instead of propagating
|
|
88
|
-
* render; the remaining handlers still run.
|
|
88
|
+
* Emit an event from inside a render commit (layout effect), or once one is
|
|
89
|
+
* over (`dialogclose`). A throwing handler is logged instead of propagating
|
|
90
|
+
* into Preact and breaking the render; the remaining handlers still run.
|
|
89
91
|
*/
|
|
90
92
|
export function emitFromRender<E extends StoryEvent>(
|
|
91
93
|
event: E,
|
package/src/index.tsx
CHANGED
|
@@ -32,6 +32,7 @@ import { registerWidgetDefinitions } from './widgets/register-widget-def';
|
|
|
32
32
|
import { errorMessage } from './utils/error-message';
|
|
33
33
|
import type { ASTNode } from './markup/ast';
|
|
34
34
|
import { passageShown } from './components/macros/PassageDisplay';
|
|
35
|
+
import { usesPassageMacro } from './components/StoryInterface';
|
|
35
36
|
import './macros/register-builtins';
|
|
36
37
|
import builtinCSS from './styles.css?inline';
|
|
37
38
|
|
|
@@ -292,11 +293,11 @@ export function boot() {
|
|
|
292
293
|
// Wire up trigger system: check triggers on variable mutations, reinit on history nav/load
|
|
293
294
|
connectTriggersToStore();
|
|
294
295
|
|
|
295
|
-
// Warn if StoryInterface passage exists but doesn't
|
|
296
|
+
// Warn if StoryInterface passage exists but doesn't use {passage}
|
|
296
297
|
const storyInterfacePassage = storyData.passages.get('StoryInterface');
|
|
297
298
|
if (
|
|
298
299
|
storyInterfacePassage &&
|
|
299
|
-
!storyInterfacePassage.content
|
|
300
|
+
!usesPassageMacro(storyInterfacePassage.content)
|
|
300
301
|
) {
|
|
301
302
|
console.warn(
|
|
302
303
|
'spindle: StoryInterface passage does not contain {passage}. ' +
|
package/src/store.ts
CHANGED
|
@@ -58,6 +58,7 @@ import {
|
|
|
58
58
|
existingObjects,
|
|
59
59
|
locateObjects,
|
|
60
60
|
deepEqual,
|
|
61
|
+
deepEqualStrict,
|
|
61
62
|
mergesWith,
|
|
62
63
|
pathKey,
|
|
63
64
|
shareEqual,
|
|
@@ -549,6 +550,24 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
|
|
|
549
550
|
);
|
|
550
551
|
}
|
|
551
552
|
|
|
553
|
+
/** How many runs of settingUpStart() are under way. */
|
|
554
|
+
let startSetups = 0;
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Run `fn`, which sets up the start moment of a new game: the StoryInit
|
|
558
|
+
* passage, or the `storyinit` handlers at boot (unless a session was
|
|
559
|
+
* restored) and on restart. recordStoryInitState() records what it leaves
|
|
560
|
+
* behind, so recordMoment() has nothing to do meanwhile (see there).
|
|
561
|
+
*/
|
|
562
|
+
export function settingUpStart<T>(fn: () => T): T {
|
|
563
|
+
startSetups++;
|
|
564
|
+
try {
|
|
565
|
+
return fn();
|
|
566
|
+
} finally {
|
|
567
|
+
startSetups--;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
552
571
|
/**
|
|
553
572
|
* Record the state StoryInit left behind as the start moment: its variable
|
|
554
573
|
* snapshot (the history base) and PRNG state. Called by executeStoryInit()
|
|
@@ -571,6 +590,70 @@ export function recordStoryInitState(): void {
|
|
|
571
590
|
keepDrawsSoFar();
|
|
572
591
|
}
|
|
573
592
|
|
|
593
|
+
/**
|
|
594
|
+
* Record the live variables as the state of the current moment (see
|
|
595
|
+
* StoryState.recordMoment): what a navigation does for the moment it
|
|
596
|
+
* enters, without the navigation.
|
|
597
|
+
*/
|
|
598
|
+
function recordCurrentMoment(get: StoreGet, set: StoreSet): void {
|
|
599
|
+
const { storyData, history, historyIndex, variables } = get();
|
|
600
|
+
if (!storyData || historyIndex < 0) return;
|
|
601
|
+
// The start moment is recorded once StoryInit and the `storyinit` handlers
|
|
602
|
+
// have run (recordStoryInitState). A session written before that would
|
|
603
|
+
// hold it half set up, and a refresh would restore that over the StoryInit
|
|
604
|
+
// it runs again.
|
|
605
|
+
if (startSetups > 0 && history.length === 1) return;
|
|
606
|
+
// navigate() records the moment it entered, and writes the session, once
|
|
607
|
+
// the watchers reacting to it (this call is in one) have run
|
|
608
|
+
if (
|
|
609
|
+
navigationTriggerPhase &&
|
|
610
|
+
enteredMoment?.navigationId === get().navigationId
|
|
611
|
+
) {
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Nothing to record when the variables are as recorded (after a load the
|
|
616
|
+
// live ones are another object): the moments after this one stay
|
|
617
|
+
const recorded =
|
|
618
|
+
variables === lastNavigationVars ||
|
|
619
|
+
deepEqualStrict(reconstructVarsAt(historyIndex), variables);
|
|
620
|
+
if (!recorded) {
|
|
621
|
+
// The moment's patch is computed before anything changes: copying the
|
|
622
|
+
// values can throw (a getter), which must leave the history as it was
|
|
623
|
+
const entry =
|
|
624
|
+
historyIndex > 0
|
|
625
|
+
? computeVarPatches(reconstructVarsAt(historyIndex - 1), variables)
|
|
626
|
+
: null;
|
|
627
|
+
// What changed is new play: as on a navigation from here, the moments
|
|
628
|
+
// after this one are dropped
|
|
629
|
+
patchEntries.length = historyIndex;
|
|
630
|
+
// patchEntries[i] leads from moment i to moment i + 1
|
|
631
|
+
if (entry) patchEntries[historyIndex - 1] = entry;
|
|
632
|
+
else variableBase = variables;
|
|
633
|
+
// The session takes the moment anew, with the variables as they are
|
|
634
|
+
if (sessionMoments.length > historyIndex) {
|
|
635
|
+
sessionMoments.length = historyIndex;
|
|
636
|
+
}
|
|
637
|
+
// The next navigate() diffs from this recorded snapshot
|
|
638
|
+
lastNavigationVars = variables;
|
|
639
|
+
if (historyIndex < history.length - 1) {
|
|
640
|
+
set((state) => {
|
|
641
|
+
state.history = state.history.slice(0, historyIndex + 1);
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
// What the watchers the passage's render consumed did is recorded now:
|
|
645
|
+
// a load must not bring them back to do it again
|
|
646
|
+
clearReplayWatchers();
|
|
647
|
+
}
|
|
648
|
+
// A save whose `beforesave` hooks are running (this call is in one) saves
|
|
649
|
+
// the moment as recorded here: only what the hooks change from now on is
|
|
650
|
+
// still to be written into its snapshot (see keepHookWrites)
|
|
651
|
+
for (const capture of hookCaptures) capture.before = variables;
|
|
652
|
+
// The moment keeps the PRNG state it was entered with: a load renders the
|
|
653
|
+
// passage again, and its rolls replay from there
|
|
654
|
+
if (!recorded) persistSessionThen(get);
|
|
655
|
+
}
|
|
656
|
+
|
|
574
657
|
// ---------------------------------------------------------------------------
|
|
575
658
|
// Playthrough setup
|
|
576
659
|
// ---------------------------------------------------------------------------
|
|
@@ -837,12 +920,20 @@ function loadedEntryMoment(
|
|
|
837
920
|
return moment;
|
|
838
921
|
}
|
|
839
922
|
|
|
840
|
-
/**
|
|
841
|
-
|
|
923
|
+
/**
|
|
924
|
+
* A save whose `beforesave` hooks are running: the variables the hooks
|
|
925
|
+
* started from, and the variable paths `Story.set` has written since.
|
|
926
|
+
*/
|
|
927
|
+
interface HookCapture {
|
|
928
|
+
before: Record<string, unknown>;
|
|
929
|
+
writes: Map<string, string[]>;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
const hookCaptures = new Set<HookCapture>();
|
|
842
933
|
|
|
843
934
|
/** Note that `path` of the variables was written (see keepHookWrites). */
|
|
844
935
|
export function recordHookWrite(path: string[]): void {
|
|
845
|
-
for (const writes of
|
|
936
|
+
for (const { writes } of hookCaptures) writes.set(pathKey(path), path);
|
|
846
937
|
}
|
|
847
938
|
|
|
848
939
|
/**
|
|
@@ -1034,6 +1125,15 @@ export interface StoryState {
|
|
|
1034
1125
|
navigate: (passageName: string) => void;
|
|
1035
1126
|
goBack: () => void;
|
|
1036
1127
|
goForward: () => void;
|
|
1128
|
+
/**
|
|
1129
|
+
* Record the story variables as they are now as the current moment's
|
|
1130
|
+
* recorded state, without navigating: a page refresh, a save made here
|
|
1131
|
+
* and loaded, and moving back to the moment then restore them, not the
|
|
1132
|
+
* state on entering the passage. Writes the session. Moments after the
|
|
1133
|
+
* current one are dropped, as a navigation from it drops them. Does
|
|
1134
|
+
* nothing when the variables are as recorded.
|
|
1135
|
+
*/
|
|
1136
|
+
recordMoment: () => void;
|
|
1037
1137
|
setVariable: (name: string, value: unknown) => void;
|
|
1038
1138
|
setTemporary: (name: string, value: unknown) => void;
|
|
1039
1139
|
deleteVariable: (name: string) => void;
|
|
@@ -1159,6 +1259,7 @@ const PROGRAM_ORDER_ACTIONS = [
|
|
|
1159
1259
|
'navigate',
|
|
1160
1260
|
'goBack',
|
|
1161
1261
|
'goForward',
|
|
1262
|
+
'recordMoment',
|
|
1162
1263
|
'restart',
|
|
1163
1264
|
'save',
|
|
1164
1265
|
'load',
|
|
@@ -1507,6 +1608,8 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1507
1608
|
|
|
1508
1609
|
goForward: () => moveInHistory(get, set, 1),
|
|
1509
1610
|
|
|
1611
|
+
recordMoment: () => recordCurrentMoment(get, set),
|
|
1612
|
+
|
|
1510
1613
|
setVariable: (name: string, value: unknown) => {
|
|
1511
1614
|
set((state) => {
|
|
1512
1615
|
checkVariableName(name, `$${name}`);
|
|
@@ -1608,7 +1711,7 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1608
1711
|
|
|
1609
1712
|
executeStoryInit();
|
|
1610
1713
|
clearSession(storyData.ifid);
|
|
1611
|
-
emit('storyinit');
|
|
1714
|
+
settingUpStart(() => emit('storyinit'));
|
|
1612
1715
|
// The storyinit handlers' changes belong to the start moment too
|
|
1613
1716
|
recordStoryInitState();
|
|
1614
1717
|
},
|
|
@@ -1831,12 +1934,14 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1831
1934
|
},
|
|
1832
1935
|
|
|
1833
1936
|
beginSave: () => {
|
|
1834
|
-
const
|
|
1937
|
+
const capture: HookCapture = {
|
|
1938
|
+
before: get().variables,
|
|
1939
|
+
writes: new Map(),
|
|
1940
|
+
};
|
|
1835
1941
|
const replaced = latestStateApplied;
|
|
1836
|
-
|
|
1837
|
-
hookWrites.add(writes);
|
|
1942
|
+
hookCaptures.add(capture);
|
|
1838
1943
|
const dispose = () => {
|
|
1839
|
-
|
|
1944
|
+
hookCaptures.delete(capture);
|
|
1840
1945
|
};
|
|
1841
1946
|
return Object.assign(
|
|
1842
1947
|
() => {
|
|
@@ -1849,8 +1954,8 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1849
1954
|
);
|
|
1850
1955
|
}
|
|
1851
1956
|
const payload = get().getSavePayload();
|
|
1852
|
-
keepHookWrites(payload, before, get().variables, [
|
|
1853
|
-
...writes.values(),
|
|
1957
|
+
keepHookWrites(payload, capture.before, get().variables, [
|
|
1958
|
+
...capture.writes.values(),
|
|
1854
1959
|
]);
|
|
1855
1960
|
return payload;
|
|
1856
1961
|
},
|
package/src/story-api.ts
CHANGED
|
@@ -136,6 +136,7 @@ export interface StoryAPI {
|
|
|
136
136
|
goto(passageName: string): void;
|
|
137
137
|
back(): void;
|
|
138
138
|
forward(): void;
|
|
139
|
+
recordMoment(): void;
|
|
139
140
|
restart(): void;
|
|
140
141
|
save(slot?: string, custom?: Record<string, unknown>): Promise<void>;
|
|
141
142
|
load(slot?: string): Promise<void>;
|
|
@@ -369,6 +370,7 @@ function createStoryAPI(): StoryAPI {
|
|
|
369
370
|
goto: storeAction('navigate'),
|
|
370
371
|
back: storeAction('goBack'),
|
|
371
372
|
forward: storeAction('goForward'),
|
|
373
|
+
recordMoment: storeAction('recordMoment'),
|
|
372
374
|
restart: storeAction('restart'),
|
|
373
375
|
save: storeAction('save'),
|
|
374
376
|
load: storeAction('load'),
|
package/src/story-init.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { ActionsDisabledContext } from './hooks/use-action';
|
|
2
2
|
import { h, render } from 'preact';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
useStoryStore,
|
|
5
|
+
recordStoryInitState,
|
|
6
|
+
settingUpStart,
|
|
7
|
+
missingPassage,
|
|
8
|
+
} from './store';
|
|
4
9
|
import { parseMarkup } from './markup/parse';
|
|
5
10
|
import { registerWidgetDefinitions } from './widgets/register-widget-def';
|
|
6
11
|
import { renderNodes } from './markup/render';
|
|
@@ -49,13 +54,15 @@ export function executeStoryInit() {
|
|
|
49
54
|
container.style.display = 'none';
|
|
50
55
|
document.body.appendChild(container);
|
|
51
56
|
storyInitContainer = container;
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
+
settingUpStart(() =>
|
|
58
|
+
render(
|
|
59
|
+
h(
|
|
60
|
+
ActionsDisabledContext.Provider,
|
|
61
|
+
{ value: true },
|
|
62
|
+
h(() => renderNodes(ast), null),
|
|
63
|
+
),
|
|
64
|
+
container,
|
|
57
65
|
),
|
|
58
|
-
container,
|
|
59
66
|
);
|
|
60
67
|
|
|
61
68
|
// The start moment was recorded before StoryInit ran; its synchronous
|
|
@@ -94,11 +101,9 @@ export function initializeStory(session?: SavePayload): void {
|
|
|
94
101
|
|
|
95
102
|
if (session) {
|
|
96
103
|
useStoryStore.getState().loadFromPayload(session);
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (!session) {
|
|
104
|
+
emit('storyinit');
|
|
105
|
+
} else {
|
|
106
|
+
settingUpStart(() => emit('storyinit'));
|
|
102
107
|
recordStoryInitState();
|
|
103
108
|
}
|
|
104
109
|
}
|