@rohal12/spindle 0.61.5 → 0.61.7

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.
@@ -11752,8 +11752,14 @@ function stringHolds(param) {
11752
11752
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11753
11753
  */
11754
11754
  function* codeAndText(src, tokens, parametersOf) {
11755
- /** The index of the closing tag of the `name` macro opened at `t`. */
11756
- const closeOf = (t, name) => tokens.findIndex((c, k) => k > t && c.type === "macro" && c.isClose && c.name.toLowerCase() === name);
11755
+ const closeOfTextBody = (t, name) => {
11756
+ for (let k = t + 1; k < tokens.length; k++) {
11757
+ const c = tokens[k];
11758
+ if (c.type === "text") continue;
11759
+ return c.type === "macro" && c.isClose && c.name.toLowerCase() === name ? k : -1;
11760
+ }
11761
+ return -1;
11762
+ };
11757
11763
  for (let t = 0; t < tokens.length; t++) {
11758
11764
  const token = tokens[t];
11759
11765
  if (token.type === "link") {
@@ -11789,7 +11795,7 @@ function* codeAndText(src, tokens, parametersOf) {
11789
11795
  else if (token.type === "macro" && !token.isClose) {
11790
11796
  const name = token.name.toLowerCase();
11791
11797
  if (name === "do") {
11792
- const close = closeOf(t, name);
11798
+ const close = closeOfTextBody(t, name);
11793
11799
  if (close < 0) continue;
11794
11800
  yield {
11795
11801
  kind: "code",
@@ -11803,9 +11809,8 @@ function* codeAndText(src, tokens, parametersOf) {
11803
11809
  }
11804
11810
  const args = token.rawArgs;
11805
11811
  if (PASSAGE_BODIES.has(name)) {
11806
- const close = closeOf(t, name);
11807
- const body = tokens.slice(t + 1, close);
11808
- if (close > t + 1 && body.every((b) => b.type === "text")) {
11812
+ const close = closeOfTextBody(t, name);
11813
+ if (close > t + 1) {
11809
11814
  const text = src.slice(token.end, tokens[close].start);
11810
11815
  const written = text.trim();
11811
11816
  yield {
@@ -12389,6 +12394,12 @@ function registerWidgetDefinitions(nodes, passageName) {
12389
12394
  */
12390
12395
  var FrozenStateContext = createContext(null);
12391
12396
  /**
12397
+ * Whether a loop has yet to reconcile its rows with newer namespaces.
12398
+ * Queued row effects wait for that reconciliation. This differs from a
12399
+ * detached click body's permanent freeze: its initial effects still run.
12400
+ */
12401
+ var PendingIterationContext = createContext(null);
12402
+ /**
12392
12403
  * Tells a timer ({repeat}, {timed}) whether the passage it belongs to has
12393
12404
  * been left: it must not run a new body then, for that would write into the
12394
12405
  * destination's state until the outgoing tree unmounts (#410). Null outside
@@ -15687,7 +15698,9 @@ function shallowCopy(value) {
15687
15698
  */
15688
15699
  function setByPath(root, segments, value, options = {}) {
15689
15700
  const parent = walkToParent(root, segments, options.createMissing ?? false);
15690
- parent[segments[segments.length - 1]] = value;
15701
+ const key = segments[segments.length - 1];
15702
+ if (value === 0 && isDraft(parent) && parent[key] === 0 && !Object.is(parent[key], value) && !(Array.isArray(parent) && key === "length")) parent[key] = void 0;
15703
+ parent[key] = value;
15691
15704
  }
15692
15705
  /**
15693
15706
  * Delete the property at dot-path `segments` below `root`, copying
@@ -19221,14 +19234,24 @@ function applyReplacement(n) {
19221
19234
  * stop (#401).
19222
19235
  */
19223
19236
  var subscribeStateReplacement = replacementListeners.subscribe;
19224
- var runtimeUnsubs = [];
19237
+ var runtimeUnsubs = /* @__PURE__ */ new Set();
19225
19238
  var inRuntimePhase = false;
19226
19239
  /**
19227
19240
  * Track an unsubscribe function for automatic cleanup on restart.
19228
- * No-op if called during the startup phase (before enterRuntimePhase).
19241
+ * Return its manual cleanup, which also releases the tracked entry.
19242
+ * Startup subscriptions (before enterRuntimePhase) survive restart.
19229
19243
  */
19230
19244
  function trackRuntimeUnsub(unsub) {
19231
- if (inRuntimePhase) runtimeUnsubs.push(unsub);
19245
+ if (!inRuntimePhase) return unsub;
19246
+ let cleanup = unsub;
19247
+ const tracked = () => {
19248
+ const call = cleanup;
19249
+ cleanup = void 0;
19250
+ runtimeUnsubs.delete(tracked);
19251
+ call?.();
19252
+ };
19253
+ runtimeUnsubs.add(tracked);
19254
+ return tracked;
19232
19255
  }
19233
19256
  /** Mark the start of the runtime phase. Called before executeStoryInit(). */
19234
19257
  function enterRuntimePhase() {
@@ -19237,7 +19260,7 @@ function enterRuntimePhase() {
19237
19260
  /** Call all tracked unsubs and reset the runtime phase. */
19238
19261
  function cleanupRuntimeHandlers() {
19239
19262
  for (const unsub of runtimeUnsubs) unsub();
19240
- runtimeUnsubs = [];
19263
+ runtimeUnsubs.clear();
19241
19264
  inRuntimePhase = false;
19242
19265
  }
19243
19266
  /** A hotkey is a `KeyboardEvent.key` value; anything else disables it. */
@@ -19590,7 +19613,8 @@ var useStoryStore = create()(storyStore((set, get) => ({
19590
19613
  return;
19591
19614
  }
19592
19615
  const previousPassage = get().currentPassage;
19593
- if (replacesState(() => emit("beforenavigate", passageName))) return;
19616
+ const navigation = get().navigationId;
19617
+ if (replacesState(() => emit("beforenavigate", passageName)) || get().navigationId !== navigation) return;
19594
19618
  const patchEntry = computeVarPatches(lastNavigationVars, get().variables);
19595
19619
  set((state) => {
19596
19620
  state.temporary = createNamespace();
@@ -21591,9 +21615,7 @@ function createStoryAPI() {
21591
21615
  },
21592
21616
  on(event, callback) {
21593
21617
  if (event === "variableChanged") ensureVariableChangedSubscription();
21594
- const unsub = on(event, callback);
21595
- trackRuntimeUnsub(unsub);
21596
- return unsub;
21618
+ return trackRuntimeUnsub(on(event, callback));
21597
21619
  },
21598
21620
  async waitForActions() {
21599
21621
  await settleRunningActions();
@@ -23068,6 +23090,7 @@ function copyLiveState(source, clone) {
23068
23090
  const input = to;
23069
23091
  input.checked = from.checked;
23070
23092
  input.indeterminate = from.indeterminate;
23093
+ if (from.type === "file") input.files = from.files;
23071
23094
  if (!VALUELESS_INPUTS.has(from.type)) input.value = from.value;
23072
23095
  } else to.value = from.value;
23073
23096
  });
@@ -23095,8 +23118,8 @@ function copyLiveState(source, clone) {
23095
23118
  * is in the page: a detached element has nothing to scroll.
23096
23119
  */
23097
23120
  function scrollOffsets(source, clone) {
23098
- const from = [source, ...source.querySelectorAll("*")];
23099
- const to = [clone, ...clone.querySelectorAll("*")];
23121
+ const from = [...source instanceof Element ? [source] : [], ...source.querySelectorAll("*")];
23122
+ const to = [...clone instanceof Element ? [clone] : [], ...clone.querySelectorAll("*")];
23100
23123
  const offsets = [];
23101
23124
  from.forEach((el, i) => {
23102
23125
  if (to[i] && (el.scrollTop || el.scrollLeft)) offsets.push([
@@ -23104,10 +23127,12 @@ function scrollOffsets(source, clone) {
23104
23127
  el.scrollTop,
23105
23128
  el.scrollLeft
23106
23129
  ]);
23130
+ if (el.shadowRoot && to[i]?.shadowRoot) offsets.push(...scrollOffsets(el.shadowRoot, to[i].shadowRoot));
23107
23131
  });
23108
23132
  return offsets;
23109
23133
  }
23110
23134
  var pendingScrolls = /* @__PURE__ */ new WeakMap();
23135
+ var snapshotStyleCleanup = /* @__PURE__ */ new WeakMap();
23111
23136
  /** Add `snapshot` to `container`, scrolled as what it shows was. */
23112
23137
  function appendSnapshot(container, snapshot) {
23113
23138
  container.appendChild(snapshot);
@@ -23117,6 +23142,97 @@ function appendSnapshot(container, snapshot) {
23117
23142
  }
23118
23143
  pendingScrolls.delete(snapshot);
23119
23144
  }
23145
+ function copyComputedStyle(style, target) {
23146
+ for (let i = 0; i < style.length; i++) {
23147
+ const name = style[i];
23148
+ target.setProperty(name, style.getPropertyValue(name));
23149
+ }
23150
+ }
23151
+ function installSnapshotStyles(root, rules) {
23152
+ if (!rules.length) return;
23153
+ const sheet = new CSSStyleSheet();
23154
+ sheet.replaceSync(rules.join("\n"));
23155
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
23156
+ return () => {
23157
+ root.adoptedStyleSheets = root.adoptedStyleSheets.filter((current) => current !== sheet);
23158
+ };
23159
+ }
23160
+ var snapshotPseudoId = 0;
23161
+ /**
23162
+ * Build a visual tree without cloning upgraded custom elements: cloneNode
23163
+ * runs their constructors, and insertion runs their connection callbacks.
23164
+ * Autonomous elements become styled spans; customized built-ins are created
23165
+ * as ordinary native elements, without an `is` option (even if the original
23166
+ * has since removed its `is` attribute).
23167
+ */
23168
+ function cloneSnapshotTree(source, freezeStyles = false, pseudoRules = []) {
23169
+ const custom = source.namespaceURI === "http://www.w3.org/1999/xhtml" && source.localName.includes("-");
23170
+ freezeStyles ||= custom || source.hasAttribute("is");
23171
+ const clone = document.createElementNS(source.namespaceURI, custom ? "span" : source.localName);
23172
+ for (const attr of [...source.attributes]) {
23173
+ if (attr.name === "id" || attr.name === "data-action" || attr.name === "is" || attr.name.toLowerCase().startsWith("on")) continue;
23174
+ if (attr.namespaceURI) clone.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
23175
+ else clone.setAttribute(attr.name, attr.value);
23176
+ }
23177
+ if (freezeStyles) {
23178
+ copyComputedStyle(getComputedStyle(source), clone.style);
23179
+ let id;
23180
+ for (const pseudo of [
23181
+ "::before",
23182
+ "::after",
23183
+ "::marker"
23184
+ ]) {
23185
+ const style = getComputedStyle(source, pseudo);
23186
+ if (!style.content || ["none", "normal"].includes(style.content)) continue;
23187
+ id ??= String(++snapshotPseudoId);
23188
+ clone.setAttribute("data-spindle-snapshot-pseudo", id);
23189
+ const target = document.createElement("span").style;
23190
+ copyComputedStyle(style, target);
23191
+ pseudoRules.push(`[data-spindle-snapshot-pseudo="${id}"]${pseudo}{${target.cssText}}`);
23192
+ }
23193
+ }
23194
+ if (source.localName === "script") clone.setAttribute("type", "application/x-spindle-snapshot");
23195
+ const from = source instanceof HTMLTemplateElement ? source.content : source;
23196
+ const to = clone instanceof HTMLTemplateElement ? clone.content : clone;
23197
+ const copyChildren = (from, to, rules = pseudoRules) => {
23198
+ for (const node of from.childNodes) to.appendChild(node instanceof Element ? cloneSnapshotTree(node, freezeStyles, rules) : node.cloneNode(false));
23199
+ };
23200
+ copyChildren(from, to);
23201
+ if (source.shadowRoot) {
23202
+ const shadow = clone.attachShadow({ mode: "open" });
23203
+ const rules = [];
23204
+ copyChildren(source.shadowRoot, shadow, rules);
23205
+ copyLiveState(source.shadowRoot, shadow);
23206
+ installSnapshotStyles(shadow, rules);
23207
+ }
23208
+ return clone;
23209
+ }
23210
+ /** Replace browsing contexts throughout the snapshot, including shadow trees. */
23211
+ function replaceEmbeddedContexts(source, clone) {
23212
+ const originals = source.querySelectorAll("*");
23213
+ clone.querySelectorAll("*").forEach((embedded, i) => {
23214
+ const original = originals[i];
23215
+ if (!original) return;
23216
+ if (original.shadowRoot && embedded.shadowRoot) replaceEmbeddedContexts(original.shadowRoot, embedded.shadowRoot);
23217
+ if (!embedded.matches("iframe, object, embed")) return;
23218
+ const placeholder = document.createElement("div");
23219
+ for (const name of [
23220
+ "class",
23221
+ "style",
23222
+ "width",
23223
+ "height"
23224
+ ]) {
23225
+ const value = embedded.getAttribute(name);
23226
+ if (value !== null) placeholder.setAttribute(name, value);
23227
+ }
23228
+ const rect = original.getBoundingClientRect();
23229
+ if (getComputedStyle(original).display === "inline") placeholder.style.display = "inline-block";
23230
+ placeholder.style.boxSizing = "border-box";
23231
+ placeholder.style.width = `${rect.width}px`;
23232
+ placeholder.style.height = `${rect.height}px`;
23233
+ embedded.replaceWith(placeholder);
23234
+ });
23235
+ }
23120
23236
  /**
23121
23237
  * Create a snapshot clone of a .passage element for outgoing transitions.
23122
23238
  * - Strips IDs, action associations and event handlers from the clone tree
@@ -23128,30 +23244,13 @@ function appendSnapshot(container, snapshot) {
23128
23244
  * - Adds `.passage-snapshot` class and `data-transition` attribute
23129
23245
  */
23130
23246
  function createSnapshot(passageEl, transitionType) {
23131
- const clone = passageEl.cloneNode(true);
23132
- for (const el of [clone, ...clone.querySelectorAll("*")]) for (const attr of [...el.attributes]) if (attr.name === "id" || attr.name === "data-action" || attr.name.toLowerCase().startsWith("on")) el.removeAttribute(attr.name);
23247
+ const pseudoRules = [];
23248
+ const clone = cloneSnapshotTree(passageEl, false, pseudoRules);
23133
23249
  copyLiveState(passageEl, clone);
23134
23250
  pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
23135
- const originals = passageEl.querySelectorAll("iframe, object, embed");
23136
- clone.querySelectorAll("iframe, object, embed").forEach((embedded, i) => {
23137
- const placeholder = document.createElement("div");
23138
- for (const name of [
23139
- "class",
23140
- "style",
23141
- "width",
23142
- "height"
23143
- ]) {
23144
- const value = embedded.getAttribute(name);
23145
- if (value !== null) placeholder.setAttribute(name, value);
23146
- }
23147
- const original = originals[i];
23148
- if (original) {
23149
- const rect = original.getBoundingClientRect();
23150
- placeholder.style.width = `${rect.width}px`;
23151
- placeholder.style.height = `${rect.height}px`;
23152
- }
23153
- embedded.replaceWith(placeholder);
23154
- });
23251
+ replaceEmbeddedContexts(passageEl, clone);
23252
+ const cleanup = installSnapshotStyles(passageEl.getRootNode(), pseudoRules);
23253
+ if (cleanup) snapshotStyleCleanup.set(clone, cleanup);
23155
23254
  clone.style.pointerEvents = "none";
23156
23255
  clone.style.userSelect = "none";
23157
23256
  clone.setAttribute("inert", "");
@@ -23186,7 +23285,12 @@ function cleanupSnapshots(containerEl) {
23186
23285
  if (!containerEl) return;
23187
23286
  containerEl.classList.remove("passage-container--crossfading");
23188
23287
  const snapshots = containerEl.querySelectorAll(".passage-snapshot");
23189
- for (let i = 0; i < snapshots.length; i++) snapshots[i].remove();
23288
+ for (let i = 0; i < snapshots.length; i++) {
23289
+ const snapshot = snapshots[i];
23290
+ snapshotStyleCleanup.get(snapshot)?.();
23291
+ snapshotStyleCleanup.delete(snapshot);
23292
+ snapshot.remove();
23293
+ }
23190
23294
  }
23191
23295
  /**
23192
23296
  * The navigation each mounted passage display last committed to the page,
@@ -23263,7 +23367,13 @@ defineMacro({
23263
23367
  scrollAfterCleanup.current = false;
23264
23368
  cleanupSnapshots(containerRef.current);
23265
23369
  }, []);
23266
- useEffect(() => cancelTransition, [cancelTransition]);
23370
+ useEffect(() => {
23371
+ const container = containerRef.current;
23372
+ return () => {
23373
+ cancelTransition();
23374
+ cleanupSnapshots(container);
23375
+ };
23376
+ }, [cancelTransition]);
23267
23377
  useEffect(() => {
23268
23378
  const store = useStoryStore.getState();
23269
23379
  const { history, historyIndex, transitionConfig } = store;
@@ -23515,6 +23625,7 @@ defineMacro({
23515
23625
  const isTemp = target.startsWith("_");
23516
23626
  const name = target.slice(1);
23517
23627
  const localsUpdate = isLocal ? ctx.update : null;
23628
+ const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
23518
23629
  const prevOutput = ctx.hooks.useRef(UNSET);
23519
23630
  const lastNavigation = ctx.hooks.useRef(-1);
23520
23631
  const compute = () => computeAndApply(expr, name, isTemp, isLocal, ctx.getValues, rawArgs, prevOutput, lastNavigation, localsUpdate);
@@ -23523,7 +23634,9 @@ defineMacro({
23523
23634
  ran.current = true;
23524
23635
  compute();
23525
23636
  }
23526
- ctx.hooks.useLayoutEffect(compute, [ctx.merged]);
23637
+ ctx.hooks.useLayoutEffect(() => {
23638
+ if (!pendingIteration?.(useStoryStore.getState())) compute();
23639
+ }, [ctx.merged, pendingIteration]);
23527
23640
  return null;
23528
23641
  }
23529
23642
  });
@@ -23705,6 +23818,17 @@ defineMacro({
23705
23818
  }
23706
23819
  ],
23707
23820
  render({ rawArgs, children = [] }, ctx) {
23821
+ const enclosingFreeze = useContext(FrozenStateContext);
23822
+ const enclosingPending = useContext(PendingIterationContext);
23823
+ const [variables, temporary, , transient] = ctx.merged;
23824
+ const pending = useMemo(() => (state) => !!enclosingPending?.(state) || (state.variables !== variables || state.temporary !== temporary || state.transient !== transient) && !enclosingFreeze?.(state), [
23825
+ enclosingPending,
23826
+ enclosingFreeze,
23827
+ variables,
23828
+ temporary,
23829
+ transient
23830
+ ]);
23831
+ const freeze = useMemo(() => (state) => !!enclosingFreeze?.(state) || pending(state), [enclosingFreeze, pending]);
23708
23832
  const keys = ctx.hooks.useRef({
23709
23833
  contents: [],
23710
23834
  generations: [],
@@ -23744,9 +23868,15 @@ defineMacro({
23744
23868
  indexValue: i,
23745
23869
  children
23746
23870
  }, `${i}-${generations[i]}`));
23747
- return ctx.wrap(/* @__PURE__ */ jsx(ItemEditContext.Provider, {
23748
- value: true,
23749
- children: content
23871
+ return ctx.wrap(/* @__PURE__ */ jsx(FrozenStateContext.Provider, {
23872
+ value: freeze,
23873
+ children: /* @__PURE__ */ jsx(PendingIterationContext.Provider, {
23874
+ value: pending,
23875
+ children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
23876
+ value: true,
23877
+ children: content
23878
+ })
23879
+ })
23750
23880
  }));
23751
23881
  },
23752
23882
  text({ rawArgs, children = [] }, ctx) {
@@ -25335,8 +25465,8 @@ function storeVarMacroNames() {
25335
25465
  * the input macros that bind a variable (registered by author JS or
25336
25466
  * StoryInit) and the roles of their parameters decide what is a reference.
25337
25467
  */
25338
- function variableErrors(storyData, schema) {
25339
- return validatePassages(storyData.passages, schema, storeVarMacroNames(), knownParameters());
25468
+ function variableErrors(storyData, schema, only = () => true) {
25469
+ return validatePassages(new Map([...storyData.passages].filter(([, passage]) => only(passage))), schema, storeVarMacroNames(), knownParameters());
25340
25470
  }
25341
25471
  /**
25342
25472
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -25387,7 +25517,7 @@ function boot() {
25387
25517
  }
25388
25518
  const schema = orStop(() => parseStoryVariables(storyVarsPassage.content));
25389
25519
  for (const { name, block } of orStop(() => effectiveWidgets(storyData.passages.values()))) setBlockWidget(name, block);
25390
- const errors = variableErrors(storyData, schema);
25520
+ const errors = variableErrors(storyData, schema, (p) => p.name === "StoryInit");
25391
25521
  errors.push(...markupErrors(storyData, (p) => p.name === "StoryInit"));
25392
25522
  let transientDefaults = {};
25393
25523
  const storyTransientsPassage = storyData.passages.get("StoryTransients");
@@ -11073,8 +11073,14 @@ function stringHolds(param) {
11073
11073
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11074
11074
  */
11075
11075
  function* codeAndText(src, tokens, parametersOf) {
11076
- /** The index of the closing tag of the `name` macro opened at `t`. */
11077
- const closeOf = (t, name) => tokens.findIndex((c, k) => k > t && c.type === "macro" && c.isClose && c.name.toLowerCase() === name);
11076
+ const closeOfTextBody = (t, name) => {
11077
+ for (let k = t + 1; k < tokens.length; k++) {
11078
+ const c = tokens[k];
11079
+ if (c.type === "text") continue;
11080
+ return c.type === "macro" && c.isClose && c.name.toLowerCase() === name ? k : -1;
11081
+ }
11082
+ return -1;
11083
+ };
11078
11084
  for (let t = 0; t < tokens.length; t++) {
11079
11085
  const token = tokens[t];
11080
11086
  if (token.type === "link") {
@@ -11110,7 +11116,7 @@ function* codeAndText(src, tokens, parametersOf) {
11110
11116
  else if (token.type === "macro" && !token.isClose) {
11111
11117
  const name = token.name.toLowerCase();
11112
11118
  if (name === "do") {
11113
- const close = closeOf(t, name);
11119
+ const close = closeOfTextBody(t, name);
11114
11120
  if (close < 0) continue;
11115
11121
  yield {
11116
11122
  kind: "code",
@@ -11124,9 +11130,8 @@ function* codeAndText(src, tokens, parametersOf) {
11124
11130
  }
11125
11131
  const args = token.rawArgs;
11126
11132
  if (PASSAGE_BODIES.has(name)) {
11127
- const close = closeOf(t, name);
11128
- const body = tokens.slice(t + 1, close);
11129
- if (close > t + 1 && body.every((b) => b.type === "text")) {
11133
+ const close = closeOfTextBody(t, name);
11134
+ if (close > t + 1) {
11130
11135
  const text = src.slice(token.end, tokens[close].start);
11131
11136
  const written = text.trim();
11132
11137
  yield {
@@ -24560,10 +24565,6 @@ function multilineJsLiterals(code) {
24560
24565
  } }, "statements");
24561
24566
  return spans;
24562
24567
  }
24563
- /** Whether an HTML tag (opening, closing or self-closing) overlaps the range. */
24564
- function lineHasTag(tags, start, end) {
24565
- return tags.some((tag) => tag.start < end && tag.end > start);
24566
- }
24567
24568
  /**
24568
24569
  * Replace `<svg>…</svg>` blocks with HTML comment placeholders so Prettier
24569
24570
  * does not reformat them (CommonMark does not recognise multi-line SVG tags
@@ -24582,6 +24583,7 @@ function replaceSvgBlocks(html) {
24582
24583
  }
24583
24584
  var SVG_PLACEHOLDERS = (i) => [`<!--SVG:${i}-->`];
24584
24585
  var SPINDLE_PLACEHOLDERS = (i) => [`<!--SP:${i}-->`, `__SP${i}__`];
24586
+ var PLACEHOLDER_PATTERN = /<!--(?:SP|SVG):\d+-->|__SP\d+__/g;
24585
24587
  /**
24586
24588
  * Whether `text` (what a formatter made of the placeholdered text) holds
24587
24589
  * the placeholder of every one of `tokens` exactly once. If not, the
@@ -24589,7 +24591,17 @@ var SPINDLE_PLACEHOLDERS = (i) => [`<!--SP:${i}-->`, `__SP${i}__`];
24589
24591
  * lose or duplicate story text.
24590
24592
  */
24591
24593
  function placeholdersIntact(text, tokens, placeholdersOf) {
24592
- return tokens.every((_, index) => placeholdersOf(index).reduce((count, placeholder) => count + text.split(placeholder).length - 1, 0) === 1);
24594
+ if (tokens.length === 0) return true;
24595
+ const indices = /* @__PURE__ */ new Map();
24596
+ const counts = new Array(tokens.length).fill(0);
24597
+ tokens.forEach((_, index) => {
24598
+ for (const marker of placeholdersOf(index)) indices.set(marker, index);
24599
+ });
24600
+ for (const [marker] of text.matchAll(PLACEHOLDER_PATTERN)) {
24601
+ const index = indices.get(marker);
24602
+ if (index !== void 0 && ++counts[index] > 1) return false;
24603
+ }
24604
+ return counts.every((count) => count === 1);
24593
24605
  }
24594
24606
  /** Whether `before` and `after` hold the same Spindle tokens, in the same order. */
24595
24607
  function sameSpindleTokens(before, after) {
@@ -24599,21 +24611,23 @@ function sameSpindleTokens(before, after) {
24599
24611
  return expected.length === found.length && expected.every((t, i) => t === found[i]);
24600
24612
  }
24601
24613
  /**
24602
- * Put each of `tokens` back in place of its placeholders (those that
24603
- * `placeholdersOf` gives for its index): the first of each.
24614
+ * Restore the first occurrence of each marker in the unchanged document.
24615
+ * Never search inserted source: literals may spell any other marker.
24604
24616
  */
24605
- function restorePlaceholders(text, tokens, placeholdersOf) {
24606
- let result = text;
24607
- tokens.forEach((token, index) => {
24608
- for (const placeholder of placeholdersOf(index)) result = result.replace(placeholder, () => token);
24617
+ function restorePlaceholders(text, groups) {
24618
+ const replacements = /* @__PURE__ */ new Map();
24619
+ for (const [tokens, placeholdersOf] of groups) tokens.forEach((token, index) => {
24620
+ for (const marker of placeholdersOf(index)) replacements.set(marker, token);
24621
+ });
24622
+ return text.replace(PLACEHOLDER_PATTERN, (marker) => {
24623
+ const token = replacements.get(marker);
24624
+ replacements.delete(marker);
24625
+ return token ?? marker;
24609
24626
  });
24610
- return result;
24611
24627
  }
24612
- /**
24613
- * Restore SVG blocks from placeholders.
24614
- */
24615
- function restoreSvgBlocks(text, tokens) {
24616
- return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
24628
+ /** Restore both families together, so neither can consume the other's source. */
24629
+ function restoreHtmlTokens(text, spindle, svg) {
24630
+ return restorePlaceholders(text, [[spindle, SPINDLE_PLACEHOLDERS], [svg, SVG_PLACEHOLDERS]]);
24617
24631
  }
24618
24632
  /**
24619
24633
  * Replace Spindle tokens with placeholders.
@@ -24649,6 +24663,7 @@ function replaceSpindleTokens(html) {
24649
24663
  const tokens = [];
24650
24664
  const resultLines = [];
24651
24665
  let unit = 0;
24666
+ let tag = 0;
24652
24667
  let lineStart = 0;
24653
24668
  while (lineStart <= html.length) {
24654
24669
  let lineEnd = lineStart;
@@ -24668,8 +24683,10 @@ function replaceSpindleTokens(html) {
24668
24683
  }
24669
24684
  const line = html.slice(lineStart, lineEnd);
24670
24685
  const indent = line.match(/^(\s*)/)?.[1] ?? "";
24686
+ while (tag < tags.length && tags[tag].end <= lineStart) tag++;
24687
+ const hasTag = tag < tags.length && tags[tag].start < lineEnd;
24671
24688
  if (lineUnits.length === 0) resultLines.push(line);
24672
- else if (!lineHasTag(tags, lineStart, lineEnd)) {
24689
+ else if (!hasTag) {
24673
24690
  const idx = tokens.length;
24674
24691
  tokens.push(line.trim());
24675
24692
  resultLines.push(`${indent}<!--SP:${idx}-->`);
@@ -24691,12 +24708,6 @@ function replaceSpindleTokens(html) {
24691
24708
  tokens
24692
24709
  };
24693
24710
  }
24694
- /**
24695
- * Restore original Spindle tokens from placeholders.
24696
- */
24697
- function restoreSpindleTokens(text, tokens) {
24698
- return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
24699
- }
24700
24711
  //#endregion
24701
24712
  //#region src/format/format-passage.ts
24702
24713
  /** Default dedenting sub-macros. */
@@ -24858,13 +24869,17 @@ async function formatLf(text, options) {
24858
24869
  continue;
24859
24870
  }
24860
24871
  const { text: svgPlaceholdered, tokens: svgTokens } = replaceSvgBlocks(htmlText);
24872
+ if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
24873
+ lines.push(...region.lines);
24874
+ continue;
24875
+ }
24861
24876
  const { text: placeholdered, tokens } = replaceSpindleTokens(svgPlaceholdered);
24862
24877
  const formatted = await formatHTML(placeholdered, prettier, prettierOptions);
24863
24878
  if (formatted === void 0 || !placeholdersIntact(formatted, tokens, SPINDLE_PLACEHOLDERS) || !placeholdersIntact(formatted, svgTokens, SVG_PLACEHOLDERS)) {
24864
24879
  lines.push(...region.lines);
24865
24880
  continue;
24866
24881
  }
24867
- const restored = restoreSvgBlocks(restoreSpindleTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel))), svgTokens);
24882
+ const restored = restoreHtmlTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel)), svgTokens);
24868
24883
  for (const fLine of restored.split("\n")) lines.push(fLine);
24869
24884
  continue;
24870
24885
  }
@@ -25068,10 +25083,10 @@ var NO_WRAP = /* @__PURE__ */ new Set([
25068
25083
  */
25069
25084
  function wrapLines(lines, maxLen, literalLines, isBlock) {
25070
25085
  const result = [];
25071
- const javaScript = doBodyLines(lines);
25086
+ const verbatim = verbatimLines(lines);
25072
25087
  const structured = markdownLines(lines.join("\n"), isBlock, NO_WRAP);
25073
25088
  for (const [index, line] of lines.entries()) {
25074
- if (line.length <= maxLen || javaScript.has(index) || structured.has(index) || literalLines.has(line.trim())) {
25089
+ if (line.length <= maxLen || verbatim.has(index) || structured.has(index) || literalLines.has(line.trim())) {
25075
25090
  result.push(line);
25076
25091
  continue;
25077
25092
  }
@@ -25090,16 +25105,23 @@ function wrapLines(lines, maxLen, literalLines, isBlock) {
25090
25105
  }
25091
25106
  return result;
25092
25107
  }
25093
- /** The indices of `lines` that hold part of a `{do}` body. */
25094
- function doBodyLines(lines) {
25108
+ /** Lines holding JavaScript or a multiline HTML tag must not be wrapped. */
25109
+ function verbatimLines(lines) {
25095
25110
  const found = /* @__PURE__ */ new Set();
25096
25111
  const text = lines.join("\n");
25097
25112
  const lineAt = sourceLines(text);
25098
- for (const block of scanSpindleMarkup(text).doBlocks) {
25113
+ const { doBlocks, tags } = scanSpindleMarkup(text);
25114
+ for (const block of doBlocks) {
25099
25115
  const first = lineAt(block.bodyStart);
25100
25116
  const last = lineAt(block.bodyEnd);
25101
25117
  for (let i = first; i <= last; i++) found.add(i);
25102
25118
  }
25119
+ for (const tag of tags) {
25120
+ const first = lineAt(tag.start);
25121
+ const last = lineAt(tag.end - 1);
25122
+ if (first === last) continue;
25123
+ for (let i = first; i <= last; i++) found.add(i);
25124
+ }
25103
25125
  return found;
25104
25126
  }
25105
25127
  /**
@@ -25112,7 +25134,7 @@ function wordWrap(text, maxLen, indent) {
25112
25134
  /** Whether the character is inside a token whose text must stay as written. */
25113
25135
  const inToken = new Array(text.length).fill(false);
25114
25136
  for (const token of tokenizeMarkupTolerant(text).tokens) {
25115
- if (token.type === "text" || token.type === "html") continue;
25137
+ if (token.type === "text") continue;
25116
25138
  inToken.fill(true, token.start, token.end);
25117
25139
  }
25118
25140
  const room = maxLen - indentColumn(indent);
@@ -25248,8 +25270,8 @@ function validateStoryMarkup(passages, macros, options = {}) {
25248
25270
  const list = [...passages];
25249
25271
  const all = [...macros];
25250
25272
  const known = /* @__PURE__ */ new Set();
25251
- const widgets = widgetDefinitions$1(list, parameterLookup(all));
25252
- const blocks = new Set(effectiveWidgetDefinitions(widgets).filter((def) => def.block).map((def) => def.name.toLowerCase()));
25273
+ const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(list, parameterLookup(all)));
25274
+ const blocks = new Set(widgets.filter((def) => def.block).map((def) => def.name.toLowerCase()));
25253
25275
  const parametersOf = parameterLookup([...all, ...definedWidgetMacros(widgets)]);
25254
25276
  for (const macro of all) {
25255
25277
  const name = macro.name.toLowerCase();
@@ -25331,7 +25353,7 @@ var NOT_MARKUP_TAGS = ["script", "stylesheet"];
25331
25353
  */
25332
25354
  function referenceOptions(macros, all = false, passages = []) {
25333
25355
  const list = [...macros];
25334
- const widgets = widgetDefinitions$1(passages, parameterLookup(list));
25356
+ const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(passages, parameterLookup(list)));
25335
25357
  return {
25336
25358
  all,
25337
25359
  storeVarMacros: new Set(list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.61.5",
3
+ "version": "0.61.7",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",