@rohal12/spindle 0.59.30 → 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.
@@ -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
- const key = this.key();
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;
169
+ this.space();
170
+ const spread = src.charAt(this.i) === '{' ? this.record() : undefined;
143
171
  this.space();
144
- if (key !== undefined && this.src.charAt(this.i) === ':') {
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
- } else if (!this.skipMember()) {
148
- // A method, a shorthand member, a spread: not a literal
149
- this.fail();
183
+ return;
150
184
  }
151
- });
152
- return ok ? { type: 'object', props } : undefined;
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. */
@@ -268,14 +314,16 @@ function macroOf(config: Datum): DiscoveredMacro | undefined {
268
314
  * file) declare, in source order, read from the text without running it. A
269
315
  * call whose config is an object literal (or a variable declared as one with
270
316
  * `const`, `let` or `var` that the call sees, see Bindings: not a parameter, a
271
- * pattern or an assignment of the name) and whose `name` is a string is found,
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,
272
319
  * wherever it is, even inside a function. Only what is written out is read: a `block`,
273
320
  * `interpolate`, `storeVar` or `merged` that is a boolean literal, the
274
321
  * strings of `subMacros`, and `parameters` when every one is an object
275
322
  * literal with a string `name` and `type` (and `holds`, `required`,
276
323
  * `description` and nested `parameters` of options when written out as such);
277
- * a list with a parameter that is not, or that `defineMacro` would refuse,
278
- * declares none. It is tolerant: text it cannot read is skipped, and it
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
279
327
  * throws for none.
280
328
  */
281
329
  export function discoverMacros(source: string): DiscoveredMacro[] {
@@ -288,7 +336,7 @@ export function discoverMacros(source: string): DiscoveredMacro[] {
288
336
  const variable = IDENTIFIER_ARGUMENT_RE.exec(code.slice(at))?.[1];
289
337
  if (!variable) continue;
290
338
  bindings ??= new Bindings(code);
291
- const object = bindings.objectOf(variable, call.index);
339
+ const object = bindings.objectOf(variable, call.index, CONFIG_KEYS);
292
340
  if (object === undefined) continue;
293
341
  at = object;
294
342
  }
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);
@@ -188,8 +188,11 @@ function expandPlaceholderText(
188
188
  );
189
189
  }
190
190
 
191
- /** An attribute: its name, value and value as written (see splitAttributes). */
192
- type Attribute = [name: string, value: string, written: string];
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
- * the live state of form controls and media, which then follows its
452
- * variable even after the reader changed it. Boolean ones written bare or
453
- * as `=""` are passed as `true`, since '' is falsy (#177); one that only
454
- * resolves to '' through an interpolation stays ''.
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
- for (const [name, value, written] of attributes) {
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
- props[lower] = lower !== 'value' && written === '' ? true : value;
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 (`&amp;lt;`, now `&lt;`)
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
- markup += (node as Text).data;
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
- [`"${value}"`, `'${value}'`].find(readsBack) ??
117
- `"${escapeTextQuotes(value, code)}"`
126
+ [`"${text}"`, `'${text}'`].find(readsBack) ??
127
+ `"${escapeMarkupText(text, code, escapeQuotes)}"`
128
+ );
129
+ }
130
+
131
+ const escapeQuotes = (text: string) => text.replace(/"/g, '&quot;');
132
+ const escapeAttributeReferences = (text: string) => text.replace(/&/g, '&amp;');
133
+ /** Also `<`, which would start a tag in the passage. */
134
+ const escapeTextReferences = (text: string) =>
135
+ escapeAttributeReferences(text).replace(/</g, '&lt;');
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 double quotes in its text written as `&quot;`, but not
123
- * those in markup (`{print "a"}`) or, in a code attribute, in sigil
124
- * references (see splitSigilTemplate), which are code.
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 escapeTextQuotes(value: string, code: boolean): string {
127
- const escape = (text: string) => text.replace(/"/g, '&quot;');
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;
@@ -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
- const playthroughs = await backend.getPlaythroughsByIfid(ifid);
235
- if (!playthroughs.some((p) => p.id === id)) {
236
- await backend.putPlaythrough({ id, ifid, createdAt, label: 'Imported' });
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 playthroughId = await playthroughPromise;
325
- if (!playthroughId) throw new Error('No playthrough');
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 playthroughId = await playthroughPromise;
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
  {