@rohal12/spindle 0.59.27 → 0.59.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/code-check.ts CHANGED
@@ -34,7 +34,12 @@ import {
34
34
  MarkupError,
35
35
  mapOffsets,
36
36
  } from './markup/parse';
37
- import { CodeSyntaxError, parseCode, type JsGoal } from './js-lexer';
37
+ import {
38
+ CodeSyntaxError,
39
+ parseCode,
40
+ stringLiteralValue,
41
+ type JsGoal,
42
+ } from './js-lexer';
38
43
  import type { ParsedCode } from './js-lexer';
39
44
  import type { ParameterDef, StringHolds } from './registry';
40
45
  import {
@@ -45,7 +50,9 @@ import {
45
50
  type PassageTarget,
46
51
  } from './components/macros/macro-args';
47
52
  import { subMacroParameters } from './components/macros/option-utils';
53
+ import { splitArgSpans } from './components/macros/arg-utils';
48
54
  import { NameMap } from './utils/macro-names';
55
+ import { hasOwn } from './utils/namespace';
49
56
 
50
57
  /** While a pass runs: the code it parsed so far, by goal and source. */
51
58
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -190,16 +197,52 @@ const PASSAGE_BODIES = new Set(['dialog']);
190
197
  /** What a passage runs and names, and where (see passagePieces). */
191
198
  export type Piece = CodePiece | TextPiece | PassagePiece | ArgumentErrorPiece;
192
199
 
200
+ /**
201
+ * A parameter of a widget, by position: what its argument holds when it
202
+ * declares it (`@target:passage`).
203
+ */
204
+ export interface WidgetParameter {
205
+ name: string;
206
+ holds?: StringHolds;
207
+ }
208
+
209
+ /**
210
+ * The parameters of a widget given its `@` parameters and what they declare
211
+ * to hold, or none when it declares nothing (a call is then not read by
212
+ * parameter).
213
+ */
214
+ export function widgetParameters(
215
+ params: readonly string[],
216
+ holds: Readonly<Record<string, StringHolds>> = {},
217
+ ): WidgetParameter[] | undefined {
218
+ if (!params.some((param) => hasOwn(holds, param))) return undefined;
219
+ return params.map((name) => ({
220
+ name,
221
+ ...(hasOwn(holds, name) ? { holds: holds[name]! } : {}),
222
+ }));
223
+ }
224
+
193
225
  /** The declared parameters of a macro, if it has any. */
194
- export type ParametersOf = (
195
- macro: string,
196
- ) => readonly ParameterDef[] | undefined;
226
+ export interface ParametersOf {
227
+ (macro: string): readonly ParameterDef[] | undefined;
228
+ /**
229
+ * The parameters of the widget `name` if it declares what some argument
230
+ * holds. Its arguments are read as a widget call reads them (separated by
231
+ * commas or spaces, see splitArgs), not by parseMacroArgs.
232
+ */
233
+ widget?(name: string): readonly WidgetParameter[] | undefined;
234
+ }
197
235
 
198
236
  /** What the argument check needs to know of a macro (see MacroMetadata). */
199
237
  export interface MacroParameters {
200
238
  name: string;
201
239
  parameters?: readonly ParameterDef[];
202
240
  interpolate?: boolean;
241
+ /** For a widget: its `@` parameters and what some declare to hold. */
242
+ widget?: {
243
+ params: readonly string[];
244
+ holds?: Readonly<Record<string, StringHolds>>;
245
+ };
203
246
  }
204
247
 
205
248
  /**
@@ -225,16 +268,20 @@ function withHolds(
225
268
  * collection and tooling read arguments by. Each `string` and `text`
226
269
  * parameter says what it holds: what it declares, else `markup` for a macro
227
270
  * with `interpolate` (which can resolve markup) and `text` for any other.
271
+ * A widget among `macros` says what its parameters hold (see ParametersOf).
228
272
  */
229
273
  export function parameterLookup(
230
274
  macros: Iterable<MacroParameters>,
231
275
  ): ParametersOf {
232
276
  const parameters = new NameMap<readonly ParameterDef[]>();
233
- for (const { name, parameters: params, interpolate } of macros) {
277
+ const widgets = new NameMap<readonly WidgetParameter[]>();
278
+ for (const { name, parameters: params, interpolate, widget } of macros) {
234
279
  if (params)
235
280
  parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
281
+ const declared = widget && widgetParameters(widget.params, widget.holds);
282
+ if (declared) widgets.set(name, declared);
236
283
  }
237
- return (name) => {
284
+ const lookup: ParametersOf = (name) => {
238
285
  let params = parameters.get(name);
239
286
  if (!params) {
240
287
  const sub = subMacroParameters(name);
@@ -242,6 +289,8 @@ export function parameterLookup(
242
289
  }
243
290
  return params;
244
291
  };
292
+ if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
293
+ return lookup;
245
294
  }
246
295
 
247
296
  /** What a `string` or `text` argument holds when its parameter doesn't say. */
@@ -390,6 +439,8 @@ export function* codeAndText(
390
439
  }
391
440
  const params = parametersOf(name);
392
441
  if (params) yield* argPieces(args, argsAt, params, token.name, label);
442
+ const widget = parametersOf.widget?.(name);
443
+ if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
393
444
  }
394
445
  }
395
446
  }
@@ -532,7 +583,6 @@ export function* argPieces(
532
583
  macro: string,
533
584
  label: string,
534
585
  ): Generator<Piece> {
535
- const name = macro.toLowerCase();
536
586
  let values: Record<string, unknown>;
537
587
  const spans: ArgSpans = new Map();
538
588
  try {
@@ -545,10 +595,56 @@ export function* argPieces(
545
595
  offset,
546
596
  length: args.length,
547
597
  label,
548
- macro: name,
598
+ macro: macro.toLowerCase(),
549
599
  };
550
600
  return;
551
601
  }
602
+ yield* valuePieces(args, offset, params, values, spans, macro, label);
603
+ }
604
+
605
+ /**
606
+ * The code and text in the arguments `args` (at `offset`) of the widget
607
+ * `macro`, the ones whose parameter declares what it holds. Such an argument
608
+ * is checked when it is one quoted string, as a `string` parameter with that
609
+ * `holds` of a macro is; any other expression is its value at run time.
610
+ */
611
+ function* widgetPieces(
612
+ args: string,
613
+ offset: number,
614
+ params: readonly WidgetParameter[],
615
+ macro: string,
616
+ label: string,
617
+ ): Generator<Piece> {
618
+ const written = splitArgSpans(args);
619
+ const declared: ParameterDef[] = [];
620
+ const values: Record<string, unknown> = {};
621
+ const spans: ArgSpans = new Map();
622
+ params.forEach(({ name, holds }, i) => {
623
+ const span = written[i];
624
+ const value = span && stringLiteralValue(args.slice(...span));
625
+ if (!holds || value == null) return;
626
+ const param: ParameterDef = { name, type: 'string', holds };
627
+ declared.push(param);
628
+ values[name] = value;
629
+ spans.set(param, span!);
630
+ });
631
+ yield* valuePieces(args, offset, declared, values, spans, macro, label);
632
+ }
633
+
634
+ /**
635
+ * The pieces of the `params` of `macro` with the `values` read from `args`
636
+ * (at `offset`), whose `spans` tell where each was written.
637
+ */
638
+ function* valuePieces(
639
+ args: string,
640
+ offset: number,
641
+ params: readonly ParameterDef[],
642
+ values: Record<string, unknown>,
643
+ spans: ArgSpans,
644
+ macro: string,
645
+ label: string,
646
+ ): Generator<Piece> {
647
+ const name = macro.toLowerCase();
552
648
  /** The pieces of the parameters `list`, with their values in `from`. */
553
649
  function* visit(
554
650
  list: readonly ParameterDef[],
@@ -4,6 +4,7 @@ import { checkVariableName } from '../../utils/namespace';
4
4
  import { MacroError } from './MacroError';
5
5
  import {
6
6
  WIDGET_PARAMETERS,
7
+ checkWidgetHolds,
7
8
  widgetDef,
8
9
  type WidgetDef,
9
10
  } from '../../widgets/widget-def';
@@ -19,6 +20,7 @@ defineMacro({
19
20
  // Refuse `@` parameters that no namespace can hold
20
21
  const def = widgetDef(ctx.args);
21
22
  for (const param of def.params) checkVariableName(param.slice(1), param);
23
+ checkWidgetHolds(def);
22
24
  parsed = def;
23
25
  } catch (err) {
24
26
  error = err;
@@ -133,23 +133,38 @@ export function topLevelIndices(
133
133
  return indices;
134
134
  }
135
135
 
136
+ /** The start and end of a run of text in a larger one. */
137
+ export type Span = [start: number, end: number];
138
+
136
139
  /**
137
- * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
138
- * are returned as written, untrimmed, and empty segments are kept, so
140
+ * The segments of `src` between its depth-0 separators (see
141
+ * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
139
142
  * `n` separators always give `n + 1` segments.
140
143
  */
141
- export function splitTopLevel(
144
+ export function topLevelSpans(
142
145
  src: string,
143
146
  isSeparator: (ch: string) => boolean,
144
- ): string[] {
145
- const segments: string[] = [];
147
+ ): Span[] {
148
+ const spans: Span[] = [];
146
149
  let from = 0;
147
150
  for (const i of topLevelIndices(src, isSeparator)) {
148
- segments.push(src.slice(from, i));
151
+ spans.push([from, i]);
149
152
  from = i + 1;
150
153
  }
151
- segments.push(src.slice(from));
152
- return segments;
154
+ spans.push([from, src.length]);
155
+ return spans;
156
+ }
157
+
158
+ /**
159
+ * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
160
+ * are returned as written, untrimmed, and empty segments are kept, so
161
+ * `n` separators always give `n + 1` segments.
162
+ */
163
+ export function splitTopLevel(
164
+ src: string,
165
+ isSeparator: (ch: string) => boolean,
166
+ ): string[] {
167
+ return topLevelSpans(src, isSeparator).map(([a, b]) => src.slice(a, b));
153
168
  }
154
169
 
155
170
  /**
@@ -189,38 +204,60 @@ function startsLikeValue(token: string): boolean {
189
204
  * Try to split a raw string on whitespace at depth 0 (respecting strings,
190
205
  * template literals, parentheses, brackets, and braces). Each resulting token
191
206
  * must pass `isStandaloneValue()` or the split is rejected and `null` is
192
- * returned.
207
+ * returned. The spans are those of the tokens in `raw`.
193
208
  */
194
- function trySplitOnWhitespace(raw: string): string[] | null {
195
- const args = splitTopLevel(raw, isWhitespace).filter(Boolean);
209
+ function trySplitOnWhitespace(raw: string): Span[] | null {
210
+ const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
196
211
 
197
212
  // Need 2+ tokens
198
213
  if (args.length < 2) return null;
199
214
 
200
215
  // Every token must be a standalone value (not an operator)
201
- for (const arg of args) {
202
- if (!isStandaloneValue(arg)) return null;
216
+ for (const [a, b] of args) {
217
+ if (!isStandaloneValue(raw.slice(a, b))) return null;
203
218
  }
204
219
 
205
220
  return args;
206
221
  }
207
222
 
223
+ /** `span` less the whitespace at its ends. */
224
+ function trimmed(src: string, [start, end]: Span): Span {
225
+ const text = src.slice(start, end);
226
+ const lead = text.length - text.trimStart().length;
227
+ return [
228
+ start + lead,
229
+ Math.max(start + lead, end - (text.length - text.trimEnd().length)),
230
+ ];
231
+ }
232
+
208
233
  /**
209
- * Split rawArgs by commas, respecting parentheses, brackets, braces, and
210
- * strings. When no top-level commas are present, also supports adjacent quoted
211
- * string literals separated by whitespace (e.g. `"Label" "target"`).
234
+ * Where the arguments in `raw` are written (see `splitArgs`), as spans of
235
+ * `raw`.
212
236
  */
213
- export function splitArgs(raw: string): string[] {
214
- const args = splitTopLevel(raw, (ch) => ch === ',').map((a) => a.trim());
237
+ export function splitArgSpans(raw: string): Span[] {
238
+ const args = topLevelSpans(raw, (ch) => ch === ',').map((span) =>
239
+ trimmed(raw, span),
240
+ );
215
241
  const hasComma = args.length > 1;
216
- if (args[args.length - 1] === '') args.pop();
242
+ const last = args[args.length - 1]!;
243
+ if (last[0] === last[1]) args.pop();
217
244
 
218
245
  // If no commas were found and we got a single expression, try splitting
219
246
  // on whitespace at depth 0 (e.g. "Label" "target", $var "text", $x $y).
220
247
  if (!hasComma && args.length === 1) {
221
- const split = trySplitOnWhitespace(args[0]!);
222
- if (split) return split;
248
+ const [start, end] = args[0]!;
249
+ const split = trySplitOnWhitespace(raw.slice(start, end));
250
+ if (split) return split.map(([a, b]) => [start + a, start + b]);
223
251
  }
224
252
 
225
253
  return args;
226
254
  }
255
+
256
+ /**
257
+ * Split rawArgs by commas, respecting parentheses, brackets, braces, and
258
+ * strings. When no top-level commas are present, also supports adjacent quoted
259
+ * string literals separated by whitespace (e.g. `"Label" "target"`).
260
+ */
261
+ export function splitArgs(raw: string): string[] {
262
+ return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
263
+ }
@@ -139,6 +139,22 @@ export function frozenCopy<T>(value: T): T {
139
139
  return freeze(cloneValue(value), true);
140
140
  }
141
141
 
142
+ /**
143
+ * Whether a built-in's mutators can still change a frozen `value` (#473):
144
+ * Object.freeze() locks properties, not internal slots. Immer locks a Map or
145
+ * Set it freezes by overriding its mutators with own properties; a Date, URL
146
+ * or URLSearchParams has no such lock, and one frozen by hand has none either.
147
+ */
148
+ function hasUnlockedSlots(value: object): boolean {
149
+ if (value instanceof Map) return !hasOwn(value, 'set');
150
+ if (value instanceof Set) return !hasOwn(value, 'add');
151
+ return (
152
+ value instanceof Date ||
153
+ value instanceof URL ||
154
+ value instanceof URLSearchParams
155
+ );
156
+ }
157
+
142
158
  /** Whether `value` and everything it holds is frozen. */
143
159
  function deeplyFrozen(value: unknown, seen = new Set<object>()): boolean {
144
160
  if (typeof value !== 'object' || value === null || seen.has(value)) {
@@ -148,7 +164,7 @@ function deeplyFrozen(value: unknown, seen = new Set<object>()): boolean {
148
164
  // a write to them would change the store's recorded history (#429): a value
149
165
  // holding one is handed out as a copy, which keeps the buffers it shares
150
166
  if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return false;
151
- if (!Object.isFrozen(value)) return false;
167
+ if (!Object.isFrozen(value) || hasUnlockedSlots(value)) return false;
152
168
  seen.add(value);
153
169
  // What a Map or Set holds is not in its properties (#388)
154
170
  if (value instanceof Map) {
package/src/index.tsx CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  } from './story-variables';
19
19
  import { getMacro, getMacroRegistry, isSubMacro } from './registry';
20
20
  import { parameterLookup } from './code-check';
21
- import { getWidget } from './widgets/widget-registry';
21
+ import { getWidget, widgetMacros } from './widgets/widget-registry';
22
22
  import {
23
23
  formatDiagnostic,
24
24
  validateMarkup,
@@ -63,6 +63,19 @@ function stopWithErrors(errors: string[]): never {
63
63
  );
64
64
  }
65
65
 
66
+ /**
67
+ * The result of `parse`, or, when it throws, the error shown on the page
68
+ * instead of the story (a declaration that does not evaluate, a widget passage
69
+ * that does not parse), prefixed with `where` when that is not in the message.
70
+ */
71
+ function orStop<T>(parse: () => T, where = ''): T {
72
+ try {
73
+ return parse();
74
+ } catch (err) {
75
+ return stopWithErrors([where + errorMessage(err)]);
76
+ }
77
+ }
78
+
66
79
  /**
67
80
  * The undeclared variables the passages refer to, with the macros known now:
68
81
  * the input macros that bind a variable (registered by author JS or
@@ -92,7 +105,7 @@ function markupErrors(
92
105
  isKnownMacro: (name) =>
93
106
  !!getMacro(name) || isSubMacro(name) || !!getWidget(name),
94
107
  macroNames: macros.map((m) => m.name),
95
- parametersOf: parameterLookup(macros),
108
+ parametersOf: parameterLookup([...macros, ...widgetMacros()]),
96
109
  only,
97
110
  }).map(formatDiagnostic);
98
111
  }
@@ -149,12 +162,14 @@ export function boot() {
149
162
  throw new Error(`spindle: ${msg}`);
150
163
  }
151
164
 
152
- const schema = parseStoryVariables(storyVarsPassage.content);
165
+ const schema = orStop(() => parseStoryVariables(storyVarsPassage.content));
153
166
  // Pass 1: Register the block widgets as block macros BEFORE any passage
154
167
  // is parsed (validation and StoryInit included), so that passages
155
168
  // invoking block widgets and widget bodies using other block widgets
156
169
  // parse correctly regardless of passage or definition order.
157
- for (const name of blockWidgetNames(storyData.passages.values())) {
170
+ for (const name of orStop(() =>
171
+ blockWidgetNames(storyData.passages.values()),
172
+ )) {
158
173
  registerBlockMacro(name);
159
174
  }
160
175
 
@@ -167,9 +182,8 @@ export function boot() {
167
182
  let transientDefaults: Record<string, unknown> = {};
168
183
  const storyTransientsPassage = storyData.passages.get('StoryTransients');
169
184
  if (storyTransientsPassage) {
170
- const transientSchema = parseStoryVariables(
171
- storyTransientsPassage.content,
172
- '%',
185
+ const transientSchema = orStop(() =>
186
+ parseStoryVariables(storyTransientsPassage.content, '%'),
173
187
  );
174
188
 
175
189
  // Check for cross-scope name collisions
@@ -198,7 +212,11 @@ export function boot() {
198
212
  // before StoryInit runs so that it can invoke them
199
213
  for (const [, passage] of storyData.passages) {
200
214
  if (passage.tags.includes('widget')) {
201
- registerWidgetDefinitions(parseMarkup(passage.content), passage.name);
215
+ orStop(
216
+ () =>
217
+ registerWidgetDefinitions(parseMarkup(passage.content), passage.name),
218
+ `Passage "${passage.name}": `,
219
+ );
202
220
  }
203
221
  }
204
222
 
@@ -684,11 +684,28 @@ function isBlankText(n: ASTNode): boolean {
684
684
  return n.type === 'text' && (n.comment === true || n.value.trim() === '');
685
685
  }
686
686
 
687
- /** The index of the summary element opening `nodes`, or -1 when none does. */
688
- function leadingSummaryIndex(nodes: ASTNode[]): number {
687
+ /**
688
+ * The element a container must open with, to stay its direct child: the
689
+ * summary of a details element (#382), the legend of a fieldset (#475), whose
690
+ * first legend exempts the controls in it from the fieldset's `disabled`.
691
+ */
692
+ const LEADING_PARTS: Record<string, string> = {
693
+ details: 'summary',
694
+ fieldset: 'legend',
695
+ };
696
+
697
+ /**
698
+ * The index of the node opening `nodes` as the leading part of the `tag`
699
+ * container, or -1 when none does: the element itself, or a macro, which may
700
+ * render it ({if}, {include}, a widget: #474).
701
+ */
702
+ function leadingPartIndex(tag: string, nodes: ASTNode[]): number {
703
+ const part = LEADING_PARTS[tag];
689
704
  const at = nodes.findIndex((n) => !isBlankText(n));
690
705
  const first = nodes[at];
691
- return first?.type === 'html' && first.tag.toLowerCase() === 'summary'
706
+ return part &&
707
+ (first?.type === 'macro' ||
708
+ (first?.type === 'html' && first.tag.toLowerCase() === part))
692
709
  ? at
693
710
  : -1;
694
711
  }
@@ -705,6 +722,9 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
705
722
  const inSvg = useContext(SvgContext);
706
723
  const tag = node.tag.toLowerCase();
707
724
  const isSvgRoot = tag === 'svg';
725
+ // The content of a foreignObject is HTML again (see below)
726
+ const isHtmlRoot = inSvg && tag === 'foreignobject';
727
+ const rawContent = inRaw && !isHtmlRoot;
708
728
  const isRawRoot = !inRaw && (isSvgRoot || PREFORMATTED_ELEMENTS.has(tag));
709
729
  const errors: AttributeError[] = [];
710
730
  const resolved = Object.entries(node.attributes).map(([k, v]): Attribute => [
@@ -731,13 +751,13 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
731
751
  children = node.children.map((n) =>
732
752
  n.type === 'text' ? n.value : renderSingleNode(n),
733
753
  );
734
- } else if (inRaw || isRawRoot) {
754
+ } else if (rawContent || isRawRoot) {
735
755
  children = renderInlineNodes(node.children);
736
756
  } else {
737
- // A details element's summary stays its direct child: it is rendered
738
- // apart from the markdown of the rest of the content.
739
- const summaryAt =
740
- tag === 'details' ? leadingSummaryIndex(node.children) : -1;
757
+ // The summary of a details element and the legend of a fieldset stay
758
+ // its direct children: rendered apart from the markdown of the rest of
759
+ // the content.
760
+ const leadAt = leadingPartIndex(tag, node.children);
741
761
  const body = (nodes: ASTNode[]) =>
742
762
  renderNodes(nodes, { nobr, locals, inline: isInline });
743
763
  structural =
@@ -747,13 +767,13 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
747
767
  node.children
748
768
  .filter((n) => n.type !== 'text')
749
769
  .map((n) => renderSingleNode(n))
750
- ) : summaryAt === -1 ? (
770
+ ) : leadAt === -1 ? (
751
771
  body(node.children)
752
772
  ) : (
753
773
  <>
754
- {body(node.children.slice(0, summaryAt))}
755
- {renderSingleNode(node.children[summaryAt]!)}
756
- {body(node.children.slice(summaryAt + 1))}
774
+ {body(node.children.slice(0, leadAt))}
775
+ {renderSingleNode(node.children[leadAt]!)}
776
+ {body(node.children.slice(leadAt + 1))}
757
777
  </>
758
778
  );
759
779
  if (isInline !== parentInline) {
@@ -772,10 +792,15 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
772
792
  }
773
793
  }
774
794
  }
775
- // The content of a foreignObject is HTML again, with HTML attributes
776
- if (inSvg && tag === 'foreignobject' && children) {
795
+ // The content of a foreignObject is HTML again: HTML attributes, and
796
+ // markdown, for the content of macros and widgets in it too (#477)
797
+ if (isHtmlRoot && children) {
777
798
  children = (
778
- <SvgContext.Provider value={false}>{children}</SvgContext.Provider>
799
+ <SvgContext.Provider value={false}>
800
+ <RawTextContext.Provider value={false}>
801
+ {children}
802
+ </RawTextContext.Provider>
803
+ </SvgContext.Provider>
779
804
  );
780
805
  }
781
806
  let element = h(node.tag, props, children);
package/src/store.ts CHANGED
@@ -53,8 +53,11 @@ import {
53
53
  deepClone,
54
54
  existingObjects,
55
55
  locateObjects,
56
+ deepEqual,
56
57
  mergesWith,
58
+ pathKey,
57
59
  shareEqual,
60
+ underChange,
58
61
  type PathChange,
59
62
  } from './structural';
60
63
  import { getByPath } from './utils/object-path';
@@ -771,6 +774,14 @@ function loadedEntryMoment(
771
774
  return moment;
772
775
  }
773
776
 
777
+ /** The variable paths `Story.set` writes while a save's hooks run. */
778
+ let hookWrites: Map<string, string[]> | null = null;
779
+
780
+ /** Note that `path` of the variables was written (see keepHookWrites). */
781
+ export function recordHookWrite(path: string[]): void {
782
+ hookWrites?.set(pathKey(path), path);
783
+ }
784
+
774
785
  /**
775
786
  * Write the changes between `before` and `after` (the live variables around
776
787
  * the `beforesave` hooks) into the payload's snapshot of the saved moment. A
@@ -788,10 +799,22 @@ function keepHookWrites(
788
799
  payload: SavePayload,
789
800
  before: Record<string, unknown>,
790
801
  after: Record<string, unknown>,
802
+ written: readonly string[][],
791
803
  ): void {
792
804
  const moment = payload.history[payload.historyIndex];
793
805
  if (!moment) return;
794
806
  const changes = changesBetween(before, after, true);
807
+ const keys = new Set(changes.map((c) => pathKey(c.path)));
808
+ // A write of the live value is no change to the live store, but the
809
+ // snapshot can still hold another one: an earlier save's hooks wrote the
810
+ // live value, which this moment's snapshot does not have (#479)
811
+ for (const path of written) {
812
+ if (underChange(path, keys)) continue;
813
+ keys.add(pathKey(path));
814
+ const value = getByPath(after, path);
815
+ if (deepEqual(getByPath(moment.variables, path), value)) continue;
816
+ changes.push({ path, deleted: false, value });
817
+ }
795
818
  if (changes.length === 0) return;
796
819
  // A copy of its own, so the writes keep the snapshot's references (which
797
820
  // the history shares with other moments) as they are
@@ -1714,9 +1737,12 @@ export const useStoryStore = create<StoryState>()(
1714
1737
 
1715
1738
  beginSave: () => {
1716
1739
  const before = get().variables;
1740
+ const writes = new Map<string, string[]>();
1741
+ hookWrites = writes;
1717
1742
  return () => {
1743
+ if (hookWrites === writes) hookWrites = null;
1718
1744
  const payload = get().getSavePayload();
1719
- keepHookWrites(payload, before, get().variables);
1745
+ keepHookWrites(payload, before, get().variables, [...writes.values()]);
1720
1746
  return payload;
1721
1747
  };
1722
1748
  },
package/src/story-api.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { useStoryStore, trackRuntimeUnsub } from './store';
1
+ import { useStoryStore, trackRuntimeUnsub, recordHookWrite } from './store';
2
2
  import type { StoryState, VariableNamespaces } from './store';
3
3
  import {
4
4
  on as emitterOn,
@@ -299,6 +299,7 @@ function createStoryAPI(): StoryAPI {
299
299
  for (const [name] of entries) {
300
300
  const { isTransient, key } = parseName(name);
301
301
  warnIfUndeclared(isTransient, key);
302
+ if (!isTransient) recordHookWrite(key.split('.'));
302
303
  }
303
304
  // One store update for all keys, so watchers see them together. Made
304
305
  // while mutation code runs ({do}, ctx.mutate, watcher run actions), it
package/src/tooling.ts CHANGED
@@ -20,7 +20,6 @@ import {
20
20
  type Piece,
21
21
  } from './code-check';
22
22
  import {
23
- blockWidgetNames,
24
23
  widgetDefinitions as readWidgetDefinitions,
25
24
  type WidgetDefinition,
26
25
  } from './widgets/widget-def';
@@ -32,6 +31,7 @@ import {
32
31
  type VariableReference,
33
32
  } from './story-variables';
34
33
  import type { ParameterDef } from './registry';
34
+ import type { WidgetDef } from './widgets/widget-def';
35
35
 
36
36
  export { parseDeclarations, parseStoryVariables } from './story-variables';
37
37
  export { discoverMacros } from './macro-discovery';
@@ -156,6 +156,12 @@ export interface ToolingMacro {
156
156
  * Its declared parameters: their types tell which arguments are code, and
157
157
  * what a `string` or `text` argument holds (see ParameterDef.holds).
158
158
  */
159
+ /**
160
+ * For a widget: its `@` parameters and what the ones that declare it hold
161
+ * (`@target:passage`, see WidgetDef), so that a call is checked like the
162
+ * call of a macro whose `string` parameter has that `holds`.
163
+ */
164
+ widget?: Pick<WidgetDef, 'params' | 'holds'>;
159
165
  parameters?: readonly ParameterDef[];
160
166
  /** Whether it resolves markup: its strings hold markup by default. */
161
167
  interpolate?: boolean;
@@ -177,10 +183,17 @@ export function validateStoryMarkup(
177
183
  const list = [...passages];
178
184
  const all = [...macros];
179
185
  const known = new Set<string>();
180
- const parametersOf = parameterLookup(all);
186
+ // The calls of widgets that declare what their arguments hold are checked
187
+ const widgets = readWidgetDefinitions(list, parameterLookup(all));
181
188
  const blocks = new Set(
182
- blockWidgetNames(list, parametersOf).map((n) => n.toLowerCase()),
189
+ widgets
190
+ .filter((def) => def.block && def.closeStart !== undefined)
191
+ .map((def) => def.name.toLowerCase()),
183
192
  );
193
+ const parametersOf = parameterLookup([
194
+ ...all,
195
+ ...widgets.map((widget) => ({ name: widget.name, widget })),
196
+ ]);
184
197
  for (const macro of all) {
185
198
  const name = macro.name.toLowerCase();
186
199
  known.add(name);