@rohal12/spindle 0.64.28 → 0.64.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.
@@ -3,7 +3,7 @@ import { useCallback, useContext, useEffect, useErrorBoundary, useId, useLayoutE
3
3
  import { memo, useSyncExternalStore } from "preact/compat";
4
4
  import { createStore } from "zustand/vanilla";
5
5
  import { immer } from "zustand/middleware/immer";
6
- import { Immer, current, enableMapSet, enablePatches, freeze, isDraft, original } from "immer";
6
+ import { Immer, current, enableMapSet, enablePatches, freeze, isDraft, original, produce } from "immer";
7
7
  import { shallow } from "zustand/vanilla/shallow";
8
8
  import { Fragment as Fragment$1, jsx, jsxs } from "preact/jsx-runtime";
9
9
  import { micromark } from "micromark";
@@ -6538,17 +6538,21 @@ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
6538
6538
  var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
6539
6539
  /** `ns[key]` if `ns` holds it as an own property, else undefined. */
6540
6540
  var ownValue = (ns, key) => ns && hasOwn(ns, key) ? ns[key] : void 0;
6541
- /**
6542
- * Set an own enumerable property. A "__proto__" key is defined as an own
6543
- * property (as JSON.parse does) instead of replacing the prototype.
6544
- */
6545
- function setOwn(target, key, value) {
6546
- if (key === "__proto__") Object.defineProperty(target, key, {
6541
+ /** Define an own data field without invoking an inherited accessor. */
6542
+ function defineData(target, key, value) {
6543
+ Object.defineProperty(target, key, {
6547
6544
  value,
6548
6545
  enumerable: true,
6549
6546
  writable: true,
6550
6547
  configurable: true
6551
6548
  });
6549
+ }
6550
+ /**
6551
+ * Set an own enumerable property. A "__proto__" key is defined as an own
6552
+ * property (as JSON.parse does) instead of replacing the prototype.
6553
+ */
6554
+ function setOwn(target, key, value) {
6555
+ if (key === "__proto__") defineData(target, key, value);
6552
6556
  else target[key] = value;
6553
6557
  }
6554
6558
  /**
@@ -7662,14 +7666,6 @@ var isObject = (v) => typeof v === "object" && v !== null;
7662
7666
  /** Whether `v` is a plain object (as devalue revives one). */
7663
7667
  var isPlainData = (v) => isObject(v) && Object.getPrototypeOf(v) === Object.prototype;
7664
7668
  var malformedClass = (name) => /* @__PURE__ */ new TypeError(`spindle: Malformed data for class "${name}"`);
7665
- var defineData = (target, key, value) => {
7666
- Object.defineProperty(target, key, {
7667
- value,
7668
- enumerable: true,
7669
- writable: true,
7670
- configurable: true
7671
- });
7672
- };
7673
7669
  /**
7674
7670
  * A reducer extracts string keys, so devalue never sees the symbol keys of
7675
7671
  * the original object: refuse them here, as it does for a plain object.
@@ -8011,12 +8007,7 @@ var builtinName = atomicName;
8011
8007
  */
8012
8008
  function shallowCopy(value) {
8013
8009
  const copy = Array.isArray(value) ? new Array(value.length) : Object.create(Object.getPrototypeOf(value));
8014
- for (const key of Object.keys(value)) Object.defineProperty(copy, key, {
8015
- value: value[key],
8016
- enumerable: true,
8017
- writable: true,
8018
- configurable: true
8019
- });
8010
+ for (const key of Object.keys(value)) defineData(copy, key, value[key]);
8020
8011
  return copy;
8021
8012
  }
8022
8013
  /**
@@ -8129,7 +8120,7 @@ function builtinLike(obj, empty, made, value) {
8129
8120
  made(empty);
8130
8121
  if (registeredClassName(obj) === void 0) return empty;
8131
8122
  Object.setPrototypeOf(empty, Object.getPrototypeOf(obj));
8132
- for (const key of extraKeys(obj)) setOwn(empty, key, value(key));
8123
+ for (const key of extraKeys(obj)) defineData(empty, key, value(key));
8133
8124
  return empty;
8134
8125
  }
8135
8126
  function deepClone(value, options = {}) {
@@ -8144,10 +8135,10 @@ function deepClone(value, options = {}) {
8144
8135
  * save refuses them, which a copy must not hide.
8145
8136
  */
8146
8137
  function copyKeys(obj, copy) {
8147
- for (const key of Object.keys(obj)) setOwn(copy, key, clone(obj[key]));
8138
+ for (const key of Object.keys(obj)) defineData(copy, key, clone(obj[key]));
8148
8139
  for (const sym of Object.getOwnPropertySymbols(obj)) {
8149
8140
  if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) continue;
8150
- copy[sym] = clone(obj[sym]);
8141
+ defineData(copy, sym, clone(obj[sym]));
8151
8142
  }
8152
8143
  return copy;
8153
8144
  }
@@ -8195,7 +8186,7 @@ function deepClone(value, options = {}) {
8195
8186
  if (seen.has(obj)) return seen.get(obj);
8196
8187
  if (Array.isArray(val)) {
8197
8188
  const arr = builtin(obj, new Array(val.length));
8198
- for (const key of arrayIndices(val)) arr[Number(key)] = clone(val[Number(key)]);
8189
+ for (const key of arrayIndices(val)) defineData(arr, key, clone(val[Number(key)]));
8199
8190
  return arr;
8200
8191
  }
8201
8192
  if (val instanceof Map) {
@@ -8321,13 +8312,13 @@ function shareEqual(prev, curr) {
8321
8312
  }
8322
8313
  if (Array.isArray(c) && Array.isArray(p)) {
8323
8314
  const out = collection(new Array(c.length));
8324
- for (const key of arrayIndices(c)) out[Number(key)] = shareKey(key);
8315
+ for (const key of arrayIndices(c)) defineData(out, key, shareKey(key));
8325
8316
  return out;
8326
8317
  }
8327
8318
  if (mergesWith(p, c, false)) {
8328
8319
  const out = Object.create(Object.getPrototypeOf(c));
8329
8320
  done.set(c, out);
8330
- for (const key of Object.keys(cr)) setOwn(out, key, shareKey(key));
8321
+ for (const key of Object.keys(cr)) defineData(out, key, shareKey(key));
8331
8322
  return out;
8332
8323
  }
8333
8324
  return fresh(c);
@@ -8925,6 +8916,13 @@ function clonerFor(target, paths) {
8925
8916
  settle
8926
8917
  });
8927
8918
  }
8919
+ /** Adopt setter inputs into a draft, retaining references to owned state. */
8920
+ function adoptStateValues(target) {
8921
+ const held = locateObjects(namespacesOf(useStoryStore.getState()), []);
8922
+ const scope = getActiveMutationScope();
8923
+ if (scope) for (const [value, path] of locateObjects(scope, [])) held.set(value, path);
8924
+ return clonerFor(target, held);
8925
+ }
8928
8926
  /** One cloner per target copy, made when first used. */
8929
8927
  var clonersFor = (paths) => {
8930
8928
  const made = /* @__PURE__ */ new Map();
@@ -14549,6 +14547,11 @@ function readWholeQuoted(src) {
14549
14547
  const quoted = readQuoted(src, 0);
14550
14548
  return quoted && quoted.end === src.length ? quoted.value : null;
14551
14549
  }
14550
+ /** A dialog body's passage name, optionally enclosed in matching quotes. */
14551
+ function readPassageBody(src) {
14552
+ const name = src.trim();
14553
+ return readWholeQuoted(name) ?? name;
14554
+ }
14552
14555
  /**
14553
14556
  * Strip an optional quote from each end of an unquoted-or-loosely-quoted
14554
14557
  * argument (`"Red`, `Red'`), leaving at least one character. This is the
@@ -15332,7 +15335,7 @@ function* codeAndText(src, tokens, parametersOf) {
15332
15335
  const written = text.trim();
15333
15336
  yield {
15334
15337
  kind: "passage",
15335
- name: written.replace(/^["']|["']$/g, ""),
15338
+ name: readPassageBody(written),
15336
15339
  offset: token.end + text.indexOf(written),
15337
15340
  length: written.length,
15338
15341
  macro: name,
@@ -19687,6 +19690,128 @@ function initializeStory(savedSession) {
19687
19690
  recordStoryInitState();
19688
19691
  }
19689
19692
  }
19693
+ // src/utils/control-edits.ts
19694
+ /**
19695
+ * Records the edits made to the items of a list from inside a {for}
19696
+ * iteration, which {for} tells apart from a list that is replaced:
19697
+ *
19698
+ * - a reader editing a variable through a control (`{textbox}`,
19699
+ * `{checkbox}`, ...): typing into a control inside an iteration changes
19700
+ * its item, but must not remount the iteration and drop the control's
19701
+ * focus (#369);
19702
+ * - mutation code an iteration runs as it renders (`{set $party[@i].hp +=
19703
+ * 1}`): remounting would run the iteration's mount-only macros, and so the
19704
+ * write, again for every write it makes (#400).
19705
+ *
19706
+ * An edit is attributed to the variable path it wrote, so a replacement made
19707
+ * elsewhere (a watcher reacting to the edit, a button outside the loop)
19708
+ * still remounts.
19709
+ */
19710
+ var version = 0;
19711
+ var MAX_LOG = 4096;
19712
+ /** Object identities at their own commit; old story graphs stay collectible. */
19713
+ var through = /* @__PURE__ */ new WeakMap();
19714
+ /** Paths, not story graphs: revisit only the prefixes an edit actually used. */
19715
+ var tracked = /* @__PURE__ */ new Map();
19716
+ /** Primitive slot edits also retain their committed value. */
19717
+ var log = [];
19718
+ function note(path, state) {
19719
+ const at = ++version;
19720
+ const key = JSON.stringify(path);
19721
+ tracked.delete(key);
19722
+ tracked.set(key, path);
19723
+ if (tracked.size > MAX_LOG) tracked.delete(tracked.keys().next().value);
19724
+ let node = state;
19725
+ for (const segment of path) {
19726
+ node = node !== null && typeof node === "object" ? getByPath(node, [segment]) : void 0;
19727
+ if (node !== null && typeof node === "object") through.set(node, at);
19728
+ }
19729
+ if (node !== null && typeof node === "object") return;
19730
+ log.push({
19731
+ version: at,
19732
+ path,
19733
+ value: node
19734
+ });
19735
+ if (log.length > MAX_LOG) log.shift();
19736
+ }
19737
+ var activeEdits;
19738
+ function withEdits(edits, run) {
19739
+ const previous = activeEdits;
19740
+ activeEdits = edits;
19741
+ try {
19742
+ run();
19743
+ } finally {
19744
+ activeEdits = previous;
19745
+ }
19746
+ }
19747
+ /** Attribute only the control's own writes, before subscribers can replace them. */
19748
+ function runAsControlEdit(segments, run) {
19749
+ withEdits([["variables", ...segments]], run);
19750
+ }
19751
+ /** Whether mutation code runs inside a {for} iteration. */
19752
+ var ItemEditContext = createContext(false);
19753
+ var NAMESPACES = [
19754
+ "variables",
19755
+ "temporary",
19756
+ "transient"
19757
+ ];
19758
+ /** Run `run`, noting each variable path its own updates change as an edit. */
19759
+ function runAsItemEdit(run) {
19760
+ withEdits("changed", run);
19761
+ }
19762
+ /** Called with finalized state before the store notifies its subscribers. */
19763
+ function notifyItemEdits(before, after, notify) {
19764
+ const compared = /* @__PURE__ */ new WeakMap();
19765
+ for (const path of tracked.values()) {
19766
+ const ns = path[0];
19767
+ if (before[ns] === after[ns]) continue;
19768
+ let previous = before[ns];
19769
+ let next = after[ns];
19770
+ for (const segment of path.slice(1)) {
19771
+ previous = previous !== null && typeof previous === "object" ? getByPath(previous, [segment]) : void 0;
19772
+ next = next !== null && typeof next === "object" ? getByPath(next, [segment]) : void 0;
19773
+ if (previous === null || typeof previous !== "object" || next === null || typeof next !== "object" || previous === next) continue;
19774
+ const edited = through.get(previous);
19775
+ if (edited === void 0) continue;
19776
+ const copies = compared.get(previous) ?? /* @__PURE__ */ new WeakSet();
19777
+ if (copies.has(next)) continue;
19778
+ copies.add(next);
19779
+ compared.set(previous, copies);
19780
+ if (deepEqualStrict(previous, next)) through.set(next, Math.max(through.get(next) ?? 0, edited));
19781
+ }
19782
+ }
19783
+ if (activeEdits === "changed") for (const ns of NAMESPACES) {
19784
+ if (before[ns] === after[ns]) continue;
19785
+ for (const { path } of diffPaths(before[ns], after[ns], true)) note([ns, ...path], after);
19786
+ }
19787
+ else for (const path of activeEdits ?? []) note(path, after);
19788
+ withEdits(void 0, notify);
19789
+ }
19790
+ function controlEditVersion() {
19791
+ return version;
19792
+ }
19793
+ /**
19794
+ * A test of whether an edit made since `since` wrote inside `item`, element
19795
+ * `index` of `list`: the path leads through the item (compared by reference
19796
+ * in `state`), or, for a primitive item, ends at its slot in the list.
19797
+ */
19798
+ function editedItems(since, state) {
19799
+ const ends = /* @__PURE__ */ new Map();
19800
+ for (let i = log.length - 1; i >= 0 && log[i].version > since; i--) {
19801
+ const { path, value } = log[i];
19802
+ const parent = getByPath(state, path.slice(0, -1));
19803
+ const key = path[path.length - 1];
19804
+ if (parent !== null && typeof parent === "object") {
19805
+ const current = getByPath(parent, [key]);
19806
+ if ((current === null || typeof current !== "object") && Object.is(current, value)) {
19807
+ const keys = ends.get(parent) ?? /* @__PURE__ */ new Set();
19808
+ keys.add(key);
19809
+ ends.set(parent, keys);
19810
+ }
19811
+ }
19812
+ }
19813
+ return (list, item, index) => typeof item === "object" && item !== null ? (through.get(item) ?? 0) > since : ends.get(list)?.has(String(index)) === true;
19814
+ }
19690
19815
  // src/passage-roles.ts
19691
19816
  /** Runtime-owned passage roles, shared with stateless authoring tools. */
19692
19817
  var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
@@ -20452,10 +20577,12 @@ function storyStateGuard(creator) {
20452
20577
  Object.assign(draft, updater);
20453
20578
  };
20454
20579
  const routed = routeStoreUpdate(recipe);
20455
- set((draft) => {
20580
+ const before = get();
20581
+ const next = produce(before, (draft) => {
20456
20582
  (routed ?? recipe)(draft);
20457
20583
  keepNamespacesBare(draft);
20458
20584
  });
20585
+ notifyItemEdits(before, next, () => set(next));
20459
20586
  });
20460
20587
  api.setState = guarded;
20461
20588
  const state = creator(guarded, get, api);
@@ -21029,12 +21156,8 @@ var FOCUSABLE = [
21029
21156
  */
21030
21157
  function isAvailable(el) {
21031
21158
  if (!isRendered(el)) return false;
21032
- for (let at = el; at; at = composedParent(at)) {
21033
- if (at.hasAttribute("hidden") || at.hasAttribute("inert")) return false;
21034
- if (at.ownerDocument.defaultView?.getComputedStyle(at).display === "none") return false;
21035
- const parent = composedParent(at);
21036
- if (parent?.localName === "details" && !parent.hasAttribute("open") && at !== Array.from(parent.children).find((child) => child.localName === "summary")) return false;
21037
- }
21159
+ if ((el.ownerDocument.defaultView ?? window).getComputedStyle(el).display === "contents") return false;
21160
+ for (let at = el; at; at = composedParent(at)) if (at.hasAttribute("inert")) return false;
21038
21161
  return !el.matches(":disabled");
21039
21162
  }
21040
21163
  /** The `tabindex` of `el` as an integer, or null when absent or invalid. */
@@ -21915,88 +22038,6 @@ var settings = {
21915
22038
  return definitions.size > 0;
21916
22039
  }
21917
22040
  };
21918
- // src/utils/control-edits.ts
21919
- /**
21920
- * Records the edits made to the items of a list from inside a {for}
21921
- * iteration, which {for} tells apart from a list that is replaced:
21922
- *
21923
- * - a reader editing a variable through a control (`{textbox}`,
21924
- * `{checkbox}`, ...): typing into a control inside an iteration changes
21925
- * its item, but must not remount the iteration and drop the control's
21926
- * focus (#369);
21927
- * - mutation code an iteration runs as it renders (`{set $party[@i].hp +=
21928
- * 1}`): remounting would run the iteration's mount-only macros, and so the
21929
- * write, again for every write it makes (#400).
21930
- *
21931
- * An edit is attributed to the variable path it wrote, so a replacement made
21932
- * elsewhere (a watcher reacting to the edit, a button outside the loop)
21933
- * still remounts.
21934
- */
21935
- var version = 0;
21936
- var MAX_LOG = 4096;
21937
- /** Edits in the order made: paths below the namespaces (`['variables', 'a']`). */
21938
- var log = [];
21939
- function note(path) {
21940
- log.push({
21941
- version: ++version,
21942
- path
21943
- });
21944
- if (log.length > MAX_LOG) log.shift();
21945
- }
21946
- /** Note an edit a control made to the story variable at `segments`. */
21947
- function noteControlEdit(segments) {
21948
- note(["variables", ...segments]);
21949
- }
21950
- /**
21951
- * Whether mutation code runs inside a {for} iteration: {for} provides true
21952
- * around its iterations, and the writes of such code are noted as edits of
21953
- * the items they reach (see runAsItemEdit).
21954
- */
21955
- var ItemEditContext = createContext(false);
21956
- var NAMESPACES = [
21957
- "variables",
21958
- "temporary",
21959
- "transient"
21960
- ];
21961
- /** Run `run`, noting each variable path it changes as an edit. */
21962
- function runAsItemEdit(run) {
21963
- const before = readState();
21964
- try {
21965
- run();
21966
- } finally {
21967
- const after = readState();
21968
- for (const ns of NAMESPACES) {
21969
- if (before[ns] === after[ns]) continue;
21970
- for (const { path } of diffPaths(before[ns], after[ns], true)) note([ns, ...path]);
21971
- }
21972
- }
21973
- }
21974
- function controlEditVersion() {
21975
- return version;
21976
- }
21977
- /**
21978
- * A test of whether an edit made since `since` wrote inside `item`, element
21979
- * `index` of `list`: the path leads through the item (compared by reference
21980
- * in `state`), or, for a primitive item, ends at its slot in the list.
21981
- */
21982
- function editedItems(since, state) {
21983
- const through = /* @__PURE__ */ new Set();
21984
- const ends = /* @__PURE__ */ new Map();
21985
- for (let i = log.length - 1; i >= 0 && log[i].version > since; i--) {
21986
- const { path } = log[i];
21987
- let node = state;
21988
- path.forEach((seg, n) => {
21989
- if (n === path.length - 1 && node !== null && typeof node === "object") {
21990
- const keys = ends.get(node) ?? /* @__PURE__ */ new Set();
21991
- keys.add(seg);
21992
- ends.set(node, keys);
21993
- }
21994
- node = node !== null && typeof node === "object" ? getByPath(node, [seg]) : void 0;
21995
- if (node !== null && typeof node === "object") through.add(node);
21996
- });
21997
- }
21998
- return (list, item, index) => typeof item === "object" && item !== null ? through.has(item) : ends.get(list)?.has(String(index)) === true;
21999
- }
22000
22041
  // src/utils/extract-text.ts
22001
22042
  /**
22002
22043
  * Collect plain text from AST nodes, ignoring non-text nodes.
@@ -22098,9 +22139,10 @@ function defineMacro(config, source = "builtin") {
22098
22139
  ctx.value = getByPath(useStoryFields("variables").variables, segments);
22099
22140
  ctx.getValue = () => getByPath(readState().variables, segments);
22100
22141
  ctx.setValue = displayOnly ? refuse : (value) => {
22101
- noteControlEdit(segments);
22102
- mutateState((work, adopt) => {
22103
- setByPath(work.variables, segments, adopt(value), { createMissing: true });
22142
+ runAsControlEdit(segments, () => {
22143
+ mutateState((work, adopt) => {
22144
+ setByPath(work.variables, segments, adopt(value), { createMissing: true });
22145
+ });
22104
22146
  });
22105
22147
  };
22106
22148
  }
@@ -22767,10 +22809,13 @@ function warnIfUndeclared(isTransient, key) {
22767
22809
  warnedUndeclared.add(label);
22768
22810
  console.warn(`spindle: Story.set() wrote ${label}, which is not declared in ${isTransient ? "StoryTransients" : "StoryVariables"}. Passages cannot reference it; check the name or declare it.`);
22769
22811
  }
22770
- /** Set a single variable on an Immer draft, resolving dot-paths if present. */
22771
- function setOne(draft, name, value) {
22772
- const { isTransient, key } = parseName(name);
22773
- setByPath(isTransient ? draft.transient : draft.variables, key.split("."), value);
22812
+ /** Adopt the whole batch before writes can replace state-owned inputs. */
22813
+ function setEntries(draft, entries, adopt) {
22814
+ const adopted = entries.map(([name, value]) => [name, adopt(value)]);
22815
+ for (const [name, value] of adopted) {
22816
+ const { isTransient, key } = parseName(name);
22817
+ setByPath(isTransient ? draft.transient : draft.variables, key.split("."), value);
22818
+ }
22774
22819
  }
22775
22820
  /**
22776
22821
  * The history index `index` names (the current moment's when left out), or
@@ -22808,12 +22853,13 @@ function createStoryAPI() {
22808
22853
  }
22809
22854
  if (entries.some(([k]) => k.includes("."))) {
22810
22855
  mutateState((work, adopt) => {
22811
- for (const [k, v] of entries) setOne(work, k, adopt(v));
22856
+ setEntries(work, entries, adopt);
22812
22857
  });
22813
22858
  return;
22814
22859
  }
22815
22860
  useStoryStore.getState().updateVariables((draft) => {
22816
- for (const [k, v] of entries) setOne(draft, k, v);
22861
+ const adopt = adoptStateValues(draft);
22862
+ setEntries(draft, entries, adopt);
22817
22863
  });
22818
22864
  },
22819
22865
  goto: storeAction("navigate"),
@@ -26139,7 +26185,7 @@ defineMacro({
26139
26185
  const [open, setOpen] = ctx.hooks.useState(false);
26140
26186
  const { noclose } = ctx.args;
26141
26187
  const label = ctx.resolve(ctx.args.label ?? "") ?? "";
26142
- const passageName = ctx.collectText(children).trim().replace(/^["']|["']$/g, "");
26188
+ const passageName = readPassageBody(ctx.collectText(children));
26143
26189
  const openDialog = () => setOpen(true);
26144
26190
  const action = useControlAction({
26145
26191
  type: "open-dialog",
@@ -10975,6 +10975,11 @@ function readWholeQuoted(src) {
10975
10975
  const quoted = readQuoted(src, 0);
10976
10976
  return quoted && quoted.end === src.length ? quoted.value : null;
10977
10977
  }
10978
+ /** A dialog body's passage name, optionally enclosed in matching quotes. */
10979
+ function readPassageBody(src) {
10980
+ const name = src.trim();
10981
+ return readWholeQuoted(name) ?? name;
10982
+ }
10978
10983
  /**
10979
10984
  * Strip an optional quote from each end of an unquoted-or-loosely-quoted
10980
10985
  * argument (`"Red`, `Red'`), leaving at least one character. This is the
@@ -11760,7 +11765,7 @@ function* codeAndText(src, tokens, parametersOf) {
11760
11765
  const written = text.trim();
11761
11766
  yield {
11762
11767
  kind: "passage",
11763
- name: written.replace(/^["']|["']$/g, ""),
11768
+ name: readPassageBody(written),
11764
11769
  offset: token.end + text.indexOf(written),
11765
11770
  length: written.length,
11766
11771
  macro: name,
@@ -13650,17 +13655,28 @@ function checkVariableReferences(passages, declared, options) {
13650
13655
  return diagnostics;
13651
13656
  }
13652
13657
  // src/js-bindings.ts
13653
- /**
13654
- * Which declaration a variable names where it is used in JavaScript, read
13655
- * from the text without running it (see discoverMacros): the scope the use is
13656
- * in, the declarations of the name that scope can see, and the innermost one.
13657
- *
13658
- * It reads the shape of the code (brackets, and the words before and after a
13659
- * name) in text whose strings, comments and regexes are blanked, so it needs
13660
- * no syntax tree and goes on through code that is not complete. What it
13661
- * cannot place, it counts as a declaration of unknown value: a parameter, a
13662
- * pattern, an assignment. Better no answer than another declaration's.
13663
- */
13658
+ /** Search arbitrary (also recovered, overlapping) bracket intervals. */
13659
+ var GroupIndex = class {
13660
+ constructor(groups) {
13661
+ this.groups = groups;
13662
+ let size = 1;
13663
+ while (size < groups.length) size *= 2;
13664
+ this.size = size;
13665
+ this.ends = new Array(size * 2).fill(-1);
13666
+ for (let i = 0; i < groups.length; i++) this.ends[size + i] = groups[i].close;
13667
+ for (let i = size - 1; i > 0; i--) this.ends[i] = Math.max(this.ends[i * 2], this.ends[i * 2 + 1]);
13668
+ }
13669
+ /** Latest opener before `at` whose closer follows it, in logarithmic time. */
13670
+ containing(at) {
13671
+ const find = (node, start, end) => {
13672
+ if (start >= this.groups.length || this.groups[start].open >= at || this.ends[node] <= at) return void 0;
13673
+ if (end - start === 1) return this.groups[start];
13674
+ const mid = start + end >>> 1;
13675
+ return find(node * 2 + 1, mid, end) ?? find(node * 2, start, mid);
13676
+ };
13677
+ return find(1, 0, this.size);
13678
+ }
13679
+ };
13664
13680
  var CLOSERS = {
13665
13681
  "}": "{",
13666
13682
  ")": "(",
@@ -13713,7 +13729,9 @@ var isWordChar = (c) => !!c && /[\w$]/.test(c);
13713
13729
  var Bindings = class {
13714
13730
  constructor(code) {
13715
13731
  this.code = code;
13732
+ this.identifiers = /* @__PURE__ */ new Map();
13716
13733
  this.groups = [];
13734
+ this.groupIndexes = /* @__PURE__ */ new Map();
13717
13735
  this.byOpen = /* @__PURE__ */ new Map();
13718
13736
  this.byClose = /* @__PURE__ */ new Map();
13719
13737
  this.functions = /* @__PURE__ */ new Map();
@@ -13724,6 +13742,17 @@ var Bindings = class {
13724
13742
  end: Infinity
13725
13743
  };
13726
13744
  this.readGroups();
13745
+ for (const kind of [
13746
+ void 0,
13747
+ "{",
13748
+ "(",
13749
+ "["
13750
+ ]) this.groupIndexes.set(kind, new GroupIndex(kind === void 0 ? this.groups : this.groups.filter((g) => g.kind === kind)));
13751
+ for (const match of code.matchAll(/[\w$]+/g)) {
13752
+ const positions = this.identifiers.get(match[0]) ?? [];
13753
+ positions.push(match.index);
13754
+ this.identifiers.set(match[0], positions);
13755
+ }
13727
13756
  }
13728
13757
  /**
13729
13758
  * The `{` of the object literal that `name`, used at `at`, is declared as
@@ -13746,11 +13775,9 @@ var Bindings = class {
13746
13775
  }
13747
13776
  /** Declaration and write facts are immutable for this source and property set. */
13748
13777
  readBindings(name, properties) {
13749
- const { code } = this;
13750
- const escaped = escapeRegExp(name);
13751
13778
  const bindings = [];
13752
- for (const m of code.matchAll(new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, "g"))) {
13753
- const binding = this.bindingAt(m.index, name.length, properties);
13779
+ for (const at of this.identifiers.get(name) ?? []) {
13780
+ const binding = this.bindingAt(at, name.length, properties);
13754
13781
  if (binding) bindings.push(binding);
13755
13782
  }
13756
13783
  const declarations = bindings.filter((b) => !b.write);
@@ -13802,11 +13829,7 @@ var Bindings = class {
13802
13829
  }
13803
13830
  /** The innermost group that has `index` inside it, of this kind if given. */
13804
13831
  innermost(index, kind) {
13805
- const { groups } = this;
13806
- for (let k = groups.length - 1; k >= 0; k--) {
13807
- const g = groups[k];
13808
- if (g.open < index && index < g.close && (!kind || g.kind === kind)) return g;
13809
- }
13832
+ return this.groupIndexes.get(kind).containing(index);
13810
13833
  }
13811
13834
  /**
13812
13835
  * The word before a `(` group (`if`, `for`, `catch`, a function's name…);
@@ -14136,7 +14159,12 @@ var Bindings = class {
14136
14159
  /** `Object.assign(x, …)` and the like: the name is the first argument. */
14137
14160
  isMutatedArgument(before, end) {
14138
14161
  const group = this.byOpen.get(before);
14139
- return group?.kind === "(" && ",)".includes(this.code.charAt(end)) && MUTATING_CALL_RE.test(this.code.slice(0, group.open));
14162
+ if (group?.kind !== "(" || !",)".includes(this.code.charAt(end))) return false;
14163
+ const method = this.wordBefore(this.backFrom(group.open) + 1);
14164
+ const dot = this.backFrom(method.start);
14165
+ if (this.code.charAt(dot) !== ".") return false;
14166
+ const owner = this.wordBefore(this.backFrom(dot) + 1);
14167
+ return MUTATING_CALL_RE.test(this.code.slice(owner.start, group.open));
14140
14168
  }
14141
14169
  };
14142
14170
  // src/macro-discovery.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.28",
3
+ "version": "0.64.30",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,7 +1,7 @@
1
1
  // Class registry for preserving class instances across clone/save/load cycles.
2
2
 
3
3
  import { parse, stringify } from 'devalue';
4
- import { hasOwn } from './utils/namespace';
4
+ import { defineData, hasOwn } from './utils/namespace';
5
5
  import {
6
6
  arrayIndices,
7
7
  extraKeys,
@@ -155,16 +155,6 @@ const isPlainData = (v: unknown): v is Record<string, unknown> =>
155
155
  const malformedClass = (name: string): TypeError =>
156
156
  new TypeError(`spindle: Malformed data for class "${name}"`);
157
157
 
158
- const defineData = (target: object, key: string, value: unknown): void => {
159
- // Define, so that a "__proto__" key stays a key (devalue refuses it)
160
- Object.defineProperty(target, key, {
161
- value,
162
- enumerable: true,
163
- writable: true,
164
- configurable: true,
165
- });
166
- };
167
-
168
158
  /**
169
159
  * A reducer extracts string keys, so devalue never sees the symbol keys of
170
160
  * the original object: refuse them here, as it does for a plain object.
package/src/code-check.ts CHANGED
@@ -55,7 +55,7 @@ import {
55
55
  type PassageTarget,
56
56
  } from './components/macros/macro-args';
57
57
  import { subMacroParameters } from './components/macros/option-utils';
58
- import { splitArgSpans } from './components/macros/arg-utils';
58
+ import { readPassageBody, splitArgSpans } from './components/macros/arg-utils';
59
59
  import { effectiveNamedDefinitions, NameMap } from './utils/macro-names';
60
60
  import { hasOwn } from './utils/namespace';
61
61
  import { isBuiltinBlockMacro, isRawMacro } from './markup/ast';
@@ -532,7 +532,7 @@ export function* codeAndText(
532
532
  const written = text.trim();
533
533
  yield {
534
534
  kind: 'passage',
535
- name: written.replace(/^["']|["']$/g, ''),
535
+ name: readPassageBody(written),
536
536
  offset: token.end + text.indexOf(written),
537
537
  length: written.length,
538
538
  macro: name,
@@ -1,6 +1,7 @@
1
1
  import { renderActionButton, useControlAction } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { PassageDialog } from '../PassageDialog';
4
+ import { readPassageBody } from './arg-utils';
4
5
 
5
6
  defineMacro({
6
7
  name: 'dialog',
@@ -15,10 +16,7 @@ defineMacro({
15
16
 
16
17
  const { noclose } = ctx.args;
17
18
  const label = ctx.resolve!(ctx.args.label ?? '') ?? '';
18
- const passageName = ctx
19
- .collectText(children)
20
- .trim()
21
- .replace(/^["']|["']$/g, '');
19
+ const passageName = readPassageBody(ctx.collectText(children));
22
20
  const openDialog = () => setOpen(true);
23
21
 
24
22
  // Its own type: the menubar's Saves and Settings are `dialog` (#540)
@@ -74,6 +74,12 @@ export function readWholeQuoted(src: string): string | null {
74
74
  return quoted && quoted.end === src.length ? quoted.value : null;
75
75
  }
76
76
 
77
+ /** A dialog body's passage name, optionally enclosed in matching quotes. */
78
+ export function readPassageBody(src: string): string {
79
+ const name = src.trim();
80
+ return readWholeQuoted(name) ?? name;
81
+ }
82
+
77
83
  /**
78
84
  * Strip an optional quote from each end of an unquoted-or-loosely-quoted
79
85
  * argument (`"Red`, `Red'`), leaving at least one character. This is the