@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.
Files changed (62) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +947 -351
  4. package/dist/pkg/macro-registry.js +19 -0
  5. package/dist/pkg/macro-registry.json +19 -0
  6. package/dist/pkg/story-variables.js +780 -107
  7. package/package.json +1 -1
  8. package/src/action-registry.ts +59 -5
  9. package/src/automation/load-yaml.ts +111 -20
  10. package/src/automation/runner.ts +19 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +87 -20
  14. package/src/components/macros/Checkbox.tsx +5 -2
  15. package/src/components/macros/Cycle.tsx +1 -0
  16. package/src/components/macros/For.tsx +1 -7
  17. package/src/components/macros/Listbox.tsx +1 -0
  18. package/src/components/macros/MenubarButtons.tsx +6 -1
  19. package/src/components/macros/Nobr.tsx +1 -0
  20. package/src/components/macros/PassageDisplay.tsx +136 -10
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/Repeat.tsx +4 -2
  23. package/src/components/macros/SaveManager.tsx +30 -8
  24. package/src/components/macros/SettingsControls.tsx +19 -4
  25. package/src/components/macros/Span.tsx +1 -0
  26. package/src/components/macros/StoryTitle.tsx +1 -0
  27. package/src/components/macros/Unset.tsx +26 -13
  28. package/src/components/macros/VarDisplay.tsx +2 -3
  29. package/src/components/macros/WidgetInvocation.tsx +5 -6
  30. package/src/components/macros/input-macro.ts +1 -0
  31. package/src/components/macros/locals-scope.tsx +19 -8
  32. package/src/components/macros/macro-args.ts +11 -3
  33. package/src/expression.ts +34 -18
  34. package/src/hooks/use-merged-locals.ts +17 -2
  35. package/src/hooks/use-modal-focus.ts +247 -133
  36. package/src/index.tsx +32 -21
  37. package/src/js-bindings.ts +594 -0
  38. package/src/js-lexer.ts +76 -14
  39. package/src/macro-discovery.ts +83 -32
  40. package/src/markup/ast.ts +22 -1
  41. package/src/markup/render.tsx +44 -15
  42. package/src/parser.ts +41 -10
  43. package/src/prng.ts +24 -1
  44. package/src/saves/save-manager.ts +36 -9
  45. package/src/static-literal.ts +87 -16
  46. package/src/store.ts +83 -6
  47. package/src/story-api.ts +23 -6
  48. package/src/story-variables.ts +91 -28
  49. package/src/structural.ts +26 -15
  50. package/src/tooling.ts +24 -10
  51. package/src/transform.ts +22 -7
  52. package/src/utils/macro-names.ts +4 -0
  53. package/src/utils/namespace.ts +15 -2
  54. package/src/utils/object-path.ts +2 -2
  55. package/src/utils/stable-key.ts +17 -6
  56. package/src/utils/value-kinds.ts +38 -1
  57. package/src/widgets/ast-scanner.ts +4 -1
  58. package/src/widgets/register-widget-def.ts +2 -3
  59. package/src/widgets/widget-def.ts +36 -6
  60. package/src/widgets/widget-registry.ts +6 -2
  61. package/types/index.d.ts +12 -5
  62. package/types/tooling.d.ts +12 -2
