@rohal12/spindle 0.61.6 → 0.62.0
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/README.md +3 -1
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +200 -90
- package/dist/pkg/play.js +3 -49
- package/dist/pkg/story-variables.js +142 -77
- package/dist/pkg/tooling.js +3 -0
- package/package.json +5 -5
- package/src/components/macros/PassageDisplay.tsx +172 -35
- package/src/components/macros/arg-utils.ts +7 -2
- package/src/components/macros/macro-args.ts +113 -19
- package/src/format/format-passage.ts +14 -6
- package/src/format/placeholders.ts +20 -18
- package/src/index.tsx +8 -3
- package/src/js-lexer.ts +47 -12
- package/src/play/resolve-story.ts +5 -63
- package/src/tooling.ts +26 -9
- package/src/types-drift-check.ts +17 -23
- package/src/utils/object-path.ts +12 -1
- package/types/tooling.d.ts +56 -1
|
@@ -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(() => {
|
|
@@ -48,16 +48,21 @@ export function unescapeQuoted(body: string): string {
|
|
|
48
48
|
* Read the `"…"` or `'…'` string whose opening quote is at `start`.
|
|
49
49
|
* Returns its unescaped value and the index just past the closing quote, or
|
|
50
50
|
* `null` if there is no such quote at `start` or the string is unterminated.
|
|
51
|
+
* With `tolerant`, an unterminated string instead extends to its scanned end.
|
|
51
52
|
*/
|
|
52
53
|
export function readQuoted(
|
|
53
54
|
src: string,
|
|
54
55
|
start: number,
|
|
56
|
+
tolerant = false,
|
|
55
57
|
): { value: string; end: number } | null {
|
|
56
58
|
const quote = src[start];
|
|
57
59
|
if (quote !== '"' && quote !== "'") return null;
|
|
58
60
|
const { end, closed } = scanStringLiteral(src, start);
|
|
59
|
-
if (!closed) return null;
|
|
60
|
-
return {
|
|
61
|
+
if (!closed && !tolerant) return null;
|
|
62
|
+
return {
|
|
63
|
+
value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
|
|
64
|
+
end,
|
|
65
|
+
};
|
|
61
66
|
}
|
|
62
67
|
|
|
63
68
|
/**
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* empty).
|
|
16
16
|
*/
|
|
17
17
|
import { parseDelay } from '../../utils/parse-delay';
|
|
18
|
+
import type { Span as SourceSpan } from '../../markup/tokens';
|
|
18
19
|
import type { MacroArgs, ParameterDef } from '../../registry';
|
|
19
20
|
import type { StoryState } from '../../store';
|
|
20
21
|
import { noPassageError } from '../../runtime-errors';
|
|
@@ -42,6 +43,8 @@ interface Place {
|
|
|
42
43
|
/** The index in the raw arguments of the text being read. */
|
|
43
44
|
at: number;
|
|
44
45
|
spans: ArgSpans | undefined;
|
|
46
|
+
/** Full parameter spans for tolerant editor input, including keywords. */
|
|
47
|
+
toolingSpans?: ArgSpans;
|
|
45
48
|
}
|
|
46
49
|
|
|
47
50
|
/** The terms of `src`: the runs of text between its depth-0 whitespace. */
|
|
@@ -80,11 +83,18 @@ export class MacroArgumentError extends Error {
|
|
|
80
83
|
|
|
81
84
|
/** Read `src`, at `place`, as `param` says. */
|
|
82
85
|
function readValue(param: ParameterDef, src: string, place: Place): unknown {
|
|
83
|
-
|
|
86
|
+
const span: Span = [place.at, place.at + src.length];
|
|
87
|
+
place.spans?.set(param, span);
|
|
88
|
+
place.toolingSpans?.set(param, span);
|
|
84
89
|
switch (param.type) {
|
|
85
90
|
case 'string': {
|
|
86
91
|
const value = readWholeQuoted(src);
|
|
87
|
-
if (value === null)
|
|
92
|
+
if (value === null) {
|
|
93
|
+
if (place.toolingSpans && (src[0] === '"' || src[0] === "'")) {
|
|
94
|
+
return readText(src);
|
|
95
|
+
}
|
|
96
|
+
throw new MacroArgumentError(param, src);
|
|
97
|
+
}
|
|
88
98
|
return value;
|
|
89
99
|
}
|
|
90
100
|
case 'text':
|
|
@@ -128,7 +138,7 @@ function matchAt(re: RegExp, src: string, pos: number): string | null {
|
|
|
128
138
|
function readOptions(
|
|
129
139
|
params: readonly ParameterDef[],
|
|
130
140
|
src: string,
|
|
131
|
-
{ at, spans }: Place,
|
|
141
|
+
{ at, spans, toolingSpans }: Place,
|
|
132
142
|
): Record<string, unknown> {
|
|
133
143
|
const options: Record<string, unknown> = {};
|
|
134
144
|
let i = 0;
|
|
@@ -136,9 +146,10 @@ function readOptions(
|
|
|
136
146
|
const key = matchAt(WORD_RE, src, i);
|
|
137
147
|
if (!key) {
|
|
138
148
|
// Skip whitespace and stray characters, or a stray quoted string.
|
|
139
|
-
i = readQuoted(src, i)?.end ?? i + 1;
|
|
149
|
+
i = readQuoted(src, i, !!toolingSpans)?.end ?? i + 1;
|
|
140
150
|
continue;
|
|
141
151
|
}
|
|
152
|
+
const keyAt = i;
|
|
142
153
|
i += key.length;
|
|
143
154
|
|
|
144
155
|
// A value is a quoted string, which may follow the keyword directly
|
|
@@ -147,7 +158,7 @@ function readOptions(
|
|
|
147
158
|
let val: string | undefined;
|
|
148
159
|
let j = i;
|
|
149
160
|
while (j < src.length && isWhitespace(src[j]!)) j++;
|
|
150
|
-
const quoted = readQuoted(src, j);
|
|
161
|
+
const quoted = readQuoted(src, j, !!toolingSpans);
|
|
151
162
|
const digits = quoted || j === i ? null : matchAt(NUMBER_RE, src, j);
|
|
152
163
|
if (quoted) {
|
|
153
164
|
val = quoted.value;
|
|
@@ -161,8 +172,9 @@ function readOptions(
|
|
|
161
172
|
if (param && param.type !== 'flag' && val !== undefined) {
|
|
162
173
|
spans?.set(param, [at + j, at + i]);
|
|
163
174
|
}
|
|
175
|
+
if (param) toolingSpans?.set(param, [at + keyAt, at + i]);
|
|
164
176
|
// A keyword that takes a string was given anything else, or nothing
|
|
165
|
-
if (param?.type === 'string' && !quoted) {
|
|
177
|
+
if (param?.type === 'string' && !quoted && !toolingSpans) {
|
|
166
178
|
throw new MacroArgumentError(
|
|
167
179
|
param,
|
|
168
180
|
matchAt(WORD_OR_PUNCT_RE, src, j) ?? '',
|
|
@@ -210,7 +222,11 @@ function takeFlag(src: string, word: string, alone: boolean): Span | null {
|
|
|
210
222
|
* term with terms on both sides; `=` is an assignment at depth 0, not part
|
|
211
223
|
* of `==` or `!=`.
|
|
212
224
|
*/
|
|
213
|
-
function findSeparator(
|
|
225
|
+
function findSeparator(
|
|
226
|
+
src: string,
|
|
227
|
+
word: string,
|
|
228
|
+
tolerant = false,
|
|
229
|
+
): Span | null {
|
|
214
230
|
if (word === '=') {
|
|
215
231
|
const indices = topLevelIndices(src, (ch) => ch === '=');
|
|
216
232
|
for (let k = 0; k < indices.length; k++) {
|
|
@@ -224,9 +240,9 @@ function findSeparator(src: string, word: string): Span | null {
|
|
|
224
240
|
return null;
|
|
225
241
|
}
|
|
226
242
|
const spans = terms(src);
|
|
227
|
-
for (let k = 1; k < spans.length - 1; k++) {
|
|
243
|
+
for (let k = 1; k < spans.length - (tolerant ? 0 : 1); k++) {
|
|
228
244
|
if (slice(src, spans[k]!) === word) {
|
|
229
|
-
return [spans[k - 1]![1], spans[k + 1]
|
|
245
|
+
return [spans[k - 1]![1], spans[k + 1]?.[0] ?? src.length];
|
|
230
246
|
}
|
|
231
247
|
}
|
|
232
248
|
return null;
|
|
@@ -252,7 +268,7 @@ function readGroup(
|
|
|
252
268
|
params: readonly ParameterDef[],
|
|
253
269
|
src: string | null,
|
|
254
270
|
args: Record<string, unknown>,
|
|
255
|
-
{ at: srcAt, spans }: Place,
|
|
271
|
+
{ at: srcAt, spans, toolingSpans }: Place,
|
|
256
272
|
): void {
|
|
257
273
|
let [text, at] = trimmed(src ?? '', srcAt);
|
|
258
274
|
// A lone word is the passage of {include inline}, not its flag
|
|
@@ -260,7 +276,14 @@ function readGroup(
|
|
|
260
276
|
for (const flag of params.filter((p) => p.type === 'flag')) {
|
|
261
277
|
const rest = src === null ? null : takeFlag(text, flag.name, alone);
|
|
262
278
|
args[flag.name] = rest !== null;
|
|
263
|
-
if (rest)
|
|
279
|
+
if (rest) {
|
|
280
|
+
const flagSpan: Span =
|
|
281
|
+
rest[0] > 0
|
|
282
|
+
? [0, text.indexOf(flag.name) + flag.name.length]
|
|
283
|
+
: [text.lastIndexOf(flag.name), text.length];
|
|
284
|
+
toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
|
|
285
|
+
[text, at] = trimmed(slice(text, rest), at + rest[0]);
|
|
286
|
+
}
|
|
264
287
|
}
|
|
265
288
|
const positional = params.filter((p) => p.type !== 'flag');
|
|
266
289
|
if (positional.length === 0) return;
|
|
@@ -271,10 +294,21 @@ function readGroup(
|
|
|
271
294
|
);
|
|
272
295
|
const restIndex = lastText < 0 ? positional.length - 1 : lastText;
|
|
273
296
|
/** Read `param` from the text from `start` to `end`. */
|
|
274
|
-
const read = (param: ParameterDef, [start, end]: Span) =>
|
|
275
|
-
start === end
|
|
276
|
-
|
|
277
|
-
|
|
297
|
+
const read = (param: ParameterDef, [start, end]: Span, tolerant = true) => {
|
|
298
|
+
if (start === end) return unset(param);
|
|
299
|
+
try {
|
|
300
|
+
return readValue(param, text.slice(start, end), {
|
|
301
|
+
at: at + start,
|
|
302
|
+
spans,
|
|
303
|
+
toolingSpans,
|
|
304
|
+
});
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (toolingSpans && tolerant && error instanceof MacroArgumentError) {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
278
312
|
|
|
279
313
|
// One parameter reads the whole text: no need to split it.
|
|
280
314
|
if (positional.length === 1) {
|
|
@@ -292,7 +326,7 @@ function readGroup(
|
|
|
292
326
|
// `string` that isn't quoted) belongs to the rest, as in {meter $hp 100}
|
|
293
327
|
const readTrailing = (param: ParameterDef, span: Span) => {
|
|
294
328
|
try {
|
|
295
|
-
return read(param, span);
|
|
329
|
+
return read(param, span, false);
|
|
296
330
|
} catch (error) {
|
|
297
331
|
if (error instanceof MacroArgumentError) return undefined;
|
|
298
332
|
throw error;
|
|
@@ -306,7 +340,10 @@ function readGroup(
|
|
|
306
340
|
args[param.name] = value ?? unset(param);
|
|
307
341
|
if (value !== undefined) to--;
|
|
308
342
|
// A term it didn't take
|
|
309
|
-
else
|
|
343
|
+
else {
|
|
344
|
+
spans?.delete(param);
|
|
345
|
+
toolingSpans?.delete(param);
|
|
346
|
+
}
|
|
310
347
|
}
|
|
311
348
|
const rest = positional[restIndex]!;
|
|
312
349
|
args[rest.name] =
|
|
@@ -328,6 +365,7 @@ export function parseMacroArgs<const P extends readonly ParameterDef[]>(
|
|
|
328
365
|
rawArgs: string,
|
|
329
366
|
parameters: P,
|
|
330
367
|
spans?: ArgSpans,
|
|
368
|
+
toolingSpans?: ArgSpans,
|
|
331
369
|
): MacroArgs<P> {
|
|
332
370
|
const args: Record<string, unknown> = {};
|
|
333
371
|
// The text after the last separator read, null once one is missing
|
|
@@ -335,18 +373,31 @@ export function parseMacroArgs<const P extends readonly ParameterDef[]>(
|
|
|
335
373
|
let groupStart = 0;
|
|
336
374
|
parameters.forEach((separator, i) => {
|
|
337
375
|
if (separator.type !== 'separator') return;
|
|
338
|
-
const at =
|
|
376
|
+
const at =
|
|
377
|
+
rest === null
|
|
378
|
+
? null
|
|
379
|
+
: findSeparator(rest, separator.name, !!toolingSpans);
|
|
339
380
|
args[separator.name] = at !== null;
|
|
381
|
+
if (at && toolingSpans) {
|
|
382
|
+
const start =
|
|
383
|
+
restAt + at[0] + rest!.slice(at[0], at[1]).indexOf(separator.name);
|
|
384
|
+
toolingSpans.set(separator, [start, start + separator.name.length]);
|
|
385
|
+
}
|
|
340
386
|
const before = at ? rest!.slice(0, at[0]) : rest;
|
|
341
387
|
readGroup(parameters.slice(groupStart, i), before, args, {
|
|
342
388
|
at: restAt,
|
|
343
389
|
spans,
|
|
390
|
+
toolingSpans,
|
|
344
391
|
});
|
|
345
392
|
rest = at ? rest!.slice(at[1]) : null;
|
|
346
393
|
if (at) restAt += at[1];
|
|
347
394
|
groupStart = i + 1;
|
|
348
395
|
});
|
|
349
|
-
readGroup(parameters.slice(groupStart), rest, args, {
|
|
396
|
+
readGroup(parameters.slice(groupStart), rest, args, {
|
|
397
|
+
at: restAt,
|
|
398
|
+
spans,
|
|
399
|
+
toolingSpans,
|
|
400
|
+
});
|
|
350
401
|
return args as MacroArgs<P>;
|
|
351
402
|
}
|
|
352
403
|
|
|
@@ -399,3 +450,46 @@ export function readBoundVariable(rawArgs: string): string {
|
|
|
399
450
|
const first = terms(src)[0];
|
|
400
451
|
return first ? slice(src, first) : '';
|
|
401
452
|
}
|
|
453
|
+
|
|
454
|
+
/** A consumed argument and its declared parameter, with UTF-16 source offsets. */
|
|
455
|
+
export interface MacroArgumentSpan extends SourceSpan {
|
|
456
|
+
/** The original parameter object, including for nested keyword options. */
|
|
457
|
+
parameter: ParameterDef;
|
|
458
|
+
/** Index of the top-level parameter, for signature help. */
|
|
459
|
+
parameterIndex: number;
|
|
460
|
+
/** Indices through nested options, starting at parameterIndex. */
|
|
461
|
+
parameterPath: number[];
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* The runtime's argument grouping, tolerant of missing or unclosed strings.
|
|
466
|
+
* Includes quotes, flags, separators and option keywords; offsets are into
|
|
467
|
+
* rawArgs. Absent arguments have no span. Options also have their enclosing
|
|
468
|
+
* parameter span, so consumers can choose the most specific overlapping span.
|
|
469
|
+
* No expressions are evaluated. Parameter identities are preserved.
|
|
470
|
+
*/
|
|
471
|
+
export function macroArgumentSpans(
|
|
472
|
+
rawArgs: string,
|
|
473
|
+
parameters: readonly ParameterDef[],
|
|
474
|
+
): MacroArgumentSpan[] {
|
|
475
|
+
const spans: ArgSpans = new Map();
|
|
476
|
+
parseMacroArgs(rawArgs, parameters, undefined, spans);
|
|
477
|
+
const result: MacroArgumentSpan[] = [];
|
|
478
|
+
const add = (params: readonly ParameterDef[], path: number[]) => {
|
|
479
|
+
params.forEach((parameter, index) => {
|
|
480
|
+
const parameterPath = [...path, index];
|
|
481
|
+
const span = spans.get(parameter);
|
|
482
|
+
if (span)
|
|
483
|
+
result.push({
|
|
484
|
+
parameter,
|
|
485
|
+
parameterIndex: parameterPath[0]!,
|
|
486
|
+
parameterPath,
|
|
487
|
+
start: span[0],
|
|
488
|
+
end: span[1],
|
|
489
|
+
});
|
|
490
|
+
if (parameter.parameters) add(parameter.parameters, parameterPath);
|
|
491
|
+
});
|
|
492
|
+
};
|
|
493
|
+
add(parameters, []);
|
|
494
|
+
return result.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
495
|
+
}
|
|
@@ -640,14 +640,14 @@ function wrapLines(
|
|
|
640
640
|
isBlock: (name: string) => boolean,
|
|
641
641
|
): string[] {
|
|
642
642
|
const result: string[] = [];
|
|
643
|
-
const
|
|
643
|
+
const verbatim = verbatimLines(lines);
|
|
644
644
|
const structured = markdownLines(lines.join('\n'), isBlock, NO_WRAP);
|
|
645
645
|
|
|
646
646
|
for (const [index, line] of lines.entries()) {
|
|
647
647
|
// A `{do}` body is JavaScript: a line break there can change the program
|
|
648
648
|
if (
|
|
649
649
|
line.length <= maxLen ||
|
|
650
|
-
|
|
650
|
+
verbatim.has(index) ||
|
|
651
651
|
structured.has(index) ||
|
|
652
652
|
literalLines.has(line.trim())
|
|
653
653
|
) {
|
|
@@ -692,16 +692,24 @@ function wrapLines(
|
|
|
692
692
|
return result;
|
|
693
693
|
}
|
|
694
694
|
|
|
695
|
-
/**
|
|
696
|
-
function
|
|
695
|
+
/** Lines holding JavaScript or a multiline HTML tag must not be wrapped. */
|
|
696
|
+
function verbatimLines(lines: string[]): Set<number> {
|
|
697
697
|
const found = new Set<number>();
|
|
698
698
|
const text = lines.join('\n');
|
|
699
699
|
const lineAt = sourceLines(text);
|
|
700
|
-
|
|
700
|
+
const { doBlocks, tags } = scanSpindleMarkup(text);
|
|
701
|
+
for (const block of doBlocks) {
|
|
701
702
|
const first = lineAt(block.bodyStart);
|
|
702
703
|
const last = lineAt(block.bodyEnd);
|
|
703
704
|
for (let i = first; i <= last; i++) found.add(i);
|
|
704
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
|
+
}
|
|
705
713
|
return found;
|
|
706
714
|
}
|
|
707
715
|
|
|
@@ -715,7 +723,7 @@ function wordWrap(text: string, maxLen: number, indent: string): string[] {
|
|
|
715
723
|
/** Whether the character is inside a token whose text must stay as written. */
|
|
716
724
|
const inToken = new Array<boolean>(text.length).fill(false);
|
|
717
725
|
for (const token of tokenizeMarkupTolerant(text).tokens) {
|
|
718
|
-
if (token.type === 'text'
|
|
726
|
+
if (token.type === 'text') continue;
|
|
719
727
|
inToken.fill(true, token.start, token.end);
|
|
720
728
|
}
|
|
721
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. */
|
|
@@ -212,7 +209,7 @@ function restorePlaceholders(
|
|
|
212
209
|
replacements.set(marker, token);
|
|
213
210
|
});
|
|
214
211
|
}
|
|
215
|
-
return text.replace(
|
|
212
|
+
return text.replace(PLACEHOLDER_PATTERN, (marker) => {
|
|
216
213
|
const token = replacements.get(marker);
|
|
217
214
|
replacements.delete(marker);
|
|
218
215
|
// Callback form also preserves literal `$&`, `$'`, etc.
|
|
@@ -276,6 +273,7 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
|
|
|
276
273
|
const tokens: string[] = [];
|
|
277
274
|
const resultLines: string[] = [];
|
|
278
275
|
let unit = 0;
|
|
276
|
+
let tag = 0;
|
|
279
277
|
let lineStart = 0;
|
|
280
278
|
while (lineStart <= html.length) {
|
|
281
279
|
// A line ends at a line break outside every unit
|
|
@@ -296,10 +294,14 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
|
|
|
296
294
|
}
|
|
297
295
|
const line = html.slice(lineStart, lineEnd);
|
|
298
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;
|
|
299
301
|
|
|
300
302
|
if (lineUnits.length === 0) {
|
|
301
303
|
resultLines.push(line);
|
|
302
|
-
} else if (!
|
|
304
|
+
} else if (!hasTag) {
|
|
303
305
|
// Spindle tokens but no HTML: one placeholder for the whole line
|
|
304
306
|
const idx = tokens.length;
|
|
305
307
|
tokens.push(line.trim());
|