@rohal12/spindle 0.64.26 → 0.64.28

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,69 @@ var SVG_NOT_TEXT = /* @__PURE__ */ new Set([
92
92
  "pattern",
93
93
  "marker"
94
94
  ]);
95
+ var hiddenDefaults = /* @__PURE__ */ new WeakSet();
96
+ var needsHiddenDefaults = /* @__PURE__ */ new WeakMap();
97
+ function ensureHiddenDefaults(el) {
98
+ if (!el.hasAttribute("hidden")) return;
99
+ const doc = el.ownerDocument;
100
+ const view = doc.defaultView ?? globalThis.window;
101
+ let needed = needsHiddenDefaults.get(doc);
102
+ if (needed === void 0) {
103
+ const detached = doc.implementation.createHTMLDocument("");
104
+ const probe = detached.createElement("div");
105
+ probe.hidden = true;
106
+ detached.body.append(probe);
107
+ needed = view?.getComputedStyle(probe).display === "block";
108
+ needsHiddenDefaults.set(doc, needed);
109
+ }
110
+ const root = el.getRootNode();
111
+ if (!needed || hiddenDefaults.has(root)) return;
112
+ const container = root.nodeType === 9 ? root.head : root;
113
+ if (root.nodeType !== 9 && !("host" in root)) return;
114
+ const style = doc.createElement("style");
115
+ style.textContent = ":where([hidden]:not([hidden=\"until-found\" i])){display:none}:where([hidden=\"until-found\" i]){content-visibility:hidden}";
116
+ container.prepend(style);
117
+ hiddenDefaults.add(root);
118
+ }
119
+ /** Detached/headless DOMs may have no computed value; CSSOM still resolves
120
+ * duplicate inline declarations and priorities correctly.
121
+ */
122
+ function styleValue(el, name) {
123
+ ensureHiddenDefaults(el);
124
+ return (el.ownerDocument.defaultView ?? globalThis.window)?.getComputedStyle?.(el).getPropertyValue(name) || el.style?.getPropertyValue(name) || "";
125
+ }
95
126
  /**
96
127
  * Whether the element hides its whole subtree, including stylesheet rules.
97
128
  * This needs computed styles but no layout, so it also works headlessly.
129
+ * A symbol referenced by SVG use is rendered only as an instance root.
98
130
  */
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");
131
+ function isHidden(el, svgInstanceRoot = false) {
132
+ const display = styleValue(el, "display");
133
+ return el.hasAttribute("hidden") && el.getAttribute("hidden")?.toLowerCase() !== "until-found" && display === "" || el.getAttribute("aria-hidden") === "true" || 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");
134
+ }
135
+ var NO_LAYOUT_CONTAINMENT = /* @__PURE__ */ new Set([
136
+ "none",
137
+ "contents",
138
+ "ruby",
139
+ "ruby-base",
140
+ "ruby-text",
141
+ "ruby-base-container",
142
+ "ruby-text-container",
143
+ "table-row",
144
+ "table-row-group",
145
+ "table-header-group",
146
+ "table-footer-group",
147
+ "table-column",
148
+ "table-column-group"
149
+ ]);
150
+ /** content-visibility suppresses contents only in layout containment boxes. */
151
+ function hidesContents(el) {
152
+ const value = styleValue(el, "content-visibility");
153
+ if (!(value === "hidden" || value === "" && el.getAttribute("hidden")?.toLowerCase() === "until-found")) return false;
154
+ const display = styleValue(el, "display") || (el.localName === "td" || el.localName === "th" ? "table-cell" : "inline");
155
+ if (NO_LAYOUT_CONTAINMENT.has(display)) return false;
156
+ if (display === "inline" || display === "inline list-item") return el.namespaceURI === "http://www.w3.org/2000/svg" || el.matches("img, input, textarea, select, button, fieldset, video, audio, canvas, iframe, embed");
157
+ return true;
101
158
  }
