@rohal12/spindle 0.61.5 → 0.61.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +178 -48
- package/dist/pkg/story-variables.js +62 -40
- package/package.json +1 -1
- package/src/code-check.ts +16 -13
- package/src/components/macros/Computed.tsx +7 -1
- package/src/components/macros/For.tsx +33 -4
- package/src/components/macros/PassageDisplay.tsx +172 -35
- package/src/format/format-passage.ts +23 -10
- package/src/format/placeholders.ts +48 -30
- package/src/hooks/use-story-fields.ts +9 -0
- package/src/index.tsx +8 -3
- package/src/store.ts +24 -11
- package/src/story-api.ts +1 -2
- package/src/tooling.ts +7 -5
- package/src/utils/object-path.ts +12 -1
package/src/code-check.ts
CHANGED
|
@@ -334,15 +334,19 @@ export function* codeAndText(
|
|
|
334
334
|
tokens: readonly Token[],
|
|
335
335
|
parametersOf: ParametersOf,
|
|
336
336
|
): Generator<Piece> {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
337
|
+
// Only a plain-text body is read here: raw JavaScript in {do}, or a
|
|
338
|
+
// passage name in {dialog}. Start at the opener and stop at any markup,
|
|
339
|
+
// including a nested opener, rather than rescanning the token prefix.
|
|
340
|
+
const closeOfTextBody = (t: number, name: string): number => {
|
|
341
|
+
for (let k = t + 1; k < tokens.length; k++) {
|
|
342
|
+
const c = tokens[k]!;
|
|
343
|
+
if (c.type === 'text') continue;
|
|
344
|
+
return c.type === 'macro' && c.isClose && c.name.toLowerCase() === name
|
|
345
|
+
? k
|
|
346
|
+
: -1;
|
|
347
|
+
}
|
|
348
|
+
return -1;
|
|
349
|
+
};
|
|
346
350
|
for (let t = 0; t < tokens.length; t++) {
|
|
347
351
|
const token = tokens[t]!;
|
|
348
352
|
if (token.type === 'link') {
|
|
@@ -393,7 +397,7 @@ export function* codeAndText(
|
|
|
393
397
|
} else if (token.type === 'macro' && !token.isClose) {
|
|
394
398
|
const name = token.name.toLowerCase();
|
|
395
399
|
if (name === 'do') {
|
|
396
|
-
const close =
|
|
400
|
+
const close = closeOfTextBody(t, name);
|
|
397
401
|
if (close < 0) continue;
|
|
398
402
|
const body = src.slice(token.end, tokens[close]!.start);
|
|
399
403
|
yield {
|
|
@@ -409,9 +413,8 @@ export function* codeAndText(
|
|
|
409
413
|
const args = token.rawArgs;
|
|
410
414
|
if (PASSAGE_BODIES.has(name)) {
|
|
411
415
|
// The body names the passage when it is only text
|
|
412
|
-
const close =
|
|
413
|
-
|
|
414
|
-
if (close > t + 1 && body.every((b) => b.type === 'text')) {
|
|
416
|
+
const close = closeOfTextBody(t, name);
|
|
417
|
+
if (close > t + 1) {
|
|
415
418
|
const text = src.slice(token.end, tokens[close]!.start);
|
|
416
419
|
const written = text.trim();
|
|
417
420
|
yield {
|
|
@@ -6,6 +6,7 @@ import { defineMacro } from '../../define-macro';
|
|
|
6
6
|
import { MacroError, logMacroError } from './MacroError';
|
|
7
7
|
import { currentSourceLocation } from '../../utils/source-location';
|
|
8
8
|
import { checkVariableName, ownValue } from '../../utils/namespace';
|
|
9
|
+
import { PendingIterationContext } from '../../hooks/use-story-fields';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* The previous output before the first successful evaluation. Distinct from
|
|
@@ -126,6 +127,7 @@ defineMacro({
|
|
|
126
127
|
const isTemp = target.startsWith('_');
|
|
127
128
|
const name = target.slice(1);
|
|
128
129
|
const localsUpdate = isLocal ? ctx.update : null;
|
|
130
|
+
const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
|
|
129
131
|
|
|
130
132
|
const prevOutput = ctx.hooks.useRef<unknown>(UNSET);
|
|
131
133
|
// The navigation the target was last checked in
|
|
@@ -153,7 +155,11 @@ defineMacro({
|
|
|
153
155
|
// The merged values only decide when to recompute; computeAndApply reads
|
|
154
156
|
// the current ones. The tuple is renewed with them and with the render
|
|
155
157
|
// counts, which rendered() / hasRendered() read.
|
|
156
|
-
ctx.hooks.useLayoutEffect(
|
|
158
|
+
ctx.hooks.useLayoutEffect(() => {
|
|
159
|
+
// A queued effect can outlive the loop state its locals belong to.
|
|
160
|
+
// Let the owner reconcile first, dropping any removed iterations.
|
|
161
|
+
if (!pendingIteration?.(useStoryStore.getState())) compute();
|
|
162
|
+
}, [ctx.merged, pendingIteration]);
|
|
157
163
|
|
|
158
164
|
return null;
|
|
159
165
|
},
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useMemo } from 'preact/hooks';
|
|
1
|
+
import { useContext, useMemo } from 'preact/hooks';
|
|
2
2
|
import { defineMacro } from '../../define-macro';
|
|
3
3
|
import { MacroError } from './MacroError';
|
|
4
4
|
import { stableKey } from '../../utils/stable-key';
|
|
@@ -11,6 +11,11 @@ import type { ASTNode } from '../../markup/ast';
|
|
|
11
11
|
import { checkVariableName } from '../../utils/namespace';
|
|
12
12
|
import { readState } from '../../execute-mutation';
|
|
13
13
|
import { LocalsScope } from './locals-scope';
|
|
14
|
+
import {
|
|
15
|
+
FrozenStateContext,
|
|
16
|
+
PendingIterationContext,
|
|
17
|
+
} from '../../hooks/use-story-fields';
|
|
18
|
+
import type { StoryState } from '../../store';
|
|
14
19
|
|
|
15
20
|
/**
|
|
16
21
|
* Check the arguments of "@item, @i of $list" or "@item of $list".
|
|
@@ -97,6 +102,26 @@ defineMacro({
|
|
|
97
102
|
{ name: 'list', type: 'expression', required: true },
|
|
98
103
|
],
|
|
99
104
|
render({ rawArgs, children = [] }, ctx) {
|
|
105
|
+
const enclosingFreeze = useContext(FrozenStateContext);
|
|
106
|
+
const enclosingPending = useContext(PendingIterationContext);
|
|
107
|
+
const [variables, temporary, , transient] = ctx.merged!;
|
|
108
|
+
// Until this loop reconciles its rows, descendants still have the old
|
|
109
|
+
// @item/@i. Keep them from independently reacting to newer namespaces.
|
|
110
|
+
const pending = useMemo(
|
|
111
|
+
() => (state: StoryState) =>
|
|
112
|
+
!!enclosingPending?.(state) ||
|
|
113
|
+
// A detached owner keeps its snapshot permanently: there is no
|
|
114
|
+
// pending reconciliation for its initial effects to wait for.
|
|
115
|
+
((state.variables !== variables ||
|
|
116
|
+
state.temporary !== temporary ||
|
|
117
|
+
state.transient !== transient) &&
|
|
118
|
+
!enclosingFreeze?.(state)),
|
|
119
|
+
[enclosingPending, enclosingFreeze, variables, temporary, transient],
|
|
120
|
+
);
|
|
121
|
+
const freeze = useMemo(
|
|
122
|
+
() => (state: StoryState) => !!enclosingFreeze?.(state) || pending(state),
|
|
123
|
+
[enclosingFreeze, pending],
|
|
124
|
+
);
|
|
100
125
|
const keys = ctx.hooks.useRef<IterationKeys>({
|
|
101
126
|
contents: [],
|
|
102
127
|
generations: [],
|
|
@@ -158,9 +183,13 @@ defineMacro({
|
|
|
158
183
|
));
|
|
159
184
|
|
|
160
185
|
return ctx.wrap(
|
|
161
|
-
<
|
|
162
|
-
{
|
|
163
|
-
|
|
186
|
+
<FrozenStateContext.Provider value={freeze}>
|
|
187
|
+
<PendingIterationContext.Provider value={pending}>
|
|
188
|
+
<ItemEditContext.Provider value={true}>
|
|
189
|
+
{content}
|
|
190
|
+
</ItemEditContext.Provider>
|
|
191
|
+
</PendingIterationContext.Provider>
|
|
192
|
+
</FrozenStateContext.Provider>,
|
|
164
193
|
);
|
|
165
194
|
},
|
|
166
195
|
text({ rawArgs, children = [] }, ctx) {
|
|
@@ -35,7 +35,7 @@ const VALUELESS_INPUTS = new Set([
|
|
|
35
35
|
* elements pair up by position. Best effort: a canvas or video that can not
|
|
36
36
|
* be drawn from stays as cloned.
|
|
37
37
|
*/
|
|
38
|
-
function copyLiveState(source:
|
|
38
|
+
function copyLiveState(source: ParentNode, clone: ParentNode): void {
|
|
39
39
|
const pairs = <T extends Element>(
|
|
40
40
|
selector: string,
|
|
41
41
|
each: (a: T, b: T) => void,
|
|
@@ -76,6 +76,7 @@ function copyLiveState(source: Element, clone: Element): void {
|
|
|
76
76
|
const input = to as HTMLInputElement;
|
|
77
77
|
input.checked = from.checked;
|
|
78
78
|
input.indeterminate = from.indeterminate;
|
|
79
|
+
if (from.type === 'file') input.files = from.files;
|
|
79
80
|
if (!VALUELESS_INPUTS.has(from.type)) input.value = from.value;
|
|
80
81
|
} else {
|
|
81
82
|
to.value = from.value;
|
|
@@ -120,19 +121,29 @@ type ScrollOffset = [element: Element, top: number, left: number];
|
|
|
120
121
|
* scrolled, keyed by the matching element of `clone`. Applied once the clone
|
|
121
122
|
* is in the page: a detached element has nothing to scroll.
|
|
122
123
|
*/
|
|
123
|
-
function scrollOffsets(source:
|
|
124
|
-
const from = [
|
|
125
|
-
|
|
124
|
+
function scrollOffsets(source: ParentNode, clone: ParentNode): ScrollOffset[] {
|
|
125
|
+
const from = [
|
|
126
|
+
...(source instanceof Element ? [source] : []),
|
|
127
|
+
...source.querySelectorAll('*'),
|
|
128
|
+
];
|
|
129
|
+
const to = [
|
|
130
|
+
...(clone instanceof Element ? [clone] : []),
|
|
131
|
+
...clone.querySelectorAll('*'),
|
|
132
|
+
];
|
|
126
133
|
const offsets: ScrollOffset[] = [];
|
|
127
134
|
from.forEach((el, i) => {
|
|
128
135
|
if (to[i] && (el.scrollTop || el.scrollLeft)) {
|
|
129
136
|
offsets.push([to[i]!, el.scrollTop, el.scrollLeft]);
|
|
130
137
|
}
|
|
138
|
+
if (el.shadowRoot && to[i]?.shadowRoot) {
|
|
139
|
+
offsets.push(...scrollOffsets(el.shadowRoot, to[i]!.shadowRoot!));
|
|
140
|
+
}
|
|
131
141
|
});
|
|
132
142
|
return offsets;
|
|
133
143
|
}
|
|
134
144
|
|
|
135
145
|
const pendingScrolls = new WeakMap<Element, ScrollOffset[]>();
|
|
146
|
+
const snapshotStyleCleanup = new WeakMap<Element, () => void>();
|
|
136
147
|
|
|
137
148
|
/** Add `snapshot` to `container`, scrolled as what it shows was. */
|
|
138
149
|
function appendSnapshot(container: Element, snapshot: HTMLElement): void {
|
|
@@ -144,6 +155,143 @@ function appendSnapshot(container: Element, snapshot: HTMLElement): void {
|
|
|
144
155
|
pendingScrolls.delete(snapshot);
|
|
145
156
|
}
|
|
146
157
|
|
|
158
|
+
function copyComputedStyle(
|
|
159
|
+
style: CSSStyleDeclaration,
|
|
160
|
+
target: CSSStyleDeclaration,
|
|
161
|
+
): void {
|
|
162
|
+
for (let i = 0; i < style.length; i++) {
|
|
163
|
+
const name = style[i]!;
|
|
164
|
+
target.setProperty(name, style.getPropertyValue(name));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function installSnapshotStyles(
|
|
169
|
+
root: Document | ShadowRoot,
|
|
170
|
+
rules: string[],
|
|
171
|
+
): (() => void) | undefined {
|
|
172
|
+
if (!rules.length) return;
|
|
173
|
+
// A style element would change :last-child and other structural selectors.
|
|
174
|
+
const sheet = new CSSStyleSheet();
|
|
175
|
+
sheet.replaceSync(rules.join('\n'));
|
|
176
|
+
root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
|
|
177
|
+
return () => {
|
|
178
|
+
root.adoptedStyleSheets = root.adoptedStyleSheets.filter(
|
|
179
|
+
(current) => current !== sheet,
|
|
180
|
+
);
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
let snapshotPseudoId = 0;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Build a visual tree without cloning upgraded custom elements: cloneNode
|
|
188
|
+
* runs their constructors, and insertion runs their connection callbacks.
|
|
189
|
+
* Autonomous elements become styled spans; customized built-ins are created
|
|
190
|
+
* as ordinary native elements, without an `is` option (even if the original
|
|
191
|
+
* has since removed its `is` attribute).
|
|
192
|
+
*/
|
|
193
|
+
function cloneSnapshotTree(
|
|
194
|
+
source: Element,
|
|
195
|
+
freezeStyles = false,
|
|
196
|
+
pseudoRules: string[] = [],
|
|
197
|
+
): Element {
|
|
198
|
+
const html = source.namespaceURI === 'http://www.w3.org/1999/xhtml';
|
|
199
|
+
const custom = html && source.localName.includes('-');
|
|
200
|
+
freezeStyles ||= custom || source.hasAttribute('is');
|
|
201
|
+
const clone = document.createElementNS(
|
|
202
|
+
source.namespaceURI,
|
|
203
|
+
custom ? 'span' : source.localName,
|
|
204
|
+
);
|
|
205
|
+
for (const attr of [...source.attributes]) {
|
|
206
|
+
if (
|
|
207
|
+
attr.name === 'id' ||
|
|
208
|
+
attr.name === 'data-action' ||
|
|
209
|
+
attr.name === 'is' ||
|
|
210
|
+
attr.name.toLowerCase().startsWith('on')
|
|
211
|
+
)
|
|
212
|
+
continue;
|
|
213
|
+
if (attr.namespaceURI)
|
|
214
|
+
clone.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
|
|
215
|
+
else clone.setAttribute(attr.name, attr.value);
|
|
216
|
+
}
|
|
217
|
+
if (freezeStyles) {
|
|
218
|
+
// Tag-name selectors no longer match the stand-in or its descendants.
|
|
219
|
+
// Keep the component subtree's current appearance through computed CSS.
|
|
220
|
+
copyComputedStyle(getComputedStyle(source), (clone as HTMLElement).style);
|
|
221
|
+
// Generated content needs CSS rules in the same document or shadow root.
|
|
222
|
+
// A unique selector keeps simultaneous snapshots from styling each other.
|
|
223
|
+
let id: string | undefined;
|
|
224
|
+
for (const pseudo of ['::before', '::after', '::marker']) {
|
|
225
|
+
const style = getComputedStyle(source, pseudo);
|
|
226
|
+
if (!style.content || ['none', 'normal'].includes(style.content))
|
|
227
|
+
continue;
|
|
228
|
+
id ??= String(++snapshotPseudoId);
|
|
229
|
+
clone.setAttribute('data-spindle-snapshot-pseudo', id);
|
|
230
|
+
const target = document.createElement('span').style;
|
|
231
|
+
copyComputedStyle(style, target);
|
|
232
|
+
pseudoRules.push(
|
|
233
|
+
`[data-spindle-snapshot-pseudo="${id}"]${pseudo}{${target.cssText}}`,
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
// Recreated scripts must remain inert when inserted, just like the
|
|
238
|
+
// already-executed script nodes that cloneNode used to produce.
|
|
239
|
+
if (source.localName === 'script')
|
|
240
|
+
clone.setAttribute('type', 'application/x-spindle-snapshot');
|
|
241
|
+
const from = source instanceof HTMLTemplateElement ? source.content : source;
|
|
242
|
+
const to = clone instanceof HTMLTemplateElement ? clone.content : clone;
|
|
243
|
+
const copyChildren = (
|
|
244
|
+
from: ParentNode,
|
|
245
|
+
to: ParentNode,
|
|
246
|
+
rules = pseudoRules,
|
|
247
|
+
) => {
|
|
248
|
+
for (const node of from.childNodes) {
|
|
249
|
+
to.appendChild(
|
|
250
|
+
node instanceof Element
|
|
251
|
+
? cloneSnapshotTree(node, freezeStyles, rules)
|
|
252
|
+
: node.cloneNode(false),
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
copyChildren(from, to);
|
|
257
|
+
if (source.shadowRoot) {
|
|
258
|
+
const shadow = clone.attachShadow({ mode: 'open' });
|
|
259
|
+
const rules: string[] = [];
|
|
260
|
+
copyChildren(source.shadowRoot, shadow, rules);
|
|
261
|
+
copyLiveState(source.shadowRoot, shadow);
|
|
262
|
+
installSnapshotStyles(shadow, rules);
|
|
263
|
+
}
|
|
264
|
+
return clone;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Replace browsing contexts throughout the snapshot, including shadow trees. */
|
|
268
|
+
function replaceEmbeddedContexts(source: ParentNode, clone: ParentNode): void {
|
|
269
|
+
const originals = source.querySelectorAll('*');
|
|
270
|
+
const copies = clone.querySelectorAll('*');
|
|
271
|
+
copies.forEach((embedded, i) => {
|
|
272
|
+
const original = originals[i];
|
|
273
|
+
if (!original) return;
|
|
274
|
+
if (original.shadowRoot && embedded.shadowRoot) {
|
|
275
|
+
replaceEmbeddedContexts(original.shadowRoot, embedded.shadowRoot);
|
|
276
|
+
}
|
|
277
|
+
if (!embedded.matches('iframe, object, embed')) return;
|
|
278
|
+
const placeholder = document.createElement('div');
|
|
279
|
+
for (const name of ['class', 'style', 'width', 'height']) {
|
|
280
|
+
const value = embedded.getAttribute(name);
|
|
281
|
+
if (value !== null) placeholder.setAttribute(name, value);
|
|
282
|
+
}
|
|
283
|
+
const rect = original.getBoundingClientRect();
|
|
284
|
+
// Unlike an iframe, an empty inline div does not honor width and height.
|
|
285
|
+
if (getComputedStyle(original).display === 'inline')
|
|
286
|
+
placeholder.style.display = 'inline-block';
|
|
287
|
+
// The measured dimensions already include any copied border and padding.
|
|
288
|
+
placeholder.style.boxSizing = 'border-box';
|
|
289
|
+
placeholder.style.width = `${rect.width}px`;
|
|
290
|
+
placeholder.style.height = `${rect.height}px`;
|
|
291
|
+
embedded.replaceWith(placeholder);
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
147
295
|
/**
|
|
148
296
|
* Create a snapshot clone of a .passage element for outgoing transitions.
|
|
149
297
|
* - Strips IDs, action associations and event handlers from the clone tree
|
|
@@ -158,40 +306,19 @@ function createSnapshot(
|
|
|
158
306
|
passageEl: Element,
|
|
159
307
|
transitionType: string,
|
|
160
308
|
): HTMLElement {
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
// media copying or insertion can reload a resource in the destination state.
|
|
164
|
-
for (const el of [clone, ...clone.querySelectorAll('*')]) {
|
|
165
|
-
for (const attr of [...el.attributes]) {
|
|
166
|
-
if (
|
|
167
|
-
attr.name === 'id' ||
|
|
168
|
-
attr.name === 'data-action' ||
|
|
169
|
-
attr.name.toLowerCase().startsWith('on')
|
|
170
|
-
)
|
|
171
|
-
el.removeAttribute(attr.name);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
309
|
+
const pseudoRules: string[] = [];
|
|
310
|
+
const clone = cloneSnapshotTree(passageEl, false, pseudoRules) as HTMLElement;
|
|
174
311
|
copyLiveState(passageEl, clone);
|
|
175
312
|
pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
|
|
176
313
|
|
|
177
314
|
// A cloned browsing context would reload and execute scripts on insertion.
|
|
178
315
|
// Keep its authored size/style as a passive placeholder instead.
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
if (value !== null) placeholder.setAttribute(name, value);
|
|
186
|
-
}
|
|
187
|
-
const original = originals[i];
|
|
188
|
-
if (original) {
|
|
189
|
-
const rect = original.getBoundingClientRect();
|
|
190
|
-
placeholder.style.width = `${rect.width}px`;
|
|
191
|
-
placeholder.style.height = `${rect.height}px`;
|
|
192
|
-
}
|
|
193
|
-
embedded.replaceWith(placeholder);
|
|
194
|
-
});
|
|
316
|
+
replaceEmbeddedContexts(passageEl, clone);
|
|
317
|
+
const cleanup = installSnapshotStyles(
|
|
318
|
+
passageEl.getRootNode() as Document | ShadowRoot,
|
|
319
|
+
pseudoRules,
|
|
320
|
+
);
|
|
321
|
+
if (cleanup) snapshotStyleCleanup.set(clone, cleanup);
|
|
195
322
|
|
|
196
323
|
// Disable interaction
|
|
197
324
|
clone.style.pointerEvents = 'none';
|
|
@@ -240,7 +367,10 @@ function cleanupSnapshots(containerEl: Element | null): void {
|
|
|
240
367
|
containerEl.classList.remove('passage-container--crossfading');
|
|
241
368
|
const snapshots = containerEl.querySelectorAll('.passage-snapshot');
|
|
242
369
|
for (let i = 0; i < snapshots.length; i++) {
|
|
243
|
-
snapshots[i]
|
|
370
|
+
const snapshot = snapshots[i]!;
|
|
371
|
+
snapshotStyleCleanup.get(snapshot)?.();
|
|
372
|
+
snapshotStyleCleanup.delete(snapshot);
|
|
373
|
+
snapshot.remove();
|
|
244
374
|
}
|
|
245
375
|
}
|
|
246
376
|
|
|
@@ -356,7 +486,14 @@ defineMacro({
|
|
|
356
486
|
}, []);
|
|
357
487
|
|
|
358
488
|
// A transition still running on unmount must not fire into it.
|
|
359
|
-
useEffect(() =>
|
|
489
|
+
useEffect(() => {
|
|
490
|
+
const container = containerRef.current;
|
|
491
|
+
return () => {
|
|
492
|
+
cancelTransition();
|
|
493
|
+
// The ref may already be cleared when the display unmounts.
|
|
494
|
+
cleanupSnapshots(container);
|
|
495
|
+
};
|
|
496
|
+
}, [cancelTransition]);
|
|
360
497
|
|
|
361
498
|
// State machine effect — triggers on every navigation
|
|
362
499
|
useEffect(() => {
|
|
@@ -14,9 +14,8 @@ import {
|
|
|
14
14
|
import {
|
|
15
15
|
multilineJsLiterals,
|
|
16
16
|
replaceSpindleTokens,
|
|
17
|
-
|
|
17
|
+
restoreHtmlTokens,
|
|
18
18
|
replaceSvgBlocks,
|
|
19
|
-
restoreSvgBlocks,
|
|
20
19
|
placeholdersIntact,
|
|
21
20
|
sameSpindleTokens,
|
|
22
21
|
SPINDLE_PLACEHOLDERS,
|
|
@@ -299,6 +298,12 @@ async function formatLf(
|
|
|
299
298
|
// HTML block — placeholder substitution + Prettier
|
|
300
299
|
const { text: svgPlaceholdered, tokens: svgTokens } =
|
|
301
300
|
replaceSvgBlocks(htmlText);
|
|
301
|
+
// A later whole-line Spindle token may hide an SVG marker. Check
|
|
302
|
+
// before that pass so a literal marker cannot stand in for it.
|
|
303
|
+
if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
|
|
304
|
+
lines.push(...region.lines);
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
302
307
|
const { text: placeholdered, tokens } =
|
|
303
308
|
replaceSpindleTokens(svgPlaceholdered);
|
|
304
309
|
const formatted = await formatHTMLPrettier(
|
|
@@ -318,11 +323,11 @@ async function formatLf(
|
|
|
318
323
|
continue;
|
|
319
324
|
}
|
|
320
325
|
// A token's line breaks are its payload: keep them out of the line steps below
|
|
321
|
-
const
|
|
326
|
+
const restored = restoreHtmlTokens(
|
|
322
327
|
formatted.trim(),
|
|
323
328
|
tokens.map((t) => replaceAll(t, '\n', sentinel)),
|
|
329
|
+
svgTokens,
|
|
324
330
|
);
|
|
325
|
-
const restored = restoreSvgBlocks(restoredSpindle, svgTokens);
|
|
326
331
|
for (const fLine of restored.split('\n')) {
|
|
327
332
|
lines.push(fLine);
|
|
328
333
|
}
|
|
@@ -635,14 +640,14 @@ function wrapLines(
|
|
|
635
640
|
isBlock: (name: string) => boolean,
|
|
636
641
|
): string[] {
|
|
637
642
|
const result: string[] = [];
|
|
638
|
-
const
|
|
643
|
+
const verbatim = verbatimLines(lines);
|
|
639
644
|
const structured = markdownLines(lines.join('\n'), isBlock, NO_WRAP);
|
|
640
645
|
|
|
641
646
|
for (const [index, line] of lines.entries()) {
|
|
642
647
|
// A `{do}` body is JavaScript: a line break there can change the program
|
|
643
648
|
if (
|
|
644
649
|
line.length <= maxLen ||
|
|
645
|
-
|
|
650
|
+
verbatim.has(index) ||
|
|
646
651
|
structured.has(index) ||
|
|
647
652
|
literalLines.has(line.trim())
|
|
648
653
|
) {
|
|
@@ -687,16 +692,24 @@ function wrapLines(
|
|
|
687
692
|
return result;
|
|
688
693
|
}
|
|
689
694
|
|
|
690
|
-
/**
|
|
691
|
-
function
|
|
695
|
+
/** Lines holding JavaScript or a multiline HTML tag must not be wrapped. */
|
|
696
|
+
function verbatimLines(lines: string[]): Set<number> {
|
|
692
697
|
const found = new Set<number>();
|
|
693
698
|
const text = lines.join('\n');
|
|
694
699
|
const lineAt = sourceLines(text);
|
|
695
|
-
|
|
700
|
+
const { doBlocks, tags } = scanSpindleMarkup(text);
|
|
701
|
+
for (const block of doBlocks) {
|
|
696
702
|
const first = lineAt(block.bodyStart);
|
|
697
703
|
const last = lineAt(block.bodyEnd);
|
|
698
704
|
for (let i = first; i <= last; i++) found.add(i);
|
|
699
705
|
}
|
|
706
|
+
for (const tag of tags) {
|
|
707
|
+
const first = lineAt(tag.start);
|
|
708
|
+
const last = lineAt(tag.end - 1);
|
|
709
|
+
if (first === last) continue;
|
|
710
|
+
// Continuation lines cannot be tokenized as HTML on their own.
|
|
711
|
+
for (let i = first; i <= last; i++) found.add(i);
|
|
712
|
+
}
|
|
700
713
|
return found;
|
|
701
714
|
}
|
|
702
715
|
|
|
@@ -710,7 +723,7 @@ function wordWrap(text: string, maxLen: number, indent: string): string[] {
|
|
|
710
723
|
/** Whether the character is inside a token whose text must stay as written. */
|
|
711
724
|
const inToken = new Array<boolean>(text.length).fill(false);
|
|
712
725
|
for (const token of tokenizeMarkupTolerant(text).tokens) {
|
|
713
|
-
if (token.type === 'text'
|
|
726
|
+
if (token.type === 'text') continue;
|
|
714
727
|
inToken.fill(true, token.start, token.end);
|
|
715
728
|
}
|
|
716
729
|
const room = maxLen - indentColumn(indent);
|
|
@@ -128,15 +128,6 @@ export function multilineJsLiterals(code: string): [number, number][] {
|
|
|
128
128
|
return spans;
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
-
/** Whether an HTML tag (opening, closing or self-closing) overlaps the range. */
|
|
132
|
-
function lineHasTag(
|
|
133
|
-
tags: { start: number; end: number }[],
|
|
134
|
-
start: number,
|
|
135
|
-
end: number,
|
|
136
|
-
): boolean {
|
|
137
|
-
return tags.some((tag) => tag.start < end && tag.end > start);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
131
|
export interface PlaceholderResult {
|
|
141
132
|
text: string;
|
|
142
133
|
tokens: string[];
|
|
@@ -166,6 +157,8 @@ export const SPINDLE_PLACEHOLDERS: PlaceholdersOf = (i) => [
|
|
|
166
157
|
`__SP${i}__`,
|
|
167
158
|
];
|
|
168
159
|
|
|
160
|
+
const PLACEHOLDER_PATTERN = /<!--(?:SP|SVG):\d+-->|__SP\d+__/g;
|
|
161
|
+
|
|
169
162
|
/**
|
|
170
163
|
* Whether `text` (what a formatter made of the placeholdered text) holds
|
|
171
164
|
* the placeholder of every one of `tokens` exactly once. If not, the
|
|
@@ -177,13 +170,17 @@ export function placeholdersIntact(
|
|
|
177
170
|
tokens: readonly string[],
|
|
178
171
|
placeholdersOf: PlaceholdersOf,
|
|
179
172
|
): boolean {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
)
|
|
173
|
+
if (tokens.length === 0) return true;
|
|
174
|
+
const indices = new Map<string, number>();
|
|
175
|
+
const counts = new Array<number>(tokens.length).fill(0);
|
|
176
|
+
tokens.forEach((_, index) => {
|
|
177
|
+
for (const marker of placeholdersOf(index)) indices.set(marker, index);
|
|
178
|
+
});
|
|
179
|
+
for (const [marker] of text.matchAll(PLACEHOLDER_PATTERN)) {
|
|
180
|
+
const index = indices.get(marker);
|
|
181
|
+
if (index !== undefined && ++counts[index]! > 1) return false;
|
|
182
|
+
}
|
|
183
|
+
return counts.every((count) => count === 1);
|
|
187
184
|
}
|
|
188
185
|
|
|
189
186
|
/** Whether `before` and `after` hold the same Spindle tokens, in the same order. */
|
|
@@ -198,29 +195,45 @@ export function sameSpindleTokens(before: string, after: string): boolean {
|
|
|
198
195
|
}
|
|
199
196
|
|
|
200
197
|
/**
|
|
201
|
-
*
|
|
202
|
-
*
|
|
198
|
+
* Restore the first occurrence of each marker in the unchanged document.
|
|
199
|
+
* Never search inserted source: literals may spell any other marker.
|
|
203
200
|
*/
|
|
204
201
|
function restorePlaceholders(
|
|
205
202
|
text: string,
|
|
206
|
-
|
|
207
|
-
placeholdersOf: PlaceholdersOf,
|
|
203
|
+
groups: readonly (readonly [readonly string[], PlaceholdersOf])[],
|
|
208
204
|
): string {
|
|
209
|
-
|
|
210
|
-
tokens
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
}
|
|
205
|
+
const replacements = new Map<string, string>();
|
|
206
|
+
for (const [tokens, placeholdersOf] of groups) {
|
|
207
|
+
tokens.forEach((token, index) => {
|
|
208
|
+
for (const marker of placeholdersOf(index))
|
|
209
|
+
replacements.set(marker, token);
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return text.replace(PLACEHOLDER_PATTERN, (marker) => {
|
|
213
|
+
const token = replacements.get(marker);
|
|
214
|
+
replacements.delete(marker);
|
|
215
|
+
// Callback form also preserves literal `$&`, `$'`, etc.
|
|
216
|
+
return token ?? marker;
|
|
215
217
|
});
|
|
216
|
-
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Restore both families together, so neither can consume the other's source. */
|
|
221
|
+
export function restoreHtmlTokens(
|
|
222
|
+
text: string,
|
|
223
|
+
spindle: string[],
|
|
224
|
+
svg: string[],
|
|
225
|
+
): string {
|
|
226
|
+
return restorePlaceholders(text, [
|
|
227
|
+
[spindle, SPINDLE_PLACEHOLDERS],
|
|
228
|
+
[svg, SVG_PLACEHOLDERS],
|
|
229
|
+
]);
|
|
217
230
|
}
|
|
218
231
|
|
|
219
232
|
/**
|
|
220
233
|
* Restore SVG blocks from placeholders.
|
|
221
234
|
*/
|
|
222
235
|
export function restoreSvgBlocks(text: string, tokens: string[]): string {
|
|
223
|
-
return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
|
|
236
|
+
return restorePlaceholders(text, [[tokens, SVG_PLACEHOLDERS]]);
|
|
224
237
|
}
|
|
225
238
|
|
|
226
239
|
/**
|
|
@@ -260,6 +273,7 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
|
|
|
260
273
|
const tokens: string[] = [];
|
|
261
274
|
const resultLines: string[] = [];
|
|
262
275
|
let unit = 0;
|
|
276
|
+
let tag = 0;
|
|
263
277
|
let lineStart = 0;
|
|
264
278
|
while (lineStart <= html.length) {
|
|
265
279
|
// A line ends at a line break outside every unit
|
|
@@ -280,10 +294,14 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
|
|
|
280
294
|
}
|
|
281
295
|
const line = html.slice(lineStart, lineEnd);
|
|
282
296
|
const indent = line.match(/^(\s*)/)?.[1] ?? '';
|
|
297
|
+
// Lines and tags are ordered: visit each tag only once, keeping a tag
|
|
298
|
+
// that spans several lines until its end is behind the current line.
|
|
299
|
+
while (tag < tags.length && tags[tag]!.end <= lineStart) tag++;
|
|
300
|
+
const hasTag = tag < tags.length && tags[tag]!.start < lineEnd;
|
|
283
301
|
|
|
284
302
|
if (lineUnits.length === 0) {
|
|
285
303
|
resultLines.push(line);
|
|
286
|
-
} else if (!
|
|
304
|
+
} else if (!hasTag) {
|
|
287
305
|
// Spindle tokens but no HTML: one placeholder for the whole line
|
|
288
306
|
const idx = tokens.length;
|
|
289
307
|
tokens.push(line.trim());
|
|
@@ -312,5 +330,5 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
|
|
|
312
330
|
* Restore original Spindle tokens from placeholders.
|
|
313
331
|
*/
|
|
314
332
|
export function restoreSpindleTokens(text: string, tokens: string[]): string {
|
|
315
|
-
return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
|
|
333
|
+
return restorePlaceholders(text, [[tokens, SPINDLE_PLACEHOLDERS]]);
|
|
316
334
|
}
|
|
@@ -15,6 +15,15 @@ export const FrozenStateContext = createContext<
|
|
|
15
15
|
((state: StoryState) => boolean) | null
|
|
16
16
|
>(null);
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Whether a loop has yet to reconcile its rows with newer namespaces.
|
|
20
|
+
* Queued row effects wait for that reconciliation. This differs from a
|
|
21
|
+
* detached click body's permanent freeze: its initial effects still run.
|
|
22
|
+
*/
|
|
23
|
+
export const PendingIterationContext = createContext<
|
|
24
|
+
((state: StoryState) => boolean) | null
|
|
25
|
+
>(null);
|
|
26
|
+
|
|
18
27
|
/**
|
|
19
28
|
* Tells a timer ({repeat}, {timed}) whether the passage it belongs to has
|
|
20
29
|
* been left: it must not run a new body then, for that would write into the
|