@rohal12/spindle 0.64.29 → 0.64.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -206,13 +206,15 @@ export const defaultCodeEnd: CodeEnd = jsCodeEnd();
206
206
 
207
207
  /**
208
208
  * 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.
209
+ * Within plain code, nested braces must close first. At a quote, slash,
210
+ * escape or HTML-style comment we stop making lexical assumptions, but the
211
+ * remaining raw `}`s still bound how many pending braces could close.
212
+ * Indexing visits each opener once, so unmatched plain-code openers can
213
+ * skip suffix scans.
213
214
  */
214
215
  export function indexCodeEnds(
215
216
  input: string,
217
+ closeBrace: CodeEnd['closeBrace'] = defaultCodeEnd.closeBrace,
216
218
  ): (start: number, codeStart?: number, limit?: number) => number {
217
219
  const possible = new Set<number>();
218
220
  const pending: number[] = [];
@@ -241,7 +243,16 @@ export function indexCodeEnds(
241
243
  remaining--;
242
244
  const open = pending.pop();
243
245
  if (open !== undefined) possible.add(open);
244
- } else if (/['"`/\\]/.test(c)) uncertain();
246
+ } else if (
247
+ /['"`/\\]/.test(c) ||
248
+ input.startsWith('<!--', i) ||
249
+ input.startsWith('-->', i)
250
+ ) {
251
+ // Acorn accepts HTML-style line comments in script code. Their
252
+ // braces are as uncertain as those after a slash; do not parse the
253
+ // comment here, or assume --> needs to be a comment at this start.
254
+ uncertain();
255
+ }
245
256
  }
246
257
  return (start, codeStart = start, limit = input.length) => {
247
258
  if (start > lastBrace || codeStart >= limit) return -1;
@@ -256,7 +267,7 @@ export function indexCodeEnds(
256
267
  possible.has(start - 1) ||
257
268
  input.slice(start, codeStart).includes('{')
258
269
  ) {
259
- return defaultCodeEnd.closeBrace(source, codeStart, start);
270
+ return closeBrace(source, codeStart, start);
260
271
  }
261
272
  // Acorn locates its starting line and syntax errors by scanning the
262
273
  // prefix. Recovery must not hand it the whole passage for every opener.
@@ -270,3 +281,28 @@ export function indexCodeEnds(
270
281
  return end < 0 ? -1 : base + end;
271
282
  };
272
283
  }
284
+
285
+ /**
286
+ * Reusable strict expression-boundary queries over one immutable source.
287
+ * Results match `findCodeEnd(input, start)`, without markup's lenient
288
+ * fallback. The shared brace index prunes unmatched plain-code prefixes;
289
+ * each queried start is cached independently, including failed queries.
290
+ */
291
+ export function indexStrictCodeEnds(input: string): (start: number) => number {
292
+ const read = indexCodeEnds(input, (source, start) => {
293
+ // Acorn computes error locations by reading the prefix. Keep just one
294
+ // preceding character so a leading #! does not become a hashbang.
295
+ const base = Math.max(0, start - 1);
296
+ const end = findCodeEnd(source.slice(base), start - base);
297
+ return end < 0 ? -1 : base + end;
298
+ });
299
+ const ends = new Map<number, number>();
300
+ return (start) => {
301
+ let end = ends.get(start);
302
+ if (end === undefined) {
303
+ end = read(start);
304
+ ends.set(start, end);
305
+ }
306
+ return end;
307
+ };
308
+ }
@@ -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
  }
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/store.ts CHANGED
@@ -4,6 +4,7 @@ import { immer } from 'zustand/middleware/immer';
4
4
  import type { StateCreator } from 'zustand/vanilla';
5
5
  import {
6
6
  current,
7
+ produce,
7
8
  enableMapSet,
8
9
  enablePatches,
9
10
  isDraft,
@@ -66,6 +67,7 @@ import {
66
67
  type PathChange,
67
68
  } from './structural';
68
69
  import { getByPath, setByPath } from './utils/object-path';
70
+ import { notifyItemEdits } from './utils/control-edits';
69
71
  import { isIndexKey } from './utils/value-kinds';
70
72
  import {
71
73
  noPassageError,
@@ -1297,10 +1299,12 @@ function storyStateGuard(
1297
1299
  Object.assign(draft, updater);
1298
1300
  };
1299
1301
  const routed = routeStoreUpdate(recipe);
1300
- set((draft) => {
1302
+ const before = get();
1303
+ const next = produce(before, (draft) => {
1301
1304
  (routed ?? recipe)(draft);
1302
1305
  keepNamespacesBare(draft);
1303
1306
  });
1307
+ notifyItemEdits(before, next, () => set(next));
1304
1308
  }) as typeof set;
1305
1309
  api.setState = guarded;
1306
1310
  const state = creator(guarded, get, api);
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,
@@ -1,6 +1,5 @@
1
1
  import { createContext } from 'preact';
2
- import { readState } from '../execute-mutation';
3
- import { diffPaths } from '../structural';
2
+ import { deepEqualStrict, diffPaths } from '../structural';
4
3
  import { getByPath } from './object-path';
5
4
  import type { VariableNamespaces } from '../store';
6
5
 
@@ -22,42 +21,119 @@ import type { VariableNamespaces } from '../store';
22
21
  */
23
22
  let version = 0;
24
23
  const MAX_LOG = 4096;
25
- /** Edits in the order made: paths below the namespaces (`['variables', 'a']`). */
26
- const log: { version: number; path: readonly string[] }[] = [];
24
+ /** Object identities at their own commit; old story graphs stay collectible. */
25
+ const through = new WeakMap<object, number>();
26
+ /** Paths, not story graphs: revisit only the prefixes an edit actually used. */
27
+ const tracked = new Map<string, readonly string[]>();
28
+ /** Primitive slot edits also retain their committed value. */
29
+ const log: { version: number; path: readonly string[]; value: unknown }[] = [];
27
30
 
28
- function note(path: readonly string[]): void {
29
- log.push({ version: ++version, path });
31
+ function note(path: readonly string[], state: VariableNamespaces): void {
32
+ const at = ++version;
33
+ const key = JSON.stringify(path);
34
+ tracked.delete(key);
35
+ tracked.set(key, path);
36
+ if (tracked.size > MAX_LOG) tracked.delete(tracked.keys().next().value!);
37
+ let node: unknown = state;
38
+ for (const segment of path) {
39
+ node =
40
+ node !== null && typeof node === 'object'
41
+ ? getByPath(node, [segment])
42
+ : undefined;
43
+ if (node !== null && typeof node === 'object') through.set(node, at);
44
+ }
45
+ if (node !== null && typeof node === 'object') return;
46
+ log.push({ version: at, path, value: node });
30
47
  if (log.length > MAX_LOG) log.shift();
31
48
  }
32
49
 
33
- /** Note an edit a control made to the story variable at `segments`. */
34
- export function noteControlEdit(segments: readonly string[]): void {
35
- note(['variables', ...segments]);
50
+ type Edits = readonly (readonly string[])[] | 'changed' | undefined;
51
+ let activeEdits: Edits;
52
+
53
+ function withEdits(edits: Edits, run: () => void): void {
54
+ const previous = activeEdits;
55
+ activeEdits = edits;
56
+ try {
57
+ run();
58
+ } finally {
59
+ activeEdits = previous;
60
+ }
36
61
  }
37
62
 
38
- /**
39
- * Whether mutation code runs inside a {for} iteration: {for} provides true
40
- * around its iterations, and the writes of such code are noted as edits of
41
- * the items they reach (see runAsItemEdit).
42
- */
63
+ /** Attribute only the control's own writes, before subscribers can replace them. */
64
+ export function runAsControlEdit(
65
+ segments: readonly string[],
66
+ run: () => void,
67
+ ): void {
68
+ withEdits([['variables', ...segments]], run);
69
+ }
70
+
71
+ /** Whether mutation code runs inside a {for} iteration. */
43
72
  export const ItemEditContext = createContext(false);
44
73
 
45
74
  const NAMESPACES = ['variables', 'temporary', 'transient'] as const;
46
75
 
47
- /** Run `run`, noting each variable path it changes as an edit. */
76
+ /** Run `run`, noting each variable path its own updates change as an edit. */
48
77
  export function runAsItemEdit(run: () => void): void {
49
- const before = readState();
50
- try {
51
- run();
52
- } finally {
53
- const after = readState();
78
+ withEdits('changed', run);
79
+ }
80
+
81
+ /** Called with finalized state before the store notifies its subscribers. */
82
+ export function notifyItemEdits(
83
+ before: VariableNamespaces,
84
+ after: VariableNamespaces,
85
+ notify: () => void,
86
+ ): void {
87
+ // Commits can copy whole arrays, including unchanged rows. Carry an
88
+ // earlier edit to an equal copy even when a watcher changed a sibling;
89
+ // a replacement with different content cannot inherit the mark.
90
+ // Skip the namespace itself so unrelated state is never walked.
91
+ const compared = new WeakMap<object, WeakSet<object>>();
92
+ for (const path of tracked.values()) {
93
+ const ns = path[0] as keyof VariableNamespaces;
94
+ if (before[ns] === after[ns]) continue;
95
+ let previous: unknown = before[ns];
96
+ let next: unknown = after[ns];
97
+ for (const segment of path.slice(1)) {
98
+ previous =
99
+ previous !== null && typeof previous === 'object'
100
+ ? getByPath(previous, [segment])
101
+ : undefined;
102
+ next =
103
+ next !== null && typeof next === 'object'
104
+ ? getByPath(next, [segment])
105
+ : undefined;
106
+ if (
107
+ previous === null ||
108
+ typeof previous !== 'object' ||
109
+ next === null ||
110
+ typeof next !== 'object' ||
111
+ previous === next
112
+ )
113
+ continue;
114
+ const edited = through.get(previous);
115
+ if (edited === undefined) continue;
116
+ const copies = compared.get(previous) ?? new WeakSet<object>();
117
+ if (copies.has(next)) continue;
118
+ copies.add(next);
119
+ compared.set(previous, copies);
120
+ if (deepEqualStrict(previous, next)) {
121
+ through.set(next, Math.max(through.get(next) ?? 0, edited));
122
+ }
123
+ }
124
+ }
125
+ if (activeEdits === 'changed') {
54
126
  for (const ns of NAMESPACES) {
55
127
  if (before[ns] === after[ns]) continue;
56
128
  for (const { path } of diffPaths(before[ns], after[ns], true)) {
57
- note([ns, ...path]);
129
+ note([ns, ...path], after);
58
130
  }
59
131
  }
132
+ } else {
133
+ for (const path of activeEdits ?? []) note(path, after);
60
134
  }
135
+ // Watcher writes are independent of the edit that triggered them.
136
+ withEdits(undefined, notify);
61
137
  }
62
138
 
63
139
  export function controlEditVersion(): number {
@@ -74,26 +150,27 @@ export function editedItems(
74
150
  state: VariableNamespaces,
75
151
  ): (list: readonly unknown[], item: unknown, index: number) => boolean {
76
152
  // The objects the paths lead through, and the keys they end at
77
- const through = new Set<unknown>();
78
153
  const ends = new Map<unknown, Set<string>>();
79
154
  for (let i = log.length - 1; i >= 0 && log[i]!.version > since; i--) {
80
- const { path } = log[i]!;
81
- let node: unknown = state;
82
- path.forEach((seg, n) => {
83
- if (n === path.length - 1 && node !== null && typeof node === 'object') {
84
- const keys = ends.get(node) ?? new Set<string>();
85
- keys.add(seg);
86
- ends.set(node, keys);
155
+ const { path, value } = log[i]!;
156
+ const parent = getByPath(state, path.slice(0, -1));
157
+ const key = path[path.length - 1]!;
158
+ if (parent !== null && typeof parent === 'object') {
159
+ const current = getByPath(parent, [key]);
160
+ // A primitive edit survives later edits of other slots, but a watcher
161
+ // assigning a different value at the very same path is a replacement.
162
+ if (
163
+ (current === null || typeof current !== 'object') &&
164
+ Object.is(current, value)
165
+ ) {
166
+ const keys = ends.get(parent) ?? new Set<string>();
167
+ keys.add(key);
168
+ ends.set(parent, keys);
87
169
  }
88
- node =
89
- node !== null && typeof node === 'object'
90
- ? getByPath(node, [seg])
91
- : undefined;
92
- if (node !== null && typeof node === 'object') through.add(node);
93
- });
170
+ }
94
171
  }
95
172
  return (list, item, index) =>
96
173
  typeof item === 'object' && item !== null
97
- ? through.has(item)
174
+ ? (through.get(item) ?? 0) > since
98
175
  : ends.get(list)?.has(String(index)) === true;
99
176
  }
@@ -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 {
@@ -131,7 +131,7 @@ function nameSpan(rawArgs: string): [number, number] {
131
131
  */
132
132
  export function widgetDefinitions(
133
133
  passages: Iterable<WidgetPassage>,
134
- parametersOf: ParametersOf = registeredParameters,
134
+ parametersOf: ParametersOf = registeredParameters(),
135
135
  ): WidgetDefinition[] {
136
136
  const list = [...passages];
137
137
  const scan = (replacesDo: boolean): WidgetDefinition[] => {
@@ -244,7 +244,7 @@ export function effectiveWidgetDefinitions(
244
244
  */
245
245
  export function effectiveWidgets(
246
246
  passages: Iterable<WidgetPassage>,
247
- parametersOf: ParametersOf = registeredParameters,
247
+ parametersOf: ParametersOf = registeredParameters(),
248
248
  ): WidgetDefinition[] {
249
249
  return effectiveWidgetDefinitions(widgetDefinitions(passages, parametersOf));
250
250
  }
@@ -252,7 +252,7 @@ export function effectiveWidgets(
252
252
  /** The names of the block widgets among the effectiveWidgets. */
253
253
  export function blockWidgetNames(
254
254
  passages: Iterable<WidgetPassage>,
255
- parametersOf: ParametersOf = registeredParameters,
255
+ parametersOf: ParametersOf = registeredParameters(),
256
256
  ): string[] {
257
257
  return effectiveWidgets(passages, parametersOf)
258
258
  .filter((def) => def.block)
@@ -315,6 +315,18 @@ export declare function findCodeEnd(
315
315
  options?: FindCodeEndOptions,
316
316
  ): number;
317
317
 
318
+ /**
319
+ * Reusable strict expression-boundary queries for one immutable source.
320
+ * The returned function matches `findCodeEnd(src, start)` (default options),
321
+ * with UTF-16 offsets into `src`. Query just after each `{` to prune
322
+ * unmatched plain-code prefixes without rescanning their suffixes. Results
323
+ * are cached per start; a failed outer query does not hide an inner span.
324
+ * There is no lenient markup recovery or custom `goal`/`stop` option.
325
+ */
326
+ export declare function indexStrictCodeEnds(
327
+ src: string,
328
+ ): (start: number) => number;
329
+
318
330
  /**
319
331
  * Scan the `"…"` or `'…'` string literal opening at `start`: `end` is just
320
332
  * past its closing quote, or `src.length` when unterminated (`closed` false).