@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.
@@ -525,16 +525,23 @@ function cloneSnapshotTree(
525
525
  if (custom) clone.setAttribute('data-spindle-snapshot-tag', source.localName);
526
526
  if (svg) clone.setAttribute('data-spindle-snapshot-svg', svgMarker);
527
527
  if (svg) svgState.copies.push({ source, clone: clone as SVGElement, ids });
528
- // A passive radio must not join either a live form's group or another
529
- // snapshot's group. With no name it cannot share checkedness at insertion.
528
+ // An explicit empty form reference prevents both external association and
529
+ // fallback to an ancestor form, including forms inside the snapshot.
530
+ // Inert controls otherwise still submit values and participate in validation.
530
531
  if (
531
532
  html &&
532
- source.localName === 'input' &&
533
- (source as HTMLInputElement).type === 'radio'
534
- ) {
533
+ source.matches('button, fieldset, input, object, output, select, textarea')
534
+ )
535
+ clone.setAttribute('form', '');
536
+ // Passive radios and details must not join live or other snapshot groups.
537
+ // Removing the name preserves their state when either tree is inserted.
538
+ if (
539
+ html &&
540
+ (source.localName === 'details' ||
541
+ (source.localName === 'input' &&
542
+ (source as HTMLInputElement).type === 'radio'))
543
+ )
535
544
  clone.removeAttribute('name');
536
- clone.removeAttribute('form');
537
- }
538
545
  // IDs and the passage class are removed, and custom tags become spans.
539
546
  // Freeze native and custom content before those selectors stop matching.
540
547
  const computed = getComputedStyle(source);
@@ -913,9 +920,9 @@ defineMacro({
913
920
  return;
914
921
  }
915
922
 
916
- // One-shot, used up by the first navigation, whatever we do with it
917
- // (not by the initial render, which no navigation caused)
918
- 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);
919
926
 
920
927
  // Cancel any in-progress transition
921
928
  cancelTransition();
@@ -1,5 +1,6 @@
1
1
  import { createContext } from 'preact';
2
2
  import { useCallback, useContext, useLayoutEffect, useRef } from 'preact/hooks';
3
+ import { h, type ComponentChildren } from 'preact';
3
4
  import {
4
5
  registerAction,
5
6
  generateActionId,
@@ -52,6 +53,20 @@ export function actionAttributes(
52
53
  };
53
54
  }
54
55
 
