@rohal12/spindle 0.62.1 → 0.62.3
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 +642 -330
- package/dist/pkg/story-variables.js +701 -430
- package/dist/pkg/tooling.js +1 -0
- package/package.json +1 -1
- package/src/code-check.ts +25 -10
- package/src/completion-context.ts +226 -0
- package/src/components/Passage.tsx +28 -3
- package/src/define-macro.ts +6 -1
- package/src/format/source-lines.ts +4 -14
- package/src/hooks/use-modal-focus.ts +140 -46
- package/src/index.tsx +29 -10
- package/src/js-bindings.ts +29 -3
- package/src/macro-discovery.ts +34 -18
- package/src/markup/ast.ts +11 -6
- package/src/markup/code-attributes.ts +10 -3
- package/src/markup/line-column.ts +19 -0
- package/src/markup/pair.ts +4 -2
- package/src/markup/parse.ts +30 -9
- package/src/markup/spindle.d.peggy.ts +2 -0
- package/src/markup/spindle.peggy +22 -13
- package/src/markup/validate.ts +30 -3
- package/src/passage-render-state.ts +7 -0
- package/src/saves/format.ts +4 -0
- package/src/saves/types.ts +6 -6
- package/src/static-literal.ts +24 -22
- package/src/store.ts +42 -16
- package/src/story-variables.ts +14 -3
- package/src/tooling.ts +14 -3
- package/src/triggers.ts +107 -0
- package/src/twine-editor/references.ts +9 -11
- package/src/widgets/ast-scanner.ts +40 -44
- package/src/widgets/widget-def.ts +74 -45
- package/types/tooling.d.ts +17 -0
package/src/markup/parse.ts
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
import type { Selectors, Token } from './tokens';
|
|
15
15
|
import { isCodeAttribute } from './code-attributes';
|
|
16
16
|
import { defaultCodeEnd, type CodeEnd } from './code-end';
|
|
17
|
-
import { lineColumn } from './line-column';
|
|
17
|
+
import { lineColumn, sourcePositions } from './line-column';
|
|
18
18
|
|
|
19
19
|
export { lineColumn };
|
|
20
20
|
|
|
@@ -91,12 +91,18 @@ function run(
|
|
|
91
91
|
source: string,
|
|
92
92
|
startRule: 'Tokens' | 'SelectorsPrefix',
|
|
93
93
|
options: ParseMarkupOptions,
|
|
94
|
+
completion = false,
|
|
94
95
|
): unknown {
|
|
95
96
|
const hooks = options.hooks
|
|
96
97
|
? { ...defaultHooks, ...options.hooks }
|
|
97
98
|
: defaultHooks;
|
|
98
99
|
try {
|
|
99
|
-
return pegParse(source, {
|
|
100
|
+
return pegParse(source, {
|
|
101
|
+
startRule,
|
|
102
|
+
text: options.text === true,
|
|
103
|
+
hooks,
|
|
104
|
+
completion,
|
|
105
|
+
});
|
|
100
106
|
} catch (err) {
|
|
101
107
|
const { location, code } = err as {
|
|
102
108
|
location?: { start: { offset: number }; end: { offset: number } };
|
|
@@ -160,9 +166,10 @@ export function analyzeMarkup(
|
|
|
160
166
|
damage[i]! + 0.5,
|
|
161
167
|
e,
|
|
162
168
|
]);
|
|
169
|
+
const position = paired.errors.length ? sourcePositions(source) : undefined;
|
|
163
170
|
for (const error of paired.errors) {
|
|
164
171
|
if (!inDamage(error.start)) {
|
|
165
|
-
noticed.push([error.noticedAt, pairingError(
|
|
172
|
+
noticed.push([error.noticedAt, pairingError(position!, error)]);
|
|
166
173
|
}
|
|
167
174
|
}
|
|
168
175
|
// Array.prototype.sort is stable: equal ones stay in the order found
|
|
@@ -185,8 +192,11 @@ export function parseMarkup(
|
|
|
185
192
|
}
|
|
186
193
|
|
|
187
194
|
/** A pairing problem as the MarkupError it is for `source`. */
|
|
188
|
-
function pairingError(
|
|
189
|
-
|
|
195
|
+
function pairingError(
|
|
196
|
+
position: ReturnType<typeof sourcePositions>,
|
|
197
|
+
error: PairingError,
|
|
198
|
+
): MarkupError {
|
|
199
|
+
const { line, column } = position(error.start);
|
|
190
200
|
return new MarkupError(
|
|
191
201
|
error.message,
|
|
192
202
|
error.start,
|
|
@@ -256,10 +266,12 @@ export function tokenizeMarkupTolerant(
|
|
|
256
266
|
export function scanMarkupTolerant(
|
|
257
267
|
source: string,
|
|
258
268
|
options: ParseMarkupOptions = {},
|
|
269
|
+
completion = false,
|
|
259
270
|
): TolerantTokens & { damage: number[] } {
|
|
260
271
|
const tokens: Token[] = [];
|
|
261
272
|
const errors: MarkupError[] = [];
|
|
262
273
|
const damage: number[] = [];
|
|
274
|
+
let position: ReturnType<typeof sourcePositions> | undefined;
|
|
263
275
|
// The code of a tag ends at a }: with none after it, the tag is unclosed
|
|
264
276
|
// without reading its code to the end of the source, which every
|
|
265
277
|
// unclosed tag would do again (#265).
|
|
@@ -275,9 +287,9 @@ export function scanMarkupTolerant(
|
|
|
275
287
|
: closeBrace(input, codeStart, lenientStart),
|
|
276
288
|
};
|
|
277
289
|
try {
|
|
278
|
-
return
|
|
279
|
-
|
|
280
|
-
);
|
|
290
|
+
return (
|
|
291
|
+
run(text, 'Tokens', { ...options, hooks }, completion) as Token[]
|
|
292
|
+
).map((token) => shiftOffsets(token, base));
|
|
281
293
|
} catch (error) {
|
|
282
294
|
if (!(error instanceof MarkupError)) throw error;
|
|
283
295
|
return error;
|
|
@@ -292,7 +304,8 @@ export function scanMarkupTolerant(
|
|
|
292
304
|
break;
|
|
293
305
|
}
|
|
294
306
|
const at = base + result.offset;
|
|
295
|
-
|
|
307
|
+
position ??= sourcePositions(source);
|
|
308
|
+
const { line, column } = position(at);
|
|
296
309
|
errors.push(
|
|
297
310
|
new MarkupError(
|
|
298
311
|
result.reason,
|
|
@@ -328,6 +341,14 @@ export function scanMarkupTolerant(
|
|
|
328
341
|
return { tokens, errors, damage };
|
|
329
342
|
}
|
|
330
343
|
|
|
344
|
+
/** Runtime grammar with unfinished EOF tokens, for cursor contexts only. */
|
|
345
|
+
export function completionTokens(
|
|
346
|
+
source: string,
|
|
347
|
+
options: ParseMarkupOptions = {},
|
|
348
|
+
): Token[] {
|
|
349
|
+
return scanMarkupTolerant(source, options, true).tokens;
|
|
350
|
+
}
|
|
351
|
+
|
|
331
352
|
/** The offset fields of a token (and of an attribute): `start`, `nameEnd`… */
|
|
332
353
|
const OFFSET_FIELD = /^(start|end|[A-Za-z]*(Start|End))$/;
|
|
333
354
|
|
|
@@ -14,6 +14,8 @@ export declare class SyntaxError extends globalThis.SyntaxError {
|
|
|
14
14
|
|
|
15
15
|
export interface ParseOptions {
|
|
16
16
|
startRule: 'Tokens' | 'SelectorsPrefix';
|
|
17
|
+
/** Internal cursor-context mode accepts unfinished EOF tokens. */
|
|
18
|
+
completion?: boolean;
|
|
17
19
|
/** Text mode (attribute values, labels). */
|
|
18
20
|
text: boolean;
|
|
19
21
|
/** What the grammar leaves to code (see parse.ts MarkupHooks). */
|
package/src/markup/spindle.peggy
CHANGED
|
@@ -130,6 +130,8 @@ function joinText(items) {
|
|
|
130
130
|
|
|
131
131
|
{
|
|
132
132
|
const textMode = options.text === true;
|
|
133
|
+
// Only cursor-context parsing accepts EOF in place of an unfinished closer.
|
|
134
|
+
const completionMode = options.completion === true;
|
|
133
135
|
const hooks = options.hooks;
|
|
134
136
|
/** End of the stretch a `.|n|` repetition consumes (see skipTo). */
|
|
135
137
|
let skipEnd = -1;
|
|
@@ -229,6 +231,7 @@ RawTokens
|
|
|
229
231
|
const loc = { start: { offset: start }, end: { offset: start + body.length } };
|
|
230
232
|
return [body ? lexeme('text', loc, { value: body }) : null, end];
|
|
231
233
|
}
|
|
234
|
+
/ &{ return completionMode; } body:$.* { return lexeme('text', location(), { value: body }); }
|
|
232
235
|
|
|
233
236
|
// ----------------------------------------------------------------- lexemes
|
|
234
237
|
|
|
@@ -243,7 +246,7 @@ TextRun
|
|
|
243
246
|
* rendering drops it. (An unclosed `<!--` is ordinary text.)
|
|
244
247
|
*/
|
|
245
248
|
Comment
|
|
246
|
-
= value:$("<!--" (">" / "->" / (!"-->" .)* "-->")) {
|
|
249
|
+
= value:$("<!--" (">" / "->" / (!"-->" .)* ("-->" / OpenEnd))) {
|
|
247
250
|
const node = lexeme('text', location(), { value });
|
|
248
251
|
node.comment = true;
|
|
249
252
|
return node;
|
|
@@ -280,7 +283,7 @@ Literal
|
|
|
280
283
|
/ "[" { return lexeme('text', location(), { value: '[' }); }
|
|
281
284
|
|
|
282
285
|
LinkLexeme
|
|
283
|
-
= &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:$LinkText "]]" {
|
|
286
|
+
= &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:$LinkText ("]]" / OpenEnd) {
|
|
284
287
|
const link = lexeme('link', location(), parseLink(inner, at, (separator) => linkSeparatorIndex(inner, at, separator)));
|
|
285
288
|
link.selectorSpan = selectorSpan(s, ss, at);
|
|
286
289
|
return withSelectors(link, s);
|
|
@@ -313,12 +316,12 @@ SelectorChar
|
|
|
313
316
|
|
|
314
317
|
/** A variable `{$a.b}` or expression `{$a + 1}`, `{(…)}`, `{!…}`. */
|
|
315
318
|
Value
|
|
316
|
-
= "{" ss:Here s:Selectors sigil:[$_@%] nameStart:Here name:$[a-zA-Z0-9_.]*
|
|
319
|
+
= "{" ss:Here s:Selectors sigil:[$_@%] nameStart:Here name:$[a-zA-Z0-9_.]* BraceEnd {
|
|
317
320
|
const variable = lexeme('variable', location(), { name, nameStart, nameEnd: nameStart + name.length, scope: SIGIL_SCOPES[sigil] });
|
|
318
321
|
variable.selectorSpan = selectorSpan(s, ss, nameStart - 1);
|
|
319
322
|
return withSelectors(variable, s);
|
|
320
323
|
}
|
|
321
|
-
/ "{" ss:Here s:Selectors after:Here &[$_@%(!] expression:CodeToBrace
|
|
324
|
+
/ "{" ss:Here s:Selectors after:Here &[$_@%(!] expression:CodeToBrace BraceEnd {
|
|
322
325
|
const node = lexeme('expression', location(), { expression, expressionStart: after, expressionEnd: after + expression.length });
|
|
323
326
|
node.selectorSpan = selectorSpan(s, ss, after);
|
|
324
327
|
return withSelectors(node, s);
|
|
@@ -327,12 +330,18 @@ Value
|
|
|
327
330
|
|
|
328
331
|
/** JavaScript up to the } that ends it: where is up to options.hooks. */
|
|
329
332
|
CodeToBrace
|
|
330
|
-
= start:Here &{
|
|
333
|
+
= start:Here &{ const end = hooks.closeBrace(input, start, start); return skipTo(end < 0 && completionMode ? input.length : end); } code:$(.|{ return skipEnd - offset(); }|) { return code; }
|
|
334
|
+
|
|
335
|
+
OpenEnd
|
|
336
|
+
= &{ return completionMode; } !.
|
|
337
|
+
|
|
338
|
+
BraceEnd
|
|
339
|
+
= "}" / OpenEnd
|
|
331
340
|
|
|
332
341
|
/** A macro tag: `{name args}`, `{/name}`, with selectors on an opener. */
|
|
333
342
|
MacroTag
|
|
334
343
|
= "{" ss:Here s:Selectors start:Here close:"/"? name:MacroName nameEnd:Here
|
|
335
|
-
tail:( &{
|
|
344
|
+
tail:( &{ const end = hooks.closeBrace(input, nameEnd, start); return skipTo(end < 0 && completionMode ? input.length : end); } args:$(.|{ return skipEnd - offset(); }|) BraceEnd { return args; } )? {
|
|
336
345
|
const loc = location();
|
|
337
346
|
const lower = name.toLowerCase();
|
|
338
347
|
const tag = lexeme('macro', loc, { name, lower, rawArgs: '', isClose: !!close });
|
|
@@ -340,7 +349,7 @@ MacroTag
|
|
|
340
349
|
tag.nameEnd = nameEnd;
|
|
341
350
|
tag.selectorSpan = selectorSpan(s, ss, start);
|
|
342
351
|
if (tail === null) fail('Unclosed ' + LB + (close ? '/' : '') + name + '…: no ' + RB + ' ends the macro', loc, 'unclosed-macro');
|
|
343
|
-
tag.rawArgs = tail.trim();
|
|
352
|
+
tag.rawArgs = completionMode ? tail.trimStart() : tail.trim();
|
|
344
353
|
tag.argsStart = tag.rawArgs ? nameEnd + tail.length - tail.trimStart().length : nameEnd;
|
|
345
354
|
tag.argsEnd = tag.argsStart + tag.rawArgs.length;
|
|
346
355
|
if (close) {
|
|
@@ -376,7 +385,7 @@ UriAutolink
|
|
|
376
385
|
{ return lexeme('text', location(), { value }); }
|
|
377
386
|
|
|
378
387
|
HtmlOpen
|
|
379
|
-
= "<" tagStart:Here tag:TagName list:Attribute* _ slash:"/"? ">" {
|
|
388
|
+
= "<" tagStart:Here tag:TagName list:Attribute* _ slash:"/"? (">" / OpenEnd) {
|
|
380
389
|
const lower = tag.toLowerCase();
|
|
381
390
|
return lexeme('html', location(), { tag, lower, tagNameStart: tagStart, tagNameEnd: tagStart + tag.length, attributes: attrs(list), attributeSpans: list, isClose: false, isSelfClose: !!slash || VOID_TAGS.has(lower) });
|
|
382
391
|
}
|
|
@@ -414,8 +423,8 @@ Attribute
|
|
|
414
423
|
|
|
415
424
|
/** An attribute value: its text, where that is written and its quote, if any. */
|
|
416
425
|
AttrValue
|
|
417
|
-
= '"' start:Here value:$(ValuePart / [^"])* end:Here '"' { return { value, start, end, quote: '"' }; }
|
|
418
|
-
/ "'" start:Here value:$(ValuePart / [^'])* end:Here "'" { return { value, start, end, quote: "'" }; }
|
|
426
|
+
= '"' start:Here value:$(ValuePart / [^"])* end:Here ('"' / OpenEnd) { return { value, start, end, quote: '"' }; }
|
|
427
|
+
/ "'" start:Here value:$(ValuePart / [^'])* end:Here ("'" / OpenEnd) { return { value, start, end, quote: "'" }; }
|
|
419
428
|
/ q:["'] { fail('Unclosed attribute value: the ' + q + ' here has no closing ' + q, location(), 'unclosed-attribute'); }
|
|
420
429
|
/ start:Here value:$[^ \t\n\r\x0B\x0C\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF>]* end:Here { return { value, start, end }; }
|
|
421
430
|
|
|
@@ -423,9 +432,9 @@ AttrValue
|
|
|
423
432
|
ValuePart
|
|
424
433
|
= &{ return !attrCode; } bs:$"\\"+ (&{ return bs.length % 2 === 1; } [{}])?
|
|
425
434
|
/ &{ return !attrCode; } "{" Selectors start:Here "/"? MacroName nameEnd:Here
|
|
426
|
-
&{
|
|
427
|
-
/ &{ return !attrCode; } "{" Selectors !("/"? [a-zA-Z]) CodeToBrace
|
|
428
|
-
/ &{ return attrCode; } "{" &[$_@%] CodeToBrace
|
|
435
|
+
&{ const end = hooks.closeBrace(input, nameEnd, start); return skipTo(end < 0 && completionMode ? input.length : end); } $(.|{ return skipEnd - offset(); }|) BraceEnd
|
|
436
|
+
/ &{ return !attrCode; } "{" Selectors !("/"? [a-zA-Z]) CodeToBrace BraceEnd
|
|
437
|
+
/ &{ return attrCode; } "{" &[$_@%] CodeToBrace BraceEnd
|
|
429
438
|
|
|
430
439
|
_
|
|
431
440
|
= _c*
|
package/src/markup/validate.ts
CHANGED
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import {
|
|
9
9
|
analyzeMarkup,
|
|
10
|
-
lineColumn,
|
|
11
10
|
MarkupError,
|
|
12
11
|
parseMarkup,
|
|
13
12
|
tokenizeMarkup,
|
|
@@ -24,6 +23,8 @@ import {
|
|
|
24
23
|
type ParametersOf,
|
|
25
24
|
} from '../code-check';
|
|
26
25
|
import { CodeSyntaxError } from '../js-lexer';
|
|
26
|
+
import { sourcePositions } from './line-column';
|
|
27
|
+
import { isRawMacro } from './ast';
|
|
27
28
|
|
|
28
29
|
/** A passage to validate. */
|
|
29
30
|
export interface MarkupPassage {
|
|
@@ -158,14 +159,24 @@ function closestName(
|
|
|
158
159
|
name: string,
|
|
159
160
|
names: Iterable<string>,
|
|
160
161
|
): string | undefined {
|
|
162
|
+
// Suggestions are optional: oversized authored names must not hold up validation.
|
|
163
|
+
if (name.length > 256) return undefined;
|
|
161
164
|
const lower = name.toLowerCase();
|
|
162
165
|
let best: string | undefined;
|
|
163
166
|
let bestDistance = Math.max(2, Math.floor(lower.length / 3)) + 1;
|
|
167
|
+
let budget = 100_000;
|
|
168
|
+
let candidates = 1000;
|
|
164
169
|
for (const candidate of names) {
|
|
170
|
+
if (--candidates < 0) break;
|
|
171
|
+
if (candidate.length > 256) continue;
|
|
172
|
+
if (Math.abs(candidate.length - lower.length) >= bestDistance) continue;
|
|
173
|
+
budget -= lower.length * candidate.length;
|
|
174
|
+
if (budget < 0) break;
|
|
165
175
|
const d = distance(lower, candidate.toLowerCase());
|
|
166
176
|
if (d < bestDistance) {
|
|
167
177
|
best = candidate;
|
|
168
178
|
bestDistance = d;
|
|
179
|
+
if (d === 0) break;
|
|
169
180
|
}
|
|
170
181
|
}
|
|
171
182
|
return best;
|
|
@@ -202,9 +213,20 @@ export function validateMarkup(
|
|
|
202
213
|
options: MarkupValidationOptions,
|
|
203
214
|
): MarkupDiagnostic[] {
|
|
204
215
|
const diagnostics: MarkupDiagnostic[] = [];
|
|
216
|
+
const positions = new Map<
|
|
217
|
+
MarkupPassage,
|
|
218
|
+
ReturnType<typeof sourcePositions>
|
|
219
|
+
>();
|
|
205
220
|
const hooks = {
|
|
206
221
|
...(options.isBlockMacro && { isBlock: options.isBlockMacro }),
|
|
207
222
|
...(options.branchParents && { branchParents: options.branchParents }),
|
|
223
|
+
isRaw: (name: string) =>
|
|
224
|
+
isRawMacro(
|
|
225
|
+
name,
|
|
226
|
+
options.parametersOf
|
|
227
|
+
? options.parametersOf.widget?.(name) !== undefined
|
|
228
|
+
: undefined,
|
|
229
|
+
),
|
|
208
230
|
};
|
|
209
231
|
const report = (
|
|
210
232
|
passage: MarkupPassage,
|
|
@@ -214,7 +236,12 @@ export function validateMarkup(
|
|
|
214
236
|
message: string,
|
|
215
237
|
data?: MarkupDiagnosticData,
|
|
216
238
|
) => {
|
|
217
|
-
|
|
239
|
+
let position = positions.get(passage);
|
|
240
|
+
if (!position) {
|
|
241
|
+
position = sourcePositions(passage.content);
|
|
242
|
+
positions.set(passage, position);
|
|
243
|
+
}
|
|
244
|
+
const { line, column } = position(start);
|
|
218
245
|
const d: MarkupDiagnostic = {
|
|
219
246
|
passage: passage.name,
|
|
220
247
|
line,
|
|
@@ -276,7 +303,7 @@ export function validateMarkup(
|
|
|
276
303
|
}
|
|
277
304
|
try {
|
|
278
305
|
// The tokens first: they don't depend on which macros take a body
|
|
279
|
-
const tokens = tokenizeMarkup(passage.content);
|
|
306
|
+
const tokens = tokenizeMarkup(passage.content, { hooks });
|
|
280
307
|
addWidgets(tokens);
|
|
281
308
|
if (!reported) continue;
|
|
282
309
|
parseMarkup(passage.content, { hooks });
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
import { createContext } from 'preact';
|
|
2
|
+
|
|
3
|
+
/** Initial render of a deferred passage subtree, until its first commit. */
|
|
4
|
+
export const EntryRenderContext = createContext<{ pending: boolean } | null>(
|
|
5
|
+
null,
|
|
6
|
+
);
|
|
7
|
+
|
|
1
8
|
/**
|
|
2
9
|
* Navigation id (the store's `navigationId`) of the passage most recently
|
|
3
10
|
* mounted by <Passage> (null until the first render, e.g. when the story
|
package/src/saves/format.ts
CHANGED
|
@@ -193,6 +193,7 @@ function isPayload(value: unknown): value is Record<string, unknown> {
|
|
|
193
193
|
isCountsMap(value.renderCounts) &&
|
|
194
194
|
isOptionalPRNGSnapshot(value.prng) &&
|
|
195
195
|
isWatchers(value.watchers) &&
|
|
196
|
+
isWatchers(value.replayWatchers) &&
|
|
196
197
|
(value.interfaceWatchers === undefined ||
|
|
197
198
|
typeof value.interfaceWatchers === 'boolean')
|
|
198
199
|
);
|
|
@@ -220,6 +221,9 @@ export function decodePayload(encoded: unknown): SavePayload {
|
|
|
220
221
|
assertTrustedWatchers(
|
|
221
222
|
(body.watchers ?? []) as NonNullable<SavePayload['watchers']>,
|
|
222
223
|
);
|
|
224
|
+
assertTrustedWatchers(
|
|
225
|
+
(body.replayWatchers ?? []) as NonNullable<SavePayload['replayWatchers']>,
|
|
226
|
+
);
|
|
223
227
|
const payload = {
|
|
224
228
|
...body,
|
|
225
229
|
visitCounts: mapToCounts(body.visitCounts),
|
package/src/saves/types.ts
CHANGED
|
@@ -28,6 +28,8 @@ export interface SavePayload {
|
|
|
28
28
|
prng?: PRNGSnapshot | null;
|
|
29
29
|
/** The {watch} macro watchers registered (absent in older saves). */
|
|
30
30
|
watchers?: SavedWatcher[];
|
|
31
|
+
/** Watchers needed to replay entry-render effects, including consumed ones. */
|
|
32
|
+
replayWatchers?: SavedWatcher[];
|
|
31
33
|
/**
|
|
32
34
|
* Whether the story interface had mounted when the save was made, so that
|
|
33
35
|
* `watchers` includes its {watch} macros (absent in older saves).
|
|
@@ -66,13 +68,11 @@ export interface PlaythroughRecord {
|
|
|
66
68
|
}
|
|
67
69
|
|
|
68
70
|
/** Public-facing save metadata for the Story API. */
|
|
69
|
-
export interface SaveInfo
|
|
71
|
+
export interface SaveInfo extends Pick<
|
|
72
|
+
SaveMeta,
|
|
73
|
+
'title' | 'passage' | 'createdAt' | 'updatedAt' | 'custom'
|
|
74
|
+
> {
|
|
70
75
|
slot: string;
|
|
71
|
-
title: string;
|
|
72
|
-
passage: string;
|
|
73
|
-
createdAt: string;
|
|
74
|
-
updatedAt: string;
|
|
75
|
-
custom: Record<string, unknown>;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
export interface SaveExport {
|
package/src/static-literal.ts
CHANGED
|
@@ -471,18 +471,33 @@ export class Reader {
|
|
|
471
471
|
|
|
472
472
|
/** Skip an array literal (or any bracketed group) at the cursor. */
|
|
473
473
|
protected skipBalanced(): boolean {
|
|
474
|
+
const close = { '[': ']', '{': '}', '(': ')' }[this.src.charAt(this.i)];
|
|
475
|
+
return close ? this.skipNested(close) : false;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Skip groups and template interpolations with an explicit stack. */
|
|
479
|
+
private skipNested(close: string): boolean {
|
|
474
480
|
const { src } = this;
|
|
475
|
-
const
|
|
476
|
-
if (!close) return false;
|
|
481
|
+
const stack = [close];
|
|
477
482
|
this.i++;
|
|
478
|
-
while (this.i < src.length) {
|
|
479
|
-
|
|
483
|
+
while (this.i < src.length && stack.length) {
|
|
484
|
+
const c = src.charAt(this.i);
|
|
485
|
+
const top = stack[stack.length - 1];
|
|
486
|
+
if (c === top) {
|
|
487
|
+
stack.pop();
|
|
480
488
|
this.i++;
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
489
|
+
} else if (top === '`') {
|
|
490
|
+
if (c === '\\') this.i += 2;
|
|
491
|
+
else if (c === '$' && src.charAt(this.i + 1) === '{') {
|
|
492
|
+
stack.push('}');
|
|
493
|
+
this.i += 2;
|
|
494
|
+
} else this.i++;
|
|
495
|
+
} else if (c === '`' || c === '[' || c === '{' || c === '(') {
|
|
496
|
+
stack.push(c === '`' ? '`' : { '[': ']', '{': '}', '(': ')' }[c]!);
|
|
497
|
+
this.i++;
|
|
498
|
+
} else if (!this.skipOne()) return false;
|
|
484
499
|
}
|
|
485
|
-
return
|
|
500
|
+
return stack.length === 0;
|
|
486
501
|
}
|
|
487
502
|
|
|
488
503
|
/** Skip one character, or one string, template, comment or group. */
|
|
@@ -512,19 +527,6 @@ export class Reader {
|
|
|
512
527
|
|
|
513
528
|
/** Skip a template literal, with the expressions in it. */
|
|
514
529
|
protected skipTemplate(): boolean {
|
|
515
|
-
|
|
516
|
-
this.i++;
|
|
517
|
-
while (this.i < src.length) {
|
|
518
|
-
const c = src.charAt(this.i);
|
|
519
|
-
if (c === '\\') this.i += 2;
|
|
520
|
-
else if (c === '`') {
|
|
521
|
-
this.i++;
|
|
522
|
-
return true;
|
|
523
|
-
} else if (c === '$' && src.charAt(this.i + 1) === '{') {
|
|
524
|
-
this.i++;
|
|
525
|
-
if (!this.skipBalanced()) return false;
|
|
526
|
-
} else this.i++;
|
|
527
|
-
}
|
|
528
|
-
return false;
|
|
530
|
+
return this.skipNested('`');
|
|
529
531
|
}
|
|
530
532
|
}
|
package/src/store.ts
CHANGED
|
@@ -26,6 +26,8 @@ import {
|
|
|
26
26
|
assertTrustedWatchers,
|
|
27
27
|
interfaceMounted,
|
|
28
28
|
savedMacroWatchers,
|
|
29
|
+
savedReplayWatchers,
|
|
30
|
+
clearReplayWatchers,
|
|
29
31
|
reinitTriggerState,
|
|
30
32
|
} from './triggers';
|
|
31
33
|
import {
|
|
@@ -206,6 +208,7 @@ function applyVarPatches(
|
|
|
206
208
|
vars: Record<string, unknown>,
|
|
207
209
|
changes: readonly VarChange[],
|
|
208
210
|
): Record<string, unknown> {
|
|
211
|
+
if (changes.length === 0) return vars;
|
|
209
212
|
const next = Object.create(
|
|
210
213
|
Object.getPrototypeOf(vars) as object | null,
|
|
211
214
|
) as Record<string, unknown>;
|
|
@@ -324,6 +327,7 @@ function persistSession(get: () => StoryState): { error: unknown } | undefined {
|
|
|
324
327
|
renderCounts,
|
|
325
328
|
prng: snapshotPRNG(),
|
|
326
329
|
watchers: savedMacroWatchers(),
|
|
330
|
+
replayWatchers: savedReplayWatchers(),
|
|
327
331
|
interfaceWatchers: interfaceMounted(),
|
|
328
332
|
});
|
|
329
333
|
}
|
|
@@ -422,6 +426,9 @@ function finishEnteredMoment(get: StoreGet, set: StoreSet): void {
|
|
|
422
426
|
const moment = enteredMoment;
|
|
423
427
|
enteredMoment = null;
|
|
424
428
|
if (!moment || get().navigationId !== moment.navigationId) return;
|
|
429
|
+
// Navigation can run inside a macro's render. Its watcher effects are
|
|
430
|
+
// recorded below, so they must not also be replayed as passage effects.
|
|
431
|
+
clearReplayWatchers();
|
|
425
432
|
if (get().variables !== moment.variables) {
|
|
426
433
|
rerecordNewestMoment(get().variables);
|
|
427
434
|
}
|
|
@@ -558,6 +565,7 @@ export function recordStoryInitState(): void {
|
|
|
558
565
|
if (history.length !== 1 || historyIndex !== 0) return;
|
|
559
566
|
|
|
560
567
|
resetModuleState(variables);
|
|
568
|
+
clearReplayWatchers();
|
|
561
569
|
|
|
562
570
|
const prng = snapshotPRNG();
|
|
563
571
|
useStoryStore.setState((state) => {
|
|
@@ -1817,6 +1825,7 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1817
1825
|
renderCounts: { ...renderCounts },
|
|
1818
1826
|
prng: snapshotPRNG(),
|
|
1819
1827
|
watchers: savedMacroWatchers(),
|
|
1828
|
+
replayWatchers: savedReplayWatchers(),
|
|
1820
1829
|
interfaceWatchers: interfaceMounted(),
|
|
1821
1830
|
};
|
|
1822
1831
|
},
|
|
@@ -1860,6 +1869,7 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1860
1869
|
// running game as it is
|
|
1861
1870
|
assertPassagesExist(get().storyData, payload);
|
|
1862
1871
|
assertTrustedWatchers(payload.watchers ?? []);
|
|
1872
|
+
assertTrustedWatchers(payload.replayWatchers ?? []);
|
|
1863
1873
|
applyReplacement(replacement);
|
|
1864
1874
|
|
|
1865
1875
|
leavingPlaythrough = leaving;
|
|
@@ -1893,18 +1903,36 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1893
1903
|
// Convert full snapshots to patch entries. They are copied in one
|
|
1894
1904
|
// piece, so values the moments share stay shared, and a transition's
|
|
1895
1905
|
// patches hold only the variables that changed.
|
|
1896
|
-
const
|
|
1897
|
-
|
|
1906
|
+
const index = Math.max(
|
|
1907
|
+
0,
|
|
1908
|
+
Math.min(payload.historyIndex, payload.history.length - 1),
|
|
1909
|
+
);
|
|
1910
|
+
const start = Math.min(
|
|
1911
|
+
index,
|
|
1912
|
+
Math.max(0, payload.history.length - get().maxHistory),
|
|
1913
|
+
);
|
|
1914
|
+
const retained = payload.history.slice(start, start + get().maxHistory);
|
|
1915
|
+
const namespaces = new Map<Record<string, unknown>, Namespace>();
|
|
1916
|
+
const snapshots = deepClone(retained.map((m) => m.variables)).map(
|
|
1917
|
+
(vars) => {
|
|
1918
|
+
let normalized = namespaces.get(vars);
|
|
1919
|
+
if (!normalized) {
|
|
1920
|
+
normalized = createNamespace(vars);
|
|
1921
|
+
namespaces.set(vars, normalized);
|
|
1922
|
+
}
|
|
1923
|
+
return normalized;
|
|
1924
|
+
},
|
|
1898
1925
|
);
|
|
1899
1926
|
variableBase = deepClone(snapshots[0]!);
|
|
1900
1927
|
patchEntries = snapshots
|
|
1901
1928
|
.slice(1)
|
|
1902
|
-
.map((curr, i) =>
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1929
|
+
.map((curr, i) =>
|
|
1930
|
+
curr === snapshots[i]
|
|
1931
|
+
? { forward: [] }
|
|
1932
|
+
: computeVarPatches(snapshots[i]!, curr),
|
|
1933
|
+
);
|
|
1934
|
+
// Seed only retained moments; repeated namespaces stay shared.
|
|
1935
|
+
sessionMoments = retained.map((m, i) => savedMoment(m, snapshots[i]!));
|
|
1908
1936
|
|
|
1909
1937
|
set((state) => {
|
|
1910
1938
|
state.currentPassage = payload.passage;
|
|
@@ -1912,17 +1940,12 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1912
1940
|
state.variables = createNamespace(
|
|
1913
1941
|
deepClone(entry?.variables ?? payload.variables),
|
|
1914
1942
|
);
|
|
1915
|
-
state.history =
|
|
1943
|
+
state.history = retained.map((m) => ({
|
|
1916
1944
|
passage: m.passage,
|
|
1917
1945
|
timestamp: m.timestamp,
|
|
1918
1946
|
prng: m.prng,
|
|
1919
1947
|
}));
|
|
1920
|
-
state.historyIndex =
|
|
1921
|
-
0,
|
|
1922
|
-
Math.min(payload.historyIndex, state.history.length - 1),
|
|
1923
|
-
);
|
|
1924
|
-
// A save made under a higher limit keeps no more than the limit
|
|
1925
|
-
trimHistory(state);
|
|
1948
|
+
state.historyIndex = index - start;
|
|
1926
1949
|
state.visitCounts = createCounts(payload.visitCounts);
|
|
1927
1950
|
state.renderCounts = createCounts(payload.renderCounts);
|
|
1928
1951
|
state.temporary = createNamespace();
|
|
@@ -1933,7 +1956,10 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1933
1956
|
// older version, leaves the registered ones), then: loaded state is
|
|
1934
1957
|
// not a change watchers react to
|
|
1935
1958
|
if (payload.watchers) {
|
|
1936
|
-
restoreMacroWatchers(
|
|
1959
|
+
restoreMacroWatchers(
|
|
1960
|
+
payload.replayWatchers ?? payload.watchers,
|
|
1961
|
+
payload.interfaceWatchers,
|
|
1962
|
+
);
|
|
1937
1963
|
}
|
|
1938
1964
|
reinitTriggerState();
|
|
1939
1965
|
|
package/src/story-variables.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
tokenizeMarkupTolerant,
|
|
7
7
|
} from './markup/parse';
|
|
8
8
|
import { isCodeAttribute } from './markup/code-attributes';
|
|
9
|
+
import { isRawMacro } from './markup/ast';
|
|
9
10
|
import { errorMessage } from './utils/error-message';
|
|
10
11
|
import {
|
|
11
12
|
CodeSyntaxError,
|
|
@@ -46,11 +47,21 @@ import { parse } from 'acorn';
|
|
|
46
47
|
function tokensOf(
|
|
47
48
|
text: string,
|
|
48
49
|
textMode: boolean,
|
|
49
|
-
{
|
|
50
|
+
{
|
|
51
|
+
tolerant,
|
|
52
|
+
parametersOf,
|
|
53
|
+
}: { tolerant?: boolean; parametersOf?: ParametersOf } = {},
|
|
50
54
|
): Token[] {
|
|
51
|
-
|
|
55
|
+
const options = {
|
|
56
|
+
text: textMode,
|
|
57
|
+
hooks: parametersOf && {
|
|
58
|
+
isRaw: (name: string) =>
|
|
59
|
+
isRawMacro(name, parametersOf.widget?.(name) !== undefined),
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
if (tolerant) return tokenizeMarkupTolerant(text, options).tokens;
|
|
52
63
|
try {
|
|
53
|
-
return tokenizeMarkup(text,
|
|
64
|
+
return tokenizeMarkup(text, options);
|
|
54
65
|
} catch (err) {
|
|
55
66
|
if (err instanceof MarkupError) return [];
|
|
56
67
|
throw err;
|
package/src/tooling.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
export {
|
|
2
|
+
completionContext,
|
|
3
|
+
type CompletionContext,
|
|
4
|
+
} from './completion-context';
|
|
1
5
|
import { branchParents } from './registry';
|
|
2
6
|
/**
|
|
3
7
|
* What the tooling entry point (`@rohal12/spindle/tooling`) bundles as
|
|
@@ -10,7 +14,7 @@ import {
|
|
|
10
14
|
type MarkupDiagnostic,
|
|
11
15
|
type MarkupPassage,
|
|
12
16
|
} from './markup/validate';
|
|
13
|
-
import { isBlockMacro } from './markup/ast';
|
|
17
|
+
import { isBlockMacro, isRawMacro } from './markup/ast';
|
|
14
18
|
import { tokenizeMarkupTolerant } from './markup/parse';
|
|
15
19
|
import {
|
|
16
20
|
parameterLookup,
|
|
@@ -263,10 +267,17 @@ export function passagePieces(
|
|
|
263
267
|
source: string,
|
|
264
268
|
macros: Iterable<ToolingMacro> = [],
|
|
265
269
|
): Piece[] {
|
|
270
|
+
const all = [...macros];
|
|
271
|
+
const parametersOf = parameterLookup(all);
|
|
266
272
|
return passagePiecesOfTokens(
|
|
267
273
|
source,
|
|
268
|
-
|
|
269
|
-
tokenizeMarkupTolerant(source
|
|
274
|
+
all,
|
|
275
|
+
tokenizeMarkupTolerant(source, {
|
|
276
|
+
hooks: {
|
|
277
|
+
isRaw: (name) =>
|
|
278
|
+
isRawMacro(name, parametersOf.widget?.(name) !== undefined),
|
|
279
|
+
},
|
|
280
|
+
}).tokens,
|
|
270
281
|
);
|
|
271
282
|
}
|
|
272
283
|
|