@rohal12/spindle 0.59.29 → 0.59.31
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/README.md +1 -0
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +947 -351
- package/dist/pkg/macro-registry.js +19 -0
- package/dist/pkg/macro-registry.json +19 -0
- package/dist/pkg/story-variables.js +780 -107
- package/package.json +1 -1
- package/src/action-registry.ts +59 -5
- package/src/automation/load-yaml.ts +111 -20
- package/src/automation/runner.ts +19 -13
- package/src/automation/types.ts +7 -5
- package/src/class-registry.ts +8 -5
- package/src/code-check.ts +87 -20
- package/src/components/macros/Checkbox.tsx +5 -2
- package/src/components/macros/Cycle.tsx +1 -0
- package/src/components/macros/For.tsx +1 -7
- package/src/components/macros/Listbox.tsx +1 -0
- package/src/components/macros/MenubarButtons.tsx +6 -1
- package/src/components/macros/Nobr.tsx +1 -0
- package/src/components/macros/PassageDisplay.tsx +136 -10
- package/src/components/macros/Radiobutton.tsx +1 -0
- package/src/components/macros/Repeat.tsx +4 -2
- package/src/components/macros/SaveManager.tsx +30 -8
- package/src/components/macros/SettingsControls.tsx +19 -4
- package/src/components/macros/Span.tsx +1 -0
- package/src/components/macros/StoryTitle.tsx +1 -0
- package/src/components/macros/Unset.tsx +26 -13
- package/src/components/macros/VarDisplay.tsx +2 -3
- package/src/components/macros/WidgetInvocation.tsx +5 -6
- package/src/components/macros/input-macro.ts +1 -0
- package/src/components/macros/locals-scope.tsx +19 -8
- package/src/components/macros/macro-args.ts +11 -3
- package/src/expression.ts +34 -18
- package/src/hooks/use-merged-locals.ts +17 -2
- package/src/hooks/use-modal-focus.ts +247 -133
- package/src/index.tsx +32 -21
- package/src/js-bindings.ts +594 -0
- package/src/js-lexer.ts +76 -14
- package/src/macro-discovery.ts +83 -32
- package/src/markup/ast.ts +22 -1
- package/src/markup/render.tsx +44 -15
- package/src/parser.ts +41 -10
- package/src/prng.ts +24 -1
- package/src/saves/save-manager.ts +36 -9
- package/src/static-literal.ts +87 -16
- package/src/store.ts +83 -6
- package/src/story-api.ts +23 -6
- package/src/story-variables.ts +91 -28
- package/src/structural.ts +26 -15
- package/src/tooling.ts +24 -10
- package/src/transform.ts +22 -7
- package/src/utils/macro-names.ts +4 -0
- package/src/utils/namespace.ts +15 -2
- package/src/utils/object-path.ts +2 -2
- package/src/utils/stable-key.ts +17 -6
- package/src/utils/value-kinds.ts +38 -1
- package/src/widgets/ast-scanner.ts +4 -1
- package/src/widgets/register-widget-def.ts +2 -3
- package/src/widgets/widget-def.ts +36 -6
- package/src/widgets/widget-registry.ts +6 -2
- package/types/index.d.ts +12 -5
- package/types/tooling.d.ts +12 -2
|
@@ -230,11 +230,36 @@ async function ensurePlaythrough(
|
|
|
230
230
|
id: string,
|
|
231
231
|
createdAt: string,
|
|
232
232
|
): Promise<void> {
|
|
233
|
+
if (!(await hasPlaythroughNow(ifid, id))) {
|
|
234
|
+
await (
|
|
235
|
+
await getBackend()
|
|
236
|
+
).putPlaythrough({ id, ifid, createdAt, label: 'Imported' });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Whether the story has a record of the playthrough `id`. */
|
|
241
|
+
async function hasPlaythroughNow(ifid: string, id: string): Promise<boolean> {
|
|
233
242
|
const backend = await getBackend();
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
243
|
+
return (await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === id);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The playthrough a save of a game in `id` belongs to: `id` if it has a
|
|
248
|
+
* record. Another tab may have deleted it since this tab cached it (#527),
|
|
249
|
+
* and a save in a playthrough without a record is grouped as "Unknown" for
|
|
250
|
+
* good. The save then joins the story's current playthrough (the one that
|
|
251
|
+
* tab went on in), or a new one if that has no record either; callers hand
|
|
252
|
+
* the result to the live game (see followSavedPlaythrough in the store).
|
|
253
|
+
*/
|
|
254
|
+
async function livePlaythroughNow(ifid: string, id: string): Promise<string> {
|
|
255
|
+
if (await hasPlaythroughNow(ifid, id)) return id;
|
|
256
|
+
const backend = await getBackend();
|
|
257
|
+
const current = await backend.getMeta<string>(currentPlaythroughKey(ifid));
|
|
258
|
+
if (current && (await hasPlaythroughNow(ifid, current))) {
|
|
259
|
+
saveSessionPlaythrough(ifid, current);
|
|
260
|
+
return current;
|
|
237
261
|
}
|
|
262
|
+
return startNewPlaythroughNow(ifid);
|
|
238
263
|
}
|
|
239
264
|
|
|
240
265
|
/**
|
|
@@ -251,9 +276,7 @@ export function establishPlaythrough(
|
|
|
251
276
|
// the shared current one is the default for a visit with no session,
|
|
252
277
|
// and may belong to what another tab has done since (#356).
|
|
253
278
|
const own = loadSessionPlaythrough(ifid);
|
|
254
|
-
const ownExists =
|
|
255
|
-
own !== undefined &&
|
|
256
|
-
(await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === own);
|
|
279
|
+
const ownExists = own !== undefined && (await hasPlaythroughNow(ifid, own));
|
|
257
280
|
const id = ownExists
|
|
258
281
|
? own
|
|
259
282
|
: ((await backend.getMeta<string>(currentPlaythroughKey(ifid))) ??
|
|
@@ -321,8 +344,9 @@ async function createSaveNow(
|
|
|
321
344
|
payload: SavePayload,
|
|
322
345
|
custom: Record<string, unknown> = {},
|
|
323
346
|
): Promise<SaveRecord> {
|
|
324
|
-
const
|
|
325
|
-
if (!
|
|
347
|
+
const requested = await playthroughPromise;
|
|
348
|
+
if (!requested) throw new Error('No playthrough');
|
|
349
|
+
const playthroughId = await livePlaythroughNow(ifid, requested);
|
|
326
350
|
const now = new Date().toISOString();
|
|
327
351
|
const meta: SaveMeta = {
|
|
328
352
|
id: randomUUID(),
|
|
@@ -369,10 +393,13 @@ async function overwriteSaveNow(
|
|
|
369
393
|
custom?: Record<string, unknown>,
|
|
370
394
|
playthroughPromise?: string | PromiseLike<string>,
|
|
371
395
|
): Promise<SaveRecord | undefined> {
|
|
372
|
-
const
|
|
396
|
+
const requested = await playthroughPromise;
|
|
373
397
|
const backend = await getBackend();
|
|
374
398
|
const existing = await backend.getSave(saveId);
|
|
375
399
|
if (!existing) return undefined;
|
|
400
|
+
const playthroughId = requested
|
|
401
|
+
? await livePlaythroughNow(existing.meta.ifid, requested)
|
|
402
|
+
: undefined;
|
|
376
403
|
|
|
377
404
|
const updated = storedRecord(
|
|
378
405
|
{
|
package/src/static-literal.ts
CHANGED
|
@@ -7,7 +7,13 @@
|
|
|
7
7
|
* an operator, a reference, a spread) is "not static", which is no error: the
|
|
8
8
|
* value is simply not known without running the code.
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
lexJs,
|
|
12
|
+
scanStringLiteral,
|
|
13
|
+
stringLiteralValue,
|
|
14
|
+
type JsGoal,
|
|
15
|
+
type JsLexHandlers,
|
|
16
|
+
} from './js-lexer';
|
|
11
17
|
|
|
12
18
|
/** The type of a variable by its default (see story-variables.ts VarType). */
|
|
13
19
|
type LiteralType =
|
|
@@ -45,11 +51,13 @@ export type StaticLiteral =
|
|
|
45
51
|
type Members = Map<string, LiteralShape | UnsupportedLiteral | null>;
|
|
46
52
|
|
|
47
53
|
const NUMBER_RE =
|
|
48
|
-
/(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d
|
|
54
|
+
/(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)(n?)/y;
|
|
49
55
|
const IDENT_RE = /[A-Za-z_$][\w$]*/y;
|
|
50
56
|
const KEY_RE = /[\w$]+/y;
|
|
51
57
|
const ARROW_RE =
|
|
52
58
|
/(?:async\s+)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*=>/y;
|
|
59
|
+
/** The end of a line: the four line terminators of JavaScript. */
|
|
60
|
+
const LINE_END_RE = /[\n\r\u2028\u2029]/g;
|
|
53
61
|
const ARRAY_INDEX_RE = /^(?:0|[1-9]\d{0,8})$/;
|
|
54
62
|
|
|
55
63
|
const UNSUPPORTED_UNDEFINED: UnsupportedLiteral = {
|
|
@@ -78,6 +86,34 @@ function entryOrder(keys: Iterable<string>): string[] {
|
|
|
78
86
|
return [...indices, ...all.filter((key) => !ARRAY_INDEX_RE.test(key))];
|
|
79
87
|
}
|
|
80
88
|
|
|
89
|
+
/**
|
|
90
|
+
* Where the regex literals in `src` are, by their start: JavaScript text
|
|
91
|
+
* cannot tell a regex from a division without the code before it, which the
|
|
92
|
+
* lexer reads. `handlers` see the same walk.
|
|
93
|
+
*/
|
|
94
|
+
export function regexLiterals(
|
|
95
|
+
src: string,
|
|
96
|
+
goal: JsGoal = 'expression',
|
|
97
|
+
handlers: JsLexHandlers = {},
|
|
98
|
+
): Map<number, number> {
|
|
99
|
+
const ends = new Map<number, number>();
|
|
100
|
+
lexJs(
|
|
101
|
+
src,
|
|
102
|
+
{
|
|
103
|
+
...handlers,
|
|
104
|
+
literal(text, index, nesting) {
|
|
105
|
+
// A comment is `//` or `/*`, which no regex starts with
|
|
106
|
+
if (text.charAt(0) === '/' && !/^\/[/*]/.test(text)) {
|
|
107
|
+
ends.set(index, index + text.length);
|
|
108
|
+
}
|
|
109
|
+
handlers.literal?.(text, index, nesting);
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
goal,
|
|
113
|
+
);
|
|
114
|
+
return ends;
|
|
115
|
+
}
|
|
116
|
+
|
|
81
117
|
/** `String(value)` of a BigInt literal's digits, or `undefined` if they are no BigInt. */
|
|
82
118
|
function bigintValue(digits: string): string | undefined {
|
|
83
119
|
try {
|
|
@@ -93,7 +129,20 @@ function bigintValue(digits: string): string | undefined {
|
|
|
93
129
|
*/
|
|
94
130
|
export class Reader {
|
|
95
131
|
i = 0;
|
|
96
|
-
|
|
132
|
+
private regexes: Map<number, number> | undefined;
|
|
133
|
+
private readonly goal: JsGoal;
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* `regexes` (see regexLiterals) are read from `src` when they are first
|
|
137
|
+
* needed, unless the caller has them already.
|
|
138
|
+
*/
|
|
139
|
+
constructor(
|
|
140
|
+
protected readonly src: string,
|
|
141
|
+
options: { goal?: JsGoal; regexes?: Map<number, number> } = {},
|
|
142
|
+
) {
|
|
143
|
+
this.goal = options.goal ?? 'expression';
|
|
144
|
+
this.regexes = options.regexes;
|
|
145
|
+
}
|
|
97
146
|
|
|
98
147
|
/** Skip whitespace and comments. */
|
|
99
148
|
space(): void {
|
|
@@ -101,8 +150,8 @@ export class Reader {
|
|
|
101
150
|
for (;;) {
|
|
102
151
|
while (/\s/.test(src.charAt(this.i))) this.i++;
|
|
103
152
|
if (src.startsWith('//', this.i)) {
|
|
104
|
-
|
|
105
|
-
this.i =
|
|
153
|
+
LINE_END_RE.lastIndex = this.i;
|
|
154
|
+
this.i = LINE_END_RE.test(src) ? LINE_END_RE.lastIndex - 1 : src.length;
|
|
106
155
|
} else if (src.startsWith('/*', this.i)) {
|
|
107
156
|
const end = src.indexOf('*/', this.i + 2);
|
|
108
157
|
this.i = end < 0 ? src.length : end + 2;
|
|
@@ -170,10 +219,9 @@ export class Reader {
|
|
|
170
219
|
i++;
|
|
171
220
|
while (/\s/.test(src.charAt(i))) i++;
|
|
172
221
|
}
|
|
173
|
-
|
|
174
|
-
const match = NUMBER_RE.exec(src);
|
|
222
|
+
const match = this.numberAt(i);
|
|
175
223
|
if (match) {
|
|
176
|
-
this.i =
|
|
224
|
+
this.i = i + match[0].length;
|
|
177
225
|
if (!match[1]) return { shape: { type: 'number' } };
|
|
178
226
|
// A BigInt: `+1n` throws, `-1n` and `1n` are values no variable can hold
|
|
179
227
|
if (sign === '+') {
|
|
@@ -189,13 +237,19 @@ export class Reader {
|
|
|
189
237
|
}
|
|
190
238
|
IDENT_RE.lastIndex = i;
|
|
191
239
|
const word = IDENT_RE.exec(src)?.[0];
|
|
192
|
-
if (word === 'Infinity') {
|
|
240
|
+
if (word === 'Infinity' || word === 'NaN') {
|
|
193
241
|
this.i = IDENT_RE.lastIndex;
|
|
194
242
|
return { shape: { type: 'number' } };
|
|
195
243
|
}
|
|
196
244
|
return undefined;
|
|
197
245
|
}
|
|
198
246
|
|
|
247
|
+
/** The numeric literal (a BigInt's `n` is `match[1]`) at `at`, if there is one. */
|
|
248
|
+
private numberAt(at: number): RegExpExecArray | null {
|
|
249
|
+
NUMBER_RE.lastIndex = at;
|
|
250
|
+
return NUMBER_RE.exec(this.src);
|
|
251
|
+
}
|
|
252
|
+
|
|
199
253
|
/** A keyword, a function, or a name (which is not static). */
|
|
200
254
|
protected word(): StaticLiteral {
|
|
201
255
|
const { src } = this;
|
|
@@ -216,6 +270,7 @@ export class Reader {
|
|
|
216
270
|
this.i = end;
|
|
217
271
|
return { shape: { type: 'null' } };
|
|
218
272
|
case 'NaN':
|
|
273
|
+
case 'Infinity':
|
|
219
274
|
this.i = end;
|
|
220
275
|
return { shape: { type: 'number' } };
|
|
221
276
|
case 'undefined':
|
|
@@ -381,17 +436,24 @@ export class Reader {
|
|
|
381
436
|
const { src } = this;
|
|
382
437
|
const c = src.charAt(this.i);
|
|
383
438
|
if (c === '"' || c === "'") return this.stringValue();
|
|
439
|
+
if (/[\d.]/.test(c)) return this.numberKey();
|
|
384
440
|
KEY_RE.lastIndex = this.i;
|
|
385
441
|
const found = KEY_RE.exec(src)?.[0];
|
|
386
442
|
if (found === undefined) return undefined;
|
|
387
443
|
this.i = KEY_RE.lastIndex;
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
444
|
+
return found;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** A number as a key: the whole literal, named as the runtime names it. */
|
|
448
|
+
private numberKey(): string | undefined {
|
|
449
|
+
const match = this.numberAt(this.i);
|
|
450
|
+
if (!match) return undefined;
|
|
451
|
+
this.i += match[0].length;
|
|
452
|
+
// `1a` is no number
|
|
453
|
+
if (/[\w$]/.test(this.src.charAt(this.i))) return undefined;
|
|
454
|
+
const digits = match[0].replace(/_/g, '');
|
|
455
|
+
if (/^0\d/.test(digits)) return undefined; // legacy octal
|
|
456
|
+
if (match[1]) return bigintValue(digits.slice(0, -1));
|
|
395
457
|
const value = Number(digits);
|
|
396
458
|
return Number.isNaN(value) ? undefined : String(value);
|
|
397
459
|
}
|
|
@@ -433,6 +495,15 @@ export class Reader {
|
|
|
433
495
|
this.space();
|
|
434
496
|
return true;
|
|
435
497
|
}
|
|
498
|
+
if (c === '/') {
|
|
499
|
+
// A regex literal, whose brackets and quotes are no JavaScript structure
|
|
500
|
+
this.regexes ??= regexLiterals(src, this.goal);
|
|
501
|
+
const end = this.regexes.get(this.i);
|
|
502
|
+
if (end !== undefined) {
|
|
503
|
+
this.i = end;
|
|
504
|
+
return true;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
436
507
|
if (c === '[' || c === '{' || c === '(') return this.skipBalanced();
|
|
437
508
|
if (c === ']' || c === '}' || c === ')') return false;
|
|
438
509
|
this.i++;
|
package/src/store.ts
CHANGED
|
@@ -61,12 +61,14 @@ import {
|
|
|
61
61
|
type PathChange,
|
|
62
62
|
} from './structural';
|
|
63
63
|
import { getByPath } from './utils/object-path';
|
|
64
|
+
import { isIndexKey } from './utils/value-kinds';
|
|
64
65
|
import { noPassageError, showRuntimeError } from './runtime-errors';
|
|
65
66
|
import {
|
|
66
67
|
snapshotPRNG,
|
|
67
68
|
restorePRNG,
|
|
68
69
|
resetPRNG,
|
|
69
70
|
withoutDraws,
|
|
71
|
+
keepDrawsSoFar,
|
|
70
72
|
type PRNGSnapshot,
|
|
71
73
|
} from './prng';
|
|
72
74
|
import { errorMessage } from './utils/error-message';
|
|
@@ -480,6 +482,17 @@ function enterStart(
|
|
|
480
482
|
state.historyIndex = 0;
|
|
481
483
|
}
|
|
482
484
|
|
|
485
|
+
/**
|
|
486
|
+
* Run `fn` (an event's handlers) and tell whether they replaced the game
|
|
487
|
+
* state (a restart or load): what the caller was about to do to the game it
|
|
488
|
+
* emitted from is then not to be done to the new one (#516, #517).
|
|
489
|
+
*/
|
|
490
|
+
function replacesState(fn: () => void): boolean {
|
|
491
|
+
const applied = latestStateApplied;
|
|
492
|
+
fn();
|
|
493
|
+
return latestStateApplied !== applied;
|
|
494
|
+
}
|
|
495
|
+
|
|
483
496
|
/**
|
|
484
497
|
* Move through history by `step` moments (back or forward), restoring the
|
|
485
498
|
* snapshot recorded for the moment moved to: live variables may hold edits
|
|
@@ -493,7 +506,13 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
|
|
|
493
506
|
|
|
494
507
|
const previousPassage = get().currentPassage;
|
|
495
508
|
const targetPassage = history[target]!.passage;
|
|
509
|
+
// The target is a place in the history as it is now: a callback that went
|
|
510
|
+
// elsewhere (a restart, a load, a navigation or traversal of its own) took
|
|
511
|
+
// the game on, and this traversal is dropped rather than applied to a
|
|
512
|
+
// history that is no longer the one it was computed from (#516)
|
|
513
|
+
const navigation = get().navigationId;
|
|
496
514
|
emit('beforenavigate', targetPassage);
|
|
515
|
+
if (get().navigationId !== navigation) return;
|
|
497
516
|
|
|
498
517
|
const restoredVars = deepClone(reconstructVarsAt(target));
|
|
499
518
|
|
|
@@ -509,6 +528,7 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
|
|
|
509
528
|
reinitTriggerState();
|
|
510
529
|
lastNavigationVars = get().variables;
|
|
511
530
|
restorePRNGFromMoment(get().history[get().historyIndex]);
|
|
531
|
+
keepDrawsSoFar();
|
|
512
532
|
persistSessionThen(get, () =>
|
|
513
533
|
emit('afternavigate', targetPassage, previousPassage),
|
|
514
534
|
);
|
|
@@ -532,6 +552,7 @@ export function recordStoryInitState(): void {
|
|
|
532
552
|
useStoryStore.setState((state) => {
|
|
533
553
|
state.history[0]!.prng = prng;
|
|
534
554
|
});
|
|
555
|
+
keepDrawsSoFar();
|
|
535
556
|
}
|
|
536
557
|
|
|
537
558
|
// ---------------------------------------------------------------------------
|
|
@@ -655,6 +676,24 @@ function switchToLoadedPlaythrough(ifid: string, id: string): void {
|
|
|
655
676
|
switchToPlaythrough(id, stored);
|
|
656
677
|
}
|
|
657
678
|
|
|
679
|
+
/**
|
|
680
|
+
* Move the running game to the playthrough a save it wrote was stored in,
|
|
681
|
+
* when that is not the one it asked for: another tab deleted the game's
|
|
682
|
+
* playthrough, and the save took the story's current one (#527). `requested`
|
|
683
|
+
* is the playthrough the save was issued with (see resolvePlaythroughId). A
|
|
684
|
+
* game that has switched since (a restart, a load) stays where it is.
|
|
685
|
+
*/
|
|
686
|
+
export async function followSavedPlaythrough(
|
|
687
|
+
requested: string | PromiseLike<string>,
|
|
688
|
+
saved: { meta: { playthroughId: string } } | undefined,
|
|
689
|
+
): Promise<void> {
|
|
690
|
+
const id = saved?.meta.playthroughId;
|
|
691
|
+
const asked = await requested;
|
|
692
|
+
if (id && id !== asked && knownPlaythroughId() === asked) {
|
|
693
|
+
switchToPlaythrough(id, Promise.resolve());
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
658
697
|
// ---------------------------------------------------------------------------
|
|
659
698
|
// Superseded loads
|
|
660
699
|
// ---------------------------------------------------------------------------
|
|
@@ -813,7 +852,7 @@ function keepHookWrites(
|
|
|
813
852
|
keys.add(pathKey(path));
|
|
814
853
|
const value = getByPath(after, path);
|
|
815
854
|
if (deepEqual(getByPath(moment.variables, path), value)) continue;
|
|
816
|
-
changes.push({ path, deleted: false, value });
|
|
855
|
+
changes.push({ path, deleted: false, value, absolute: true });
|
|
817
856
|
}
|
|
818
857
|
if (changes.length === 0) return;
|
|
819
858
|
// A copy of its own, so the writes keep the snapshot's references (which
|
|
@@ -832,7 +871,8 @@ function keepHookWrites(
|
|
|
832
871
|
* value of it is written. Into an array, elements removed from the end are
|
|
833
872
|
* removed at the same indices and elements added are appended; changes at
|
|
834
873
|
* indices the array lacks are dropped (it was resized, so its indices do not
|
|
835
|
-
* line up with the live ones).
|
|
874
|
+
* line up with the live ones). The hooks' explicit writes are not diffs: an
|
|
875
|
+
* array's length or an element they set is set to that value (#515).
|
|
836
876
|
*/
|
|
837
877
|
function writeHookChange(
|
|
838
878
|
work: Record<string, unknown>,
|
|
@@ -865,7 +905,9 @@ function writeKey(
|
|
|
865
905
|
change?: PathChange,
|
|
866
906
|
): void {
|
|
867
907
|
const deleted = change?.deleted ?? false;
|
|
868
|
-
|
|
908
|
+
// The elements of an array and its length; its other keys are the fields of
|
|
909
|
+
// a subclass instance (#490)
|
|
910
|
+
if (Array.isArray(holder) && (key === 'length' || isIndexKey(key))) {
|
|
869
911
|
const index = Number(key);
|
|
870
912
|
if (deleted) {
|
|
871
913
|
// A hole stays where it was; anything else was cut off
|
|
@@ -875,6 +917,11 @@ function writeKey(
|
|
|
875
917
|
// After the holes it followed
|
|
876
918
|
holder.length += change.gap ?? 0;
|
|
877
919
|
holder.push(value);
|
|
920
|
+
} else if (change && 'absolute' in change) {
|
|
921
|
+
// A write the hooks made: the length or element they set, whatever
|
|
922
|
+
// the snapshot's array looks like
|
|
923
|
+
if (key === 'length') holder.length = value as number;
|
|
924
|
+
else holder[index] = value;
|
|
878
925
|
} else if (key === 'length' && change) {
|
|
879
926
|
// Holes added at the end
|
|
880
927
|
holder.length += value as number;
|
|
@@ -1361,7 +1408,9 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1361
1408
|
}
|
|
1362
1409
|
|
|
1363
1410
|
const previousPassage = get().currentPassage;
|
|
1364
|
-
|
|
1411
|
+
// A callback that restarted or loaded replaced the game this
|
|
1412
|
+
// navigation was requested in: it does not carry on into the new one
|
|
1413
|
+
if (replacesState(() => emit('beforenavigate', passageName))) return;
|
|
1365
1414
|
|
|
1366
1415
|
// Compute variable delta before Immer set(). Read the variables after
|
|
1367
1416
|
// beforenavigate so changes made by its handlers are recorded.
|
|
@@ -1410,8 +1459,16 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1410
1459
|
const deferred = deferredNavigations;
|
|
1411
1460
|
deferredNavigations = [];
|
|
1412
1461
|
finishEnteredMoment(get, set);
|
|
1462
|
+
// The draws so far are the entered moment's recorded position
|
|
1463
|
+
keepDrawsSoFar();
|
|
1413
1464
|
persistSessionThen(get, () => {
|
|
1414
|
-
|
|
1465
|
+
if (
|
|
1466
|
+
replacesState(() =>
|
|
1467
|
+
emit('afternavigate', passageName, previousPassage),
|
|
1468
|
+
)
|
|
1469
|
+
) {
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1415
1472
|
for (const next of deferred) get().navigate(next);
|
|
1416
1473
|
});
|
|
1417
1474
|
},
|
|
@@ -1538,7 +1595,14 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1538
1595
|
state.saveError = null;
|
|
1539
1596
|
});
|
|
1540
1597
|
// Queued now, in call order with other storage operations
|
|
1541
|
-
await quickSave(
|
|
1598
|
+
const saved = await quickSave(
|
|
1599
|
+
storyData.ifid,
|
|
1600
|
+
playthrough,
|
|
1601
|
+
payload,
|
|
1602
|
+
slot,
|
|
1603
|
+
custom,
|
|
1604
|
+
);
|
|
1605
|
+
await followSavedPlaythrough(playthrough, saved);
|
|
1542
1606
|
recordKnownSave(set, slot, true);
|
|
1543
1607
|
}),
|
|
1544
1608
|
'spindle: failed to save',
|
|
@@ -1737,10 +1801,18 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1737
1801
|
|
|
1738
1802
|
beginSave: () => {
|
|
1739
1803
|
const before = get().variables;
|
|
1804
|
+
const replaced = latestStateApplied;
|
|
1740
1805
|
const writes = new Map<string, string[]>();
|
|
1741
1806
|
hookWrites = writes;
|
|
1742
1807
|
return () => {
|
|
1743
1808
|
if (hookWrites === writes) hookWrites = null;
|
|
1809
|
+
// A restart or load in a hook left the game the save was issued
|
|
1810
|
+
// for (its playthrough) for another: no save describes both
|
|
1811
|
+
if (latestStateApplied !== replaced) {
|
|
1812
|
+
throw new Error(
|
|
1813
|
+
'spindle: a beforesave handler restarted or loaded the game, so the save was not made',
|
|
1814
|
+
);
|
|
1815
|
+
}
|
|
1744
1816
|
const payload = get().getSavePayload();
|
|
1745
1817
|
keepHookWrites(payload, before, get().variables, [...writes.values()]);
|
|
1746
1818
|
return payload;
|
|
@@ -1773,6 +1845,10 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1773
1845
|
} finally {
|
|
1774
1846
|
leavingPlaythrough = null;
|
|
1775
1847
|
}
|
|
1848
|
+
// A restart or load its handlers issued replaced the game after this
|
|
1849
|
+
// load did: the later one wins, as one issued after the load returned
|
|
1850
|
+
// would (#517)
|
|
1851
|
+
if (latestStateApplied !== replacement) return;
|
|
1776
1852
|
|
|
1777
1853
|
// Loading a save moves the game to the save's playthrough, after the
|
|
1778
1854
|
// `beforeload` handlers (whose saves belong to the game being left).
|
|
@@ -1845,6 +1921,7 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1845
1921
|
// Replay the passage's random rolls from its entry PRNG state; saves
|
|
1846
1922
|
// whose moments predate PRNG snapshots use the payload's.
|
|
1847
1923
|
restorePRNGFrom(entry?.prng !== undefined ? entry.prng : payload.prng);
|
|
1924
|
+
keepDrawsSoFar();
|
|
1848
1925
|
|
|
1849
1926
|
// Write the loaded game to the session so a refresh restores it.
|
|
1850
1927
|
// Draws made by the handlers would shift the passage's replayed rolls
|
package/src/story-api.ts
CHANGED
|
@@ -34,7 +34,13 @@ import { defineMacro } from './define-macro';
|
|
|
34
34
|
import type { MacroDefinition } from './define-macro';
|
|
35
35
|
import { getMacroRegistry as _getMacroRegistry } from './registry';
|
|
36
36
|
import type { MacroMetadata } from './registry';
|
|
37
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
getActions,
|
|
39
|
+
getAction,
|
|
40
|
+
performRegisteredAction,
|
|
41
|
+
settleRunningActions,
|
|
42
|
+
type StoryAction,
|
|
43
|
+
} from './action-registry';
|
|
38
44
|
import { getRenderedNavigationId } from './passage-render-state';
|
|
39
45
|
import {
|
|
40
46
|
initPRNG,
|
|
@@ -95,9 +101,11 @@ function ensureVariableChangedSubscription(): void {
|
|
|
95
101
|
prefix: string,
|
|
96
102
|
) => {
|
|
97
103
|
for (const key of changedNames(prev, next)) {
|
|
104
|
+
// As Story.get() hands values out: a retained value must not be a
|
|
105
|
+
// way to change live state or recorded history (#518)
|
|
98
106
|
changed[prefix + key] = {
|
|
99
|
-
from: ownValue(prev, key),
|
|
100
|
-
to: ownValue(next, key),
|
|
107
|
+
from: readOnlyValue(ownValue(prev, key)),
|
|
108
|
+
to: readOnlyValue(ownValue(next, key)),
|
|
101
109
|
};
|
|
102
110
|
}
|
|
103
111
|
};
|
|
@@ -156,7 +164,7 @@ export interface StoryAPI {
|
|
|
156
164
|
readonly backend: 'indexeddb' | 'localstorage' | 'memory';
|
|
157
165
|
};
|
|
158
166
|
getActions(): StoryAction[];
|
|
159
|
-
performAction(id: string, value?: unknown): void
|
|
167
|
+
performAction(id: string, value?: unknown): void | Promise<void>;
|
|
160
168
|
on<E extends StoryEvent>(
|
|
161
169
|
event: E,
|
|
162
170
|
callback: StoryEventCallback<E>,
|
|
@@ -411,7 +419,7 @@ function createStoryAPI(): StoryAPI {
|
|
|
411
419
|
return getActions();
|
|
412
420
|
},
|
|
413
421
|
|
|
414
|
-
performAction(id: string, value?: unknown): void {
|
|
422
|
+
performAction(id: string, value?: unknown): void | Promise<void> {
|
|
415
423
|
const action = getAction(id);
|
|
416
424
|
if (!action) {
|
|
417
425
|
throw new Error(`spindle: Action "${id}" not found.`);
|
|
@@ -419,7 +427,7 @@ function createStoryAPI(): StoryAPI {
|
|
|
419
427
|
if (action.disabled) {
|
|
420
428
|
throw new Error(`spindle: Action "${id}" is disabled.`);
|
|
421
429
|
}
|
|
422
|
-
action
|
|
430
|
+
return performRegisteredAction(action, value);
|
|
423
431
|
},
|
|
424
432
|
|
|
425
433
|
on<E extends StoryEvent>(
|
|
@@ -435,9 +443,18 @@ function createStoryAPI(): StoryAPI {
|
|
|
435
443
|
},
|
|
436
444
|
|
|
437
445
|
async waitForActions(): Promise<StoryAction[]> {
|
|
446
|
+
// An action that finishes later (QuickLoad) has not changed what the
|
|
447
|
+
// checks below look at until it has (#504)
|
|
448
|
+
await settleRunningActions();
|
|
438
449
|
await new Promise<void>((resolve) => {
|
|
439
450
|
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
|
440
451
|
});
|
|
452
|
+
// Preact runs a component's effects a frame and a timer after it
|
|
453
|
+
// renders, and a store subscription made in one (useSyncExternalStore)
|
|
454
|
+
// only then sees an update made before it: the re-render it triggers is
|
|
455
|
+
// ahead of what the frames above wait for. A timer queued now runs after
|
|
456
|
+
// the one Preact queued in its frame.
|
|
457
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
|
441
458
|
// A navigation can still be rendering: the passage display mounts the
|
|
442
459
|
// new passage from an effect, after a fade-through's outgoing phase.
|
|
443
460
|
// Its actions exist only once it is mounted, so wait for that. Compare
|