@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.59.29",
3
+ "version": "0.59.30",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -26,7 +26,13 @@ export interface StoryAction {
26
26
  options?: string[];
27
27
  value?: unknown;
28
28
  disabled?: boolean;
29
- perform: (value?: unknown) => void;
29
+ /**
30
+ * What the control does. An action that finishes later (QuickSave and
31
+ * QuickLoad wait for storage) returns a promise that settles when it has
32
+ * finished; `Story.performAction()` passes it on and
33
+ * `Story.waitForActions()` waits for it (#504).
34
+ */
35
+ perform: (value?: unknown) => void | Promise<void>;
30
36
  }
31
37
 
32
38
  /** The fields of a StoryAction that are left out when unset. */
@@ -60,19 +66,30 @@ interface Entry {
60
66
  */
61
67
  const actions = new Map<string, Entry[]>();
62
68
  const idCounters = new Map<string, number>();
69
+ /**
70
+ * IDs handed out and not yet registered, or registered: a control registers
71
+ * in a layout effect, after every control of the same render has allocated its
72
+ * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
73
+ * Released when the last registration of an ID goes.
74
+ */
75
+ const reserved = new Set<string>();
63
76
 
64
77
  /**
65
78
  * The counters reset on every navigation, so a passage's controls get the
66
79
  * same IDs each time it is shown. Controls that stay mounted across
67
80
  * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
68
- * ID still registered (#233).
81
+ * ID still registered (#233) and every one allocated but not registered yet
82
+ * (#486).
69
83
  */
70
84
  export function generateActionId(
71
85
  type: ActionType,
72
86
  key: string,
73
87
  authorId?: string,
74
88
  ): string {
75
- if (authorId) return authorId;
89
+ if (authorId) {
90
+ reserved.add(authorId);
91
+ return authorId;
92
+ }
76
93
 
77
94
  const base = `${type}:${key}`;
78
95
  let count = idCounters.get(base) ?? 0;
@@ -80,8 +97,9 @@ export function generateActionId(
80
97
  do {
81
98
  count++;
82
99
  id = count === 1 ? base : `${base}:${count}`;
83
- } while (actions.has(id));
100
+ } while (actions.has(id) || reserved.has(id));
84
101
  idCounters.set(base, count);
102
+ reserved.add(id);
85
103
  return id;
86
104
  }
87
105
 
@@ -113,12 +131,45 @@ export function registerAction(action: StoryAction): ActionRegistration {
113
131
  const index = current ? current.indexOf(entry) : -1;
114
132
  if (!current || index === -1) return;
115
133
  current.splice(index, 1);
116
- if (current.length === 0) actions.delete(id);
134
+ if (current.length === 0) {
135
+ actions.delete(id);
136
+ reserved.delete(id);
137
+ }
117
138
  if (index === current.length) notify(); // it was the listed one
118
139
  },
119
140
  };
120
141
  }
121
142
 
143
+ /** The promises of the performed actions that have not settled yet. */
144
+ const running = new Set<Promise<void>>();
145
+
146
+ /**
147
+ * Perform an action, as `Story.performAction()` does. One that returns a
148
+ * promise is tracked until it settles, for `settleRunningActions()`, and the
149
+ * promise is returned for the caller to await (its rejection stays the
150
+ * caller's to handle).
151
+ */
152
+ export function performRegisteredAction(
153
+ action: StoryAction,
154
+ value?: unknown,
155
+ ): void | Promise<void> {
156
+ const result = action.perform(value);
157
+ if (!result || typeof result.then !== 'function') return result;
158
+
159
+ const done = () => void running.delete(result);
160
+ running.add(result);
161
+ result.then(done, done);
162
+ return result.then((v) => v);
163
+ }
164
+
165
+ /** Wait until every performed action has finished, whether or not it failed. */
166
+ export async function settleRunningActions(): Promise<void> {
167
+ // An action can perform another while it finishes
168
+ while (running.size > 0) {
169
+ await Promise.allSettled(running);
170
+ }
171
+ }
172
+
122
173
  export function getActions(): StoryAction[] {
123
174
  return Array.from(actions.values(), listed);
124
175
  }
