@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
package/src/js-lexer.ts
CHANGED
|
@@ -53,9 +53,17 @@ export interface JsLexHandlers {
|
|
|
53
53
|
literal?(text: string, index: number, nesting: number): void;
|
|
54
54
|
/**
|
|
55
55
|
* A sigil variable reference — `$name`, `_name`, `@name` or `%name` —
|
|
56
|
-
* covering the sigil and `name
|
|
56
|
+
* covering the sigil and `name`, which is the name JavaScript reads (one
|
|
57
|
+
* written with an escape, `$fo\u006f`, is `foo`). It is written from
|
|
58
|
+
* `index` up to `end` (the sigil and the name as written).
|
|
57
59
|
*/
|
|
58
|
-
variable?(
|
|
60
|
+
variable?(
|
|
61
|
+
sigil: Sigil,
|
|
62
|
+
name: string,
|
|
63
|
+
index: number,
|
|
64
|
+
nesting: number,
|
|
65
|
+
end: number,
|
|
66
|
+
): void;
|
|
59
67
|
}
|
|
60
68
|
|
|
61
69
|
/**
|
|
@@ -144,7 +152,10 @@ const SigilParser = class extends (Parser as unknown as Base) {
|
|
|
144
152
|
colonEndsTernary = false;
|
|
145
153
|
/** The last `}` closed a block. */
|
|
146
154
|
closedBlock = false;
|
|
147
|
-
/**
|
|
155
|
+
/**
|
|
156
|
+
* The value of the token before the one being finished, but for a member
|
|
157
|
+
* name (`a.static`).
|
|
158
|
+
*/
|
|
148
159
|
prevValue: unknown;
|
|
149
160
|
/** The type of the token before the last one. */
|
|
150
161
|
typeBeforeLast: TokenType = tt.eof;
|
|
@@ -218,10 +229,11 @@ const SigilParser = class extends (Parser as unknown as Base) {
|
|
|
218
229
|
// or an object key (`class D { function; }`, `{ class: 1 }`)
|
|
219
230
|
const self = this as unknown as ParserState;
|
|
220
231
|
const prevType = self.type;
|
|
221
|
-
|
|
232
|
+
// The word before, unless it is a member name (`a.static`, `a?.let`),
|
|
233
|
+
// which no contextual keyword is
|
|
234
|
+
this.prevValue = isMemberDot(this.typeBeforeLast) ? undefined : self.value;
|
|
222
235
|
const property =
|
|
223
|
-
(type.keyword !== undefined &&
|
|
224
|
-
(prevType === tt.dot || prevType === tt.questionDot)) ||
|
|
236
|
+
(type.keyword !== undefined && isMemberDot(prevType)) ||
|
|
225
237
|
((type === tt._function || type === tt._class) &&
|
|
226
238
|
notABody(self.input, self.pos));
|
|
227
239
|
// acorn takes a `function` or `class` for a statement's (whose `}` a
|
|
@@ -241,14 +253,17 @@ const SigilParser = class extends (Parser as unknown as Base) {
|
|
|
241
253
|
this.typeBeforeLast = prevType;
|
|
242
254
|
// @ts-expect-error acorn internals
|
|
243
255
|
super.finishToken(property ? tt.name : type, value);
|
|
244
|
-
//
|
|
245
|
-
//
|
|
256
|
+
// acorn takes a name for a contextual keyword wherever it reads (`of`
|
|
257
|
+
// of a for-of loop, `yield` in a generator), after which an operand
|
|
258
|
+
// comes. A member name (`a?.of`, which acorn checks only after `.`) and
|
|
259
|
+
// a variable named `of` (`const of of list`) are operands.
|
|
246
260
|
if (
|
|
247
261
|
type === tt.name &&
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
262
|
+
(isMemberDot(prevType) ||
|
|
263
|
+
(value === 'of' &&
|
|
264
|
+
(prevType === tt._const ||
|
|
265
|
+
prevType === tt._var ||
|
|
266
|
+
this.prevValue === 'let')))
|
|
252
267
|
) {
|
|
253
268
|
self.exprAllowed = false;
|
|
254
269
|
}
|
|
@@ -305,6 +320,11 @@ function transientAssignment(p: ParserState, end: number): boolean {
|
|
|
305
320
|
}
|
|
306
321
|
}
|
|
307
322
|
|
|
323
|
+
/** Is `type` the `.` or `?.` of a member access? */
|
|
324
|
+
function isMemberDot(type: TokenType): boolean {
|
|
325
|
+
return type === tt.dot || type === tt.questionDot;
|
|
326
|
+
}
|
|
327
|
+
|
|
308
328
|
const OPENERS = new Set([tt.parenL, tt.bracketL, tt.braceL, tt.dollarBraceL]);
|
|
309
329
|
const CLOSERS = new Set([tt.parenR, tt.bracketR, tt.braceR]);
|
|
310
330
|
|
|
@@ -501,6 +521,14 @@ export function parseCode(
|
|
|
501
521
|
src: string,
|
|
502
522
|
goal: JsGoal = 'expression',
|
|
503
523
|
): ParsedCode {
|
|
524
|
+
return parseWithAst(src, goal).out;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** What parseCode finds in `src`, and the syntax tree it is in. */
|
|
528
|
+
function parseWithAst(
|
|
529
|
+
src: string,
|
|
530
|
+
goal: JsGoal,
|
|
531
|
+
): { out: ParsedCode; ast: AnyNode } {
|
|
504
532
|
// Whether `%name` is a transient or `%` modulo is guessed from the tokens
|
|
505
533
|
// before it, as acorn guesses whether `/` opens a regex. Where the guess
|
|
506
534
|
// makes the parser fail at a `%`, the other reading is tried, and the
|
|
@@ -513,7 +541,7 @@ export function parseCode(
|
|
|
513
541
|
const out: ParsedCode = { refs: [], strings: [] };
|
|
514
542
|
walk(ast, src, out, false, false);
|
|
515
543
|
out.refs.sort((a, b) => a.start - b.start);
|
|
516
|
-
return out;
|
|
544
|
+
return { out, ast };
|
|
517
545
|
} catch (error) {
|
|
518
546
|
const pos = (error as { pos?: number }).pos ?? -1;
|
|
519
547
|
if (!(error instanceof SyntaxError) || percentAt.has(pos)) throw error;
|
|
@@ -524,6 +552,39 @@ export function parseCode(
|
|
|
524
552
|
}
|
|
525
553
|
}
|
|
526
554
|
|
|
555
|
+
/** The variable at the root of a reference path, and whether it has members. */
|
|
556
|
+
export interface ReferencePath {
|
|
557
|
+
sigil: Sigil;
|
|
558
|
+
name: string;
|
|
559
|
+
/** The path goes on past the variable (`$a.b`, `$a["b"]`, `$a[i]`). */
|
|
560
|
+
nested: boolean;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Read `src` as a reference path: a variable with any number of `.name` and
|
|
565
|
+
* `[expression]` members after it (`$data["field"]`, `@list[_i].x`), and
|
|
566
|
+
* nothing else. Returns null for any other code (`$a + 1`, `$a.b()`, `$a,
|
|
567
|
+
* $b`, `$a = 1`), and throws a `CodeSyntaxError` for code that is not
|
|
568
|
+
* well-formed.
|
|
569
|
+
*/
|
|
570
|
+
export function parseReferencePath(src: string): ReferencePath | null {
|
|
571
|
+
const { ast } = parseWithAst(src, 'expression');
|
|
572
|
+
// `$a?.b` is a chain expression around the members
|
|
573
|
+
let node: AnyNode =
|
|
574
|
+
ast.type === 'ChainExpression' ? (ast.expression as AnyNode) : ast;
|
|
575
|
+
let nested = false;
|
|
576
|
+
while (node.type === 'MemberExpression') {
|
|
577
|
+
node = node.object as AnyNode;
|
|
578
|
+
nested = true;
|
|
579
|
+
}
|
|
580
|
+
if (node.type !== 'Identifier') return null;
|
|
581
|
+
const sigil = sigilOf(node, src);
|
|
582
|
+
// Parentheses around the variable or a member (`($a).b`) are not part of
|
|
583
|
+
// a path as written
|
|
584
|
+
if (!sigil || node.start !== 0) return null;
|
|
585
|
+
return { sigil: sigil[0], name: sigil[1], nested };
|
|
586
|
+
}
|
|
587
|
+
|
|
527
588
|
/**
|
|
528
589
|
* Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
|
|
529
590
|
* noting where it read a transient in `transientsRead`.
|
|
@@ -1055,9 +1116,10 @@ function walkTokens(
|
|
|
1055
1116
|
if (sigil && !property) {
|
|
1056
1117
|
handlers.variable?.(
|
|
1057
1118
|
sigil,
|
|
1058
|
-
|
|
1119
|
+
(tok.value as string).slice(1),
|
|
1059
1120
|
tok.start,
|
|
1060
1121
|
nesting,
|
|
1122
|
+
tok.end,
|
|
1061
1123
|
);
|
|
1062
1124
|
} else code(tok.start, tok.end);
|
|
1063
1125
|
} else if (
|
package/src/macro-discovery.ts
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
* without running it (see discoverMacros): the literal parts of the config
|
|
4
4
|
* object, and nothing else.
|
|
5
5
|
*/
|
|
6
|
-
import { lexJs } from './js-lexer';
|
|
7
6
|
import {
|
|
8
7
|
checkParameterTypes,
|
|
9
8
|
type ParameterDef,
|
|
10
9
|
type ParameterType,
|
|
11
10
|
type StringHolds,
|
|
12
11
|
} from './registry';
|
|
13
|
-
import {
|
|
12
|
+
import { Bindings } from './js-bindings';
|
|
13
|
+
import { Reader, regexLiterals } from './static-literal';
|
|
14
14
|
import type { ToolingMacro } from './tooling';
|
|
15
15
|
|
|
16
16
|
/** A macro that a `defineMacro` call declares, and where its name is written. */
|
|
@@ -34,6 +34,20 @@ type Datum =
|
|
|
34
34
|
const CALL_RE = /(?<![\w$])defineMacro\s*\(\s*/g;
|
|
35
35
|
const IDENTIFIER_ARGUMENT_RE = /^([A-Za-z_$][\w$]*)\s*[,)]/;
|
|
36
36
|
const WORD_RE = /[A-Za-z_]+/y;
|
|
37
|
+
/** Before the key of a member that is an accessor, an async method or a generator. */
|
|
38
|
+
const MODIFIER_RE = /^(?:get|set|async)?$/;
|
|
39
|
+
const KEY_START_RE = /[\w$'"[.*]/;
|
|
40
|
+
/** The properties of a config that its macro is read from. */
|
|
41
|
+
const CONFIG_KEYS: ReadonlySet<string> = new Set([
|
|
42
|
+
'name',
|
|
43
|
+
'block',
|
|
44
|
+
'subMacros',
|
|
45
|
+
'parameters',
|
|
46
|
+
'interpolate',
|
|
47
|
+
'storeVar',
|
|
48
|
+
'merged',
|
|
49
|
+
'description',
|
|
50
|
+
]);
|
|
37
51
|
|
|
38
52
|
/** The literals of a config object, read to the end of what is static. */
|
|
39
53
|
class ConfigReader extends Reader {
|
|
@@ -138,18 +152,50 @@ class ConfigReader extends Reader {
|
|
|
138
152
|
|
|
139
153
|
private record(): Datum | undefined {
|
|
140
154
|
const props = new Map<string, Datum | undefined>();
|
|
141
|
-
const ok = this.elements('}', () =>
|
|
142
|
-
|
|
155
|
+
const ok = this.elements('}', () => this.property(props));
|
|
156
|
+
return ok ? { type: 'object', props } : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* A member: what it sets replaces an earlier member of the key. One that is
|
|
161
|
+
* not a literal (a method, an accessor, a shorthand) sets its key to a
|
|
162
|
+
* value not known; a spread of an object literal sets the members of it, a
|
|
163
|
+
* spread of anything else or a computed key can set any key.
|
|
164
|
+
*/
|
|
165
|
+
private property(props: Map<string, Datum | undefined>): void {
|
|
166
|
+
const { src } = this;
|
|
167
|
+
if (src.startsWith('...', this.i)) {
|
|
168
|
+
this.i += 3;
|
|
143
169
|
this.space();
|
|
144
|
-
|
|
170
|
+
const spread = src.charAt(this.i) === '{' ? this.record() : undefined;
|
|
171
|
+
this.space();
|
|
172
|
+
if (spread?.type === 'object' && this.atElementEnd()) {
|
|
173
|
+
for (const [key, value] of spread.props) props.set(key, value);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
props.clear();
|
|
177
|
+
} else {
|
|
178
|
+
let key = this.key();
|
|
179
|
+
this.space();
|
|
180
|
+
if (key !== undefined && src.charAt(this.i) === ':') {
|
|
145
181
|
this.i++;
|
|
146
182
|
props.set(key, this.member());
|
|
147
|
-
|
|
148
|
-
// A method, a shorthand member, a spread: not a literal
|
|
149
|
-
this.fail();
|
|
183
|
+
return;
|
|
150
184
|
}
|
|
151
|
-
|
|
152
|
-
|
|
185
|
+
// `get name() {}`, `async name() {}`, `*name() {}`: the key follows
|
|
186
|
+
if (
|
|
187
|
+
MODIFIER_RE.test(key ?? '') &&
|
|
188
|
+
KEY_START_RE.test(src.charAt(this.i))
|
|
189
|
+
) {
|
|
190
|
+
if (src.charAt(this.i) === '*') this.i++;
|
|
191
|
+
this.space();
|
|
192
|
+
key = this.key();
|
|
193
|
+
}
|
|
194
|
+
if (key === undefined) props.clear();
|
|
195
|
+
else props.set(key, undefined);
|
|
196
|
+
}
|
|
197
|
+
// The rest of the member: not a literal
|
|
198
|
+
if (!this.skipMember()) this.fail();
|
|
153
199
|
}
|
|
154
200
|
|
|
155
201
|
/** Stop reading: the text cannot be skipped through. */
|
|
@@ -158,19 +204,21 @@ class ConfigReader extends Reader {
|
|
|
158
204
|
}
|
|
159
205
|
}
|
|
160
206
|
|
|
161
|
-
/**
|
|
162
|
-
|
|
207
|
+
/**
|
|
208
|
+
* The text with everything but code (strings, comments, regexes) blanked, and
|
|
209
|
+
* where its regex literals are.
|
|
210
|
+
*/
|
|
211
|
+
function codeOnly(source: string): {
|
|
212
|
+
code: string;
|
|
213
|
+
regexes: Map<number, number>;
|
|
214
|
+
} {
|
|
163
215
|
const chars = Array.from({ length: source.length }, () => ' ');
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
code(ch, index) {
|
|
168
|
-
for (let k = 0; k < ch.length; k++) chars[index + k] = ch[k]!;
|
|
169
|
-
},
|
|
216
|
+
const regexes = regexLiterals(source, 'statements', {
|
|
217
|
+
code(ch, index) {
|
|
218
|
+
for (let k = 0; k < ch.length; k++) chars[index + k] = ch[k]!;
|
|
170
219
|
},
|
|
171
|
-
|
|
172
|
-
);
|
|
173
|
-
return chars.join('');
|
|
220
|
+
});
|
|
221
|
+
return { code: chars.join(''), regexes };
|
|
174
222
|
}
|
|
175
223
|
|
|
176
224
|
const stringOf = (d: Datum | undefined) =>
|
|
@@ -265,31 +313,34 @@ function macroOf(config: Datum): DiscoveredMacro | undefined {
|
|
|
265
313
|
* `source` (JavaScript: a script passage, the body of a `{do}`, a project
|
|
266
314
|
* file) declare, in source order, read from the text without running it. A
|
|
267
315
|
* call whose config is an object literal (or a variable declared as one with
|
|
268
|
-
* `const`, `let` or `var`
|
|
269
|
-
*
|
|
316
|
+
* `const`, `let` or `var` that the call sees, see Bindings: not a parameter, a
|
|
317
|
+
* pattern or an assignment of the name, or a write to a property the macro
|
|
318
|
+
* is read from) and whose `name` is a string is found,
|
|
319
|
+
* wherever it is, even inside a function. Only what is written out is read: a `block`,
|
|
270
320
|
* `interpolate`, `storeVar` or `merged` that is a boolean literal, the
|
|
271
321
|
* strings of `subMacros`, and `parameters` when every one is an object
|
|
272
322
|
* literal with a string `name` and `type` (and `holds`, `required`,
|
|
273
323
|
* `description` and nested `parameters` of options when written out as such);
|
|
274
|
-
* a
|
|
275
|
-
*
|
|
324
|
+
* a later member that sets one of these again (a spread, a method, an
|
|
325
|
+
* accessor, a computed key) replaces it; a list with a parameter that is not,
|
|
326
|
+
* or that `defineMacro` would refuse, declares none. It is tolerant: text it cannot read is skipped, and it
|
|
276
327
|
* throws for none.
|
|
277
328
|
*/
|
|
278
329
|
export function discoverMacros(source: string): DiscoveredMacro[] {
|
|
279
|
-
const code = codeOnly(source);
|
|
330
|
+
const { code, regexes } = codeOnly(source);
|
|
280
331
|
const found: DiscoveredMacro[] = [];
|
|
332
|
+
let bindings: Bindings | undefined;
|
|
281
333
|
for (const call of code.matchAll(CALL_RE)) {
|
|
282
334
|
let at = call.index + call[0].length;
|
|
283
335
|
if (code.charAt(at) !== '{') {
|
|
284
336
|
const variable = IDENTIFIER_ARGUMENT_RE.exec(code.slice(at))?.[1];
|
|
285
337
|
if (!variable) continue;
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
at = declaration.index + declaration[0].length;
|
|
338
|
+
bindings ??= new Bindings(code);
|
|
339
|
+
const object = bindings.objectOf(variable, call.index, CONFIG_KEYS);
|
|
340
|
+
if (object === undefined) continue;
|
|
341
|
+
at = object;
|
|
291
342
|
}
|
|
292
|
-
const reader = new ConfigReader(source);
|
|
343
|
+
const reader = new ConfigReader(source, { goal: 'statements', regexes });
|
|
293
344
|
reader.i = at;
|
|
294
345
|
const config = reader.datum();
|
|
295
346
|
const macro = config && macroOf(config);
|
package/src/markup/ast.ts
CHANGED
|
@@ -65,6 +65,13 @@ const BLOCK_MACROS = new NameSet([
|
|
|
65
65
|
'nobr',
|
|
66
66
|
]);
|
|
67
67
|
|
|
68
|
+
/**
|
|
69
|
+
* The block widgets (those whose body renders `{@children}`), kept apart from
|
|
70
|
+
* BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
|
|
71
|
+
* definition is, whereas the macros in BLOCK_MACROS stay blocks.
|
|
72
|
+
*/
|
|
73
|
+
const BLOCK_WIDGETS = new NameSet();
|
|
74
|
+
|
|
68
75
|
/** Macros whose body is JavaScript source, kept verbatim. */
|
|
69
76
|
const RAW_BODY_MACROS = new Set(['do']);
|
|
70
77
|
|
|
@@ -75,7 +82,7 @@ export function isRawMacro(name: string): boolean {
|
|
|
75
82
|
|
|
76
83
|
/** Whether a macro takes a body closed by `{/name}`. */
|
|
77
84
|
export function isBlockMacro(name: string): boolean {
|
|
78
|
-
return BLOCK_MACROS.has(name);
|
|
85
|
+
return BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
|
|
79
86
|
}
|
|
80
87
|
|
|
81
88
|
/** Register a custom macro as a block macro so the parser nests children. */
|
|
@@ -83,6 +90,20 @@ export function registerBlockMacro(name: string): void {
|
|
|
83
90
|
BLOCK_MACROS.add(name);
|
|
84
91
|
}
|
|
85
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Record whether the widget `name` takes a body, as its latest definition
|
|
95
|
+
* does. A block macro registered under the same name stays a block.
|
|
96
|
+
*/
|
|
97
|
+
export function setBlockWidget(name: string, isBlock: boolean): void {
|
|
98
|
+
if (isBlock) BLOCK_WIDGETS.add(name);
|
|
99
|
+
else BLOCK_WIDGETS.delete(name);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Forget which widgets take a body (see clearWidgets). */
|
|
103
|
+
export function clearBlockWidgets(): void {
|
|
104
|
+
BLOCK_WIDGETS.clear();
|
|
105
|
+
}
|
|
106
|
+
|
|
86
107
|
/** Unregister a custom block macro (for test cleanup). */
|
|
87
108
|
export function unregisterBlockMacro(name: string): void {
|
|
88
109
|
BLOCK_MACROS.delete(name);
|
package/src/markup/render.tsx
CHANGED
|
@@ -188,8 +188,11 @@ function expandPlaceholderText(
|
|
|
188
188
|
);
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
-
/**
|
|
192
|
-
|
|
191
|
+
/**
|
|
192
|
+
* An attribute: its name, value, value as written and whether the value is
|
|
193
|
+
* bound to variables (see splitAttributes).
|
|
194
|
+
*/
|
|
195
|
+
type Attribute = [name: string, value: string, written: string, bound: boolean];
|
|
193
196
|
|
|
194
197
|
/**
|
|
195
198
|
* An element of markdown output whose attributes contain placeholders (a
|
|
@@ -214,12 +217,12 @@ function PlaceholderAttributes({
|
|
|
214
217
|
const errors: AttributeError[] = [];
|
|
215
218
|
const resolved = attributes.map(([name, value, written]): Attribute => {
|
|
216
219
|
const nodes = placeholders[name];
|
|
217
|
-
if (!nodes) return [name, value, written];
|
|
220
|
+
if (!nodes) return [name, value, written, false];
|
|
218
221
|
const result = renderText(nodes, scope);
|
|
219
222
|
for (const error of result.errors) errors.push([name, error]);
|
|
220
|
-
return [name, result.text, written];
|
|
223
|
+
return [name, result.text, written, true];
|
|
221
224
|
});
|
|
222
|
-
const { props, direct } = splitAttributes(resolved, svg);
|
|
225
|
+
const { props, direct } = splitAttributes(resolved, svg, tag);
|
|
223
226
|
const ref = useDirectAttributes(direct);
|
|
224
227
|
return withAttributeErrors(
|
|
225
228
|
errors,
|
|
@@ -349,7 +352,7 @@ function convertDomNode(
|
|
|
349
352
|
const attributes: Attribute[] = [];
|
|
350
353
|
let placeholders: Record<string, ASTNode[]> | undefined;
|
|
351
354
|
for (const { name, value } of Array.from(el.attributes)) {
|
|
352
|
-
attributes.push([name, value, value]);
|
|
355
|
+
attributes.push([name, value, value, false]);
|
|
353
356
|
const parts = splitPlaceholderText(value, ph);
|
|
354
357
|
if (parts.every((part) => typeof part === 'string')) continue;
|
|
355
358
|
placeholders ??= {};
|
|
@@ -377,7 +380,7 @@ function convertDomNode(
|
|
|
377
380
|
/>
|
|
378
381
|
);
|
|
379
382
|
}
|
|
380
|
-
const { props, direct } = splitAttributes(attributes, svg);
|
|
383
|
+
const { props, direct } = splitAttributes(attributes, svg, tag);
|
|
381
384
|
if (direct.length > 0) {
|
|
382
385
|
return (
|
|
383
386
|
<DirectAttributes
|
|
@@ -447,11 +450,18 @@ const INLINE_ELEMENTS = new Set([
|
|
|
447
450
|
]);
|
|
448
451
|
|
|
449
452
|
/**
|
|
450
|
-
* Attributes that Preact keeps as DOM properties on author HTML elements
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
* as `=""` are passed as
|
|
454
|
-
*
|
|
453
|
+
* Attributes that Preact keeps as DOM properties on author HTML elements
|
|
454
|
+
* when their value is bound to variables (`value="{$name}"`): the live state
|
|
455
|
+
* of form controls and media, which then follows its variable even after the
|
|
456
|
+
* reader changed it. Boolean ones written bare or as `=""` are passed as
|
|
457
|
+
* `true`, since '' is falsy (#177); one that only resolves to '' through an
|
|
458
|
+
* interpolation stays ''.
|
|
459
|
+
*
|
|
460
|
+
* A static `value`, `checked` or `selected` is the control's default, as in
|
|
461
|
+
* HTML: set as an attribute, so a reset restores it and a rerender leaves
|
|
462
|
+
* what the reader entered alone (#528). Not so for `muted`, which as an
|
|
463
|
+
* attribute is ignored on an element made by script, nor for the `value` of
|
|
464
|
+
* the controls that have no attribute for it.
|
|
455
465
|
*/
|
|
456
466
|
const LIVE_PROPERTIES = new Set(['value', 'checked', 'selected', 'muted']);
|
|
457
467
|
|
|
@@ -521,6 +531,15 @@ function setRawAttribute(el: Element, name: string, value: string) {
|
|
|
521
531
|
el.setAttributeNode(attr);
|
|
522
532
|
}
|
|
523
533
|
|
|
534
|
+
/**
|
|
535
|
+
* Whether the static `name` attribute of `tag` is its default (#528). HTML has
|
|
536
|
+
* no `value` attribute on `select` and `textarea`, so theirs stays a property.
|
|
537
|
+
*/
|
|
538
|
+
function isNativeDefault(tag: string, name: string): boolean {
|
|
539
|
+
if (name === 'muted') return false;
|
|
540
|
+
return name !== 'value' || (tag !== 'select' && tag !== 'textarea');
|
|
541
|
+
}
|
|
542
|
+
|
|
524
543
|
/**
|
|
525
544
|
* Split author attributes into Preact props and attributes to set directly.
|
|
526
545
|
*
|
|
@@ -541,15 +560,23 @@ function setRawAttribute(el: Element, name: string, value: string) {
|
|
|
541
560
|
function splitAttributes(
|
|
542
561
|
attributes: Attribute[],
|
|
543
562
|
svg: boolean,
|
|
563
|
+
tag: string,
|
|
544
564
|
): { props: Record<string, unknown>; direct: [string, string][] } {
|
|
545
565
|
const props: Record<string, unknown> = {};
|
|
546
566
|
const direct: [string, string][] = [];
|
|
547
|
-
|
|
567
|
+
// Set after the other attributes, as Preact does for a live control: a
|
|
568
|
+
// range's value is clamped by the min and max it has by then
|
|
569
|
+
const defaults: [string, string][] = [];
|
|
570
|
+
for (const [name, value, written, bound] of attributes) {
|
|
548
571
|
const lower = name.toLowerCase();
|
|
549
572
|
if (BOOLEAN_ATTRIBUTES.has(lower) && written !== '' && value === '') {
|
|
550
573
|
continue;
|
|
551
574
|
} else if (!svg && LIVE_PROPERTIES.has(lower)) {
|
|
552
|
-
|
|
575
|
+
if (!bound && isNativeDefault(tag, lower)) {
|
|
576
|
+
defaults.push([name.toUpperCase(), lower === 'value' ? value : '']);
|
|
577
|
+
} else {
|
|
578
|
+
props[lower] = lower !== 'value' && written === '' ? true : value;
|
|
579
|
+
}
|
|
553
580
|
} else if (
|
|
554
581
|
!SETTABLE_NAME.test(name) ||
|
|
555
582
|
lower.startsWith('on') ||
|
|
@@ -561,6 +588,7 @@ function splitAttributes(
|
|
|
561
588
|
props[svg ? name : name.toUpperCase()] = value;
|
|
562
589
|
}
|
|
563
590
|
}
|
|
591
|
+
for (const [name, value] of defaults) props[name] = value;
|
|
564
592
|
return { props, direct };
|
|
565
593
|
}
|
|
566
594
|
|
|
@@ -731,8 +759,9 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
|
|
|
731
759
|
k,
|
|
732
760
|
resolveAttributeValue(k, v, scope, errors),
|
|
733
761
|
v,
|
|
762
|
+
hasInterpolation(v),
|
|
734
763
|
]);
|
|
735
|
-
const { props, direct } = splitAttributes(resolved, inSvg || isSvgRoot);
|
|
764
|
+
const { props, direct } = splitAttributes(resolved, inSvg || isSvgRoot, tag);
|
|
736
765
|
const ref = useDirectAttributes(direct);
|
|
737
766
|
if (ref) props.ref = ref;
|
|
738
767
|
const isInline = INLINE_ELEMENTS.has(tag);
|
package/src/parser.ts
CHANGED
|
@@ -57,11 +57,18 @@ const VOID_ELEMENTS = new Set([
|
|
|
57
57
|
* early, while text it leaves unescaped (in `<style>`, comments) would be
|
|
58
58
|
* decoded wrongly.
|
|
59
59
|
*/
|
|
60
|
-
function passageMarkup(parent: ParentNode): string {
|
|
60
|
+
function passageMarkup(parent: ParentNode, inElement = false): string {
|
|
61
|
+
// Text of the passage itself is its source. Text in a parsed element is
|
|
62
|
+
// what the browser decoded, so a reference it left (`&lt;`, now `<`)
|
|
63
|
+
// is written again as one, or rendering would decode it a second time.
|
|
64
|
+
const escapeText = inElement && !isLiteralTextElement(parent);
|
|
61
65
|
let markup = '';
|
|
62
66
|
for (const node of Array.from(parent.childNodes)) {
|
|
63
67
|
if (node.nodeType === Node.TEXT_NODE) {
|
|
64
|
-
|
|
68
|
+
const { data } = node as Text;
|
|
69
|
+
markup += escapeText
|
|
70
|
+
? escapeMarkupText(data, false, escapeTextReferences)
|
|
71
|
+
: data;
|
|
65
72
|
} else if (node.nodeType === Node.COMMENT_NODE) {
|
|
66
73
|
markup += `<!--${(node as Comment).data}-->`;
|
|
67
74
|
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
|
@@ -84,7 +91,7 @@ function elementMarkup(el: Element): string {
|
|
|
84
91
|
}
|
|
85
92
|
const content =
|
|
86
93
|
name === 'template' ? (el as HTMLTemplateElement).content : el;
|
|
87
|
-
return `${markup}${passageMarkup(content)}</${name}>`;
|
|
94
|
+
return `${markup}${passageMarkup(content, true)}</${name}>`;
|
|
88
95
|
}
|
|
89
96
|
|
|
90
97
|
/**
|
|
@@ -112,19 +119,43 @@ function quoteAttribute(name: string, value: string): string {
|
|
|
112
119
|
tag.attributes[probe] === quoted.slice(1, -1)
|
|
113
120
|
);
|
|
114
121
|
};
|
|
122
|
+
// Rendering decodes the references in the value, so one the browser
|
|
123
|
+
// already decoded is written again as one
|
|
124
|
+
const text = escapeMarkupText(value, code, escapeAttributeReferences);
|
|
115
125
|
return (
|
|
116
|
-
[`"${
|
|
117
|
-
`"${
|
|
126
|
+
[`"${text}"`, `'${text}'`].find(readsBack) ??
|
|
127
|
+
`"${escapeMarkupText(text, code, escapeQuotes)}"`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const escapeQuotes = (text: string) => text.replace(/"/g, '"');
|
|
132
|
+
const escapeAttributeReferences = (text: string) => text.replace(/&/g, '&');
|
|
133
|
+
/** Also `<`, which would start a tag in the passage. */
|
|
134
|
+
const escapeTextReferences = (text: string) =>
|
|
135
|
+
escapeAttributeReferences(text).replace(/</g, '<');
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Elements whose text the renderer shows as written, with no character
|
|
139
|
+
* references decoded: the one it treats as raw text (`style`, see
|
|
140
|
+
* HtmlNodeRenderer), for which the browser did not decode any either.
|
|
141
|
+
*/
|
|
142
|
+
function isLiteralTextElement(parent: ParentNode): boolean {
|
|
143
|
+
return (
|
|
144
|
+
(parent as Element).localName === 'style' &&
|
|
145
|
+
(parent as Element).namespaceURI === HTML_NAMESPACE
|
|
118
146
|
);
|
|
119
147
|
}
|
|
120
148
|
|
|
121
149
|
/**
|
|
122
|
-
* `value` with the
|
|
123
|
-
*
|
|
124
|
-
*
|
|
150
|
+
* `value` with the text in it escaped by `escape`, but not markup
|
|
151
|
+
* (`{print "a"}`) or, in a code attribute, sigil references (see
|
|
152
|
+
* splitSigilTemplate), which are code.
|
|
125
153
|
*/
|
|
126
|
-
function
|
|
127
|
-
|
|
154
|
+
function escapeMarkupText(
|
|
155
|
+
value: string,
|
|
156
|
+
code: boolean,
|
|
157
|
+
escape: (text: string) => string,
|
|
158
|
+
): string {
|
|
128
159
|
if (code) {
|
|
129
160
|
return splitSigilTemplate(value)
|
|
130
161
|
.map((part) =>
|
package/src/prng.ts
CHANGED
|
@@ -106,19 +106,26 @@ export function resetPRNG(): void {
|
|
|
106
106
|
generator = null;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** The position each running withoutDraws() takes its draws back to. */
|
|
110
|
+
const neutralScopes: Array<{ generation: number; seed: string; pull: number }> =
|
|
111
|
+
[];
|
|
112
|
+
|
|
109
113
|
/**
|
|
110
114
|
* Run `fn` without its draws advancing the sequence: the draws it makes are
|
|
111
115
|
* taken back afterwards (also when it throws), so the next draws return the
|
|
112
116
|
* same values again. Save and load event handlers run like this, so that
|
|
113
117
|
* saving or loading never shifts the story's random sequence (a load replays
|
|
114
118
|
* the saved passage from its entry state, without the save's handlers). A
|
|
115
|
-
* generator `fn` replaced (a restart or load it started) is kept
|
|
119
|
+
* generator `fn` replaced (a restart or load it started) is kept, and so are
|
|
120
|
+
* the draws made before a navigation `fn` started (see keepDrawsSoFar()).
|
|
116
121
|
*/
|
|
117
122
|
export function withoutDraws<T>(fn: () => T): T {
|
|
118
123
|
const start = { generation, seed: currentSeed, pull: currentPull };
|
|
124
|
+
neutralScopes.push(start);
|
|
119
125
|
try {
|
|
120
126
|
return fn();
|
|
121
127
|
} finally {
|
|
128
|
+
neutralScopes.splice(neutralScopes.indexOf(start), 1);
|
|
122
129
|
if (
|
|
123
130
|
enabled &&
|
|
124
131
|
generation === start.generation &&
|
|
@@ -129,6 +136,22 @@ export function withoutDraws<T>(fn: () => T): T {
|
|
|
129
136
|
}
|
|
130
137
|
}
|
|
131
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Make the draws up to now part of the story: the position of the generator
|
|
141
|
+
* is the one a history moment the story just entered records, and the
|
|
142
|
+
* moment's passage replays its rolls from there. A running withoutDraws()
|
|
143
|
+
* takes back only the draws made after this, so that the position the
|
|
144
|
+
* passage renders from stays the recorded one (#535). Navigation calls this
|
|
145
|
+
* once it has recorded the moment it enters.
|
|
146
|
+
*/
|
|
147
|
+
export function keepDrawsSoFar(): void {
|
|
148
|
+
for (const scope of neutralScopes) {
|
|
149
|
+
scope.generation = generation;
|
|
150
|
+
scope.seed = currentSeed;
|
|
151
|
+
scope.pull = currentPull;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
132
155
|
/** Returns the current PRNG state for snapshotting, or null if disabled. */
|
|
133
156
|
export function snapshotPRNG(): PRNGSnapshot | null {
|
|
134
157
|
if (!enabled) return null;
|