56
+ /** Render a native macro button with its registered action and label. */
57
+ export function renderActionButton(
58
+ action: ControlAction,
59
+ control: { id?: string; cls?: string },
60
+ onClick: () => void,
61
+ label: ComponentChildren,
62
+ ) {
63
+ return h(
64
+ 'button',
65
+ { type: 'button', ...actionAttributes(action, control), onClick },
66
+ label,
67
+ );
68
+ }
69
+
55
70
  /**
56
71
  * While true, controls rendered underneath do not register actions or reserve
57
72
  * IDs. Used for display-only content mounted off-screen, so it never shows up
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',
@@ -0,0 +1,69 @@
1
+ /** HTML foreign-content name adjustments; unknown foreign names stay intact.
2
+ * https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
3
+ */
4
+ const TAGS = `svg a animate circle defs desc discard ellipse filter g image line
5
+ marker mask metadata mpath path pattern polygon polyline rect script set stop
6
+ style switch symbol text title tspan use view
7
+ altGlyph altGlyphDef altGlyphItem animateColor animateMotion
8
+ animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite
9
+ feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow
10
+ feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode
11
+ feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile
12
+ feTurbulence foreignObject glyphRef linearGradient radialGradient textPath`;
13
+
14
+ const ATTRIBUTES = `id class style lang tabindex role autofocus
15
+ accent-height accumulate additive alignment-baseline alphabetic amplitude
16
+ arabic-form ascent azimuth baseline-shift bbox begin bias by clip
17
+ clip-path clip-rule color color-interpolation color-interpolation-filters
18
+ color-profile color-rendering contentscripttype contentstyletype cursor
19
+ cx cy d decelerate descent direction display divisor dominant-baseline dur dx dy
20
+ elevation enable-background end exponent externalresourcesrequired fill
21
+ fill-opacity fill-rule filter flood-color flood-opacity focusable font-family
22
+ font-size font-size-adjust font-stretch font-style font-variant font-weight
23
+ format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal
24
+ glyph-orientation-vertical hanging height horiz-adv-x horiz-origin-x href
25
+ ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kerning
26
+ letter-spacing lighting-color local marker-end marker-mid marker-start
27
+ mathematical max media method min mode name offset opacity operator order orient
28
+ orientation origin overflow overline-position overline-thickness panose-1
29
+ paint-order pointer-events points r radius rendering-intent restart result
30
+ rotate rx ry scale seed shape-rendering slope spacing speed stemh stemv
31
+ stop-color stop-opacity strikethrough-position strikethrough-thickness string
32
+ stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin
33
+ stroke-miterlimit stroke-opacity stroke-width target text-anchor
34
+ text-decoration text-overflow text-rendering to transform transform-origin type u1 u2
35
+ underline-position underline-thickness unicode unicode-bidi unicode-range
36
+ units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values
37
+ vector-effect version vert-adv-y vert-origin-x vert-origin-y visibility width
38
+ widths word-spacing writing-mode x x-height x1 x2 xlink:actuate xlink:arcrole
39
+ xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space
40
+ xmlns xmlns:xlink y y1 y2 z
41
+ attributeName attributeType baseFrequency baseProfile calcMode
42
+ clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform
43
+ gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes
44
+ lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth
45
+ maskContentUnits maskUnits numOctaves pathLength patternContentUnits
46
+ patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha
47
+ preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur
48
+ requiredExtensions requiredFeatures specularConstant specularExponent
49
+ spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage
50
+ tableValues targetX targetY textLength viewBox viewTarget xChannelSelector
51
+ yChannelSelector zoomAndPan`;
52
+
53
+ function adjustments(names: string): Map<string, string> {
54
+ return new Map(names.split(/\s+/).map((name) => [name.toLowerCase(), name]));
55
+ }
56
+
57
+ const tags = adjustments(TAGS);
58
+ const attributes = adjustments(ATTRIBUTES);
59
+
60
+ export function svgTagName(name: string): string {
61
+ return tags.get(name.toLowerCase()) ?? name;
62
+ }
63
+
64
+ export function svgAttributeName(name: string): string {
65
+ const lower = name.toLowerCase();
66
+ return (
67
+ attributes.get(lower) ?? (/^(?:aria-|data-)/.test(lower) ? lower : name)
68
+ );
69
+ }
@@ -6,6 +6,7 @@ import {
6
6
  isRendered,
7
7
  } from '../utils/element-visibility';
8
8
  import { getAction } from '../action-registry';
9
+ import { SvgInstances } from './svg-instances';
9
10
 
10
11
  /** Elements that start and end a line. */
