@rohal12/spindle 0.59.29 → 0.59.30

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 (50) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +560 -272
  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 +494 -90
  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 +15 -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 +42 -0
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/SaveManager.tsx +19 -4
  23. package/src/components/macros/SettingsControls.tsx +19 -4
  24. package/src/components/macros/Span.tsx +1 -0
  25. package/src/components/macros/StoryTitle.tsx +1 -0
  26. package/src/components/macros/VarDisplay.tsx +2 -3
  27. package/src/components/macros/WidgetInvocation.tsx +5 -6
  28. package/src/components/macros/input-macro.ts +1 -0
  29. package/src/components/macros/locals-scope.tsx +19 -8
  30. package/src/components/macros/macro-args.ts +11 -3
  31. package/src/expression.ts +34 -18
  32. package/src/hooks/use-merged-locals.ts +17 -2
  33. package/src/hooks/use-modal-focus.ts +190 -129
  34. package/src/index.tsx +22 -12
  35. package/src/js-bindings.ts +332 -0
  36. package/src/js-lexer.ts +12 -3
  37. package/src/macro-discovery.ts +25 -22
  38. package/src/static-literal.ts +87 -16
  39. package/src/store.ts +4 -1
  40. package/src/story-api.ts +13 -4
  41. package/src/story-variables.ts +91 -28
  42. package/src/structural.ts +19 -15
  43. package/src/tooling.ts +21 -8
  44. package/src/transform.ts +22 -7
  45. package/src/utils/namespace.ts +4 -0
  46. package/src/utils/object-path.ts +2 -2
  47. package/src/utils/stable-key.ts +17 -6
  48. package/src/utils/value-kinds.ts +38 -1
  49. package/types/index.d.ts +12 -5
  50. package/types/tooling.d.ts +12 -2
@@ -15,11 +15,52 @@ import { Passage, renderPassageContent } from '../Passage';
15
15
  import { defineMacro } from '../../define-macro';
16
16
  import { resolveTransition, type ResolvedTransition } from '../../transition';
17
17
 
18
+ /**
19
+ * Copy the live state cloneNode drops from `source` into its clone: the
20
+ * pixels of each canvas and the values of form controls (cloneNode keeps
21
+ * attributes only, and a canvas's bitmap is not one). Source and clone have
22
+ * the same structure, so elements pair up by position. Best effort: a canvas
23
+ * that can not be drawn from stays as cloned.
24
+ */
25
+ function copyLiveState(source: Element, clone: Element): void {
26
+ const pairs = <T extends Element>(
27
+ selector: string,
28
+ each: (a: T, b: T) => void,
29
+ ) => {
30
+ const from = source.querySelectorAll<T>(selector);
31
+ const to = clone.querySelectorAll<T>(selector);
32
+ from.forEach((el, i) => to[i] && each(el, to[i]!));
33
+ };
34
+
35
+ pairs<HTMLCanvasElement>('canvas', (from, to) => {
36
+ if (!from.width || !from.height) return;
37
+ try {
38
+ if (to.width !== from.width) to.width = from.width;
39
+ if (to.height !== from.height) to.height = from.height;
40
+ to.getContext('2d')?.drawImage(from, 0, 0);
41
+ } catch {
42
+ // tainted, lost or foreign-context canvas: the snapshot shows it blank
43
+ }
44
+ });
45
+
46
+ pairs<HTMLInputElement>('input, textarea, select', (from, to) => {
47
+ if (from instanceof HTMLInputElement && to instanceof HTMLInputElement) {
48
+ to.checked = from.checked;
49
+ }
50
+ // A file input's value can not be set
51
+ if (!(from instanceof HTMLInputElement && from.type === 'file')) {
52
+ to.value = from.value;
53
+ }
54
+ });
55
+ }
56
+
18
57
  /**
19
58
  * Create a snapshot clone of a .passage element for outgoing transitions.
20
59
  * - Strips `id` attributes from the clone tree
21
60
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
22
61
  * - Pauses/mutes any <audio>/<video>
62
+ * - Copies what cloneNode leaves behind: canvas pixels and the values of
63
+ * form controls (#512)
23
64
  * - Adds `.passage-snapshot` class and `data-transition` attribute
24
65
  */
25
66
  function createSnapshot(
@@ -27,6 +68,7 @@ function createSnapshot(
27
68
  transitionType: string,
28
69
  ): HTMLElement {
29
70
  const clone = passageEl.cloneNode(true) as HTMLElement;
71
+ copyLiveState(passageEl, clone);
30
72
 
31
73
  // Strip id attributes to avoid duplicates
32
74
  clone.removeAttribute('id');
@@ -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,
@@ -54,7 +54,13 @@ function formatDate(iso: string): string {
54
54
  });
55
55
  }
56
56
 
57
- export function SaveManagerContent() {
57
+ export function SaveManagerContent({
58
+ className,
59
+ id,
60
+ }: {
61
+ className?: string;
62
+ id?: string;
63
+ }) {
58
64
  const [mode, setMode] = useState<'save' | 'load'>('load');
59
65
  const [groups, setGroups] = useState<PlaythroughGroup[]>([]);
60
66
  const [loading, setLoading] = useState(true);
@@ -307,7 +313,10 @@ export function SaveManagerContent() {
307
313
  const totalSaves = groups.reduce((n, g) => n + g.saves.length, 0);
308
314
 
309
315
  return (
310
- <div class="save-manager">
316
+ <div
317
+ id={id}
318
+ class={className ? `save-manager ${className}` : 'save-manager'}
319
+ >
311
320
  <div class="saves-header">
312
321
  <div class="saves-header-left">
313
322
  <div class="saves-mode-toggle">
@@ -512,7 +521,13 @@ export function SaveManagerContent() {
512
521
 
513
522
  defineMacro({
514
523
  name: 'save-manager',
515
- render() {
516
- return <SaveManagerContent />;
524
+ interpolate: true,
525
+ render(_props, ctx) {
526
+ return (
527
+ <SaveManagerContent
528
+ className={ctx.className}
529
+ id={ctx.id}
530
+ />
531
+ );
517
532
  },
518
533
  });
@@ -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,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
  /**
@@ -1,6 +1,21 @@
1
1
  import { useContext, useMemo } from 'preact/hooks';
2
2
  import { useStoryFields } from './use-story-fields';
3
- import { LocalsValuesContext } from '../markup/render';
3
+ import { LocalsUpdateContext, LocalsValuesContext } from '../markup/render';
4
+ import { liveLocalsView } from '../utils/live-locals';
5
+
6
+ /**
7
+ * The locals in scope, read as they are when code looks (a local the
8
+ * preceding {set} assigned in this pass included, which the context value
9
+ * only gains in the re-render that follows). The returned view is renewed
10
+ * whenever the context value changes, so what depends on it re-renders and
11
+ * recomputes as before.
12
+ */
13
+ export function useLiveLocals(): Record<string, unknown> {
14
+ const values = useContext(LocalsValuesContext);
15
+ const { getValues } = useContext(LocalsUpdateContext);
16
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `values` renews the view
17
+ return useMemo(() => liveLocalsView(getValues), [getValues, values]);
18
+ }
4
19
 
5
20
  /**
6
21
  * Return store variables, temporary, locals from context, and transient.
@@ -20,7 +35,7 @@ export function useMergedLocals(): readonly [
20
35
  'transient',
21
36
  'renderCounts',
22
37
  );
23
- const localsValues = useContext(LocalsValuesContext);
38
+ const localsValues = useLiveLocals();
24
39
 
25
40
  return useMemo(() => {
26
41
  return [variables, temporary, localsValues, transient] as const;