@@ -134,11 +185,14 @@ function listed(entries: Entry[]): StoryAction {
134
185
 
135
186
  export function clearActions(): void {
136
187
  actions.clear();
188
+ reserved.clear();
137
189
  notify();
138
190
  }
139
191
 
140
192
  export function resetIdCounters(): void {
141
193
  idCounters.clear();
194
+ // Only what is registered stays taken; the rest was never mounted
195
+ for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
142
196
  }
143
197
 
144
198
  function notify(): void {
@@ -1,33 +1,118 @@
1
1
  import * as yaml from 'js-yaml';
2
2
  import type { AutomationScript, AutomationStep } from './types';
3
3
 
4
- function validateStep(step: unknown, index: number): AutomationStep {
5
- if (typeof step !== 'object' || step === null) {
6
- throw new Error(`Invalid automation step ${index + 1}: expected an object`);
4
+ type Fail = (message: string) => never;
5
+
6
+ function isRecord(value: unknown): value is Record<string, unknown> {
7
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
8
+ }
9
+
10
+ /** `value` as an object whose keys are all in `allowed`. */
11
+ function checkObject(
12
+ value: unknown,
13
+ what: string,
14
+ allowed: readonly string[],
15
+ fail: Fail,
16
+ ): Record<string, unknown> {
17
+ if (!isRecord(value)) fail(`${what} must be an object`);
18
+ for (const key of Object.keys(value)) {
19
+ if (!allowed.includes(key)) {
20
+ fail(`${what} has an unknown field "${key}" (${allowed.join(', ')})`);
21
+ }
7
22
  }
8
- const s = step as Record<string, unknown>;
23
+ return value;
24
+ }
9
25
 
10
- const hasAction = 'action' in s;
11
- const hasAssert = 'assert' in s;
12
- const hasWait = 'wait' in s;
13
- const hasSet = 'set' in s;
26
+ type FieldCheck = (value: unknown) => boolean;
14
27
 
15
- if (!hasAction && !hasAssert && !hasWait && !hasSet) {
16
- throw new Error(
17
- `Invalid automation step ${index + 1}: must have at least one of action, assert, wait, set`,
18
- );
28
+ const isString: FieldCheck = (v) => typeof v === 'string';
29
+ const isBoolean: FieldCheck = (v) => typeof v === 'boolean';
30
+ const isCount: FieldCheck = (v) => Number.isInteger(v) && (v as number) >= 0;
31
+
32
+ function checkFields(
33
+ obj: Record<string, unknown>,
34
+ what: string,
35
+ checks: Record<string, [FieldCheck, string]>,
36
+ fail: Fail,
37
+ ): void {
38
+ for (const [key, [valid, expected]] of Object.entries(checks)) {
39
+ if (key in obj && !valid(obj[key])) {
40
+ fail(`"${key}" of ${what} must be ${expected}`);
41
+ }
19
42
  }
43
+ }
20
44
 
21
- if (hasWait && typeof s.wait !== 'number') {
22
- throw new Error(
23
- `Invalid automation step ${index + 1}: "wait" must be a number`,
45
+ const MATCHER_FIELDS: Record<string, [FieldCheck, string]> = {
46
+ type: [isString, 'a string'],
47
+ id: [isString, 'a string'],
48
+ target: [isString, 'a string'],
49
+ variable: [isString, 'a string'],
50
+ label: [isString, 'a string'],
51
+ disabled: [isBoolean, 'true or false'],
52
+ };
53
+
54
+ const ASSERT_FIELDS: Record<string, [FieldCheck, string]> = {
55
+ passage: [isString, 'a string'],
56
+ variables: [isRecord, 'an object of variable names and values'],
57
+ actions: [Array.isArray, 'a list of action matchers'],
58
+ actionCount: [isCount, 'a non-negative integer'],
59
+ };
60
+
61
+ function checkAssert(value: unknown, fail: Fail): void {
62
+ const assert = checkObject(
63
+ value,
64
+ '"assert"',
65
+ Object.keys(ASSERT_FIELDS),
66
+ fail,
67
+ );
68
+ checkFields(assert, '"assert"', ASSERT_FIELDS, fail);
69
+ for (const matcher of (assert.actions as unknown[] | undefined) ?? []) {
70
+ const m = checkObject(
71
+ matcher,
72
+ 'an action matcher in "assert.actions"',
73
+ Object.keys(MATCHER_FIELDS),
74
+ fail,
24
75
  );
76
+ checkFields(m, 'an action matcher', MATCHER_FIELDS, fail);
25
77
  }
78
+ }
26
79
 
27
- if (hasSet && (typeof s.set !== 'object' || s.set === null)) {
28
- throw new Error(
29
- `Invalid automation step ${index + 1}: "set" must be an object`,
30
- );
80
+ function checkAction(value: unknown, fail: Fail): void {
81
+ if (typeof value === 'string') return;
82
+ const action = checkObject(value, '"action"', ['id', 'value'], fail);
83
+ if (typeof action.id !== 'string') {
84
+ fail('"action" needs an "id" string (or be an action ID string)');
85
+ }
86
+ }
87
+
88
+ const STEP_CHECKS: Record<string, (value: unknown, fail: Fail) => void> = {
89
+ action: checkAction,
90
+ assert: checkAssert,
91
+ wait(value, fail) {
92
+ if (typeof value !== 'number' || !(value >= 0) || !isFinite(value)) {
93
+ fail('"wait" must be a number of milliseconds');
94
+ }
95
+ },
96
+ set(value, fail) {
97
+ if (!isRecord(value)) fail('"set" must be an object');
98
+ },
99
+ };
100
+
101
+ function validateStep(step: unknown, index: number): AutomationStep {
102
+ const fail: Fail = (message) => {
103
+ throw new Error(`Invalid automation step ${index + 1}: ${message}`);
104
+ };
105
+ const fields = Object.keys(STEP_CHECKS);
106
+ if (typeof step !== 'object' || step === null) {
107
+ fail('expected an object');
108
+ }
109
+ const s = checkObject(step, 'a step', fields, fail);
110
+
111
+ if (!fields.some((field) => field in s)) {
112
+ fail(`must have at least one of ${fields.join(', ')}`);
113
+ }
114
+ for (const [field, check] of Object.entries(STEP_CHECKS)) {
115
+ if (field in s) check(s[field], fail);
31
116
  }
32
117
 
33
118
  return s as AutomationStep;
@@ -50,9 +135,15 @@ export function parseAutomationYaml(yamlContent: string): AutomationScript {
50
135
 
51
136
  const steps = doc.steps.map((step, i) => validateStep(step, i));
52
137
 
138
+ if ('start' in doc && typeof doc.start !== 'string') {
139
+ throw new Error(
140
+ 'Invalid automation script: "start" must be a passage name',
141
+ );
142
+ }
143
+
53
144
  return {
54
145
  name: doc.name,
55
- start: typeof doc.start === 'string' ? doc.start : undefined,
146
+ start: doc.start as string | undefined,
56
147
  steps,
57
148
  };
58
149
  }
@@ -66,7 +66,8 @@ async function executeStep(
66
66
  const id = typeof step.action === 'string' ? step.action : step.action.id;
67
67
  const value =
68
68
  typeof step.action === 'string' ? undefined : step.action.value;
69
- story.performAction(id, value);
69
+ // An action that finishes later (QuickLoad) is awaited, then the UI
70
+ await story.performAction(id, value);
70
71
  await story.waitForActions();
71
72
  }
72
73
 
@@ -122,20 +123,21 @@ async function executeStep(
122
123
  }
123
124
  }
124
125
 
126
+ /** The matcher fields compared with the action field of the same name. */
127
+ const MATCHED_FIELDS = ['id', 'type', 'target', 'variable', 'label'] as const;
128
+
125
129
  function findMatchingAction(
126
130
  actions: StoryAction[],
127
131
  matcher: ActionMatcher,
128
132
  ): StoryAction | undefined {
129
- return actions.find((action) => {
130
- if (matcher.id !== undefined && action.id !== matcher.id) return false;
131
- if (matcher.type !== undefined && action.type !== matcher.type)
132
- return false;
133
- if (matcher.target !== undefined && action.target !== matcher.target)
134
- return false;
135
- if (matcher.variable !== undefined && action.variable !== matcher.variable)
136
- return false;
137
- if (matcher.label !== undefined && action.label !== matcher.label)
138
- return false;
139
- return true;
140
- });
133
+ return actions.find(
134
+ (action) =>
135
+ MATCHED_FIELDS.every(
136
+ (field) =>
137
+ matcher[field] === undefined || action[field] === matcher[field],
138
+ ) &&
139
+ // An action that does not set `disabled` is enabled
140
+ (matcher.disabled === undefined ||
141
+ !!action.disabled === matcher.disabled),
142
+ );
141
143
  }
@@ -1,9 +1,11 @@
1
- export interface ActionMatcher {
1
+ import type { StoryAction } from '../action-registry';
2
+
3
+ export interface ActionMatcher extends Partial<
4
+ Pick<StoryAction, 'id' | 'target' | 'variable' | 'label'>
5
+ > {
2
6
  type?: string;
3
- id?: string;
4
- target?: string;
5
- variable?: string;
6
- label?: string;
7
+ /** `true` matches only disabled actions, `false` only enabled ones. */
8
+ disabled?: boolean;
7
9
  }
8
10
 
9
11
  export interface AssertStep {
@@ -2,7 +2,12 @@
2
2
 
3
3
  import { parse, stringify } from 'devalue';
4
4
  import { hasOwn } from './utils/namespace';
5
- import { extraKeys, mapEntries, setMembers } from './utils/value-kinds';
5
+ import {
6
+ extraKeys,
7
+ mapEntries,
8
+ regExpParts,
9
+ setMembers,
10
+ } from './utils/value-kinds';
6
11
 
7
12
  type Constructor = new (...args: any[]) => any;
8
13
 
@@ -229,9 +234,7 @@ function classData(value: object): unknown {
229
234
  return ['Date', Date.prototype.getTime.call(value), extra()];
230
235
  }
231
236
  if (value instanceof RegExp) {
232
- const source = Reflect.get(RegExp.prototype, 'source', value) as string;
233
- const flags = Reflect.get(RegExp.prototype, 'flags', value) as string;
234
- return ['RegExp', [source, flags, value.lastIndex], extra()];
237
+ return ['RegExp', [...regExpParts(value), value.lastIndex], extra()];
235
238
  }
236
239
  return savedData(ownData(value));
237
240
  }
@@ -297,7 +300,7 @@ function reducers(): Record<string, (value: unknown) => unknown> {
297
300
  };
298
301
  out[REGEXP_TAG] = (v) =>
299
302
  v instanceof RegExp &&
300
- v.lastIndex !== 0 && [v.source, v.flags, v.lastIndex];
303
+ v.lastIndex !== 0 && [...regExpParts(v), v.lastIndex];
301
304
  if (GUARD_V8_KEYS) {
302
305
  out[KEYS_TAG] = (v) => {
303
306
  return isPlainData(v) && keyEntries(v);
package/src/code-check.ts CHANGED
@@ -546,30 +546,66 @@ function nestedPiece(
546
546
  : { ...piece, ...nested };
547
547
  }
548
548
 
549
+ /** How the string of an argument is unescaped, which its escapes depend on. */
550
+ type Escapes =
551
+ /** A macro's text: a backslash before a quote or a backslash is dropped. */
552
+ | 'quotes'
553
+ /** A widget's argument: a JavaScript string literal, with all its escapes. */
554
+ | 'javascript';
555
+
556
+ /** An escape sequence of a JavaScript string literal (with its backslash). */
557
+ const JS_ESCAPE_RE =
558
+ /\\(?:u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-3][0-7]{0,2}|[4-7][0-7]?|\r\n|[^])/y;
559
+
560
+ /**
561
+ * The escape written at `raw[i]` (a backslash): how long it is as written and
562
+ * what it stands for, or none when it is not one under these `escapes`.
563
+ */
564
+ function escapeAt(
565
+ raw: string,
566
+ i: number,
567
+ escapes: Escapes,
568
+ ): { length: number; text: string } | undefined {
569
+ if (escapes === 'quotes') {
570
+ const next = raw.charAt(i + 1);
571
+ return /["'\\]/.test(next) ? { length: 2, text: next } : undefined;
572
+ }
573
+ JS_ESCAPE_RE.lastIndex = i;
574
+ const written = JS_ESCAPE_RE.exec(raw)?.[0];
575
+ const text = written && stringLiteralValue(`"${written}"`);
576
+ return typeof text === 'string'
577
+ ? { length: written!.length, text }
578
+ : undefined;
579
+ }
580
+
549
581
  /**
550
582
  * Where each character of `value`, the unescaped text of a quoted string
551
- * written as `raw` from `at` on (a backslash before a quote or a backslash
552
- * is dropped), is
553
- * in the source, and where the text ends. None when the text is where its
554
- * length says, or is not that string.
583
+ * written as `raw` from `at` on (its escapes are those of `escapes`), is in
584
+ * the source, and where the text ends. A character that an escape stands for
585
+ * is where the escape begins. None when the text is where its length says, or
586
+ * is not that string.
555
587
  */
556
588
  function escapeOffsets(
557
589
  raw: string,
558
590
  at: number,
559
591
  value: string,
592
+ escapes: Escapes,
560
593
  ): number[] | undefined {
561
594
  const offsets: number[] = [];
562
595
  let escaped = false;
563
596
  let i = 0;
564
597
  while (offsets.length < value.length) {
565
598
  if (i >= raw.length) return undefined;
566
- offsets.push(at + i);
567
- if (raw[i] === '\\' && /["'\\]/.test(raw.charAt(i + 1))) {
568
- escaped = true;
569
- i += 2;
570
- } else {
571
- i++;
599
+ const escape = raw[i] === '\\' ? escapeAt(raw, i, escapes) : undefined;
600
+ if (!escape) {
601
+ offsets.push(at + i++);
602
+ continue;
572
603
  }
604
+ // What the escape stands for is what the text has there
605
+ if (!value.startsWith(escape.text, offsets.length)) return undefined;
606
+ for (let k = 0; k < escape.text.length; k++) offsets.push(at + i);
607
+ escaped = true;
608
+ i += escape.length;
573
609
  }
574
610
  offsets.push(at + i);
575
611
  return escaped ? offsets : undefined;
@@ -599,7 +635,16 @@ export function* argPieces(
599
635
  };
600
636
  return;
601
637
  }
602
- yield* valuePieces(args, offset, params, values, spans, macro, label);
638
+ yield* valuePieces(
639
+ args,
640
+ offset,
641
+ params,
642
+ values,
643
+ spans,
644
+ macro,
645
+ label,
646
+ 'quotes',
647
+ );
603
648
  }
604
649
 
605
650
  /**
@@ -608,7 +653,7 @@ export function* argPieces(
608
653
  * is checked when it is one quoted string, as a `string` parameter with that
609
654
  * `holds` of a macro is; any other expression is its value at run time.
610
655
  */
611
- function* widgetPieces(
656
+ export function* widgetPieces(
612
657
  args: string,
613
658
  offset: number,
614
659
  params: readonly WidgetParameter[],
@@ -628,12 +673,22 @@ function* widgetPieces(
628
673
  values[name] = value;
629
674
  spans.set(param, span!);
630
675
  });
631
- yield* valuePieces(args, offset, declared, values, spans, macro, label);
676
+ yield* valuePieces(
677
+ args,
678
+ offset,
679
+ declared,
680
+ values,
681
+ spans,
682
+ macro,
683
+ label,
684
+ 'javascript',
685
+ );
632
686
  }
633
687
 
634
688
  /**
635
689
  * The pieces of the `params` of `macro` with the `values` read from `args`
636
- * (at `offset`), whose `spans` tell where each was written.
690
+ * (at `offset`), whose `spans` tell where each was written and whose strings
691
+ * are unescaped as `escapes` says.
637
692
  */
638
693
  function* valuePieces(
639
694
  args: string,
@@ -643,6 +698,7 @@ function* valuePieces(
643
698
  spans: ArgSpans,
644
699
  macro: string,
645
700
  label: string,
701
+ escapes: Escapes,
646
702
  ): Generator<Piece> {
647
703
  const name = macro.toLowerCase();
648
704
  /** The pieces of the parameters `list`, with their values in `from`. */
@@ -700,7 +756,12 @@ function* valuePieces(
700
756
  const at =
701
757
  offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
702
758
  const holds = stringHolds(param);
703
- const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
759
+ const sourceOffsets = escapeOffsets(
760
+ args.slice(at - offset),
761
+ at,
762
+ value,
763
+ escapes,
764
+ );
704
765
  if (holds === 'expression' || holds === 'statements') {
705
766
  const piece: CodePiece = {
706
767
  kind: 'code',
@@ -774,7 +835,10 @@ export function attributeValues(
774
835
 
775
836
  /**
776
837
  * The `{$…}` expressions in the value of a code attribute (`onclick`, see
777
- * isCodeAttribute), with where each is in the value.
838
+ * isCodeAttribute), with where each is in the value. The parts of the value
839
+ * are written out as they are (splitSigilTemplate decodes nothing), so each
840
+ * starts where the one before it ends: an expression is not found by its
841
+ * text, which a string of the code may repeat.
778
842
  */
779
843
  export function sigilExpressions(
780
844
  value: string,
@@ -782,10 +846,13 @@ export function sigilExpressions(
782
846
  const found = [];
783
847
  let from = 0;
784
848
  for (const part of splitSigilTemplate(value)) {
785
- if (!('expr' in part)) continue;
786
- const at = locate(value, part.expr, from);
787
- from = at + part.expr.length;
788
- found.push({ expr: part.expr, at });
849
+ if ('expr' in part) {
850
+ // Inside its braces
851
+ found.push({ expr: part.expr, at: from + 1 });
852
+ from += part.expr.length + 2;
853
+ } else {
854
+ from += ('text' in part ? part.text : part.verbatim).length;
855
+ }
789
856
  }
790
857
  return found;
791
858
  }
@@ -3,6 +3,7 @@ import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
3
3
 
4
4
  defineMacro({
5
5
  name: 'checkbox',
6
+ interpolate: true,
6
7
  storeVar: true,
7
8
  parameters: [
8
9
  VARIABLE_PARAMETER,
@@ -15,7 +16,7 @@ defineMacro({
15
16
  type: 'checkbox',
16
17
  label: label || ctx.varName || '',
17
18
  value: !!ctx.value,
18
- perform: (v) => ctx.setValue!(v !== undefined ? !!v : !ctx.value),
19
+ perform: (v) => ctx.setValue!(v !== undefined ? !!v : !ctx.getValue!()),
19
20
  });
20
21
 
21
22
  return (
@@ -26,7 +27,9 @@ defineMacro({
26
27
  <input
27
28
  type="checkbox"
28
29
  checked={!!ctx.value}
29
- onChange={() => ctx.setValue!(!ctx.value)}
30
+ onChange={(e) =>
31
+ ctx.setValue!((e.target as HTMLInputElement).checked)
32
+ }
30
33
  />
31
34
  {label ? ` ${label}` : null}
32
35
  </label>
@@ -4,6 +4,7 @@ import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
4
4
  defineMacro({
5
5
  name: 'cycle',
6
6
  block: true,
7
+ interpolate: true,
7
8
  storeVar: true,
8
9
  parameters: [VARIABLE_PARAMETER],
9
10
  render({ children = [] }, ctx) {
@@ -1,5 +1,4 @@
1
- import { useContext, useMemo } from 'preact/hooks';
2
- import { LocalsValuesContext } from '../../markup/render';
1
+ import { useMemo } from 'preact/hooks';
3
2
  import { defineMacro } from '../../define-macro';
4
3
  import { MacroError } from './MacroError';
5
4
  import { stableKey } from '../../utils/stable-key';
@@ -51,14 +50,12 @@ function loopArgs(
51
50
  }
52
51
 
53
52
  function ForIteration({
54
- parentValues,
55
53
  itemVar,
56
54
  itemValue,
57
55
  indexVar,
58
56
  indexValue,
59
57
  children,
60
58
  }: {
61
- parentValues: Record<string, unknown>;
62
59
  itemVar: string;
63
60
  itemValue: unknown;
64
61
  indexVar: string | null;
@@ -76,7 +73,6 @@ function ForIteration({
76
73
  return (
77
74
  <LocalsScope
78
75
  body={children}
79
- parentValues={parentValues}
80
76
  ownKeys={ownKeys}
81
77
  />
82
78
  );
@@ -101,7 +97,6 @@ defineMacro({
101
97
  { name: 'list', type: 'expression', required: true },
102
98
  ],
103
99
  render({ rawArgs, children = [] }, ctx) {
104
- const parentValues = useContext(LocalsValuesContext);
105
100
  const keys = ctx.hooks.useRef<IterationKeys>({
106
101
  contents: [],
107
102
  generations: [],
@@ -154,7 +149,6 @@ defineMacro({
154
149
  const content = list.map((item, i) => (
155
150
  <ForIteration
156
151
  key={`${i}-${generations[i]}`}
157
- parentValues={parentValues}
158
152
  itemVar={itemVar}
159
153
  itemValue={item}
160
154
  indexVar={indexVar}
@@ -4,6 +4,7 @@ import { display } from './display';
4
4
 
5
5
  defineMacro({
6
6
  name: 'listbox',
7
+ interpolate: true,
7
8
  subMacros: ['option'],
8
9
  storeVar: true,
9
10
  parameters: [VARIABLE_PARAMETER],
@@ -15,7 +15,11 @@ interface MenubarActionConfig {
15
15
  title?: string;
16
16
  confirm?: string;
17
17
  hidden?: () => boolean;
18
- setup?: () => { perform: () => void; disabled?: boolean; title?: string };
18
+ setup?: () => {
19
+ perform: () => void | Promise<void>;
20
+ disabled?: boolean;
21
+ title?: string;
22
+ };
19
23
  dialog?: {
20
24
  passageName: string;
21
25
  fallbackMarkup?: string;
@@ -31,6 +35,7 @@ function hotkeyTitle(label: string, key: string | null): string {
31
35
  export function defineMenubarAction(config: MenubarActionConfig) {
32
36
  defineMacro({
33
37
  name: config.name,
38
+ interpolate: true,
34
39
  render(_, ctx) {
35
40
  if (config.hidden?.()) return null;
36
41
 
@@ -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(