11
12
  const BLOCKS = new Set([
@@ -102,13 +103,38 @@ export function observableText(
102
103
  if (out !== '' && !out.endsWith('\n')) out += '\n';
103
104
  };
104
105
 
105
- const walk = (node: Node, inPre: boolean) => {
106
+ // A use element has no DOM children for its rendered instance tree. Follow
107
+ // local references at that position, never unused definitions or external
108
+ // documents. Bound both depth and total work for cyclic or expanding graphs.
109
+ const references = new Set<Element>();
110
+ const instances = new SvgInstances();
111
+ let instanceNodes = 10_000;
112
+ const localTarget = (use: Element): Element | undefined => {
113
+ use = instances.source(use);
114
+ const href =
115
+ use.getAttribute('href') ??
116
+ use.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
117
+ if (!href?.startsWith('#') || href.length === 1) return;
118
+ let id: string;
119
+ try {
120
+ id = decodeURIComponent(href.slice(1));
121
+ } catch {
122
+ return;
123
+ }
124
+ const root = use.getRootNode() as Document | ShadowRoot | Element;
125
+ return 'getElementById' in root
126
+ ? (root.getElementById(id) ?? undefined)
127
+ : [root, ...root.querySelectorAll('[id]')].find((node) => node.id === id);
128
+ };
129
+
130
+ const walk = (node: Node, inPre: boolean, instanceRoot?: Element) => {
131
+ if (instanceRoot && --instanceNodes < 0) return;
106
132
  if (node.nodeType === 3) {
107
133
  const parent =
108
134
  (node as Text).assignedSlot ??
109
135
  node.parentElement ??
110
136
  (node.getRootNode() as ShadowRoot).host;
111
- if (parent && !isRendered(parent, visibilityRoot)) return;
137
+ if (parent && !isRendered(parent, instanceRoot ?? visibilityRoot)) return;
112
138
  const data = node.textContent ?? '';
113
139
  if (inPre) out += data;
114
140
  else {
@@ -121,20 +147,44 @@ export function observableText(
121
147
  }
122
148
  if (node.nodeType !== 1) return;
123
149
  const child = node as Element;
124
- if (isHidden(child) || (skip && child !== el && child.matches(skip)))
150
+ if (
151
+ isHidden(child, child === instanceRoot) ||
152
+ (skip && child !== el && child.matches(skip))
153
+ )
125
154
  return;
155
+ if (
156
+ child.namespaceURI === 'http://www.w3.org/2000/svg' &&
157
+ child.localName === 'use'
158
+ ) {
159
+ // Visibility is inherited by the instance and can be overridden inside
160
+ // it; unlike display:none, it does not hide the entire subtree.
161
+ if (!isRendered(child, instanceRoot ?? visibilityRoot, false)) return;
162
+ const target = localTarget(child);
163
+ if (
164
+ !target ||
165
+ target.namespaceURI !== child.namespaceURI ||
166
+ references.has(target) ||
167
+ references.size >= 32
168
+ )
169
+ return;
170
+ references.add(target);
171
+ const instance = instances.expand(child, target);
172
+ if (instance) walk(instance, inPre, instance);
173
+ references.delete(target);
174
+ return;
175
+ }
126
176
  if (
127
177
  child.matches('input, textarea, select') ||
128
178
  (child.hasAttribute('data-action') &&
129
179
  getAction(child.getAttribute('data-action')!)?.type === 'cycle')
130
180
  ) {
131
181
  if (child.matches('input[type="hidden" i]')) return;
132
- if (!isRendered(child, visibilityRoot)) return;
182
+ if (!isRendered(child, instanceRoot ?? visibilityRoot)) return;
133
183
  out += controlMarker(child);
134
184
  return;
135
185
  }
136
186
  if (child.tagName === 'BR') {
137
- if (isRendered(child, visibilityRoot)) out += '\n';
187
+ if (isRendered(child, instanceRoot ?? visibilityRoot)) out += '\n';
138
188
  return;
139
189
  }
140
190
  const block = BLOCKS.has(child.tagName);
@@ -146,13 +196,17 @@ export function observableText(
146
196
  ? rendered.filter((c) => c.nodeType === 1 && !isHidden(c as Element))
147
197
  : rendered;
148
198
  for (const c of children) {
149
- walk(c, inPre || child.tagName === 'PRE');
199
+ walk(c, inPre || child.tagName === 'PRE', instanceRoot);
150
200
  }
151
201
  if (child.tagName === 'TD' || child.tagName === 'TH') out += '\t';
152
202
  if (block) endLine();
153
203
  };
154
204
 
155
- walk(el, false);
205
+ try {
206
+ walk(el, false);
207
+ } finally {
208
+ instances.dispose();
209
+ }
156
210
  return (
157
211
  out
158
212
  .split('\n')
@@ -0,0 +1,210 @@
1
+ // Keep the isolated browsing context across observations. Repeatedly inserting
2
+ // and removing it would retrigger author MutationObservers that call observe().
3
+ const frames = new WeakMap<Document, HTMLIFrameElement>();
4
+ const detachedDocuments = new WeakMap<Document, Document>();
5
+
6
+ /**
7
+ * Resolve a use instance's styles in an isolated tree. Source computed styles
8
+ * inherit from the definition's ancestors, whereas SVG instances inherit from
9
+ * their use host and match selectors within their own shadow tree.
10
+ */
11
+ export class SvgInstances {
12
+ private document?: Document;
13
+ private hosts: Element[] = [];
14
+ private sources = new WeakMap<Element, Element>();
15
+ private stylesheets = new WeakMap<Node, string>();
16
+ private remaining = 10_000;
17
+
18
+ source(element: Element): Element {
19
+ return this.sources.get(element) ?? element;
20
+ }
21
+
22
+ private stylesheet(use: Element): string {
23
+ const root = this.source(use).getRootNode() as Document | ShadowRoot;
24
+ const cached = this.stylesheets.get(root);
25
+ if (cached !== undefined) return cached;
26
+ const rules = (sheet: CSSStyleSheet): string => {
27
+ try {
28
+ return [...sheet.cssRules]
29
+ .map((rule) => {
30
+ if (rule.type === 3) {
31
+ const imported = rule as CSSImportRule;
32
+ if (!imported.styleSheet) return '';
33
+ const text = rules(imported.styleSheet);
34
+ let wrapped = imported.media.mediaText
35
+ ? `@media ${imported.media.mediaText}{${text}}`
36
+ : text;
37
+ if (imported.supportsText) {
38
+ wrapped = `@supports (${imported.supportsText}){${wrapped}}`;
39
+ }
40
+ if (
41
+ imported.layerName !== null &&
42
+ imported.layerName !== undefined
43
+ ) {
44
+ wrapped = `@layer ${imported.layerName}{${wrapped}}`;
45
+ }
46
+ return wrapped;
47
+ }
48
+ return rule.cssText;
49
+ })
50
+ .join('\n');
51
+ } catch {
52
+ // As elsewhere in headless observations, inaccessible external CSS
53
+ // cannot be inspected. Inline styles and presentation attributes work.
54
+ return '';
55
+ }
56
+ };
57
+ const text = [
58
+ ...(root.styleSheets ?? []),
59
+ ...(root.adoptedStyleSheets ?? []),
60
+ ]
61
+ .filter((sheet) => !sheet.disabled)
62
+ .map((sheet) => {
63
+ const text = rules(sheet);
64
+ return sheet.media.mediaText
65
+ ? `@media ${sheet.media.mediaText}{${text}}`
66
+ : text;
67
+ })
68
+ .join('\n');
69
+ this.stylesheets.set(root, text);
70
+ return text;
71
+ }
72
+
73
+ expand(use: Element, target: Element): Element | undefined {
74
+ if (this.remaining <= 0) return;
75
+ if (!this.document) {
76
+ const doc = use.ownerDocument;
77
+ const detached = doc.implementation.createHTMLDocument('');
78
+ const probe = detached.createElement('div');
79
+ probe.style.visibility = 'hidden';
80
+ detached.body.appendChild(probe);
81
+ // DOMs without layout can resolve styles in a detached document. Avoid
82
+ // creating a browsing context there (headless hosts disable iframes).
83
+ if (
84
+ (doc.defaultView ?? globalThis.window)?.getComputedStyle(probe)
85
+ .visibility === 'hidden'
86
+ ) {
87
+ probe.remove();
88
+ let isolated = detachedDocuments.get(doc);
89
+ if (!isolated) {
90
+ // Headless DOM constructors provide an independent custom-element
91
+ // registry. createHTMLDocument alone still shares the author's one.
92
+ const view = doc.defaultView ?? globalThis.window;
93
+ isolated = detached;
94
+ try {
95
+ const context = Reflect.construct((view as typeof window).Window, [
96
+ {
97
+ settings: {
98
+ disableJavaScriptEvaluation: true,
99
+ disableCSSFileLoading: true,
100
+ disableIframePageLoading: true,
101
+ },
102
+ },
103
+ ]) as Window;
104
+ isolated = context.document ?? detached;
105
+ } catch {
106
+ // Other DOMs (including jsdom) expose a nonconstructible Window;
107
+ // their inert documents already have an isolated element registry.
108
+ }
109
+ detachedDocuments.set(doc, isolated);
110
+ }
111
+ this.document = isolated;
112
+ } else {
113
+ let frame = frames.get(doc);
114
+ if (!frame?.isConnected) {
115
+ frame = doc.createElement('iframe');
116
+ // A separate registry avoids running author custom-element constructors;
117
+ // sandboxing and CSP also prevent cloned content from executing scripts
118
+ // or fetching resources. Nothing in the author's source tree is changed.
119
+ frame.setAttribute('sandbox', 'allow-same-origin');
120
+ frame.setAttribute('aria-hidden', 'true');
121
+ frame.tabIndex = -1;
122
+ frame.style.cssText =
123
+ 'all:initial!important;display:block!important;position:fixed!important;' +
124
+ 'left:-100000px!important;top:0!important;' +
125
+ 'visibility:hidden!important;pointer-events:none!important;border:0!important;' +
126
+ `width:${doc.defaultView?.innerWidth ?? 1024}px!important;` +
127
+ `height:${doc.defaultView?.innerHeight ?? 768}px!important;`;
128
+ doc.documentElement.insertBefore(frame, doc.body);
129
+ frames.set(doc, frame);
130
+ const isolated = frame.contentDocument;
131
+ if (isolated) {
132
+ const meta = isolated.createElement('meta');
133
+ meta.httpEquiv = 'Content-Security-Policy';
134
+ meta.content = "default-src 'none'; style-src 'unsafe-inline'";
135
+ isolated.head.appendChild(meta);
136
+ }
137
+ }
138
+ this.document = frame.contentDocument ?? undefined;
139
+ if (!this.document) return;
140
+ // Only write changed dimensions, so observing from a MutationObserver
141
+ // does not create another mutation on every call.
142
+ const width = `${doc.defaultView?.innerWidth ?? 1024}px`;
143
+ const height = `${doc.defaultView?.innerHeight ?? 768}px`;
144
+ if (frame.style.width !== width)
145
+ frame.style.setProperty('width', width, 'important');
146
+ if (frame.style.height !== height)
147
+ frame.style.setProperty('height', height, 'important');
148
+ }
149
+ }
150
+ const doc = this.document;
151
+ const host = doc.createElement('div');
152
+ const computed = (
153
+ use.ownerDocument.defaultView ?? globalThis.window
154
+ )?.getComputedStyle(use);
155
+ // Custom properties can drive visibility/display in the referenced tree.
156
+ if (computed) {
157
+ host.style.visibility =
158
+ computed.visibility ||
159
+ (use as SVGElement).style.visibility ||
160
+ use.getAttribute('visibility') ||
161
+ '';
162
+ host.style.display =
163
+ computed.display || (use as SVGElement).style.display;
164
+ for (const name of Array.from(computed)) {
165
+ if (name.startsWith('--')) {
166
+ host.style.setProperty(name, computed.getPropertyValue(name));
167
+ }
168
+ }
169
+ }
170
+ doc.body.appendChild(host);
171
+ this.hosts.push(host);
172
+ const shadow = host.attachShadow({ mode: 'open' });
173
+ const style = doc.createElement('style');
174
+ style.textContent = this.stylesheet(use);
175
+ const copy = (node: Node): Node | undefined => {
176
+ if (--this.remaining < 0) return;
177
+ let clone: Node;
178
+ if (node.nodeType === 1) {
179
+ const element = node as Element;
180
+ clone = doc.createElementNS(element.namespaceURI, element.localName);
181
+ for (const attribute of element.attributes) {
182
+ (clone as Element).setAttributeNS(
183
+ attribute.namespaceURI,
184
+ attribute.name,
185
+ attribute.value,
186
+ );
187
+ }
188
+ this.sources.set(clone as Element, this.source(node as Element));
189
+ } else if (node.nodeType === 3) {
190
+ clone = doc.createTextNode(node.textContent ?? '');
191
+ } else {
192
+ return;
193
+ }
194
+ for (const child of node.childNodes) {
195
+ if (this.remaining <= 0) break;
196
+ const copied = copy(child);
197
+ if (copied) clone.appendChild(copied);
198
+ }
199
+ return clone;
200
+ };
201
+ const clone = copy(target) as Element | undefined;
202
+ if (clone) shadow.appendChild(clone);
203
+ shadow.appendChild(style);
204
+ return clone;
205
+ }
206
+
207
+ dispose(): void {
208
+ for (const host of this.hosts) host.remove();
209
+ }
210
+ }
@@ -953,17 +953,33 @@ export function saveSession(
953
953
  * warning, and the story starts fresh.
954
954
  */
955
955
  export function loadSession(ifid: string): SavePayload | undefined {
956
+ return prepareSessionRestore(ifid)();
957
+ }
958
+
959
+ /** Capture storage before StoryInit can navigate and write a new session,
960
+ * but defer revival until its class registrations have run.
961
+ */
962
+ export function prepareSessionRestore(
963
+ ifid: string,
964
+ ): () => SavePayload | undefined {
965
+ let raw: string | null;
956
966
  try {
957
- const raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
958
- if (!raw) return undefined;
959
- return decodePayload(JSON.parse(raw));
960
- } catch (err) {
961
- if (err instanceof IncompatibleSaveError) {
962
- console.warn(`spindle: ${err.message}; the session was not restored.`);
963
- clearSession(ifid);
964
- }
965
- return undefined;
967
+ raw = sessionStorage.getItem(`${SESSION_KEY_PREFIX}${ifid}`);
968
+ } catch {
969
+ return () => undefined;
966
970
  }
971
+ return () => {
972
+ try {
973
+ if (!raw) return undefined;
974
+ return decodePayload(JSON.parse(raw));
975
+ } catch (err) {
976
+ if (err instanceof IncompatibleSaveError) {
977
+ console.warn(`spindle: ${err.message}; the session was not restored.`);
978
+ clearSession(ifid);
979
+ }
980
+ return undefined;
981
+ }
982
+ };
967
983
  }
968
984
 
969
985
  export function clearSession(ifid: string): void {
package/src/store.ts CHANGED
@@ -1197,7 +1197,7 @@ export interface StoryState {
1197
1197
  getHistoryVariables: (index: number) => Record<string, unknown>;
1198
1198
  setTransition: (config: TransitionConfig | null) => void;
1199
1199
  setNextTransition: (config: TransitionConfig | null) => void;
1200
- consumeNextTransition: () => TransitionConfig | null;
1200
+ consumeNextTransition: (navigationId?: number) => TransitionConfig | null;
1201
1201
  deferRender: () => void;
1202
1202
  clearDeferredRender: () => void;
1203
1203
  }
@@ -1398,6 +1398,10 @@ function clearAndRestart(
1398
1398
  return reported(cleared, message);
1399
1399
  }
1400
1400
 
1401
+ // All mounted passage displays share the override consumed for a navigation.
1402
+ let consumedTransition:
1403
+ { navigationId: number; config: TransitionConfig | null } | undefined;
1404
+
1401
1405
  export const useStoryStore = create<StoryState>()(
1402
1406
  storyStore((set, get) => ({
1403
1407
  storyData: null,
@@ -1452,6 +1456,7 @@ export const useStoryStore = create<StoryState>()(
1452
1456
  variableDefaults: Record<string, unknown> = {},
1453
1457
  transientDefaults: Record<string, unknown> = {},
1454
1458
  ) => {
1459
+ consumedTransition = undefined;
1455
1460
  const startPassage = storyData.passagesById.get(storyData.startNode);
1456
1461
  if (!startPassage) {
1457
1462
  throw new Error(
@@ -2109,8 +2114,17 @@ export const useStoryStore = create<StoryState>()(
2109
2114
  });
2110
2115
  },
2111
2116
 
2112
- consumeNextTransition: (): TransitionConfig | null => {
2117
+ consumeNextTransition: (navigationId): TransitionConfig | null => {
2118
+ if (
2119
+ navigationId !== undefined &&
2120
+ consumedTransition?.navigationId === navigationId
2121
+ ) {
2122
+ return consumedTransition.config;
2123
+ }
2113
2124
  const current = get().nextTransition;
2125
+ if (navigationId !== undefined) {
2126
+ consumedTransition = { navigationId, config: current };
2127
+ }
2114
2128
  if (current !== null) {
2115
2129
  set((state) => {
2116
2130
  state.nextTransition = null;
package/src/story-init.ts CHANGED
@@ -84,8 +84,13 @@ export function executeStoryInit() {
84
84
  * handlers set synchronously belongs to the start moment, like StoryInit's
85
85
  * changes; a restored session keeps the history it recorded.
86
86
  */
87
- export function initializeStory(session?: SavePayload): void {
87
+ export function initializeStory(
88
+ savedSession?: SavePayload | (() => SavePayload | undefined),
89
+ ): void {
88
90
  executeStoryInit();
91
+ // StoryInit can register the classes needed to revive saved variables.
92
+ let session =
93
+ typeof savedSession === 'function' ? savedSession() : savedSession;
89
94
 
90
95
  // A session that refers to a passage the story no longer has (it was
91
96
  // updated since) is dropped: the game starts from the beginning