@rohal12/spindle 0.64.30 → 0.64.32

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.
@@ -1,5 +1,8 @@
1
1
  import { h } from 'preact';
2
+ import { useCallback, useLayoutEffect, useRef, useState } from 'preact/hooks';
2
3
  import { defineMacro, type MacroContext } from '../../define-macro';
4
+ import { useStoryStore } from '../../store';
5
+ import { subscribeVariableWrites } from '../../utils/variable-writes';
3
6
  import {
4
7
  actionAttributes,
5
8
  useControlAction,
@@ -14,24 +17,195 @@ export const VARIABLE_PARAMETER = {
14
17
  required: true,
15
18
  } as const;
16
19
 
20
+ type FormControl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
21
+
22
+ interface ResetReader {
23
+ element: FormControl;
24
+ prepare: () => {
25
+ read: (snapshot: FormControl) => () => void;
26
+ off: () => void;
27
+ };
28
+ }
29
+ const formResets = new WeakMap<
30
+ HTMLFormElement,
31
+ {
32
+ readers: Set<ResetReader>;
33
+ reset: (event: Event) => void;
34
+ }
35
+ >();
36
+
37
+ /** Read every reset value before any binding write can trigger a rerender. */
38
+ function subscribeFormReset(
39
+ form: HTMLFormElement,
40
+ read: ResetReader,
41
+ ): () => void {
42
+ let subscription = formResets.get(form);
43
+ if (!subscription) {
44
+ const readers = new Set<ResetReader>();
45
+ const reset = (event: Event) => {
46
+ const pending = Array.from(readers, (reader) => ({
47
+ reader,
48
+ ...reader.prepare(),
49
+ }));
50
+ // Trusted reset events can run microtasks before their default action.
51
+ // A task sees the native values and the final cancellation state.
52
+ setTimeout(() => {
53
+ for (const { off } of pending) off();
54
+ if (event.defaultPrevented) return;
55
+ // An unrelated store write can already have rerendered the live
56
+ // controls. Let a detached form recover their native defaults,
57
+ // including number sanitization, select fallback and radio groups.
58
+ const snapshot = form.ownerDocument.createElement('form');
59
+ const restoreDefaults = snapshot.reset.bind(snapshot);
60
+ const controls = pending.map(({ reader, read }) => {
61
+ const element = reader.element.cloneNode(true) as FormControl;
62
+ element.removeAttribute('form');
63
+ snapshot.appendChild(element);
64
+ return { read, element };
65
+ });
66
+ restoreDefaults();
67
+ const commits = controls.map(({ read, element }) => read(element));
68
+ for (const commit of commits) commit();
69
+ }, 0);
70
+ };
71
+ subscription = { readers, reset };
72
+ formResets.set(form, subscription);
73
+ form.addEventListener('reset', subscription.reset);
74
+ }
75
+ const { readers, reset } = subscription;
76
+ readers.add(read);
77
+ return () => {
78
+ readers.delete(read);
79
+ if (readers.size === 0) {
80
+ form.removeEventListener('reset', reset);
81
+ formResets.delete(form);
82
+ }
83
+ };
84
+ }
85
+
86
+ /** Native defaults belong to the binding's initial rendered control value. */
87
+ function setResetDefault(control: FormControl): void {
88
+ if (control.tagName === 'SELECT') {
89
+ const options = Array.from((control as HTMLSelectElement).options);
90
+ const selected = options.map((option) => option.selected);
91
+ options.forEach((option, i) => (option.defaultSelected = selected[i]!));
92
+ } else if (
93
+ control.tagName === 'INPUT' &&
94
+ ['checkbox', 'radio'].includes((control as HTMLInputElement).type)
95
+ ) {
96
+ (control as HTMLInputElement).defaultChecked = (
97
+ control as HTMLInputElement
98
+ ).checked;
99
+ } else {
100
+ (control as HTMLInputElement | HTMLTextAreaElement).defaultValue =
101
+ control.value;
102
+ }
103
+ }
104
+
17
105
  /**
18
106
  * Register the automation action of a macro bound to a story variable: keyed
19
107
  * by the variable (or `key`), with the variable's value unless `action`
20
108
  * gives another.
21
109
  */
22
110
  export function useVariableAction(
23
- ctx: Pick<MacroContext, 'id' | 'varName' | 'value'>,
111
+ ctx: Pick<MacroContext, 'id' | 'varName' | 'value' | 'setValue' | 'getValue'>,
24
112
  action: Omit<UseActionOptions, 'key' | 'authorId' | 'variable'> & {
25
113
  key?: string;
26
114
  },
115
+ onReset?: (control: FormControl) => unknown,
27
116
  ): ReturnType<typeof useControlAction> {
28
- return useControlAction({
117
+ const registered = useControlAction({
29
118
  key: `$${ctx.varName}`,
30
119
  authorId: ctx.id,
31
120
  variable: ctx.varName,
32
121
  value: ctx.value,
33
122
  ...action,
34
123
  });
124
+ const control = useRef<FormControl | null>(null);
125
+ const [, refresh] = useState(0);
126
+ const initialized = useRef<FormControl | null>(null);
127
+ const subscription = useRef<{
128
+ element: FormControl;
129
+ form: HTMLFormElement;
130
+ off: () => void;
131
+ } | null>(null);
132
+ const resetValue = useRef({
133
+ read: onReset,
134
+ set: ctx.setValue,
135
+ get: ctx.getValue,
136
+ name: ctx.varName,
137
+ });
138
+ resetValue.current = {
139
+ read: onReset,
140
+ set: ctx.setValue,
141
+ get: ctx.getValue,
142
+ name: ctx.varName,
143
+ };
144
+ const ref = useCallback(
145
+ (element: Element | null) => {
146
+ control.current = element as FormControl | null;
147
+ registered.ref(element);
148
+ },
149
+ [registered.ref],
150
+ );
151
+ // Reattach after commits in case the control's form owner changed.
152
+ useLayoutEffect(() => {
153
+ const element = control.current;
154
+ const form = element?.form;
155
+ if (
156
+ subscription.current?.element === element &&
157
+ subscription.current?.form === form
158
+ )
159
+ return;
160
+ subscription.current?.off();
161
+ subscription.current = null;
162
+ if (!element || !onReset) return;
163
+ if (initialized.current !== element) {
164
+ setResetDefault(element);
165
+ initialized.current = element;
166
+ }
167
+ if (!form) return;
168
+ subscription.current = {
169
+ element,
170
+ form,
171
+ off: subscribeFormReset(form, {
172
+ element,
173
+ prepare: () => {
174
+ const before = resetValue.current.get!();
175
+ let changed = false;
176
+ const offWrite = subscribeVariableWrites(
177
+ resetValue.current.name!.split('.'),
178
+ () => (changed = true),
179
+ );
180
+ const offStore = useStoryStore.subscribe(() => {
181
+ changed ||= !Object.is(resetValue.current.get!(), before);
182
+ });
183
+ return {
184
+ off: () => {
185
+ offWrite();
186
+ offStore();
187
+ },
188
+ read: (snapshot) => {
189
+ // Decide before any reset commits, including other controls of
190
+ // this binding. No-op writes and changes away and back count too.
191
+ const value = changed
192
+ ? undefined
193
+ : resetValue.current.read!(snapshot);
194
+ return () => {
195
+ if (control.current !== element || element.form !== form)
196
+ return;
197
+ // A trusted reset may have undone a handler's earlier render.
198
+ if (changed) refresh((version) => version + 1);
199
+ else resetValue.current.set!(value);
200
+ };
201
+ },
202
+ };
203
+ },
204
+ }),
205
+ };
206
+ });
207
+ useLayoutEffect(() => () => subscription.current?.off(), []);
208
+ return { ...registered, ref };
35
209
  }
36
210
 
37
211
  /**
@@ -56,13 +230,7 @@ export function defineInputMacro(
56
230
  { name: 'placeholder', type: 'string', holds: 'text' },
57
231
  ],
58
232
  render(_props, ctx) {
59
- const placeholder = ctx.args.placeholder ?? '';
60
-
61
- const action = useVariableAction(ctx, {
62
- type: name,
63
- label: placeholder || ctx.varName!,
64
- perform: (v) => ctx.setValue!(toValue(v)),
65
- });
233
+ const { placeholder = '' } = ctx.args;
66
234
 
67
235
  // What the reader last typed. A number input reports an unfinished
68
236
  // number ("-", "2e") as an empty value, so the text is kept for as
@@ -76,6 +244,19 @@ export function defineInputMacro(
76
244
  ? typed.current
77
245
  : display(ctx.value);
78
246
 
247
+ const action = useVariableAction(
248
+ ctx,
249
+ {
250
+ type: name,
251
+ label: placeholder || ctx.varName!,
252
+ perform: (v) => ctx.setValue!(toValue(v)),
253
+ },
254
+ (control) => {
255
+ typed.current = control.value;
256
+ return toValue(control.value);
257
+ },
258
+ );
259
+
79
260
  return h(type ? 'input' : 'textarea', {
80
261
  type,
81
262
  ...actionAttributes(action, ctx),
@@ -278,17 +278,36 @@ function readGroup(
278
278
  let [text, at] = trimmed(src ?? '', srcAt);
279
279
  // A lone word is the passage of {include inline}, not its flag
280
280
  const alone = !params.some((p) => p.type !== 'flag' && p.required);
281
- for (const flag of params.filter((p) => p.type === 'flag')) {
282
- const rest = src === null ? null : takeFlag(text, flag.name, alone);
283
- args[flag.name] = rest !== null;
284
- if (rest) {
285
- const flagSpan: Span =
286
- rest[0] > 0
287
- ? [0, text.indexOf(flag.name) + flag.name.length]
288
- : [text.lastIndexOf(flag.name), text.length];
289
- toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
290
- [text, at] = trimmed(slice(text, rest), at + rest[0]);
281
+ const flags = params.filter((p) => p.type === 'flag');
282
+ for (const flag of flags) args[flag.name] = false;
283
+ const byName = new Map(flags.map((flag) => [flag.name, flag]));
284
+ // Consume from the boundaries in source order, independently of declaration
285
+ // order. Prefer the trailing flag when a required lone argument must remain.
286
+ while (text && byName.size) {
287
+ const parts = terms(text);
288
+ if (parts.length === 0) break;
289
+ let changed = false;
290
+ for (const name of [
291
+ slice(text, parts[parts.length - 1]!),
292
+ slice(text, parts[0]!),
293
+ ]) {
294
+ const flag = byName.get(name);
295
+ if (!flag || args[flag.name]) continue;
296
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
297
+ if (rest) {
298
+ args[flag.name] = true;
299
+ byName.delete(flag.name);
300
+ changed = true;
301
+ const flagSpan: Span =
302
+ rest[0] > 0
303
+ ? [0, text.indexOf(flag.name) + flag.name.length]
304
+ : [text.lastIndexOf(flag.name), text.length];
305
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
306
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
307
+ break;
308
+ }
291
309
  }
310
+ if (!changed) break;
292
311
  }
293
312
  const positional = params.filter((p) => p.type !== 'flag');
294
313
  if (positional.length === 0) return;
@@ -47,6 +47,7 @@ import {
47
47
  displayOnlyError,
48
48
  } from './display-only';
49
49
  import { NameSet } from './utils/macro-names';
50
+ import { notifyVariableWrite } from './utils/variable-writes';
50
51
  import {
51
52
  checkParameterTypes,
52
53
  registerMacro,
@@ -254,6 +255,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
254
255
  ctx.setValue = displayOnly
255
256
  ? refuse
256
257
  : (value: unknown) => {
258
+ notifyVariableWrite(segments);
257
259
  // The commit mutation code uses, which keeps the references among
258
260
  // variables: a write to a draft copies only the path written, and
259
261
  // other variables sharing the object would keep the old one.
@@ -189,6 +189,17 @@ function joinSpans(
189
189
  return out + text.slice(last);
190
190
  }
191
191
 
192
+ /** Collapse the trailing blank lines without probing every whitespace suffix. */
193
+ function trimBlankLines(text: string): string {
194
+ let end = text.length;
195
+ let newline = false;
196
+ while (end > 0 && /[ \t\n]/.test(text[end - 1]!)) {
197
+ newline ||= text[end - 1] === '\n';
198
+ end--;
199
+ }
200
+ return newline ? text.slice(0, end) + '\n' : text;
201
+ }
202
+
192
203
  async function formatLf(
193
204
  text: string,
194
205
  options: PassageFormatOptions,
@@ -201,7 +212,7 @@ async function formatLf(
201
212
  const format = options.kind === 'script' ? formatJS : formatCSS;
202
213
  const code = body.trim();
203
214
  const formatted = await format(code, prettier, prettierOptions);
204
- return (formatted ?? code).trim().replace(/\n*$/, '\n');
215
+ return (formatted ?? code).trim() + '\n';
205
216
  }
206
217
 
207
218
  const isBlock = options.isBlock ?? defaultIsBlock(body, options.blockMacros);
@@ -217,17 +228,18 @@ async function formatLf(
217
228
  const literalMarkers = new Set<string>();
218
229
  const fenced = markdownLines(body, isBlock, new Set(['codeFenced']));
219
230
  const literalHtml = whitespaceSensitiveLines(body, isBlock);
220
- body = body
221
- .split('\n')
222
- .map((line, index) => {
223
- if (!fenced.has(index) && !literalHtml.has(index)) return line;
224
- const marker = `${literalSentinel}L${literalLines.size}${literalSentinel}`;
225
- literalLines.set(marker, line);
226
- literalMarkers.add(marker);
227
- return (line.match(/^[ \t]*/)?.[0] ?? '') + marker;
228
- })
229
- .join('\n')
230
- .replace(/(?:[ \t]*\n)+[ \t]*$/, '\n');
231
+ body = trimBlankLines(
232
+ body
233
+ .split('\n')
234
+ .map((line, index) => {
235
+ if (!fenced.has(index) && !literalHtml.has(index)) return line;
236
+ const marker = `${literalSentinel}L${literalLines.size}${literalSentinel}`;
237
+ literalLines.set(marker, line);
238
+ literalMarkers.add(marker);
239
+ return (line.match(/^[ \t]*/)?.[0] ?? '') + marker;
240
+ })
241
+ .join('\n'),
242
+ );
231
243
  const lines: string[] = [];
232
244
  /** Indices in lines whose trailing two spaces are a hard line break. */
233
245
  const hardBreakLines = new Set<number>();
@@ -359,12 +371,12 @@ async function formatLf(
359
371
  // normalized by indentMacros) and ensure single trailing newline
360
372
  let output = lines
361
373
  .map((l, i) =>
362
- hardBreakLines.has(i) || preservedLines.has(i)
363
- ? l
364
- : l.replace(/\s+$/, ''),
374
+ hardBreakLines.has(i) || preservedLines.has(i) ? l : l.trimEnd(),
365
375
  )
366
376
  .join('\n');
367
- output = output.replace(/\n*$/, '\n');
377
+ let end = output.length;
378
+ while (end > 0 && output[end - 1] === '\n') end--;
379
+ output = output.slice(0, end) + '\n';
368
380
 
369
381
  return replaceAll(
370
382
  output
@@ -613,7 +625,7 @@ function indentMacros(
613
625
  (body.keepRelative ? line.col - (isRoot ? 0 : body.minCol) : 0);
614
626
  }
615
627
  outCol.push(col);
616
- const hardBreak = / {2,}$/.test(lines[i]!) && info[i + 1] ? ' ' : '';
628
+ const hardBreak = lines[i]!.endsWith(' ') && info[i + 1] ? ' ' : '';
617
629
  result.push(' '.repeat(col) + line.text + hardBreak);
618
630
  }
619
631
 
@@ -1,4 +1,6 @@
1
1
  import { findCodeEnd, parsedCodeEnd } from '../js-lexer';
2
+ import { escapeRegExp } from '../components/macros/arg-utils';
3
+ import { upperBound } from '../utils/sorted';
2
4
 
3
5
  /**
4
6
  * Where the JavaScript inside markup ends. The grammar (spindle.peggy) leaves
@@ -161,6 +163,10 @@ export type OnOpenCodeEnd = (input: string, codeStart: number) => void;
161
163
  * input (see `OnOpenCodeEnd`); the ends it finds are the same.
162
164
  */
163
165
  export function jsCodeEnd(onOpenEnd?: OnOpenCodeEnd): CodeEnd {
166
+ // Keep only the latest immutable source. Missing closers are indexed too,
167
+ // so every unclosed raw opener does not search the same suffix again.
168
+ let indexedInput = '';
169
+ const rawClosers = new Map<string, number[]>();
164
170
  return {
165
171
  closeBrace(input, codeStart, lenientStart) {
166
172
  let ranOut = false;
@@ -172,10 +178,21 @@ export function jsCodeEnd(onOpenEnd?: OnOpenCodeEnd): CodeEnd {
172
178
  return end;
173
179
  },
174
180
  rawBodyEnd(input, bodyStart, name) {
175
- const closer = `\\{/${name}\\s*\\}`;
176
- const first = new RegExp(closer, 'gi');
177
- first.lastIndex = bodyStart;
178
- const firstAt = first.exec(input)?.index ?? -1;
181
+ if (indexedInput !== input) {
182
+ indexedInput = input;
183
+ rawClosers.clear();
184
+ }
185
+ name = name.toLowerCase();
186
+ const closer = `\\{/${escapeRegExp(name)}\\s*\\}`;
187
+ let candidates = rawClosers.get(name);
188
+ if (!candidates) {
189
+ candidates = Array.from(
190
+ input.matchAll(new RegExp(closer, 'gi')),
191
+ (m) => m.index,
192
+ );
193
+ rawClosers.set(name, candidates);
194
+ }
195
+ const firstAt = candidates[upperBound(candidates, bodyStart - 1)] ?? -1;
179
196
  if (firstAt === -1) return -1;
180
197
  const at = new RegExp(closer, 'iy');
181
198
  let ranOut = false;
@@ -192,7 +209,8 @@ export function jsCodeEnd(onOpenEnd?: OnOpenCodeEnd): CodeEnd {
192
209
  // with its `}` follows
193
210
  if (
194
211
  onOpenEnd &&
195
- (ranOut || new RegExp(`\\{/${name}\\s*$`, 'i').test(input))
212
+ (ranOut ||
213
+ new RegExp(`\\{/${escapeRegExp(name)}\\s*$`, 'i').test(input))
196
214
  ) {
197
215
  onOpenEnd(input, bodyStart);
198
216
  }
@@ -206,13 +224,15 @@ export const defaultCodeEnd: CodeEnd = jsCodeEnd();
206
224
 
207
225
  /**
208
226
  * Index possible brace ends for repeated recovery attempts in one template.
209
- * Within plain code, nested braces must close first. At a quote, slash or
210
- * escape we stop making lexical assumptions, but the remaining raw `}`s
211
- * still bound how many pending braces could close. Indexing visits each
212
- * opener once, so unmatched plain-code openers can skip suffix scans.
227
+ * Within plain code, nested braces must close first. At a quote, slash,
228
+ * escape or HTML-style comment we stop making lexical assumptions, but the
229
+ * remaining raw `}`s still bound how many pending braces could close.
230
+ * Indexing visits each opener once, so unmatched plain-code openers can
231
+ * skip suffix scans.
213
232
  */
214
233
  export function indexCodeEnds(
215
234
  input: string,
235
+ closeBrace: CodeEnd['closeBrace'] = defaultCodeEnd.closeBrace,
216
236
  ): (start: number, codeStart?: number, limit?: number) => number {
217
237
  const possible = new Set<number>();
218
238
  const pending: number[] = [];
@@ -241,7 +261,16 @@ export function indexCodeEnds(
241
261
  remaining--;
242
262
  const open = pending.pop();
243
263
  if (open !== undefined) possible.add(open);
244
- } else if (/['"`/\\]/.test(c)) uncertain();
264
+ } else if (
265
+ /['"`/\\]/.test(c) ||
266
+ input.startsWith('<!--', i) ||
267
+ input.startsWith('-->', i)
268
+ ) {
269
+ // Acorn accepts HTML-style line comments in script code. Their
270
+ // braces are as uncertain as those after a slash; do not parse the
271
+ // comment here, or assume --> needs to be a comment at this start.
272
+ uncertain();
273
+ }
245
274
  }
246
275
  return (start, codeStart = start, limit = input.length) => {
247
276
  if (start > lastBrace || codeStart >= limit) return -1;
@@ -256,7 +285,7 @@ export function indexCodeEnds(
256
285
  possible.has(start - 1) ||
257
286
  input.slice(start, codeStart).includes('{')
258
287
  ) {
259
- return defaultCodeEnd.closeBrace(source, codeStart, start);
288
+ return closeBrace(source, codeStart, start);
260
289
  }
261
290
  // Acorn locates its starting line and syntax errors by scanning the
262
291
  // prefix. Recovery must not hand it the whole passage for every opener.
@@ -270,3 +299,28 @@ export function indexCodeEnds(
270
299
  return end < 0 ? -1 : base + end;
271
300
  };
272
301
  }
302
+
303
+ /**
304
+ * Reusable strict expression-boundary queries over one immutable source.
305
+ * Results match `findCodeEnd(input, start)`, without markup's lenient
306
+ * fallback. The shared brace index prunes unmatched plain-code prefixes;
307
+ * each queried start is cached independently, including failed queries.
308
+ */
309
+ export function indexStrictCodeEnds(input: string): (start: number) => number {
310
+ const read = indexCodeEnds(input, (source, start) => {
311
+ // Acorn computes error locations by reading the prefix. Keep just one
312
+ // preceding character so a leading #! does not become a hashbang.
313
+ const base = Math.max(0, start - 1);
314
+ const end = findCodeEnd(source.slice(base), start - base);
315
+ return end < 0 ? -1 : base + end;
316
+ });
317
+ const ends = new Map<number, number>();
318
+ return (start) => {
319
+ let end = ends.get(start);
320
+ if (end === undefined) {
321
+ end = read(start);
322
+ ends.set(start, end);
323
+ }
324
+ return end;
325
+ };
326
+ }
@@ -972,7 +972,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
972
972
  );
973
973
  }
974
974
  const element = authorElement(
975
- namespace === 'svg' ? svgTagName(node.tag) : node.tag,
975
+ namespace === 'svg' ? svgTagName(node.tag) : tag,
976
976
  props,
977
977
  children,
978
978
  namespace === 'math',
@@ -116,10 +116,14 @@ export function observableText(
116
116
  const href =
117
117
  use.getAttribute('href') ??
118
118
  use.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
119
- if (!href?.startsWith('#') || href.length === 1) return;
119
+ if (!href) return;
120
120
  let id: string;
121
121
  try {
122
- id = decodeURIComponent(href.slice(1));
122
+ const url = new URL(href, use.baseURI);
123
+ const current = new URL(use.ownerDocument.URL);
124
+ if (url.href.split('#')[0] !== current.href.split('#')[0]) return;
125
+ if (url.hash.length <= 1) return;
126
+ id = decodeURIComponent(url.hash.slice(1));
123
127
  } catch {
124
128
  return;
125
129
  }
@@ -228,7 +232,8 @@ export function observableText(
228
232
  .map((line) => line.trimEnd())
229
233
  .join('\n')
230
234
  .replace(/\n{3,}/g, '\n\n')
231
- .replace(/^\n+|\s+$/g, '')
235
+ .replace(/^\n+/, '')
236
+ .trimEnd()
232
237
  );
233
238
  }
234
239
 
package/src/settings.ts CHANGED
@@ -38,8 +38,16 @@ let storageLoaded = false;
38
38
  let unsubscribeStoryData: (() => void) | null = null;
39
39
 
40
40
  const listeners = new Set<() => void>();
41
+ let revision = 0;
41
42
 
42
- /** Call `listener` after a setting changes; returns the unsubscribe. */
43
+ export const getSettingsRevision = (): number => revision;
44
+
45
+ function notify(): void {
46
+ revision++;
47
+ for (const listener of [...listeners]) listener();
48
+ }
49
+
50
+ /** Call `listener` after a definition or value changes; returns the unsubscribe. */
43
51
  export function subscribeSettings(listener: () => void): () => void {
44
52
  listeners.add(listener);
45
53
  return () => listeners.delete(listener);
@@ -98,6 +106,7 @@ function define(name: string, def: SettingDef): void {
98
106
  definitions.set(name, def);
99
107
  if (!hasOwn(values, name)) values[name] = def.config.default;
100
108
  loadFromStorage();
109
+ notify();
101
110
  }
102
111
 
103
112
  /** The value of setting `name` if it has the type of `fallback`, else that. */
@@ -148,7 +157,7 @@ export const settings = {
148
157
  values[name] = value;
149
158
  persist();
150
159
  if (unchanged) return;
151
- for (const listener of [...listeners]) listener();
160
+ notify();
152
161
  emit('settingchanged', name, value);
153
162
  },
154
163
 
package/src/story-api.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { useStoryStore, trackRuntimeUnsub, recordHookWrite } from './store';
2
+ import { notifyVariableWrite } from './utils/variable-writes';
2
3
  import type { StoryState, VariableNamespaces } from './store';
3
4
  import { freeze } from 'immer';
4
5
  import {
@@ -350,7 +351,11 @@ function createStoryAPI(): StoryAPI {
350
351
  for (const [name] of entries) {
351
352
  const { isTransient, key } = parseName(name);
352
353
  warnIfUndeclared(isTransient, key);
353
- if (!isTransient) recordHookWrite(key.split('.'));
354
+ if (!isTransient) {
355
+ const path = key.split('.');
356
+ recordHookWrite(path);
357
+ notifyVariableWrite(path);
358
+ }
354
359
  }
355
360
  // One store update for all keys, in program order with any running
356
361
  // mutation. Nested writes use the mutation merge to preserve aliases.
package/src/tooling.ts CHANGED
@@ -95,6 +95,7 @@ export {
95
95
  parseCode,
96
96
  scanStringLiteral,
97
97
  } from './js-lexer';
98
+ export { indexStrictCodeEnds } from './markup/code-end';
98
99
  export type {
99
100
  ParsedCode,
100
101
  VariableRef,
@@ -0,0 +1,24 @@
1
+ /** Explicit writes, including assignments that leave a binding unchanged. */
2
+ const listeners = new Set<(path: readonly string[]) => void>();
3
+
4
+ export function notifyVariableWrite(path: readonly string[]): void {
5
+ for (const listener of listeners) listener(path);
6
+ }
7
+
8
+ /** Observe writes to a binding, its parent, or one of its children. */
9
+ export function subscribeVariableWrites(
10
+ binding: readonly string[],
11
+ onWrite: () => void,
12
+ ): () => void {
13
+ const listener = (path: readonly string[]) => {
14
+ const length = Math.min(path.length, binding.length);
15
+ for (let i = 0; i < length; i++) {
16
+ if (path[i] !== binding[i]) return;
17
+ }
18
+ onWrite();
19
+ };
20
+ listeners.add(listener);
21
+ return () => {
22
+ listeners.delete(listener);
23
+ };
24
+ }
@@ -2,13 +2,12 @@ import type { ASTNode } from '../markup/ast';
2
2
  import type { Token } from '../markup/tokens';
3
3
  import { codeAndText, parameterLookup, type ParametersOf } from '../code-check';
4
4
  import { parseMarkup, type MarkupHooks } from '../markup/parse';
5
- import { getMacroRegistry, getMacroParameters } from '../registry';
5
+ import { getMacroRegistry } from '../registry';
6
6
  import { MarkupExpansionBudget } from '../markup/expansion-budget';
7
7
 
8
- /** The declared parameters of the macros registered so far. */
9
- export const registeredParameters: ParametersOf = (name) =>
10
- parameterLookup(getMacroRegistry())(name);
11
- registeredParameters.source = getMacroParameters.source;
8
+ /** Snapshot effective macro metadata once per scan. */
9
+ export const registeredParameters = (): ParametersOf =>
10
+ parameterLookup(getMacroRegistry());
12
11
 
13
12
  /**
14
13
  * Whether the text of an attribute value or macro label renders a
@@ -43,7 +42,7 @@ function textContainsChildren(
43
42
  */
44
43
  export function tokenTextContainsChildren(
45
44
  token: Token,
46
- parametersOf: ParametersOf = registeredParameters,
45
+ parametersOf: ParametersOf = registeredParameters(),
47
46
  src = '',
48
47
  hooks?: Partial<MarkupHooks>,
49
48
  budget?: MarkupExpansionBudget,
@@ -68,7 +67,7 @@ export function tokenTextContainsChildren(
68
67
  */
69
68
  export function astContainsChildren(
70
69
  nodes: ASTNode[],
71
- parametersOf: ParametersOf = registeredParameters,
70
+ parametersOf: ParametersOf = registeredParameters(),
72
71
  hooks?: Partial<MarkupHooks>,
73
72
  budget?: MarkupExpansionBudget,
74
73
  ): boolean {