102
159
  /**
103
160
  * Whether `el` is in a closed `<details>`, other than in the summary that
@@ -122,12 +179,12 @@ function inClosedDetails(el, root) {
122
179
  * `<details>`. An optional root bounds ancestor checks, so observations can
123
180
  * read StoryContext inside its deliberately hidden host.
124
181
  */
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;
182
+ function isRendered(el, root, checkVisibility = true) {
183
+ const visibility = styleValue(el, "visibility");
184
+ if (checkVisibility && (visibility === "hidden" || visibility === "collapse")) return false;
129
185
  for (let e = el; e; e = composedParent(e)) {
130
- if (style(e)?.display === "none") return false;
186
+ if (styleValue(e, "display") === "none") return false;
187
+ if (e !== el && hidesContents(e)) return false;
131
188
  if (e === root) break;
132
189
  const parent = e.parentElement;
133
190
  if (parent?.shadowRoot && !e.assignedSlot) return false;
@@ -141,6 +198,35 @@ function isReaderVisible(el) {
141
198
  for (let at = el; at; at = composedParent(at)) if (isHidden(at) || at.hasAttribute("inert")) return false;
142
199
  return true;
143
200
  }
201
+ // src/utils/type-reveal.ts
202
+ /** Remaining revealed characters at this node, across nested typewriters. */
203
+ function revealedCharacters(node) {
204
+ let available = Infinity;
205
+ const element = node.nodeType === 1 ? node : node.parentElement;
206
+ for (let at = element; at; at = composedParent(at)) {
207
+ const count = at.getAttribute("data-type-revealed");
208
+ if (count === null) continue;
209
+ let left = Number(count);
210
+ if (!Number.isFinite(left)) continue;
211
+ if (!at.contains(node)) return 0;
212
+ for (let child = node; child !== at; child = child.parentNode) for (let sibling = child.previousSibling; sibling; sibling = sibling.previousSibling) if (sibling.nodeType === 1 || sibling.nodeType === 3) left -= sibling.textContent?.length ?? 0;
213
+ available = Math.min(available, Math.max(0, left));
214
+ }
215
+ return available;
216
+ }
217
+ /** Only the prefix that every containing typewriter has revealed. */
218
+ function revealedText(node) {
219
+ return node.data.slice(0, revealedCharacters(node));
220
+ }
221
+ /** Offer a control once its entire label is revealed, avoiding label spoilers.
222
+ * Controls without DOM text have no measured clip boxes; wait for completion.
223
+ */
224
+ function isFullyRevealed(el) {
225
+ const available = revealedCharacters(el);
226
+ if (available !== Infinity && (!el.textContent || available < el.textContent.length)) return false;
227
+ for (const child of composedElements(el)) if (child.hasAttribute("data-type-revealed") && revealedCharacters(child) < (child.textContent?.length ?? 0)) return false;
228
+ return true;
229
+ }
144
230
  // src/prng.ts
145
231
  /**
146
232
  * Seedable PRNG for Spindle — Mulberry32 algorithm.
@@ -9504,7 +9590,7 @@ function effectiveAction(action) {
9504
9590
  /** Whether any connected instance of this action is visible to a reader. */
9505
9591
  function isActionVisible(action) {
9506
9592
  const elements = actionElements(action.id);
9507
- return elements.length === 0 || elements.some(isReaderVisible);
9593
+ return elements.length === 0 || elements.some((el) => isReaderVisible(el) && isFullyRevealed(el));
9508
9594
  }
9509
9595
  function resetIdCounters() {
9510
9596
  idCounters.clear();
@@ -16766,6 +16852,69 @@ function HtmlAnnotation({ attributes, children }) {
16766
16852
  }
16767
16853
  }, isHtmlEncoding(attributes.encoding) ? void 0 : children), container && isHtmlEncoding(attributes.encoding) && createPortal(children, container)] });
16768
16854
  }
