@rohal12/spindle 0.64.25 → 0.64.27

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.
@@ -92,12 +92,19 @@ var SVG_NOT_TEXT = /* @__PURE__ */ new Set([
92
92
  "pattern",
93
93
  "marker"
94
94
  ]);
95
+ /** Detached/headless DOMs may have no computed value; CSSOM still resolves
96
+ * duplicate inline declarations and priorities correctly.
97
+ */
98
+ function styleValue(el, name) {
99
+ return (el.ownerDocument.defaultView ?? globalThis.window)?.getComputedStyle?.(el)[name] || el.style?.[name] || "";
100
+ }
95
101
  /**
96
102
  * Whether the element hides its whole subtree, including stylesheet rules.
97
103
  * This needs computed styles but no layout, so it also works headlessly.
104
+ * A symbol referenced by SVG use is rendered only as an instance root.
98
105
  */
99
- function isHidden(el) {
100
- return el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true" || /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute("style") ?? "") || el.ownerDocument.defaultView?.getComputedStyle(el).display === "none" || NOT_TEXT.has(el.localName.toLowerCase()) || el.namespaceURI === "http://www.w3.org/2000/svg" && SVG_NOT_TEXT.has(el.localName.toLowerCase()) || el.parentElement?.tagName === "DETAILS" && !el.parentElement.hasAttribute("open") && el !== Array.from(el.parentElement.children).find((c) => c.tagName === "SUMMARY");
106
+ function isHidden(el, svgInstanceRoot = false) {
107
+ return el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true" || styleValue(el, "display") === "none" || NOT_TEXT.has(el.localName.toLowerCase()) || el.namespaceURI === "http://www.w3.org/2000/svg" && SVG_NOT_TEXT.has(el.localName.toLowerCase()) && !(svgInstanceRoot && el.localName.toLowerCase() === "symbol") || el.parentElement?.tagName === "DETAILS" && !el.parentElement.hasAttribute("open") && el !== Array.from(el.parentElement.children).find((c) => c.tagName === "SUMMARY");
101
108
  }
102
109
  /**
103
110
  * Whether `el` is in a closed `<details>`, other than in the summary that
@@ -122,12 +129,11 @@ function inClosedDetails(el, root) {
122
129
  * `<details>`. An optional root bounds ancestor checks, so observations can
123
130
  * read StoryContext inside its deliberately hidden host.
124
131
  */
125
- function isRendered(el, root) {
126
- const style = (e) => e.ownerDocument.defaultView?.getComputedStyle(e);
127
- const visibility = style(el)?.visibility;
128
- if (visibility === "hidden" || visibility === "collapse") return false;
132
+ function isRendered(el, root, checkVisibility = true) {
133
+ const visibility = styleValue(el, "visibility");
134
+ if (checkVisibility && (visibility === "hidden" || visibility === "collapse")) return false;
129
135
  for (let e = el; e; e = composedParent(e)) {
130
- if (style(e)?.display === "none") return false;
136
+ if (styleValue(e, "display") === "none") return false;
131
137
  if (e === root) break;
132
138
  const parent = e.parentElement;
133
139
  if (parent?.shadowRoot && !e.assignedSlot) return false;
@@ -9548,6 +9554,14 @@ function actionAttributes(action, control) {
9548
9554
  ref: action.ref
9549
9555
  };
9550
9556
  }
9557
+ /** Render a native macro button with its registered action and label. */
9558
+ function renderActionButton(action, control, onClick, label) {
9559
+ return h("button", {
9560
+ type: "button",
9561
+ ...actionAttributes(action, control),
9562
+ onClick
9563
+ }, label);
9564
+ }
9551
9565
  /**
9552
9566
  * While true, controls rendered underneath do not register actions or reserve
9553
9567
  * IDs. Used for display-only content mounted off-screen, so it never shows up
@@ -16758,6 +16772,69 @@ function HtmlAnnotation({ attributes, children }) {
16758
16772
  }
16759
16773
  }, isHtmlEncoding(attributes.encoding) ? void 0 : children), container && isHtmlEncoding(attributes.encoding) && createPortal(children, container)] });
16760
16774
  }
16775
+ // src/markup/svg-names.ts
16776
+ /** HTML foreign-content name adjustments; unknown foreign names stay intact.
16777
+ * https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
16778
+ */
16779
+ var TAGS = `svg a animate circle defs desc discard ellipse filter g image line
16780
+ marker mask metadata mpath path pattern polygon polyline rect script set stop
16781
+ style switch symbol text title tspan use view
16782
+ altGlyph altGlyphDef altGlyphItem animateColor animateMotion
16783
+ animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite
16784
+ feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow
16785
+ feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode
16786
+ feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile
16787
+ feTurbulence foreignObject glyphRef linearGradient radialGradient textPath`;
16788
+ var ATTRIBUTES = `id class style lang tabindex role autofocus
16789
+ accent-height accumulate additive alignment-baseline alphabetic amplitude
16790
+ arabic-form ascent azimuth baseline-shift bbox begin bias by clip
16791
+ clip-path clip-rule color color-interpolation color-interpolation-filters
16792
+ color-profile color-rendering contentscripttype contentstyletype cursor
16793
+ cx cy d decelerate descent direction display divisor dominant-baseline dur dx dy
16794
+ elevation enable-background end exponent externalresourcesrequired fill
16795
+ fill-opacity fill-rule filter flood-color flood-opacity focusable font-family
16796
+ font-size font-size-adjust font-stretch font-style font-variant font-weight
16797
+ format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal
16798
+ glyph-orientation-vertical hanging height horiz-adv-x horiz-origin-x href
16799
+ ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kerning
16800
+ letter-spacing lighting-color local marker-end marker-mid marker-start
16801
+ mathematical max media method min mode name offset opacity operator order orient
16802
+ orientation origin overflow overline-position overline-thickness panose-1
16803
+ paint-order pointer-events points r radius rendering-intent restart result
16804
+ rotate rx ry scale seed shape-rendering slope spacing speed stemh stemv
16805
+ stop-color stop-opacity strikethrough-position strikethrough-thickness string
16806
+ stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin
16807
+ stroke-miterlimit stroke-opacity stroke-width target text-anchor
16808
+ text-decoration text-overflow text-rendering to transform transform-origin type u1 u2
16809
+ underline-position underline-thickness unicode unicode-bidi unicode-range
16810
+ units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values
16811
+ vector-effect version vert-adv-y vert-origin-x vert-origin-y visibility width
16812
+ widths word-spacing writing-mode x x-height x1 x2 xlink:actuate xlink:arcrole
16813
+ xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space
16814
+ xmlns xmlns:xlink y y1 y2 z
16815
+ attributeName attributeType baseFrequency baseProfile calcMode
16816
+ clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform
16817
+ gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes
16818
+ lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth
16819
+ maskContentUnits maskUnits numOctaves pathLength patternContentUnits
16820
+ patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha
16821
+ preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur
16822
+ requiredExtensions requiredFeatures specularConstant specularExponent
16823
+ spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage
16824
+ tableValues targetX targetY textLength viewBox viewTarget xChannelSelector
16825
+ yChannelSelector zoomAndPan`;
16826
+ function adjustments(names) {
16827
+ return new Map(names.split(/\s+/).map((name) => [name.toLowerCase(), name]));
16828
+ }
16829
+ var tags = adjustments(TAGS);
16830
+ var attributes = adjustments(ATTRIBUTES);
16831
+ function svgTagName(name) {
16832
+ return tags.get(name.toLowerCase()) ?? name;
16833
+ }
16834
+ function svgAttributeName(name) {
16835
+ const lower = name.toLowerCase();
16836
+ return attributes.get(lower) ?? (/^(?:aria-|data-)/.test(lower) ? lower : name);
16837
+ }
16761
16838
  // src/components/macros/include-args.ts
16762
16839
  /**
16763
16840
  * The parameters of `{include}`. A standalone `inline` flag only counts
@@ -17415,7 +17492,7 @@ function HtmlNodeRenderer({ node }) {
17415
17492
  const namespace = tag === "svg" || tag === "math" ? tag : parentNamespace;
17416
17493
  const errors = [];
17417
17494
  const resolved = Object.entries(node.attributes).map(([k, v]) => [
17418
- k,
17495
+ namespace === "svg" ? svgAttributeName(k) : k,
17419
17496
  resolveAttributeValue(k, v, scope, errors),
17420
17497
  v,
17421
17498
  hasInterpolation(v)
@@ -17465,7 +17542,7 @@ function HtmlNodeRenderer({ node }) {
17465
17542
  value: childNamespace,
17466
17543
  children
17467
17544
  });
17468
- const element = authorElement(node.tag, props, children, namespace === "math");
17545
+ const element = authorElement(namespace === "svg" ? svgTagName(node.tag) : node.tag, props, children, namespace === "math");
17469
17546
  return withAttributeErrors(errors, isRawRoot ? /* @__PURE__ */ jsx(RawTextContext.Provider, {
17470
17547
  value: true,
17471
17548
  children: element
@@ -19290,23 +19367,28 @@ function saveSession(ifid, payload) {
19290
19367
  return { error };
19291
19368
  }
19292
19369
  }
19293
- /**
19294
- * The live payload of the stored session, if there is one that loads. A
19295
- * session written by an incompatible version of Spindle is dropped with a
19296
- * warning, and the story starts fresh.
19370
+ /** Capture storage before StoryInit can navigate and write a new session,
19371
+ * but defer revival until its class registrations have run.
19297
19372
  */
19298
- function loadSession(ifid) {
19373
+ function prepareSessionRestore(ifid) {
19374
+ let raw;
19299
19375
  try {
19300
- const raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
19301
- if (!raw) return void 0;
19302
- return decodePayload(JSON.parse(raw));
19303
- } catch (err) {
19304
- if (err instanceof IncompatibleSaveError) {
19305
- console.warn(`spindle: ${err.message}; the session was not restored.`);
19306
- clearSession(ifid);
19307
- }
19308
- return;
19376
+ raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
19377
+ } catch {
19378
+ return () => void 0;
19309
19379
  }
19380
+ return () => {
19381
+ try {
19382
+ if (!raw) return void 0;
19383
+ return decodePayload(JSON.parse(raw));
19384
+ } catch (err) {
19385
+ if (err instanceof IncompatibleSaveError) {
19386
+ console.warn(`spindle: ${err.message}; the session was not restored.`);
19387
+ clearSession(ifid);
19388
+ }
19389
+ return;
19390
+ }
19391
+ };
19310
19392
  }
19311
19393
  function clearSession(ifid) {
19312
19394
  try {
@@ -19509,8 +19591,9 @@ function executeStoryInit() {
19509
19591
  * handlers set synchronously belongs to the start moment, like StoryInit's
19510
19592
  * changes; a restored session keeps the history it recorded.
19511
19593
  */
19512
- function initializeStory(session) {
19594
+ function initializeStory(savedSession) {
19513
19595
  executeStoryInit();
19596
+ let session = typeof savedSession === "function" ? savedSession() : savedSession;
19514
19597
  const missing = session ? missingPassage(useStoryStore.getState().storyData, session) : void 0;
19515
19598
  if (missing !== void 0) {
19516
19599
  console.warn(`spindle: discarding the saved session: the story no longer has the passage "${missing}"`);
@@ -20365,6 +20448,7 @@ function clearAndRestart(get, set, clearing, message) {
20365
20448
  get().restart();
20366
20449
  return reported(cleared, message);
20367
20450
  }
20451
+ var consumedTransition;
20368
20452
  var useStoryStore = create()(storyStore((set, get) => ({
20369
20453
  storyData: null,
20370
20454
  currentPassage: "",
@@ -20409,6 +20493,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20409
20493
  });
20410
20494
  },
20411
20495
  init: (storyData, variableDefaults = {}, transientDefaults = {}) => {
20496
+ consumedTransition = void 0;
20412
20497
  const startPassage = storyData.passagesById.get(storyData.startNode);
20413
20498
  if (!startPassage) throw new Error(`spindle: Start passage (pid=${storyData.startNode}) not found.`);
20414
20499
  const initialVars = startVariables(variableDefaults);
@@ -20775,8 +20860,13 @@ var useStoryStore = create()(storyStore((set, get) => ({
20775
20860
  state.nextTransition = config;
20776
20861
  });
20777
20862
  },
20778
- consumeNextTransition: () => {
20863
+ consumeNextTransition: (navigationId) => {
20864
+ if (navigationId !== void 0 && consumedTransition?.navigationId === navigationId) return consumedTransition.config;
20779
20865
  const current = get().nextTransition;
20866
+ if (navigationId !== void 0) consumedTransition = {
20867
+ navigationId,
20868
+ config: current
20869
+ };
20780
20870
  if (current !== null) set((state) => {
20781
20871
  state.nextTransition = null;
20782
20872
  });
@@ -22050,6 +22140,142 @@ function storyContextElement() {
22050
22140
  }
22051
22141
  return el;
22052
22142
  }
22143
+ // src/observe/svg-instances.ts
22144
+ var frames = /* @__PURE__ */ new WeakMap();
22145
+ var detachedDocuments = /* @__PURE__ */ new WeakMap();
22146
+ /**
22147
+ * Resolve a use instance's styles in an isolated tree. Source computed styles
22148
+ * inherit from the definition's ancestors, whereas SVG instances inherit from
22149
+ * their use host and match selectors within their own shadow tree.
22150
+ */
22151
+ var SvgInstances = class {
22152
+ constructor() {
22153
+ this.hosts = [];
22154
+ this.sources = /* @__PURE__ */ new WeakMap();
22155
+ this.stylesheets = /* @__PURE__ */ new WeakMap();
22156
+ this.remaining = 1e4;
22157
+ }
22158
+ source(element) {
22159
+ return this.sources.get(element) ?? element;
22160
+ }
22161
+ stylesheet(use) {
22162
+ const root = this.source(use).getRootNode();
22163
+ const cached = this.stylesheets.get(root);
22164
+ if (cached !== void 0) return cached;
22165
+ const rules = (sheet) => {
22166
+ try {
22167
+ return [...sheet.cssRules].map((rule) => {
22168
+ if (rule.type === 3) {
22169
+ const imported = rule;
22170
+ if (!imported.styleSheet) return "";
22171
+ const text = rules(imported.styleSheet);
22172
+ let wrapped = imported.media.mediaText ? `@media ${imported.media.mediaText}{${text}}` : text;
22173
+ if (imported.supportsText) wrapped = `@supports (${imported.supportsText}){${wrapped}}`;
22174
+ if (imported.layerName !== null && imported.layerName !== void 0) wrapped = `@layer ${imported.layerName}{${wrapped}}`;
22175
+ return wrapped;
22176
+ }
22177
+ return rule.cssText;
22178
+ }).join("\n");
22179
+ } catch {
22180
+ return "";
22181
+ }
22182
+ };
22183
+ const text = [...root.styleSheets ?? [], ...root.adoptedStyleSheets ?? []].filter((sheet) => !sheet.disabled).map((sheet) => {
22184
+ const text = rules(sheet);
22185
+ return sheet.media.mediaText ? `@media ${sheet.media.mediaText}{${text}}` : text;
22186
+ }).join("\n");
22187
+ this.stylesheets.set(root, text);
22188
+ return text;
22189
+ }
22190
+ expand(use, target) {
22191
+ if (this.remaining <= 0) return;
22192
+ if (!this.document) {
22193
+ const doc = use.ownerDocument;
22194
+ const detached = doc.implementation.createHTMLDocument("");
22195
+ const probe = detached.createElement("div");
22196
+ probe.style.visibility = "hidden";
22197
+ detached.body.appendChild(probe);
22198
+ if ((doc.defaultView ?? globalThis.window)?.getComputedStyle(probe).visibility === "hidden") {
22199
+ probe.remove();
22200
+ let isolated = detachedDocuments.get(doc);
22201
+ if (!isolated) {
22202
+ const view = doc.defaultView ?? globalThis.window;
22203
+ isolated = detached;
22204
+ try {
22205
+ isolated = Reflect.construct(view.Window, [{ settings: {
22206
+ disableJavaScriptEvaluation: true,
22207
+ disableCSSFileLoading: true,
22208
+ disableIframePageLoading: true
22209
+ } }]).document ?? detached;
22210
+ } catch {}
22211
+ detachedDocuments.set(doc, isolated);
22212
+ }
22213
+ this.document = isolated;
22214
+ } else {
22215
+ let frame = frames.get(doc);
22216
+ if (!frame?.isConnected) {
22217
+ frame = doc.createElement("iframe");
22218
+ frame.setAttribute("sandbox", "allow-same-origin");
22219
+ frame.setAttribute("aria-hidden", "true");
22220
+ frame.tabIndex = -1;
22221
+ frame.style.cssText = `all:initial!important;display:block!important;position:fixed!important;left:-100000px!important;top:0!important;visibility:hidden!important;pointer-events:none!important;border:0!important;width:${doc.defaultView?.innerWidth ?? 1024}px!important;height:${doc.defaultView?.innerHeight ?? 768}px!important;`;
22222
+ doc.documentElement.insertBefore(frame, doc.body);
22223
+ frames.set(doc, frame);
22224
+ const isolated = frame.contentDocument;
22225
+ if (isolated) {
22226
+ const meta = isolated.createElement("meta");
22227
+ meta.httpEquiv = "Content-Security-Policy";
22228
+ meta.content = "default-src 'none'; style-src 'unsafe-inline'";
22229
+ isolated.head.appendChild(meta);
22230
+ }
22231
+ }
22232
+ this.document = frame.contentDocument ?? void 0;
22233
+ if (!this.document) return;
22234
+ const width = `${doc.defaultView?.innerWidth ?? 1024}px`;
22235
+ const height = `${doc.defaultView?.innerHeight ?? 768}px`;
22236
+ if (frame.style.width !== width) frame.style.setProperty("width", width, "important");
22237
+ if (frame.style.height !== height) frame.style.setProperty("height", height, "important");
22238
+ }
22239
+ }
22240
+ const doc = this.document;
22241
+ const host = doc.createElement("div");
22242
+ const computed = (use.ownerDocument.defaultView ?? globalThis.window)?.getComputedStyle(use);
22243
+ if (computed) {
22244
+ host.style.visibility = computed.visibility || use.style.visibility || use.getAttribute("visibility") || "";
22245
+ host.style.display = computed.display || use.style.display;
22246
+ for (const name of Array.from(computed)) if (name.startsWith("--")) host.style.setProperty(name, computed.getPropertyValue(name));
22247
+ }
22248
+ doc.body.appendChild(host);
22249
+ this.hosts.push(host);
22250
+ const shadow = host.attachShadow({ mode: "open" });
22251
+ const style = doc.createElement("style");
22252
+ style.textContent = this.stylesheet(use);
22253
+ const copy = (node) => {
22254
+ if (--this.remaining < 0) return;
22255
+ let clone;
22256
+ if (node.nodeType === 1) {
22257
+ const element = node;
22258
+ clone = doc.createElementNS(element.namespaceURI, element.localName);
22259
+ for (const attribute of element.attributes) clone.setAttributeNS(attribute.namespaceURI, attribute.name, attribute.value);
22260
+ this.sources.set(clone, this.source(node));
22261
+ } else if (node.nodeType === 3) clone = doc.createTextNode(node.textContent ?? "");
22262
+ else return;
22263
+ for (const child of node.childNodes) {
22264
+ if (this.remaining <= 0) break;
22265
+ const copied = copy(child);
22266
+ if (copied) clone.appendChild(copied);
22267
+ }
22268
+ return clone;
22269
+ };
22270
+ const clone = copy(target);
22271
+ if (clone) shadow.appendChild(clone);
22272
+ shadow.appendChild(style);
22273
+ return clone;
22274
+ }
22275
+ dispose() {
22276
+ for (const host of this.hosts) host.remove();
22277
+ }
22278
+ };
22053
22279
  // src/observe/observable-text.ts
22054
22280
  /** Elements that start and end a line. */
22055
22281
  var BLOCKS = /* @__PURE__ */ new Set([
@@ -22113,10 +22339,27 @@ function observableText(el, skip, visibilityRoot) {
22113
22339
  const endLine = () => {
22114
22340
  if (out !== "" && !out.endsWith("\n")) out += "\n";
22115
22341
  };
22116
- const walk = (node, inPre) => {
22342
+ const references = /* @__PURE__ */ new Set();
22343
+ const instances = new SvgInstances();
22344
+ let instanceNodes = 1e4;
22345
+ const localTarget = (use) => {
22346
+ use = instances.source(use);
22347
+ const href = use.getAttribute("href") ?? use.getAttributeNS("http://www.w3.org/1999/xlink", "href");
22348
+ if (!href?.startsWith("#") || href.length === 1) return;
22349
+ let id;
22350
+ try {
22351
+ id = decodeURIComponent(href.slice(1));
22352
+ } catch {
22353
+ return;
22354
+ }
22355
+ const root = use.getRootNode();
22356
+ return "getElementById" in root ? root.getElementById(id) ?? void 0 : [root, ...root.querySelectorAll("[id]")].find((node) => node.id === id);
22357
+ };
22358
+ const walk = (node, inPre, instanceRoot) => {
22359
+ if (instanceRoot && --instanceNodes < 0) return;
22117
22360
  if (node.nodeType === 3) {
22118
22361
  const parent = node.assignedSlot ?? node.parentElement ?? node.getRootNode().host;
22119
- if (parent && !isRendered(parent, visibilityRoot)) return;
22362
+ if (parent && !isRendered(parent, instanceRoot ?? visibilityRoot)) return;
22120
22363
  const data = node.textContent ?? "";
22121
22364
  if (inPre) out += data;
22122
22365
  else {
@@ -22127,15 +22370,25 @@ function observableText(el, skip, visibilityRoot) {
22127
22370
  }
22128
22371
  if (node.nodeType !== 1) return;
22129
22372
  const child = node;
22130
- if (isHidden(child) || skip && child !== el && child.matches(skip)) return;
22373
+ if (isHidden(child, child === instanceRoot) || skip && child !== el && child.matches(skip)) return;
22374
+ if (child.namespaceURI === "http://www.w3.org/2000/svg" && child.localName === "use") {
22375
+ if (!isRendered(child, instanceRoot ?? visibilityRoot, false)) return;
22376
+ const target = localTarget(child);
22377
+ if (!target || target.namespaceURI !== child.namespaceURI || references.has(target) || references.size >= 32) return;
22378
+ references.add(target);
22379
+ const instance = instances.expand(child, target);
22380
+ if (instance) walk(instance, inPre, instance);
22381
+ references.delete(target);
22382
+ return;
22383
+ }
22131
22384
  if (child.matches("input, textarea, select") || child.hasAttribute("data-action") && getAction(child.getAttribute("data-action"))?.type === "cycle") {
22132
22385
  if (child.matches("input[type=\"hidden\" i]")) return;
22133
- if (!isRendered(child, visibilityRoot)) return;
22386
+ if (!isRendered(child, instanceRoot ?? visibilityRoot)) return;
22134
22387
  out += controlMarker(child);
22135
22388
  return;
22136
22389
  }
22137
22390
  if (child.tagName === "BR") {
22138
- if (isRendered(child, visibilityRoot)) out += "\n";
22391
+ if (isRendered(child, instanceRoot ?? visibilityRoot)) out += "\n";
22139
22392
  return;
22140
22393
  }
22141
22394
  const block = BLOCKS.has(child.tagName);
@@ -22143,11 +22396,15 @@ function observableText(el, skip, visibilityRoot) {
22143
22396
  const closedDetails = child.tagName === "DETAILS" && !child.hasAttribute("open");
22144
22397
  const rendered = composedChildNodes(child);
22145
22398
  const children = closedDetails ? rendered.filter((c) => c.nodeType === 1 && !isHidden(c)) : rendered;
22146
- for (const c of children) walk(c, inPre || child.tagName === "PRE");
22399
+ for (const c of children) walk(c, inPre || child.tagName === "PRE", instanceRoot);
22147
22400
  if (child.tagName === "TD" || child.tagName === "TH") out += " ";
22148
22401
  if (block) endLine();
22149
22402
  };
22150
- walk(el, false);
22403
+ try {
22404
+ walk(el, false);
22405
+ } finally {
22406
+ instances.dispose();
22407
+ }
22151
22408
  return out.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\s+$/g, "");
22152
22409
  }
22153
22410
  /**
@@ -24395,10 +24652,8 @@ function cloneSnapshotTree(source, ids, pseudoRules = [], svgMarker = String(++s
24395
24652
  clone,
24396
24653
  ids
24397
24654
  });
24398
- if (html && source.localName === "input" && source.type === "radio") {
24399
- clone.removeAttribute("name");
24400
- clone.removeAttribute("form");
24401
- }
24655
+ if (html && source.matches("button, fieldset, input, object, output, select, textarea")) clone.setAttribute("form", "");
24656
+ if (html && (source.localName === "details" || source.localName === "input" && source.type === "radio")) clone.removeAttribute("name");
24402
24657
  const computed = getComputedStyle(source);
24403
24658
  if (!svg) copyComputedStyle(computed, clone.style, ids);
24404
24659
  let pseudoId;
@@ -24637,7 +24892,7 @@ defineMacro({
24637
24892
  const isFirstLoad = !displayedPassage;
24638
24893
  const isReplacement = navigationId === replacementNavigationId;
24639
24894
  if (navigationId === displayed.id) return;
24640
- const next = store.consumeNextTransition();
24895
+ const next = store.consumeNextTransition(navigationId);
24641
24896
  cancelTransition();
24642
24897
  const targetPassage = storyData?.passages.get(currentPassage);
24643
24898
  if (!targetPassage) {
@@ -25348,19 +25603,13 @@ defineMacro({
25348
25603
  const label = ctx.resolve?.(ctx.args.label ?? "") ?? rawArgs;
25349
25604
  const runBody = useDetachedBody();
25350
25605
  const handleClick = () => runBody(children);
25351
- const action = useControlAction({
25606
+ return renderActionButton(useControlAction({
25352
25607
  type: "button",
25353
25608
  key: rawArgs,
25354
25609
  authorId: ctx.id,
25355
25610
  label,
25356
25611
  perform: handleClick
25357
- });
25358
- return /* @__PURE__ */ jsx("button", {
25359
- type: "button",
25360
- ...actionAttributes(action, ctx),
25361
- onClick: handleClick,
25362
- children: label
25363
- });
25612
+ }), ctx, handleClick, label);
25364
25613
  }
25365
25614
  });
25366
25615
  // src/components/macros/MacroLink.tsx
@@ -25817,12 +26066,7 @@ defineMacro({
25817
26066
  target: passageName,
25818
26067
  perform: openDialog
25819
26068
  });
25820
- return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
25821
- type: "button",
25822
- ...actionAttributes(action, ctx),
25823
- onClick: openDialog,
25824
- children: label
25825
- }), open && /* @__PURE__ */ jsx(PassageDialog, {
26069
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [renderActionButton(action, ctx, openDialog, label), open && /* @__PURE__ */ jsx(PassageDialog, {
25826
26070
  passageName,
25827
26071
  onClose: () => setOpen(false),
25828
26072
  showCloseButton: !noclose
@@ -26623,27 +26867,22 @@ defineMacro({
26623
26867
  parameters: [VARIABLE_PARAMETER],
26624
26868
  render({ children = [] }, ctx) {
26625
26869
  const options = ctx.extractOptions(children);
26870
+ const label = ctx.value == null ? "Choose an option" : String(ctx.value);
26626
26871
  const handleClick = () => {
26627
26872
  if (options.length === 0) return;
26628
26873
  const current = ctx.getValue();
26629
- const nextIndex = (options.indexOf(String(current)) + 1) % options.length;
26874
+ const nextIndex = ((current == null ? -1 : options.indexOf(String(current))) + 1) % options.length;
26630
26875
  ctx.setValue(options[nextIndex]);
26631
26876
  };
26632
- const action = useVariableAction(ctx, {
26877
+ return renderActionButton(useVariableAction(ctx, {
26633
26878
  type: "cycle",
26634
- label: ctx.value == null ? options[0] || "" : String(ctx.value),
26879
+ label,
26635
26880
  options,
26636
26881
  perform: (v) => {
26637
26882
  if (v !== void 0) ctx.setValue(v);
26638
26883
  else handleClick();
26639
26884
  }
26640
- });
26641
- return /* @__PURE__ */ jsx("button", {
26642
- type: "button",
26643
- ...actionAttributes(action, ctx),
26644
- onClick: handleClick,
26645
- children: ctx.value == null ? options[0] || "" : String(ctx.value)
26646
- });
26885
+ }), ctx, handleClick, label);
26647
26886
  }
26648
26887
  });
26649
26888
  // src/components/macros/Span.tsx
@@ -26828,7 +27067,7 @@ function boot() {
26828
27067
  useStoryStore.getState().init(storyData, defaults, transientDefaults);
26829
27068
  enterRuntimePhase();
26830
27069
  for (const [, passage] of storyData.passages) if (passage.tags.includes("widget")) orStop(() => registerWidgetDefinitions(parseMarkup(passage.content), passage.name), `Passage "${passage.name}": `);
26831
- initializeStory(loadSession(storyData.ifid));
27070
+ initializeStory(prepareSessionRestore(storyData.ifid));
26832
27071
  const markup = [...variableErrors(storyData, schema), ...markupErrors(storyData, (p) => p.name !== "StoryInit")];
26833
27072
  const storyContext = storyData.passages.get("StoryContext");
26834
27073
  if (storyContext) markup.push(...storyContextErrors(storyContext.content, storeVarMacroNames()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.25",
3
+ "version": "0.64.27",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,4 @@
1
- import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
+ import { renderActionButton, useControlAction } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { useDetachedBody } from './detached-body';
4
4
 
@@ -25,14 +25,6 @@ defineMacro({
25
25
  perform: handleClick,
26
26
  });
27
27
 
28
- return (
29
- <button
30
- type="button"
31
- {...actionAttributes(action, ctx)}
32
- onClick={handleClick}
33
- >
34
- {label}
35
- </button>
36
- );
28
+ return renderActionButton(action, ctx, handleClick, label);
37
29
  },
38
30
  });
@@ -1,4 +1,4 @@
1
- import { actionAttributes } from '../../hooks/use-action';
1
+ import { renderActionButton } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
4
4
  import { OPTION_CLAUSE } from './option-clauses';
@@ -12,18 +12,20 @@ defineMacro({
12
12
  parameters: [VARIABLE_PARAMETER],
13
13
  render({ children = [] }, ctx) {
14
14
  const options = ctx.extractOptions(children);
15
+ const label = ctx.value == null ? 'Choose an option' : String(ctx.value);
15
16
 
16
17
  const handleClick = () => {
17
18
  if (options.length === 0) return;
18
19
  const current = ctx.getValue!();
19
- const currentIndex = options.indexOf(String(current));
20
+ const currentIndex =
21
+ current == null ? -1 : options.indexOf(String(current));
20
22
  const nextIndex = (currentIndex + 1) % options.length;
21
23
  ctx.setValue!(options[nextIndex]);
22
24
  };
23
25
 
24
26
  const action = useVariableAction(ctx, {
25
27
  type: 'cycle',
26
- label: ctx.value == null ? options[0] || '' : String(ctx.value),
28
+ label,
27
29
  options,
28
30
  perform: (v) => {
29
31
  if (v !== undefined) {
@@ -34,14 +36,6 @@ defineMacro({
34
36
  },
35
37
  });
36
38
 
37
- return (
38
- <button
39
- type="button"
40
- {...actionAttributes(action, ctx)}
41
- onClick={handleClick}
42
- >
43
- {ctx.value == null ? options[0] || '' : String(ctx.value)}
44
- </button>
45
- );
39
+ return renderActionButton(action, ctx, handleClick, label);
46
40
  },
47
41
  });
@@ -1,4 +1,4 @@
1
- import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
+ import { renderActionButton, useControlAction } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { PassageDialog } from '../PassageDialog';
4
4
 
@@ -33,13 +33,7 @@ defineMacro({
33
33
 
34
34
  return (
35
35
  <>
36
- <button
37
- type="button"
38
- {...actionAttributes(action, ctx)}
39
- onClick={openDialog}
40
- >
41
- {label}
42
- </button>
36
+ {renderActionButton(action, ctx, openDialog, label)}
43
37
  {open && (
44
38
  <PassageDialog
45
39
  passageName={passageName}