@@ -4,6 +4,7 @@ import { NobrContext } from '../../markup/render';
4
4
  defineMacro({
5
5
  name: 'nobr',
6
6
  block: true,
7
+ interpolate: true,
7
8
  render({ children = [] }, ctx) {
8
9
  return ctx.wrap(
9
10
  ctx.h(
@@ -15,11 +15,143 @@ import { Passage, renderPassageContent } from '../Passage';
15
15
  import { defineMacro } from '../../define-macro';
16
16
  import { resolveTransition, type ResolvedTransition } from '../../transition';
17
17
 
18
+ /** Input types whose `value` is not what the user sees or edits. */
19
+ const VALUELESS_INPUTS = new Set([
20
+ 'checkbox',
21
+ 'radio',
22
+ 'file', // its value can not be set
23
+ 'hidden',
24
+ 'button',
25
+ 'submit',
26
+ 'reset',
27
+ 'image',
28
+ ]);
29
+
30
+ /**
31
+ * Copy the live state cloneNode drops from `source` into its clone: the
32
+ * pixels of each canvas, the state of form controls (cloneNode keeps
33
+ * attributes only, and a canvas's bitmap is not one), and the visible frame
34
+ * and position of media. Source and clone have the same structure, so
35
+ * elements pair up by position. Best effort: a canvas or video that can not
36
+ * be drawn from stays as cloned.
37
+ */
38
+ function copyLiveState(source: Element, clone: Element): void {
39
+ const pairs = <T extends Element>(
40
+ selector: string,
41
+ each: (a: T, b: T) => void,
42
+ ) => {
43
+ const from = source.querySelectorAll<T>(selector);
44
+ const to = clone.querySelectorAll<T>(selector);
45
+ from.forEach((el, i) => to[i] && each(el, to[i]!));
46
+ };
47
+
48
+ pairs<HTMLCanvasElement>('canvas', (from, to) => {
49
+ if (!from.width || !from.height) return;
50
+ try {
51
+ if (to.width !== from.width) to.width = from.width;
52
+ if (to.height !== from.height) to.height = from.height;
53
+ to.getContext('2d')?.drawImage(from, 0, 0);
54
+ } catch {
55
+ // tainted, lost or foreign-context canvas: the snapshot shows it blank
56
+ }
57
+ });
58
+
59
+ pairs<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(
60
+ 'input, textarea, select',
61
+ (from, to) => {
62
+ if (from instanceof HTMLSelectElement) {
63
+ // `select.value` is the first selected option only: it loses the other
64
+ // selections of a multiple select (and the pick among options of one
65
+ // value), so a multiple select goes option by option
66
+ const select = to as HTMLSelectElement;
67
+ if (!from.multiple) {
68
+ select.selectedIndex = from.selectedIndex;
69
+ } else {
70
+ for (let i = 0; i < from.options.length; i++) {
71
+ const option = select.options[i];
72
+ if (option) option.selected = from.options[i]!.selected;
73
+ }
74
+ }
75
+ } else if (from instanceof HTMLInputElement) {
76
+ const input = to as HTMLInputElement;
77
+ input.checked = from.checked;
78
+ input.indeterminate = from.indeterminate;
79
+ if (!VALUELESS_INPUTS.has(from.type)) input.value = from.value;
80
+ } else {
81
+ to.value = from.value;
82
+ }
83
+ },
84
+ );
85
+
86
+ pairs<HTMLMediaElement>('audio, video', (from, to) => {
87
+ // The snapshot is a picture: silent, still, and not started by autoplay
88
+ to.pause?.();
89
+ to.muted = true;
90
+ to.removeAttribute('autoplay');
91
+ try {
92
+ // Applied once the metadata is there: the progress of native controls
93
+ to.currentTime = from.currentTime;
94
+ } catch {
95
+ // no such position yet: the snapshot shows the start
96
+ }
97
+ if (!(from instanceof HTMLVideoElement && to instanceof HTMLVideoElement)) {
98
+ return;
99
+ }
100
+ // A fresh clone decodes nothing, so it would show its first frame (or
101
+ // the poster). Draw the frame on screen now into the poster, which is
102
+ // shown at once and needs no load or seek to finish.
103
+ if (from.readyState < 2 || !from.videoWidth || !from.videoHeight) return;
104
+ try {
105
+ const frame = document.createElement('canvas');
106
+ frame.width = from.videoWidth;
107
+ frame.height = from.videoHeight;
108
+ frame.getContext('2d')?.drawImage(from, 0, 0);
109
+ to.setAttribute('poster', frame.toDataURL('image/jpeg', 0.92));
110
+ } catch {
111
+ // a cross-origin video without CORS taints the canvas: keeps its poster
112
+ }
113
+ });
114
+ }
115
+
116
+ type ScrollOffset = [element: Element, top: number, left: number];
117
+
118
+ /**
119
+ * Scroll offsets of the elements of `source` (itself included) that are
120
+ * scrolled, keyed by the matching element of `clone`. Applied once the clone
121
+ * is in the page: a detached element has nothing to scroll.
122
+ */
123
+ function scrollOffsets(source: Element, clone: Element): ScrollOffset[] {
124
+ const from = [source, ...source.querySelectorAll('*')];
125
+ const to = [clone, ...clone.querySelectorAll('*')];
126
+ const offsets: ScrollOffset[] = [];
127
+ from.forEach((el, i) => {
128
+ if (to[i] && (el.scrollTop || el.scrollLeft)) {
129
+ offsets.push([to[i]!, el.scrollTop, el.scrollLeft]);
130
+ }
131
+ });
132
+ return offsets;
133
+ }
134
+
135
+ const pendingScrolls = new WeakMap<Element, ScrollOffset[]>();
136
+
137
+ /** Add `snapshot` to `container`, scrolled as what it shows was. */
138
+ function appendSnapshot(container: Element, snapshot: HTMLElement): void {
139
+ container.appendChild(snapshot);
140
+ for (const [el, top, left] of pendingScrolls.get(snapshot) ?? []) {
141
+ el.scrollTop = top;
142
+ el.scrollLeft = left;
143
+ }
144
+ pendingScrolls.delete(snapshot);
145
+ }
146
+
18
147
  /**
19
148
  * Create a snapshot clone of a .passage element for outgoing transitions.
20
149
  * - Strips `id` attributes from the clone tree
21
150
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
22
151
  * - Pauses/mutes any <audio>/<video>
152
+ * - Copies what cloneNode leaves behind: canvas pixels, the state of form
153
+ * controls, the visible frame of videos (#512, #525, #536) and, through
154
+ * `appendSnapshot`, scroll offsets
23
155
  * - Adds `.passage-snapshot` class and `data-transition` attribute
24
156
  */
25
157
  function createSnapshot(
@@ -27,6 +159,8 @@ function createSnapshot(
27
159
  transitionType: string,
28
160
  ): HTMLElement {
29
161
  const clone = passageEl.cloneNode(true) as HTMLElement;
162
+ copyLiveState(passageEl, clone);
163
+ pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
30
164
 
31
165
  // Strip id attributes to avoid duplicates
32
166
  clone.removeAttribute('id');
@@ -43,14 +177,6 @@ function createSnapshot(
43
177
  clone.setAttribute('inert', '');
44
178
  clone.setAttribute('aria-hidden', 'true');
45
179
 
46
- // Pause/mute media
47
- const mediaEls = clone.querySelectorAll('audio, video');
48
- for (let i = 0; i < mediaEls.length; i++) {
49
- const media = mediaEls[i] as HTMLMediaElement;
50
- media.pause?.();
51
- media.muted = true;
52
- }
53
-
54
180
  // Mark as snapshot
55
181
  clone.classList.remove('passage');
56
182
  clone.classList.add('passage-snapshot');
@@ -291,7 +417,7 @@ defineMacro({
291
417
 
292
418
  if (config.type === 'fade-through') {
293
419
  // idle → outgoing (fade out snapshot) → paused → incoming (mount new, fade in) → idle
294
- containerEl.appendChild(snapshot);
420
+ appendSnapshot(containerEl, snapshot);
295
421
 
296
422
  // Hide the current passage during outgoing phase by setting empty key
297
423
  setDisplayedPassage('');
@@ -319,7 +445,7 @@ defineMacro({
319
445
 
320
446
  // Use CSS grid stacking for crossfade
321
447
  containerEl.classList.add('passage-container--crossfading');
322
- containerEl.appendChild(snapshot);
448
+ appendSnapshot(containerEl, snapshot);
323
449
 
324
450
  // Mount new passage immediately alongside snapshot
325
451
  setDisplayedPassage(currentPassage);
@@ -4,6 +4,7 @@ import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
4
4
 
5
5
  defineMacro({
6
6
  name: 'radiobutton',
7
+ interpolate: true,
7
8
  storeVar: true,
8
9
  parameters: [
9
10
  VARIABLE_PARAMETER,
@@ -1,4 +1,4 @@
1
- import { createContext } from 'preact';
1
+ import { createContext, Fragment } from 'preact';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { DELAY_PARAMETER } from './macro-args';
4
4
  import { OutgoingContext } from '../../hooks/use-story-fields';
@@ -37,7 +37,9 @@ defineMacro({
37
37
 
38
38
  const content = (
39
39
  <RepeatContext.Provider value={{ stop }}>
40
- <span key={count}>{ctx.renderNodes(children)}</span>
40
+ {/* A keyed Fragment remounts the body each tick without a DOM
41
+ wrapper that would break `tbody > tr`, `ul > li`, ... (#520) */}
42
+ <Fragment key={count}>{ctx.renderNodes(children)}</Fragment>
41
43
  </RepeatContext.Provider>
42
44
  );
43
45
 
@@ -8,6 +8,7 @@ import {
8
8
  import {
9
9
  useStoryStore,
10
10
  resolvePlaythroughId,
11
+ followSavedPlaythrough,
11
12
  issueStateReplacement,
12
13
  isStateReplacementSuperseded,
13
14
  } from '../../store';
@@ -54,7 +55,13 @@ function formatDate(iso: string): string {
54
55
  });
55
56
  }
56
57
 
57
- export function SaveManagerContent() {
58
+ export function SaveManagerContent({
59
+ className,
60
+ id,
61
+ }: {
62
+ className?: string;
63
+ id?: string;
64
+ }) {
58
65
  const [mode, setMode] = useState<'save' | 'load'>('load');
59
66
  const [groups, setGroups] = useState<PlaythroughGroup[]>([]);
60
67
  const [loading, setLoading] = useState(true);
@@ -148,7 +155,8 @@ export function SaveManagerContent() {
148
155
  try {
149
156
  await saveWithHooks(undefined, undefined, beginSave, async (payload) => {
150
157
  // Queued now, in call order with other storage operations
151
- return createSave(ifid, playthrough, payload);
158
+ const saved = await createSave(ifid, playthrough, payload);
159
+ await followSavedPlaythrough(playthrough, saved);
152
160
  });
153
161
  showStatus(temporary ? 'Save created (temporary)' : 'Save created');
154
162
  await refresh();
@@ -162,9 +170,14 @@ export function SaveManagerContent() {
162
170
  try {
163
171
  await saveWithHooks(undefined, undefined, beginSave, async (payload) => {
164
172
  // Only the current playthrough's saves offer "Save Here"
165
- if (!(await overwriteSave(saveId, payload, undefined, playthrough))) {
166
- throw new Error('Save not found');
167
- }
173
+ const saved = await overwriteSave(
174
+ saveId,
175
+ payload,
176
+ undefined,
177
+ playthrough,
178
+ );
179
+ if (!saved) throw new Error('Save not found');
180
+ await followSavedPlaythrough(playthrough, saved);
168
181
  });
169
182
  showStatus('Save overwritten');
170
183
  await refresh();
@@ -307,7 +320,10 @@ export function SaveManagerContent() {
307
320
  const totalSaves = groups.reduce((n, g) => n + g.saves.length, 0);
308
321
 
309
322
  return (
310
- <div class="save-manager">
323
+ <div
324
+ id={id}
325
+ class={className ? `save-manager ${className}` : 'save-manager'}
326
+ >
311
327
  <div class="saves-header">
312
328
  <div class="saves-header-left">
313
329
  <div class="saves-mode-toggle">
@@ -512,7 +528,13 @@ export function SaveManagerContent() {
512
528
 
513
529
  defineMacro({
514
530
  name: 'save-manager',
515
- render() {
516
- return <SaveManagerContent />;
531
+ interpolate: true,
532
+ render(_props, ctx) {
533
+ return (
534
+ <SaveManagerContent
535
+ className={ctx.className}
536
+ id={ctx.id}
537
+ />
538
+ );
517
539
  },
518
540
  });
@@ -68,11 +68,20 @@ function SettingControl({ name, def }: { name: string; def: SettingDef }) {
68
68
  }
69
69
  }
70
70
 
71
- function SettingsControlsContent() {
71
+ function SettingsControlsContent({
72
+ className,
73
+ id,
74
+ }: {
75
+ className?: string;
76
+ id?: string;
77
+ }) {
72
78
  const defs = settings.getDefinitions();
73
79
 
74
80
  return (
75
- <div class="settings-controls">
81
+ <div
82
+ id={id}
83
+ class={className ? `settings-controls ${className}` : 'settings-controls'}
84
+ >
76
85
  {Array.from(defs.entries()).map(([name, def]) => (
77
86
  <SettingControl
78
87
  key={name}
@@ -86,7 +95,13 @@ function SettingsControlsContent() {
86
95
 
87
96
  defineMacro({
88
97
  name: 'settings-controls',
89
- render() {
90
- return <SettingsControlsContent />;
98
+ interpolate: true,
99
+ render(_props, ctx) {
100
+ return (
101
+ <SettingsControlsContent
102
+ className={ctx.className}
103
+ id={ctx.id}
104
+ />
105
+ );
91
106
  },
92
107
  });
@@ -3,6 +3,7 @@ import { defineMacro } from '../../define-macro';
3
3
  defineMacro({
4
4
  name: 'span',
5
5
  block: true,
6
+ interpolate: true,
6
7
  render({ children = [] }, ctx) {
7
8
  return ctx.wrap(ctx.renderNodes(children));
8
9
  },
@@ -3,6 +3,7 @@ import { defineMacro } from '../../define-macro';
3
3
 
4
4
  defineMacro({
5
5
  name: 'story-title',
6
+ interpolate: true,
6
7
  render(_, ctx) {
7
8
  const name = useStoryStore((s) => s.storyData?.name || '');
8
9
  const cls = ctx.className ? `story-title ${ctx.className}` : 'story-title';
@@ -1,7 +1,19 @@
1
1
  import { useStoryStore } from '../../store';
2
2
  import { defineMacro } from '../../define-macro';
3
+ import { CodeSyntaxError, parseReferencePath } from '../../js-lexer';
4
+ import type { ReferencePath } from '../../js-lexer';
3
5
  import { useRunOnce } from './MacroError';
4
6
 
7
+ /** What `name` is as a variable reference, or null if it is no reference. */
8
+ function referencePath(name: string): ReferencePath | null {
9
+ try {
10
+ return parseReferencePath(name);
11
+ } catch (error) {
12
+ if (error instanceof CodeSyntaxError) return null;
13
+ throw error;
14
+ }
15
+ }
16
+
5
17
  defineMacro({
6
18
  name: 'unset',
7
19
  parameters: [{ name: 'variable', type: 'variable', required: true }],
@@ -9,24 +21,25 @@ defineMacro({
9
21
  return useRunOnce('unset', rawArgs, () => {
10
22
  const state = useStoryStore.getState();
11
23
  const name = ctx.args.variable ?? '';
24
+ const path = referencePath(name);
12
25
 
13
- if (/^[$_%@][^.]*\./.test(name)) {
26
+ if (!path) {
27
+ throw new Error(
28
+ `{unset} expects a variable ($name, _name, %name, or @name, or a field of one such as $name.field or $name["field"]), got "${name}"`,
29
+ );
30
+ } else if (path.nested) {
14
31
  // A field of a variable: delete it as mutation code does, which
15
32
  // resolves the path in every namespace
16
33
  ctx.mutate(`delete ${name}`);
17
- } else if (name.startsWith('$')) {
18
- state.deleteVariable(name.slice(1));
19
- } else if (name.startsWith('_')) {
20
- state.deleteTemporary(name.slice(1));
21
- } else if (name.startsWith('%')) {
22
- state.deleteTransient(name.slice(1));
23
- } else if (name.startsWith('@')) {
24
- // Throws outside a locals scope ({for}, widget, {link}, {button})
25
- ctx.update(name.slice(1), undefined);
34
+ } else if (path.sigil === '$') {
35
+ state.deleteVariable(path.name);
36
+ } else if (path.sigil === '_') {
37
+ state.deleteTemporary(path.name);
38
+ } else if (path.sigil === '%') {
39
+ state.deleteTransient(path.name);
26
40
  } else {
27
- throw new Error(
28
- `{unset} expects a variable ($name, _name, %name, or @name), got "${name}"`,
29
- );
41
+ // Throws outside a locals scope ({for}, widget, {link}, {button})
42
+ ctx.update(path.name, undefined);
30
43
  }
31
44
  });
32
45
  },
@@ -1,6 +1,5 @@
1
1
  import { useStoryStore } from '../../store';
2
- import { useContext } from 'preact/hooks';
3
- import { LocalsValuesContext } from '../../markup/render';
2
+ import { useLiveLocals } from '../../hooks/use-merged-locals';
4
3
  import { useInterpolate } from '../../hooks/use-interpolate';
5
4
  import { ownValue, variableNameError } from '../../utils/namespace';
6
5
  import { SCOPE_SIGILS } from '../../markup/tokens';
@@ -19,7 +18,7 @@ export function VarDisplay({ node }: { node: VariableNode }) {
19
18
  const resolve = useInterpolate();
20
19
  const className = resolve(node.className);
21
20
  const id = resolve(node.id);
22
- const localsValues = useContext(LocalsValuesContext);
21
+ const localsValues = useLiveLocals();
23
22
  const parts = name.split('.');
24
23
  const root = parts[0]!;
25
24
  // Own entries only, as the expression engine reads them
@@ -5,7 +5,6 @@ import { evaluate } from '../../expression';
5
5
  import type { ASTNode } from '../../markup/ast';
6
6
  import { splitArgs } from './arg-utils';
7
7
  import { createNamespace } from '../../utils/namespace';
8
- import { useRenderOptions } from '../../hooks/use-render-options';
9
8
  import { LocalsScope } from './locals-scope';
10
9
  import { useInterpolate } from '../../hooks/use-interpolate';
11
10
  import { wrapContent } from './display';
@@ -40,8 +39,6 @@ function WidgetContent({
40
39
  rawArgs,
41
40
  invocationChildren,
42
41
  }: WidgetInvocationProps) {
43
- const renderOptions = useRenderOptions();
44
- const parentValues = renderOptions.locals;
45
42
  const [mergedVars, mergedTemps, mergedLocals, mergedTrans] =
46
43
  useMergedLocals();
47
44
 
@@ -76,6 +73,9 @@ function WidgetContent({
76
73
  values.push(value);
77
74
  }
78
75
 
76
+ // The names too: the widget may be redefined under a mounted invocation,
77
+ // with other parameters for the same argument values (#511)
78
+ const paramsKey = params.join(' ');
79
79
  const ownKeys = useMemo(() => {
80
80
  const keys = createNamespace();
81
81
  for (let i = 0; i < params.length; i++) {
@@ -83,15 +83,14 @@ function WidgetContent({
83
83
  values[i];
84
84
  }
85
85
  return keys;
86
- // params is stable per widget instance; values tracks evaluated args
86
+ // paramsKey stands for params; values tracks evaluated args
87
87
  // eslint-disable-next-line react-hooks/exhaustive-deps
88
- }, values);
88
+ }, [paramsKey, ...values]);
89
89
 
90
90
  return (
91
91
  <WidgetChildrenContext.Provider value={childrenValue}>
92
92
  <LocalsScope
93
93
  body={body}
94
- parentValues={parentValues}
95
94
  ownKeys={ownKeys}
96
95
  />
97
96
  </WidgetChildrenContext.Provider>
@@ -45,6 +45,7 @@ export function defineInputMacro(
45
45
  ): void {
46
46
  defineMacro({
47
47
  name,
48
+ interpolate: true,
48
49
  storeVar: true,
49
50
  parameters: [
50
51
  VARIABLE_PARAMETER,
@@ -1,4 +1,10 @@
1
- import { useState, useCallback, useRef, useMemo } from 'preact/hooks';
1
+ import {
2
+ useState,
3
+ useCallback,
4
+ useContext,
5
+ useRef,
6
+ useMemo,
7
+ } from 'preact/hooks';
2
8
  import {
3
9
  LocalsValuesContext,
4
10
  LocalsUpdateContext,
@@ -13,17 +19,15 @@ import {
13
19
  } from '../../utils/namespace';
14
20
 
15
21
  /**
16
- * Render `body` in a new locals scope: the locals of `parentValues`, with
17
- * `ownKeys` (an iteration's loop variables, a widget's parameters) on top.
18
- * Locals the body assigns are kept in this scope.
22
+ * Render `body` in a new locals scope: the locals of the enclosing scope,
23
+ * with `ownKeys` (an iteration's loop variables, a widget's parameters) on
24
+ * top. Locals the body assigns are kept in this scope.
19
25
  */
20
26
  export function LocalsScope({
21
27
  body,
22
- parentValues,
23
28
  ownKeys,
24
29
  }: {
25
30
  body: ASTNode[];
26
- parentValues: Record<string, unknown>;
27
31
  ownKeys: Record<string, unknown>;
28
32
  }) {
29
33
  const options = useRenderOptions();
@@ -31,9 +35,16 @@ export function LocalsScope({
31
35
  {},
32
36
  );
33
37
 
38
+ // The enclosing scope as it is now: a local assigned before this scope
39
+ // renders is in it, while the context value only gains it in the re-render
40
+ // that follows (and the body may have acted on its absence by then).
41
+ const enclosing = useContext(LocalsUpdateContext).getValues();
42
+ const parentValues = useContext(LocalsValuesContext);
34
43
  const localState = useMemo(
35
- () => createNamespace(parentValues, ownKeys, localMutations),
36
- [parentValues, ownKeys, localMutations],
44
+ () => createNamespace(enclosing, ownKeys, localMutations),
45
+ // `parentValues` renews the scope when the enclosing one re-renders
46
+ // eslint-disable-next-line react-hooks/exhaustive-deps
47
+ [enclosing, parentValues, ownKeys, localMutations],
37
48
  );
38
49
 
39
50
  const valuesRef = useRef(localState);
@@ -182,10 +182,16 @@ const LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
182
182
  * Where the rest of `src` is without the flag `word` as its last or first
183
183
  * term, or `null` if it has no such flag. Next to a binary operator the
184
184
  * word is an operand (`"a" + inline`), not a flag; the closing `/` of a
185
- * regex literal is not one.
185
+ * regex literal is not one. A word with nothing else beside it is the flag
186
+ * only when `alone` says no argument is waiting for it (#499).
186
187
  */
187
- function takeFlag(src: string, word: string): Span | null {
188
+ function takeFlag(src: string, word: string, alone: boolean): Span | null {
188
189
  const spans = terms(src);
190
+ if (spans.length === 1) {
191
+ return alone && slice(src, spans[0]!) === word
192
+ ? [src.length, src.length]
193
+ : null;
194
+ }
189
195
  if (spans.length < 2) return null;
190
196
  if (slice(src, spans[spans.length - 1]!) === word) {
191
197
  const rest: Span = [0, spans[spans.length - 2]![1]];
@@ -249,8 +255,10 @@ function readGroup(
249
255
  { at: srcAt, spans }: Place,
250
256
  ): void {
251
257
  let [text, at] = trimmed(src ?? '', srcAt);
258
+ // A lone word is the passage of {include inline}, not its flag
259
+ const alone = !params.some((p) => p.type !== 'flag' && p.required);
252
260
  for (const flag of params.filter((p) => p.type === 'flag')) {
253
- const rest = src === null ? null : takeFlag(text, flag.name);
261
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
254
262
  args[flag.name] = rest !== null;
255
263
  if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
256
264
  }
package/src/expression.ts CHANGED
@@ -2,7 +2,13 @@ import type { StoryState } from './store';
2
2
  import { useStoryStore } from './store';
3
3
  import type { Passage } from './parser';
4
4
  import { random, randomInt } from './prng';
5
- import { clearTransformCache, transform } from './transform';
5
+ import {
6
+ BINDINGS,
7
+ FNS_BINDING,
8
+ clearTransformCache,
9
+ transform,
10
+ } from './transform';
11
+ import type { JsGoal } from './js-lexer';
6
12
  import {
7
13
  EMPTY_NAMESPACE,
8
14
  asNamespace,
@@ -40,10 +46,31 @@ export { transform };
40
46
  const FN_CACHE_MAX = 500;
41
47
  const fnCache = new Map<string, CompiledExpression>();
42
48
 
43
- const preamble =
44
- 'const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=__fns;';
49
+ const preamble = `const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=${FNS_BINDING};`;
45
50
 
46
- function getOrCompile(key: string, body: string): CompiledExpression {
51
+ /**
52
+ * Compile `source`: the function takes the namespaces and the function
53
+ * table under the names the transform uses for the references (see
54
+ * BINDINGS). The statements are a block of their own, so that they may
55
+ * declare any name, those of the history functions the preamble declares
56
+ * included.
57
+ */
58
+ function compile(source: string, goal: JsGoal): CompiledExpression {
59
+ const code = transform(source, goal);
60
+ // The line break keeps a trailing `// comment` from swallowing the closer.
61
+ const body = goal === 'statements' ? `{${code}\n}` : `return (${code}\n);`;
62
+ return new Function(
63
+ BINDINGS.$,
64
+ BINDINGS._,
65
+ BINDINGS['@'],
66
+ FNS_BINDING,
67
+ BINDINGS['%'],
68
+ preamble + body,
69
+ ) as CompiledExpression;
70
+ }
71
+
72
+ function getOrCompile(source: string, goal: JsGoal): CompiledExpression {
73
+ const key = (goal === 'statements' ? 's' : 'e') + source;
47
74
  const cached = fnCache.get(key);
48
75
  if (cached) {
49
76
  // Move to end for LRU ordering (Map preserves insertion order)
@@ -51,14 +78,7 @@ function getOrCompile(key: string, body: string): CompiledExpression {
51
78
  fnCache.set(key, cached);
52
79
  return cached;
53
80
  }
54
- const fn = new Function(
55
- 'variables',
56
- 'temporary',
57
- 'locals',
58
- '__fns',
59
- 'transient',
60
- preamble + body,
61
- ) as CompiledExpression;
81
+ const fn = compile(source, goal);
62
82
  fnCache.set(key, fn);
63
83
  if (fnCache.size > FN_CACHE_MAX) {
64
84
  // Evict oldest entry
@@ -188,10 +208,7 @@ function run(
188
208
  * e.g. evaluate("$health + 10", variables, temporary) → number
189
209
  */
190
210
  export function evaluate(expr: string, ...namespaces: Namespaces): unknown {
191
- const transformed = transform(expr);
192
- // The line break keeps a trailing `// comment` from swallowing the `)`.
193
- const body = `return (${transformed}\n);`;
194
- return run(getOrCompile(body, body), ...namespaces);
211
+ return run(getOrCompile(expr, 'expression'), ...namespaces);
195
212
  }
196
213
 
197
214
  /**
@@ -199,8 +216,7 @@ export function evaluate(expr: string, ...namespaces: Namespaces): unknown {
199
216
  * e.g. execute("$health = 100; $name = 'Hero'", variables, temporary)
200
217
  */
201
218
  export function execute(code: string, ...namespaces: Namespaces): void {
202
- const transformed = transform(code, 'statements');
203
- run(getOrCompile('exec:' + transformed, transformed), ...namespaces);
219
+ run(getOrCompile(code, 'statements'), ...namespaces);
204
220
  }
205
221
 
206
222
  /**