16855
+ // src/markup/svg-names.ts
16856
+ /** HTML foreign-content name adjustments; unknown foreign names stay intact.
16857
+ * https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
16858
+ */
16859
+ var TAGS = `svg a animate circle defs desc discard ellipse filter g image line
16860
+ marker mask metadata mpath path pattern polygon polyline rect script set stop
16861
+ style switch symbol text title tspan use view
16862
+ altGlyph altGlyphDef altGlyphItem animateColor animateMotion
16863
+ animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite
16864
+ feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow
16865
+ feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode
16866
+ feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile
16867
+ feTurbulence foreignObject glyphRef linearGradient radialGradient textPath`;
16868
+ var ATTRIBUTES = `id class style lang tabindex role autofocus
16869
+ accent-height accumulate additive alignment-baseline alphabetic amplitude
16870
+ arabic-form ascent azimuth baseline-shift bbox begin bias by clip
16871
+ clip-path clip-rule color color-interpolation color-interpolation-filters
16872
+ color-profile color-rendering contentscripttype contentstyletype cursor
16873
+ cx cy d decelerate descent direction display divisor dominant-baseline dur dx dy
16874
+ elevation enable-background end exponent externalresourcesrequired fill
16875
+ fill-opacity fill-rule filter flood-color flood-opacity focusable font-family
16876
+ font-size font-size-adjust font-stretch font-style font-variant font-weight
16877
+ format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal
16878
+ glyph-orientation-vertical hanging height horiz-adv-x horiz-origin-x href
16879
+ ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kerning
16880
+ letter-spacing lighting-color local marker-end marker-mid marker-start
16881
+ mathematical max media method min mode name offset opacity operator order orient
16882
+ orientation origin overflow overline-position overline-thickness panose-1
16883
+ paint-order pointer-events points r radius rendering-intent restart result
16884
+ rotate rx ry scale seed shape-rendering slope spacing speed stemh stemv
16885
+ stop-color stop-opacity strikethrough-position strikethrough-thickness string
16886
+ stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin
16887
+ stroke-miterlimit stroke-opacity stroke-width target text-anchor
16888
+ text-decoration text-overflow text-rendering to transform transform-origin type u1 u2
16889
+ underline-position underline-thickness unicode unicode-bidi unicode-range
16890
+ units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values
16891
+ vector-effect version vert-adv-y vert-origin-x vert-origin-y visibility width
16892
+ widths word-spacing writing-mode x x-height x1 x2 xlink:actuate xlink:arcrole
16893
+ xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space
16894
+ xmlns xmlns:xlink y y1 y2 z
16895
+ attributeName attributeType baseFrequency baseProfile calcMode
16896
+ clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform
16897
+ gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes
16898
+ lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth
16899
+ maskContentUnits maskUnits numOctaves pathLength patternContentUnits
16900
+ patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha
16901
+ preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur
16902
+ requiredExtensions requiredFeatures specularConstant specularExponent
16903
+ spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage
16904
+ tableValues targetX targetY textLength viewBox viewTarget xChannelSelector
16905
+ yChannelSelector zoomAndPan`;
16906
+ function adjustments(names) {
16907
+ return new Map(names.split(/\s+/).map((name) => [name.toLowerCase(), name]));
16908
+ }
16909
+ var tags = adjustments(TAGS);
16910
+ var attributes = adjustments(ATTRIBUTES);
16911
+ function svgTagName(name) {
16912
+ return tags.get(name.toLowerCase()) ?? name;
16913
+ }
16914
+ function svgAttributeName(name) {
16915
+ const lower = name.toLowerCase();
16916
+ return attributes.get(lower) ?? (/^(?:aria-|data-)/.test(lower) ? lower : name);
16917
+ }
16769
16918
  // src/components/macros/include-args.ts
