@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.
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +369 -37
- package/package.json +1 -1
- package/src/action-registry.ts +5 -1
- package/src/components/macros/PassageDisplay.tsx +3 -3
- package/src/components/macros/Type.tsx +1 -0
- package/src/index.tsx +2 -2
- package/src/markup/render.tsx +3 -2
- package/src/markup/svg-names.ts +69 -0
- package/src/observe/observable-text.ts +77 -9
- package/src/observe/svg-instances.ts +210 -0
- package/src/saves/save-manager.ts +25 -9
- package/src/store.ts +16 -2
- package/src/story-init.ts +6 -1
- package/src/utils/element-visibility.ts +110 -11
- package/src/utils/type-reveal.ts +55 -0
|
@@ -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
|
+
}
|
|
@@ -4,8 +4,11 @@ import {
|
|
|
4
4
|
composedParent,
|
|
5
5
|
isHidden,
|
|
6
6
|
isRendered,
|
|
7
|
+
hidesContents,
|
|
7
8
|
} from '../utils/element-visibility';
|
|
9
|
+
import { isFullyRevealed, revealedText } from '../utils/type-reveal';
|
|
8
10
|
import { getAction } from '../action-registry';
|
|
11
|
+
import { SvgInstances } from './svg-instances';
|
|
9
12
|
|
|
10
13
|
/** Elements that start and end a line. */
|
|
11
14
|
const BLOCKS = new Set([
|
|
@@ -102,14 +105,44 @@ export function observableText(
|
|
|
102
105
|
if (out !== '' && !out.endsWith('\n')) out += '\n';
|
|
103
106
|
};
|
|
104
107
|
|
|
105
|
-
|
|
108
|
+
// A use element has no DOM children for its rendered instance tree. Follow
|
|
109
|
+
// local references at that position, never unused definitions or external
|
|
110
|
+
// documents. Bound both depth and total work for cyclic or expanding graphs.
|
|
111
|
+
const references = new Set<Element>();
|
|
112
|
+
const instances = new SvgInstances();
|
|
113
|
+
let instanceNodes = 10_000;
|
|
114
|
+
const localTarget = (use: Element): Element | undefined => {
|
|
115
|
+
use = instances.source(use);
|
|
116
|
+
const href =
|
|
117
|
+
use.getAttribute('href') ??
|
|
118
|
+
use.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
|
|
119
|
+
if (!href?.startsWith('#') || href.length === 1) return;
|
|
120
|
+
let id: string;
|
|
121
|
+
try {
|
|
122
|
+
id = decodeURIComponent(href.slice(1));
|
|
123
|
+
} catch {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const root = use.getRootNode() as Document | ShadowRoot | Element;
|
|
127
|
+
return 'getElementById' in root
|
|
128
|
+
? (root.getElementById(id) ?? undefined)
|
|
129
|
+
: [root, ...root.querySelectorAll('[id]')].find((node) => node.id === id);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const walk = (node: Node, inPre: boolean, instanceRoot?: Element) => {
|
|
133
|
+
if (instanceRoot && --instanceNodes < 0) return;
|
|
106
134
|
if (node.nodeType === 3) {
|
|
107
135
|
const parent =
|
|
108
136
|
(node as Text).assignedSlot ??
|
|
109
137
|
node.parentElement ??
|
|
110
138
|
(node.getRootNode() as ShadowRoot).host;
|
|
111
|
-
if (
|
|
112
|
-
|
|
139
|
+
if (
|
|
140
|
+
parent &&
|
|
141
|
+
(hidesContents(parent) ||
|
|
142
|
+
!isRendered(parent, instanceRoot ?? visibilityRoot))
|
|
143
|
+
)
|
|
144
|
+
return;
|
|
145
|
+
const data = revealedText(node as Text);
|
|
113
146
|
if (inPre) out += data;
|
|
114
147
|
else {
|
|
115
148
|
// Source whitespace between blocks isn't a line of its own
|
|
@@ -121,23 +154,53 @@ export function observableText(
|
|
|
121
154
|
}
|
|
122
155
|
if (node.nodeType !== 1) return;
|
|
123
156
|
const child = node as Element;
|
|
124
|
-
if (
|
|
157
|
+
if (
|
|
158
|
+
isHidden(child, child === instanceRoot) ||
|
|
159
|
+
(skip && child !== el && child.matches(skip))
|
|
160
|
+
)
|
|
125
161
|
return;
|
|
162
|
+
if (!isRendered(child, instanceRoot ?? visibilityRoot, false)) return;
|
|
163
|
+
if (
|
|
164
|
+
child.namespaceURI === 'http://www.w3.org/2000/svg' &&
|
|
165
|
+
child.localName === 'use'
|
|
166
|
+
) {
|
|
167
|
+
// Visibility is inherited by the instance and can be overridden inside
|
|
168
|
+
// it; unlike display:none, it does not hide the entire subtree.
|
|
169
|
+
if (hidesContents(child) || !isFullyRevealed(child)) return;
|
|
170
|
+
const target = localTarget(child);
|
|
171
|
+
if (
|
|
172
|
+
!target ||
|
|
173
|
+
target.namespaceURI !== child.namespaceURI ||
|
|
174
|
+
references.has(target) ||
|
|
175
|
+
references.size >= 32
|
|
176
|
+
)
|
|
177
|
+
return;
|
|
178
|
+
references.add(target);
|
|
179
|
+
const instance = instances.expand(child, target);
|
|
180
|
+
if (instance) walk(instance, inPre, instance);
|
|
181
|
+
references.delete(target);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
126
184
|
if (
|
|
127
185
|
child.matches('input, textarea, select') ||
|
|
128
186
|
(child.hasAttribute('data-action') &&
|
|
129
187
|
getAction(child.getAttribute('data-action')!)?.type === 'cycle')
|
|
130
188
|
) {
|
|
131
189
|
if (child.matches('input[type="hidden" i]')) return;
|
|
132
|
-
if (
|
|
190
|
+
if (
|
|
191
|
+
!isRendered(child, instanceRoot ?? visibilityRoot) ||
|
|
192
|
+
!isFullyRevealed(child)
|
|
193
|
+
)
|
|
194
|
+
return;
|
|
133
195
|
out += controlMarker(child);
|
|
134
196
|
return;
|
|
135
197
|
}
|
|
136
198
|
if (child.tagName === 'BR') {
|
|
137
|
-
if (isRendered(child, visibilityRoot)) out += '\n';
|
|
199
|
+
if (isRendered(child, instanceRoot ?? visibilityRoot)) out += '\n';
|
|
138
200
|
return;
|
|
139
201
|
}
|
|
140
202
|
const block = BLOCKS.has(child.tagName);
|
|
203
|
+
if (hidesContents(child)) return;
|
|
141
204
|
if (block) endLine();
|
|
142
205
|
const closedDetails =
|
|
143
206
|
child.tagName === 'DETAILS' && !child.hasAttribute('open');
|
|
@@ -146,13 +209,17 @@ export function observableText(
|
|
|
146
209
|
? rendered.filter((c) => c.nodeType === 1 && !isHidden(c as Element))
|
|
147
210
|
: rendered;
|
|
148
211
|
for (const c of children) {
|
|
149
|
-
walk(c, inPre || child.tagName === 'PRE');
|
|
212
|
+
walk(c, inPre || child.tagName === 'PRE', instanceRoot);
|
|
150
213
|
}
|
|
151
214
|
if (child.tagName === 'TD' || child.tagName === 'TH') out += '\t';
|
|
152
215
|
if (block) endLine();
|
|
153
216
|
};
|
|
154
217
|
|
|
155
|
-
|
|
218
|
+
try {
|
|
219
|
+
walk(el, false);
|
|
220
|
+
} finally {
|
|
221
|
+
instances.dispose();
|
|
222
|
+
}
|
|
156
223
|
return (
|
|
157
224
|
out
|
|
158
225
|
.split('\n')
|
|
@@ -187,5 +254,6 @@ export function observableErrors(
|
|
|
187
254
|
.filter(
|
|
188
255
|
(e) => e.matches('.error') && !left(e) && isRendered(e, visibilityRoot),
|
|
189
256
|
)
|
|
190
|
-
.map((e) => observableText(e, skip, visibilityRoot).trim())
|
|
257
|
+
.map((e) => observableText(e, skip, visibilityRoot).trim())
|
|
258
|
+
.filter(Boolean);
|
|
191
259
|
}
|
|
@@ -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
|
-
|
|
958
|
-
|
|
959
|
-
return
|
|
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(
|
|
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
|
|
@@ -47,19 +47,70 @@ const SVG_NOT_TEXT = new Set([
|
|
|
47
47
|
'marker',
|
|
48
48
|
]);
|
|
49
49
|
|
|
50
|
+
// DOM shims may omit the native hidden rules. Supply their defaults at zero
|
|
51
|
+
// specificity, before author rules, so the CSS cascade still decides visibility.
|
|
52
|
+
const hiddenDefaults = new WeakSet<Node>();
|
|
53
|
+
const needsHiddenDefaults = new WeakMap<Document, boolean>();
|
|
54
|
+
function ensureHiddenDefaults(el: Element): void {
|
|
55
|
+
if (!el.hasAttribute('hidden')) return;
|
|
56
|
+
const doc = el.ownerDocument;
|
|
57
|
+
const view = doc.defaultView ?? globalThis.window;
|
|
58
|
+
let needed = needsHiddenDefaults.get(doc);
|
|
59
|
+
if (needed === undefined) {
|
|
60
|
+
const detached = doc.implementation.createHTMLDocument('');
|
|
61
|
+
const probe = detached.createElement('div');
|
|
62
|
+
probe.hidden = true;
|
|
63
|
+
detached.body.append(probe);
|
|
64
|
+
// Browsers don't compute styles in documents without a browsing context.
|
|
65
|
+
needed = view?.getComputedStyle(probe).display === 'block';
|
|
66
|
+
needsHiddenDefaults.set(doc, needed);
|
|
67
|
+
}
|
|
68
|
+
const root = el.getRootNode() as Document | ShadowRoot;
|
|
69
|
+
if (!needed || hiddenDefaults.has(root)) return;
|
|
70
|
+
const container = root.nodeType === 9 ? (root as Document).head : root;
|
|
71
|
+
if (root.nodeType !== 9 && !('host' in root)) return;
|
|
72
|
+
const style = doc.createElement('style');
|
|
73
|
+
style.textContent =
|
|
74
|
+
':where([hidden]:not([hidden="until-found" i])){display:none}' +
|
|
75
|
+
':where([hidden="until-found" i]){content-visibility:hidden}';
|
|
76
|
+
container.prepend(style);
|
|
77
|
+
hiddenDefaults.add(root);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Detached/headless DOMs may have no computed value; CSSOM still resolves
|
|
81
|
+
* duplicate inline declarations and priorities correctly.
|
|
82
|
+
*/
|
|
83
|
+
function styleValue(
|
|
84
|
+
el: Element,
|
|
85
|
+
name: 'display' | 'visibility' | 'content-visibility',
|
|
86
|
+
): string {
|
|
87
|
+
ensureHiddenDefaults(el);
|
|
88
|
+
return (
|
|
89
|
+
(el.ownerDocument.defaultView ?? globalThis.window)
|
|
90
|
+
?.getComputedStyle?.(el)
|
|
91
|
+
.getPropertyValue(name) ||
|
|
92
|
+
(el as HTMLElement).style?.getPropertyValue(name) ||
|
|
93
|
+
''
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
50
97
|
/**
|
|
51
98
|
* Whether the element hides its whole subtree, including stylesheet rules.
|
|
52
99
|
* This needs computed styles but no layout, so it also works headlessly.
|
|
100
|
+
* A symbol referenced by SVG use is rendered only as an instance root.
|
|
53
101
|
*/
|
|
54
|
-
export function isHidden(el: Element): boolean {
|
|
102
|
+
export function isHidden(el: Element, svgInstanceRoot = false): boolean {
|
|
103
|
+
const display = styleValue(el, 'display');
|
|
55
104
|
return (
|
|
56
|
-
el.hasAttribute('hidden')
|
|
105
|
+
(el.hasAttribute('hidden') &&
|
|
106
|
+
el.getAttribute('hidden')?.toLowerCase() !== 'until-found' &&
|
|
107
|
+
display === '') ||
|
|
57
108
|
el.getAttribute('aria-hidden') === 'true' ||
|
|
58
|
-
|
|
59
|
-
el.ownerDocument.defaultView?.getComputedStyle(el).display === 'none' ||
|
|
109
|
+
display === 'none' ||
|
|
60
110
|
NOT_TEXT.has(el.localName.toLowerCase()) ||
|
|
61
111
|
(el.namespaceURI === 'http://www.w3.org/2000/svg' &&
|
|
62
|
-
SVG_NOT_TEXT.has(el.localName.toLowerCase())
|
|
112
|
+
SVG_NOT_TEXT.has(el.localName.toLowerCase()) &&
|
|
113
|
+
!(svgInstanceRoot && el.localName.toLowerCase() === 'symbol')) ||
|
|
63
114
|
(el.parentElement?.tagName === 'DETAILS' &&
|
|
64
115
|
!el.parentElement.hasAttribute('open') &&
|
|
65
116
|
el !==
|
|
@@ -69,6 +120,50 @@ export function isHidden(el: Element): boolean {
|
|
|
69
120
|
);
|
|
70
121
|
}
|
|
71
122
|
|
|
123
|
+
// Layout containment cannot apply to these box types. In particular, an
|
|
124
|
+
// ordinary inline span still paints its contents with content-visibility:hidden.
|
|
125
|
+
const NO_LAYOUT_CONTAINMENT = new Set([
|
|
126
|
+
'none',
|
|
127
|
+
'contents',
|
|
128
|
+
'ruby',
|
|
129
|
+
'ruby-base',
|
|
130
|
+
'ruby-text',
|
|
131
|
+
'ruby-base-container',
|
|
132
|
+
'ruby-text-container',
|
|
133
|
+
'table-row',
|
|
134
|
+
'table-row-group',
|
|
135
|
+
'table-header-group',
|
|
136
|
+
'table-footer-group',
|
|
137
|
+
'table-column',
|
|
138
|
+
'table-column-group',
|
|
139
|
+
]);
|
|
140
|
+
|
|
141
|
+
/** content-visibility suppresses contents only in layout containment boxes. */
|
|
142
|
+
export function hidesContents(el: Element): boolean {
|
|
143
|
+
const value = styleValue(el, 'content-visibility');
|
|
144
|
+
const hidden =
|
|
145
|
+
value === 'hidden' ||
|
|
146
|
+
(value === '' &&
|
|
147
|
+
el.getAttribute('hidden')?.toLowerCase() === 'until-found');
|
|
148
|
+
if (!hidden) return false;
|
|
149
|
+
// Some headless DOMs omit the native table-cell and inline display defaults.
|
|
150
|
+
const display =
|
|
151
|
+
styleValue(el, 'display') ||
|
|
152
|
+
(el.localName === 'td' || el.localName === 'th' ? 'table-cell' : 'inline');
|
|
153
|
+
if (NO_LAYOUT_CONTAINMENT.has(display)) return false;
|
|
154
|
+
if (display === 'inline' || display === 'inline list-item') {
|
|
155
|
+
// SVG rendering and native replaced/formatting contexts still suppress
|
|
156
|
+
// their contents even when the computed display is inline.
|
|
157
|
+
return (
|
|
158
|
+
el.namespaceURI === 'http://www.w3.org/2000/svg' ||
|
|
159
|
+
el.matches(
|
|
160
|
+
'img, input, textarea, select, button, fieldset, video, audio, canvas, iframe, embed',
|
|
161
|
+
)
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
|
|
72
167
|
/**
|
|
73
168
|
* Whether `el` is in a closed `<details>`, other than in the summary that
|
|
74
169
|
* toggles it: the browser renders none of that content (#389).
|
|
@@ -95,13 +190,17 @@ function inClosedDetails(el: Element, root?: Element): boolean {
|
|
|
95
190
|
* `<details>`. An optional root bounds ancestor checks, so observations can
|
|
96
191
|
* read StoryContext inside its deliberately hidden host.
|
|
97
192
|
*/
|
|
98
|
-
export function isRendered(
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
193
|
+
export function isRendered(
|
|
194
|
+
el: Element,
|
|
195
|
+
root?: Element,
|
|
196
|
+
checkVisibility = true,
|
|
197
|
+
): boolean {
|
|
198
|
+
const visibility = styleValue(el, 'visibility');
|
|
199
|
+
if (checkVisibility && (visibility === 'hidden' || visibility === 'collapse'))
|
|
200
|
+
return false;
|
|
103
201
|
for (let e: Element | null = el; e; e = composedParent(e)) {
|
|
104
|
-
if (
|
|
202
|
+
if (styleValue(e, 'display') === 'none') return false;
|
|
203
|
+
if (e !== el && hidesContents(e)) return false;
|
|
105
204
|
if (e === root) break;
|
|
106
205
|
const parent = e.parentElement;
|
|
107
206
|
// Connected light DOM may have no place in its host's rendered tree.
|