16770
16919
  /**
16771
16920
  * The parameters of `{include}`. A standalone `inline` flag only counts
@@ -17423,7 +17572,7 @@ function HtmlNodeRenderer({ node }) {
17423
17572
  const namespace = tag === "svg" || tag === "math" ? tag : parentNamespace;
17424
17573
  const errors = [];
17425
17574
  const resolved = Object.entries(node.attributes).map(([k, v]) => [
17426
- k,
17575
+ namespace === "svg" ? svgAttributeName(k) : k,
17427
17576
  resolveAttributeValue(k, v, scope, errors),
17428
17577
  v,
17429
17578
  hasInterpolation(v)
@@ -17473,7 +17622,7 @@ function HtmlNodeRenderer({ node }) {
17473
17622
  value: childNamespace,
17474
17623
  children
17475
17624
  });
17476
- const element = authorElement(node.tag, props, children, namespace === "math");
17625
+ const element = authorElement(namespace === "svg" ? svgTagName(node.tag) : node.tag, props, children, namespace === "math");
17477
17626
  return withAttributeErrors(errors, isRawRoot ? /* @__PURE__ */ jsx(RawTextContext.Provider, {
17478
17627
  value: true,
17479
17628
  children: element
@@ -19298,23 +19447,28 @@ function saveSession(ifid, payload) {
19298
19447
  return { error };
19299
19448
  }
19300
19449
  }
19301
- /**
19302
- * The live payload of the stored session, if there is one that loads. A
19303
- * session written by an incompatible version of Spindle is dropped with a
19304
- * warning, and the story starts fresh.
19450
+ /** Capture storage before StoryInit can navigate and write a new session,
19451
+ * but defer revival until its class registrations have run.
19305
19452
  */
19306
- function loadSession(ifid) {
19453
+ function prepareSessionRestore(ifid) {
19454
+ let raw;
19307
19455
  try {
19308
- const raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
19309
- if (!raw) return void 0;
19310
- return decodePayload(JSON.parse(raw));
19311
- } catch (err) {
19312
- if (err instanceof IncompatibleSaveError) {
19313
- console.warn(`spindle: ${err.message}; the session was not restored.`);
19314
- clearSession(ifid);
19315
- }
19316
- return;
19456
+ raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
19457
+ } catch {
19458
+ return () => void 0;
19317
19459
  }
19460
+ return () => {
19461
+ try {
19462
+ if (!raw) return void 0;
19463
+ return decodePayload(JSON.parse(raw));
19464
+ } catch (err) {
19465
+ if (err instanceof IncompatibleSaveError) {
19466
+ console.warn(`spindle: ${err.message}; the session was not restored.`);
19467
+ clearSession(ifid);
19468
+ }
19469
+ return;
19470
+ }
19471
+ };
19318
19472
  }
19319
19473
  function clearSession(ifid) {
19320
19474
  try {
@@ -19517,8 +19671,9 @@ function executeStoryInit() {
19517
19671
  * handlers set synchronously belongs to the start moment, like StoryInit's
19518
19672
  * changes; a restored session keeps the history it recorded.
19519
19673
  */
19520
- function initializeStory(session) {
19674
+ function initializeStory(savedSession) {
19521
19675
  executeStoryInit();
19676
+ let session = typeof savedSession === "function" ? savedSession() : savedSession;
19522
19677
  const missing = session ? missingPassage(useStoryStore.getState().storyData, session) : void 0;
19523
19678
  if (missing !== void 0) {
19524
19679
  console.warn(`spindle: discarding the saved session: the story no longer has the passage "${missing}"`);
@@ -20373,6 +20528,7 @@ function clearAndRestart(get, set, clearing, message) {
20373
20528
  get().restart();
20374
20529
  return reported(cleared, message);
20375
20530
  }
20531
+ var consumedTransition;
20376
20532
  var useStoryStore = create()(storyStore((set, get) => ({
20377
20533
  storyData: null,
20378
20534
  currentPassage: "",
@@ -20417,6 +20573,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20417
20573
  });
20418
20574
  },
20419
20575
  init: (storyData, variableDefaults = {}, transientDefaults = {}) => {
20576
+ consumedTransition = void 0;
20420
20577
  const startPassage = storyData.passagesById.get(storyData.startNode);
20421
20578
  if (!startPassage) throw new Error(`spindle: Start passage (pid=${storyData.startNode}) not found.`);
20422
20579
  const initialVars = startVariables(variableDefaults);
@@ -20783,8 +20940,13 @@ var useStoryStore = create()(storyStore((set, get) => ({
20783
20940
  state.nextTransition = config;
20784
20941
  });
20785
20942
  },
20786
- consumeNextTransition: () => {
20943
+ consumeNextTransition: (navigationId) => {
20944
+ if (navigationId !== void 0 && consumedTransition?.navigationId === navigationId) return consumedTransition.config;
20787
20945
  const current = get().nextTransition;
20946
+ if (navigationId !== void 0) consumedTransition = {
20947
+ navigationId,
20948
+ config: current
20949
+ };
20788
20950
  if (current !== null) set((state) => {
20789
20951
  state.nextTransition = null;
20790
20952
  });
@@ -22058,6 +22220,142 @@ function storyContextElement() {
22058
22220
  }
22059
22221
  return el;
22060
22222
  }
22223
+ // src/observe/svg-instances.ts
22224
+ var frames = /* @__PURE__ */ new WeakMap();
22225
+ var detachedDocuments = /* @__PURE__ */ new WeakMap();
22226
+ /**
22227
+ * Resolve a use instance's styles in an isolated tree. Source computed styles
22228
+ * inherit from the definition's ancestors, whereas SVG instances inherit from
22229
+ * their use host and match selectors within their own shadow tree.
22230
+ */
22231
+ var SvgInstances = class {
22232
+ constructor() {
22233
+ this.hosts = [];
22234
+ this.sources = /* @__PURE__ */ new WeakMap();
22235
+ this.stylesheets = /* @__PURE__ */ new WeakMap();
22236
+ this.remaining = 1e4;
22237
+ }
22238
+ source(element) {
22239
+ return this.sources.get(element) ?? element;
22240
+ }
22241
+ stylesheet(use) {
22242
+ const root = this.source(use).getRootNode();
22243
+ const cached = this.stylesheets.get(root);
22244
+ if (cached !== void 0) return cached;
22245
+ const rules = (sheet) => {
22246
+ try {
22247
+ return [...sheet.cssRules].map((rule) => {
22248
+ if (rule.type === 3) {
22249
+ const imported = rule;
22250
+ if (!imported.styleSheet) return "";
22251
+ const text = rules(imported.styleSheet);
22252
+ let wrapped = imported.media.mediaText ? `@media ${imported.media.mediaText}{${text}}` : text;
22253
+ if (imported.supportsText) wrapped = `@supports (${imported.supportsText}){${wrapped}}`;
22254
+ if (imported.layerName !== null && imported.layerName !== void 0) wrapped = `@layer ${imported.layerName}{${wrapped}}`;
22255
+ return wrapped;
22256
+ }
22257
+ return rule.cssText;
22258
+ }).join("\n");
22259
+ } catch {
22260
+ return "";
22261
+ }
22262
+ };
22263
+ const text = [...root.styleSheets ?? [], ...root.adoptedStyleSheets ?? []].filter((sheet) => !sheet.disabled).map((sheet) => {
22264
+ const text = rules(sheet);
22265
+ return sheet.media.mediaText ? `@media ${sheet.media.mediaText}{${text}}` : text;
22266
+ }).join("\n");
22267
+ this.stylesheets.set(root, text);
22268
+ return text;
22269
+ }
22270
+ expand(use, target) {
22271
+ if (this.remaining <= 0) return;
22272
+ if (!this.document) {
22273
+ const doc = use.ownerDocument;
22274
+ const detached = doc.implementation.createHTMLDocument("");
22275
+ const probe = detached.createElement("div");
22276
+ probe.style.visibility = "hidden";
22277
+ detached.body.appendChild(probe);
22278
+ if ((doc.defaultView ?? globalThis.window)?.getComputedStyle(probe).visibility === "hidden") {
22279
+ probe.remove();
22280
+ let isolated = detachedDocuments.get(doc);
22281
+ if (!isolated) {
22282
+ const view = doc.defaultView ?? globalThis.window;
22283
+ isolated = detached;
22284
+ try {
22285
+ isolated = Reflect.construct(view.Window, [{ settings: {
22286
+ disableJavaScriptEvaluation: true,
22287
+ disableCSSFileLoading: true,
22288
+ disableIframePageLoading: true
22289
+ } }]).document ?? detached;
22290
+ } catch {}
22291
+ detachedDocuments.set(doc, isolated);
22292
+ }
22293
+ this.document = isolated;
22294
+ } else {
22295
+ let frame = frames.get(doc);
22296
+ if (!frame?.isConnected) {
22297
+ frame = doc.createElement("iframe");
22298
+ frame.setAttribute("sandbox", "allow-same-origin");
22299
+ frame.setAttribute("aria-hidden", "true");
22300
+ frame.tabIndex = -1;
22301
+ 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;`;
22302
+ doc.documentElement.insertBefore(frame, doc.body);
22303
+ frames.set(doc, frame);
22304
+ const isolated = frame.contentDocument;
22305
+ if (isolated) {
22306
+ const meta = isolated.createElement("meta");
22307
+ meta.httpEquiv = "Content-Security-Policy";
22308
+ meta.content = "default-src 'none'; style-src 'unsafe-inline'";
22309
+ isolated.head.appendChild(meta);
22310
+ }
22311
+ }
22312
+ this.document = frame.contentDocument ?? void 0;
22313
+ if (!this.document) return;
22314
+ const width = `${doc.defaultView?.innerWidth ?? 1024}px`;
22315
+ const height = `${doc.defaultView?.innerHeight ?? 768}px`;
22316
+ if (frame.style.width !== width) frame.style.setProperty("width", width, "important");
22317
+ if (frame.style.height !== height) frame.style.setProperty("height", height, "important");
22318
+ }
22319
+ }
22320
+ const doc = this.document;
22321
+ const host = doc.createElement("div");
22322
+ const computed = (use.ownerDocument.defaultView ?? globalThis.window)?.getComputedStyle(use);
22323
+ if (computed) {
22324
+ host.style.visibility = computed.visibility || use.style.visibility || use.getAttribute("visibility") || "";
22325
+ host.style.display = computed.display || use.style.display;
22326
+ for (const name of Array.from(computed)) if (name.startsWith("--")) host.style.setProperty(name, computed.getPropertyValue(name));
22327
+ }
22328
+ doc.body.appendChild(host);
22329
+ this.hosts.push(host);
22330
+ const shadow = host.attachShadow({ mode: "open" });
22331
+ const style = doc.createElement("style");
22332
+ style.textContent = this.stylesheet(use);
22333
+ const copy = (node) => {
22334
+ if (--this.remaining < 0) return;
22335
+ let clone;
22336
+ if (node.nodeType === 1) {
22337
+ const element = node;
22338
+ clone = doc.createElementNS(element.namespaceURI, element.localName);
22339
+ for (const attribute of element.attributes) clone.setAttributeNS(attribute.namespaceURI, attribute.name, attribute.value);
22340
+ this.sources.set(clone, this.source(node));
22341
+ } else if (node.nodeType === 3) clone = doc.createTextNode(node.textContent ?? "");
22342
+ else return;
22343
+ for (const child of node.childNodes) {
22344
+ if (this.remaining <= 0) break;
22345
+ const copied = copy(child);
22346
+ if (copied) clone.appendChild(copied);
22347
+ }
22348
+ return clone;
22349
+ };
22350
+ const clone = copy(target);
22351
+ if (clone) shadow.appendChild(clone);
22352
+ shadow.appendChild(style);
22353
+ return clone;
22354
+ }
22355
+ dispose() {
22356
+ for (const host of this.hosts) host.remove();
22357
+ }
22358
+ };
22061
22359
  // src/observe/observable-text.ts
22062
22360
  /** Elements that start and end a line. */
22063
22361
  var BLOCKS = /* @__PURE__ */ new Set([
@@ -22121,11 +22419,28 @@ function observableText(el, skip, visibilityRoot) {
22121
22419
  const endLine = () => {
22122
22420
  if (out !== "" && !out.endsWith("\n")) out += "\n";
22123
22421
  };
22124
- const walk = (node, inPre) => {
22422
+ const references = /* @__PURE__ */ new Set();
22423
+ const instances = new SvgInstances();
22424
+ let instanceNodes = 1e4;
22425
+ const localTarget = (use) => {
22426
+ use = instances.source(use);
22427
+ const href = use.getAttribute("href") ?? use.getAttributeNS("http://www.w3.org/1999/xlink", "href");
22428
+ if (!href?.startsWith("#") || href.length === 1) return;
22429
+ let id;
22430
+ try {
22431
+ id = decodeURIComponent(href.slice(1));
22432
+ } catch {
22433
+ return;
22434
+ }
22435
+ const root = use.getRootNode();
22436
+ return "getElementById" in root ? root.getElementById(id) ?? void 0 : [root, ...root.querySelectorAll("[id]")].find((node) => node.id === id);
22437
+ };
22438
+ const walk = (node, inPre, instanceRoot) => {
22439
+ if (instanceRoot && --instanceNodes < 0) return;
22125
22440
  if (node.nodeType === 3) {
22126
22441
  const parent = node.assignedSlot ?? node.parentElement ?? node.getRootNode().host;
22127
- if (parent && !isRendered(parent, visibilityRoot)) return;
22128
- const data = node.textContent ?? "";
22442
+ if (parent && (hidesContents(parent) || !isRendered(parent, instanceRoot ?? visibilityRoot))) return;
22443
+ const data = revealedText(node);
22129
22444
  if (inPre) out += data;
22130
22445
  else {
22131
22446
  const collapsed = data.replace(/\s+/g, " ");
@@ -22135,27 +22450,43 @@ function observableText(el, skip, visibilityRoot) {
22135
22450
  }
22136
22451
  if (node.nodeType !== 1) return;
22137
22452
  const child = node;
22138
- if (isHidden(child) || skip && child !== el && child.matches(skip)) return;
22453
+ if (isHidden(child, child === instanceRoot) || skip && child !== el && child.matches(skip)) return;
22454
+ if (!isRendered(child, instanceRoot ?? visibilityRoot, false)) return;
22455
+ if (child.namespaceURI === "http://www.w3.org/2000/svg" && child.localName === "use") {
22456
+ if (hidesContents(child) || !isFullyRevealed(child)) return;
22457
+ const target = localTarget(child);
22458
+ if (!target || target.namespaceURI !== child.namespaceURI || references.has(target) || references.size >= 32) return;
22459
+ references.add(target);
22460
+ const instance = instances.expand(child, target);
22461
+ if (instance) walk(instance, inPre, instance);
22462
+ references.delete(target);
22463
+ return;
22464
+ }
22139
22465
  if (child.matches("input, textarea, select") || child.hasAttribute("data-action") && getAction(child.getAttribute("data-action"))?.type === "cycle") {
22140
22466
  if (child.matches("input[type=\"hidden\" i]")) return;
22141
- if (!isRendered(child, visibilityRoot)) return;
22467
+ if (!isRendered(child, instanceRoot ?? visibilityRoot) || !isFullyRevealed(child)) return;
22142
22468
  out += controlMarker(child);
22143
22469
  return;
22144
22470
  }
22145
22471
  if (child.tagName === "BR") {
22146
- if (isRendered(child, visibilityRoot)) out += "\n";
22472
+ if (isRendered(child, instanceRoot ?? visibilityRoot)) out += "\n";
22147
22473
  return;
22148
22474
  }
22149
22475
  const block = BLOCKS.has(child.tagName);
22476
+ if (hidesContents(child)) return;
22150
22477
  if (block) endLine();
22151
22478
  const closedDetails = child.tagName === "DETAILS" && !child.hasAttribute("open");
22152
22479
  const rendered = composedChildNodes(child);
22153
22480
  const children = closedDetails ? rendered.filter((c) => c.nodeType === 1 && !isHidden(c)) : rendered;
22154
- for (const c of children) walk(c, inPre || child.tagName === "PRE");
22481
+ for (const c of children) walk(c, inPre || child.tagName === "PRE", instanceRoot);
22155
22482
  if (child.tagName === "TD" || child.tagName === "TH") out += " ";
22156
22483
  if (block) endLine();
22157
22484
  };
22158
- walk(el, false);
22485
+ try {
22486
+ walk(el, false);
22487
+ } finally {
22488
+ instances.dispose();
22489
+ }
22159
22490
  return out.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\s+$/g, "");
22160
22491
  }
22161
22492
  /**
@@ -22172,7 +22503,7 @@ function observableErrors(el, skip, visibilityRoot) {
22172
22503
  }
22173
22504
  return false;
22174
22505
  };
22175
- return [...composedElements(el)].filter((e) => e.matches(".error") && !left(e) && isRendered(e, visibilityRoot)).map((e) => observableText(e, skip, visibilityRoot).trim());
22506
+ return [...composedElements(el)].filter((e) => e.matches(".error") && !left(e) && isRendered(e, visibilityRoot)).map((e) => observableText(e, skip, visibilityRoot).trim()).filter(Boolean);
22176
22507
  }
22177
22508
  // src/utils/stable-key.ts
22178
22509
  /**
@@ -24643,7 +24974,7 @@ defineMacro({
24643
24974
  const isFirstLoad = !displayedPassage;
24644
24975
  const isReplacement = navigationId === replacementNavigationId;
24645
24976
  if (navigationId === displayed.id) return;
24646
- const next = store.consumeNextTransition();
24977
+ const next = store.consumeNextTransition(navigationId);
24647
24978
  cancelTransition();
24648
24979
  const targetPassage = storyData?.passages.get(currentPassage);
24649
24980
  if (!targetPassage) {
@@ -25610,6 +25941,7 @@ defineMacro({
25610
25941
  children: [/* @__PURE__ */ jsx("span", {
25611
25942
  ref: innerRef,
25612
25943
  class: "macro-type-inner",
25944
+ "data-type-revealed": done ? void 0 : visibleChars,
25613
25945
  style: {
25614
25946
  display: "inline",
25615
25947
  visibility: measured === null ? "hidden" : "visible",
@@ -26818,7 +27150,7 @@ function boot() {
26818
27150
  useStoryStore.getState().init(storyData, defaults, transientDefaults);
26819
27151
  enterRuntimePhase();
26820
27152
  for (const [, passage] of storyData.passages) if (passage.tags.includes("widget")) orStop(() => registerWidgetDefinitions(parseMarkup(passage.content), passage.name), `Passage "${passage.name}": `);
26821
- initializeStory(loadSession(storyData.ifid));
27153
+ initializeStory(prepareSessionRestore(storyData.ifid));
26822
27154
  const markup = [...variableErrors(storyData, schema), ...markupErrors(storyData, (p) => p.name !== "StoryInit")];
26823
27155
  const storyContext = storyData.passages.get("StoryContext");
26824
27156
  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.26",
3
+ "version": "0.64.28",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,5 @@
1
1
  import { isReaderVisible } from './utils/element-visibility';
2
+ import { isFullyRevealed } from './utils/type-reveal';
2
3
  import { readOnlyValue } from './execute-mutation';
3
4
  import { emit } from './event-emitter';
4
5
  import {
@@ -307,7 +308,10 @@ export function isActionVisible(action: StoryAction): boolean {
307
308
  // Older custom actions need not associate a DOM control. Keep those
308
309
  // registrations available; built-ins and associated custom controls are
309
310
  // filtered against the live DOM.
310
- return elements.length === 0 || elements.some(isReaderVisible);
311
+ return (
312
+ elements.length === 0 ||
313
+ elements.some((el) => isReaderVisible(el) && isFullyRevealed(el))
314
+ );
311
315
  }
312
316
 
313
317
  export function clearActions(): void {
@@ -920,9 +920,9 @@ defineMacro({
920
920
  return;
921
921
  }
922
922
 
923
- // One-shot, used up by the first navigation, whatever we do with it
924
- // (not by the initial render, which no navigation caused)
925
- const next = store.consumeNextTransition();
923
+ // Consume once per navigation and share across all displays (including
924
+ // when tags override it). Initial render doesn't consume the one-shot.
925
+ const next = store.consumeNextTransition(navigationId);
926
926
 
927
927
  // Cancel any in-progress transition
928
928
  cancelTransition();
@@ -119,6 +119,7 @@ defineMacro({
119
119
  <span
120
120
  ref={innerRef}
121
121
  class="macro-type-inner"
122
+ data-type-revealed={done ? undefined : visibleChars}
122
123
  style={{
123
124
  display: 'inline',
124
125
  visibility: measured === null ? 'hidden' : 'visible',
package/src/index.tsx CHANGED
@@ -11,7 +11,7 @@ import { resetIdCounters } from './action-registry';
11
11
  import { initializeStory } from './story-init';
12
12
  import { storyContextErrors } from './story-context-passage';
13
13
  import { connectTriggersToStore } from './triggers';
14
- import { loadSession } from './saves/save-manager';
14
+ import { prepareSessionRestore } from './saves/save-manager';
15
15
  import {
16
16
  parseStoryVariables,
17
17
  validatePassages,
@@ -262,7 +262,7 @@ export function boot() {
262
262
 
263
263
  // Run StoryInit, restore the session if the page was refreshed, and fire
264
264
  // storyinit after all state is settled (defaults + StoryInit + session)
265
- initializeStory(loadSession(storyData.ifid));
265
+ initializeStory(prepareSessionRestore(storyData.ifid));
266
266
 
267
267
  // Every other passage's markup, now that StoryInit may have defined macros;
268
268
  // so are the variable references, which macros' parameters decide
@@ -27,6 +27,7 @@ import { isCodeAttribute } from './code-attributes';
27
27
  import { errorMessage } from '../utils/error-message';
28
28
  import { EMPTY_NAMESPACE } from '../utils/namespace';
29
29
  import { authorElement, isHtmlEncoding } from './html-integration';
30
+ import { svgTagName, svgAttributeName } from './svg-names';
30
31
  import { parseMarkup } from './parse';
31
32
  import { useStoryStore } from '../store';
32
33
  import { passageTarget } from '../components/macros/macro-args';
@@ -871,7 +872,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
871
872
  const namespace = tag === 'svg' || tag === 'math' ? tag : parentNamespace;
872
873
  const errors: AttributeError[] = [];
873
874
  const resolved = Object.entries(node.attributes).map(([k, v]): Attribute => [
874
- k,
875
+ namespace === 'svg' ? svgAttributeName(k) : k,
875
876
  resolveAttributeValue(k, v, scope, errors),
876
877
  v,
877
878
  hasInterpolation(v),
@@ -971,7 +972,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
971
972
  );
972
973
  }
973
974
  const element = authorElement(
974
- node.tag,
975
+ namespace === 'svg' ? svgTagName(node.tag) : node.tag,
975
976
  props,
976
977
  children,
977
978
  namespace === 'math',