@rohal12/spindle 0.62.0 → 0.62.2

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.
@@ -14,6 +14,7 @@ import {
14
14
  import { Passage, renderPassageContent } from '../Passage';
15
15
  import { defineMacro } from '../../define-macro';
16
16
  import { resolveTransition, type ResolvedTransition } from '../../transition';
17
+ import { skipString } from './arg-utils';
17
18
 
18
19
  /** Input types whose `value` is not what the user sees or edits. */
19
20
  const VALUELESS_INPUTS = new Set([
@@ -158,11 +159,265 @@ function appendSnapshot(container: Element, snapshot: HTMLElement): void {
158
159
  function copyComputedStyle(
159
160
  style: CSSStyleDeclaration,
160
161
  target: CSSStyleDeclaration,
162
+ ids: ReadonlyMap<string, string>,
161
163
  ): void {
162
164
  for (let i = 0; i < style.length; i++) {
163
165
  const name = style[i]!;
164
- target.setProperty(name, style.getPropertyValue(name));
166
+ target.setProperty(
167
+ name,
168
+ snapshotUrls(style.getPropertyValue(name), ids),
169
+ 'important',
170
+ );
171
+ }
172
+ }
173
+
174
+ let snapshotFragmentId = 0;
175
+
176
+ /** SVG definitions need local targets without sharing IDs with live passages. */
177
+ function snapshotIds(root: ParentNode): Map<string, string> {
178
+ const ids = new Map<string, string>();
179
+ if (root instanceof Element && root.id) ids.set(root.id, '');
180
+ for (const element of root.querySelectorAll('[id]')) {
181
+ ids.set(element.id, '');
165
182
  }
183
+ for (const original of ids.keys()) {
184
+ let id: string;
185
+ do {
186
+ id = `spindle-snapshot-${++snapshotFragmentId}`;
187
+ } while (ids.has(id) || document.getElementById(id));
188
+ ids.set(original, id);
189
+ }
190
+ return ids;
191
+ }
192
+
193
+ /** Rewrite only fragments in this document; external SVG URLs stay external. */
194
+ function snapshotFragment(value: string, ids: ReadonlyMap<string, string>) {
195
+ try {
196
+ const url = new URL(value, document.baseURI);
197
+ const current = new URL(document.URL);
198
+ if (url.href.split('#')[0] !== current.href.split('#')[0]) return value;
199
+ let fragment = url.hash.slice(1);
200
+ try {
201
+ fragment = decodeURIComponent(fragment);
202
+ } catch {
203
+ // Browsers also resolve authored IDs containing a literal percent sign.
204
+ }
205
+ const id = ids.get(fragment);
206
+ return id ? `#${id}` : value;
207
+ } catch {
208
+ return value;
209
+ }
210
+ }
211
+
212
+ /** URL-valued presentation attributes, inline CSS and computed CSS alike. */
213
+ function snapshotUrls(
214
+ value: string,
215
+ ids: ReadonlyMap<string, string>,
216
+ base?: string,
217
+ ) {
218
+ return value.replace(
219
+ /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi,
220
+ (match, double, single, bare) => {
221
+ const original: string = double ?? single ?? bare;
222
+ try {
223
+ const resolved = base ? new URL(original, base).href : original;
224
+ const rewritten = snapshotFragment(resolved, ids);
225
+ return original === rewritten ? match : `url("${rewritten}")`;
226
+ } catch {
227
+ return match;
228
+ }
229
+ },
230
+ );
231
+ }
232
+
233
+ /** Keep SVG's specified CSS: a use instance inherits from its use element,
234
+ * rather than from the definition's original parent. Computed defaults on
235
+ * definitions would replace that inheritance (and resolve currentColor).
236
+ */
237
+ const snapshotSvgRules = new WeakSet<CSSRule>();
238
+
239
+ /** A detached style element has no sheet yet. Carry its CSSOM, including
240
+ * script-inserted rules and imported styles, into the passive tree.
241
+ */
242
+ function copySnapshotSheet(
243
+ source: CSSStyleSheet,
244
+ ids: ReadonlyMap<string, string>,
245
+ onOpaque?: () => void,
246
+ ): CSSStyleSheet {
247
+ const seen = new Set<CSSStyleSheet>();
248
+ const textOf = (sheet: CSSStyleSheet): string => {
249
+ if (seen.has(sheet)) return '';
250
+ seen.add(sheet);
251
+ let rules: CSSRule[];
252
+ try {
253
+ rules = [...sheet.cssRules];
254
+ } catch {
255
+ // Imported cross-origin CSS is opaque to the CSSOM. It must not
256
+ // prevent an otherwise valid passage from navigating.
257
+ onOpaque?.();
258
+ return '';
259
+ }
260
+ return rules
261
+ .filter((rule) => !snapshotSvgRules.has(rule))
262
+ .map((rule) => {
263
+ if (rule instanceof CSSImportRule && rule.styleSheet) {
264
+ let css = textOf(rule.styleSheet);
265
+ if (rule.layerName !== null) css = `@layer ${rule.layerName}{${css}}`;
266
+ if (rule.supportsText)
267
+ css = `@supports (${rule.supportsText}){${css}}`;
268
+ if (rule.media.mediaText)
269
+ css = `@media ${rule.media.mediaText}{${css}}`;
270
+ return css;
271
+ }
272
+ return snapshotUrls(rule.cssText, ids, sheet.href ?? document.baseURI);
273
+ })
274
+ .join('\n');
275
+ };
276
+ const copy = new CSSStyleSheet({
277
+ media: source.media.mediaText,
278
+ disabled: source.disabled,
279
+ });
280
+ copy.replaceSync(textOf(source));
281
+ return copy;
282
+ }
283
+
284
+ function installSnapshotSvgStyles(
285
+ root: Document | ShadowRoot,
286
+ ids: ReadonlyMap<string, string>,
287
+ marker: string,
288
+ targetSheets: readonly CSSStyleSheet[] = [
289
+ ...root.styleSheets,
290
+ ...root.adoptedStyleSheets,
291
+ ],
292
+ ): () => void {
293
+ if (!root.querySelector('svg')) return () => {};
294
+ const customTags = new Set(
295
+ [
296
+ ...(root instanceof ShadowRoot ? [root.host] : []),
297
+ ...root.querySelectorAll('*'),
298
+ ]
299
+ .filter((element) => element.localName.includes('-'))
300
+ .map((element) => element.localName),
301
+ );
302
+ const identity =
303
+ /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\[(?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\]"'\\])*\]|([#.])?((?:\\[0-9a-fA-F]{1,6}\s?|\\.|[\w-]|[^\x00-\x7f])+)/g;
304
+ const selectorOf = (selector: string, scoped = true) => {
305
+ const rewritten = selector.replace(
306
+ identity,
307
+ (written, sigil, escaped, at) => {
308
+ if (!escaped)
309
+ return written.replace(
310
+ /^\[\s*id(?=[\s~|^$*=\]])/,
311
+ '[data-spindle-snapshot-original-id',
312
+ );
313
+ const name = escaped.replace(
314
+ /\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,
315
+ (_: string, hex: string, char: string) =>
316
+ hex ? String.fromCodePoint(parseInt(hex, 16)) : char,
317
+ );
318
+ if (sigil === '.' && name === 'passage')
319
+ return ':is(.passage,.passage-snapshot)';
320
+ if (!sigil && customTags.has(name) && selector[at - 1] !== ':')
321
+ return `:is(${CSS.escape(name)},:where([data-spindle-snapshot-tag="${name}"]))`;
322
+ const id = sigil === '#' && ids.get(name);
323
+ return id
324
+ ? `:is(#${id},:where([data-spindle-snapshot-id="${id}"]))`
325
+ : written;
326
+ },
327
+ );
328
+ if (!scoped) return rewritten;
329
+ // Keep each selector's specificity, including lists with unequal members.
330
+ const selectors: string[] = [];
331
+ let start = 0;
332
+ let depth = 0;
333
+ for (let i = 0; i <= rewritten.length; i++) {
334
+ const ch = rewritten[i];
335
+ if (ch === '\\') i++;
336
+ else if (ch === '"' || ch === "'") i = skipString(rewritten, i) - 1;
337
+ else if (ch === '(' || ch === '[') depth++;
338
+ else if (ch === ')' || ch === ']') depth--;
339
+ else if (i === rewritten.length || (ch === ',' && depth === 0)) {
340
+ selectors.push(
341
+ `:where([data-spindle-snapshot-svg="${marker}"]):is(${rewritten.slice(start, i)})`,
342
+ );
343
+ start = i + 1;
344
+ }
345
+ }
346
+ return selectors.join(',');
347
+ };
348
+ const rulesOf = (rules: Iterable<CSSRule>, base: string): string[] => {
349
+ const result: string[] = [];
350
+ for (const rule of rules) {
351
+ if (rule instanceof CSSStyleRule) {
352
+ const css = snapshotUrls(rule.style.cssText, ids, base);
353
+ result.push(`${selectorOf(rule.selectorText)}{${css}}`);
354
+ if (rule.cssRules.length) {
355
+ // Keep the parent selector as the native nesting context. Only
356
+ // declaration targets get the snapshot marker, so an HTML parent
357
+ // can still select an SVG descendant.
358
+ result.push(
359
+ `${selectorOf(rule.selectorText, false)}{${rulesOf(rule.cssRules, base).join('\n')}}`,
360
+ );
361
+ }
362
+ } else if ('cssRules' in rule && !(rule instanceof CSSKeyframesRule)) {
363
+ const contents = rulesOf((rule as CSSGroupingRule).cssRules, base);
364
+ result.push(
365
+ `${rule.cssText.slice(0, rule.cssText.indexOf('{'))}{${contents.join('\n')}}`,
366
+ );
367
+ }
368
+ }
369
+ return result;
370
+ };
371
+ type RuleContainer = CSSStyleSheet | CSSGroupingRule;
372
+ const inserted: [RuleContainer, CSSRule][] = [];
373
+ const sheets = new Set<CSSStyleSheet>();
374
+ const sheetRules = (sheet: CSSStyleSheet) => {
375
+ if (
376
+ sheets.has(sheet) ||
377
+ sheet.disabled ||
378
+ !matchMedia(sheet.media.mediaText || 'all').matches
379
+ )
380
+ return;
381
+ sheets.add(sheet);
382
+ try {
383
+ visit(sheet, sheet.href ?? document.baseURI);
384
+ } catch {
385
+ // Cross-origin sheets cannot be inspected. Their unchanged selectors
386
+ // still apply to the passive SVG tree.
387
+ }
388
+ };
389
+ const visit = (parent: RuleContainer, base: string) => {
390
+ for (const rule of [...parent.cssRules]) {
391
+ if (snapshotSvgRules.has(rule)) continue;
392
+ if (rule instanceof CSSStyleRule) {
393
+ let index = [...parent.cssRules].indexOf(rule) + 1;
394
+ for (const css of rulesOf([rule], base)) {
395
+ parent.insertRule(css, index);
396
+ const insertedRule = parent.cssRules[index++]!;
397
+ inserted.push([parent, insertedRule]);
398
+ snapshotSvgRules.add(insertedRule);
399
+ }
400
+ } else if (rule instanceof CSSImportRule) {
401
+ if (
402
+ rule.styleSheet &&
403
+ matchMedia(rule.media.mediaText || 'all').matches
404
+ )
405
+ sheetRules(rule.styleSheet);
406
+ } else if ('cssRules' in rule && !(rule instanceof CSSKeyframesRule)) {
407
+ visit(rule as CSSGroupingRule, base);
408
+ }
409
+ }
410
+ };
411
+ // Adjacent aliases keep the original layer identity and cascade order,
412
+ // including anonymous layers. They match snapshot elements only.
413
+ for (const sheet of targetSheets) sheetRules(sheet);
414
+ return () => {
415
+ for (const [parent, rule] of inserted) {
416
+ const index = [...parent.cssRules].indexOf(rule);
417
+ if (index >= 0) parent.deleteRule(index);
418
+ snapshotSvgRules.delete(rule);
419
+ }
420
+ };
166
421
  }
167
422
 
168
423
  function installSnapshotStyles(
@@ -192,12 +447,14 @@ let snapshotPseudoId = 0;
192
447
  */
193
448
  function cloneSnapshotTree(
194
449
  source: Element,
195
- freezeStyles = false,
450
+ ids: ReadonlyMap<string, string>,
196
451
  pseudoRules: string[] = [],
452
+ svgMarker = String(++snapshotPseudoId),
453
+ cleanups: (() => void)[] = [],
197
454
  ): Element {
198
455
  const html = source.namespaceURI === 'http://www.w3.org/1999/xhtml';
456
+ const svg = source.namespaceURI === 'http://www.w3.org/2000/svg';
199
457
  const custom = html && source.localName.includes('-');
200
- freezeStyles ||= custom || source.hasAttribute('is');
201
458
  const clone = document.createElementNS(
202
459
  source.namespaceURI,
203
460
  custom ? 'span' : source.localName,
@@ -210,29 +467,48 @@ function cloneSnapshotTree(
210
467
  attr.name.toLowerCase().startsWith('on')
211
468
  )
212
469
  continue;
470
+ const value =
471
+ svg && attr.localName === 'href'
472
+ ? snapshotFragment(attr.value, ids)
473
+ : svg || attr.localName === 'style'
474
+ ? snapshotUrls(attr.value, ids)
475
+ : attr.value;
213
476
  if (attr.namespaceURI)
214
- clone.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
215
- else clone.setAttribute(attr.name, attr.value);
477
+ clone.setAttributeNS(attr.namespaceURI, attr.name, value);
478
+ else clone.setAttribute(attr.name, value);
216
479
  }
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
- }
480
+ if (svg && source.id) {
481
+ clone.id = ids.get(source.id)!;
482
+ }
483
+ if (source.id)
484
+ clone.setAttribute('data-spindle-snapshot-id', ids.get(source.id)!);
485
+ if (source.id)
486
+ clone.setAttribute('data-spindle-snapshot-original-id', source.id);
487
+ if (custom) clone.setAttribute('data-spindle-snapshot-tag', source.localName);
488
+ if (svg) clone.setAttribute('data-spindle-snapshot-svg', svgMarker);
489
+ // IDs and the passage class are removed, and custom tags become spans.
490
+ // Freeze native and custom content before those selectors stop matching.
491
+ const computed = getComputedStyle(source);
492
+ if (!svg) copyComputedStyle(computed, (clone as HTMLElement).style, ids);
493
+ // Generated content needs CSS rules in the same document or shadow root.
494
+ // A unique selector keeps simultaneous snapshots from styling each other.
495
+ let pseudoId: string | undefined;
496
+ for (const pseudo of ['::before', '::after', '::marker']) {
497
+ const style = getComputedStyle(source, pseudo);
498
+ const nativeMarker =
499
+ pseudo === '::marker' && computed.display === 'list-item';
500
+ if (
501
+ !nativeMarker &&
502
+ (!style.content || ['none', 'normal'].includes(style.content))
503
+ )
504
+ continue;
505
+ pseudoId ??= String(++snapshotPseudoId);
506
+ clone.setAttribute('data-spindle-snapshot-pseudo', pseudoId);
507
+ const target = document.createElement('span').style;
508
+ copyComputedStyle(style, target, ids);
509
+ pseudoRules.push(
510
+ `[data-spindle-snapshot-pseudo="${pseudoId}"]${pseudo}{${target.cssText}}`,
511
+ );
236
512
  }
237
513
  // Recreated scripts must remain inert when inserted, just like the
238
514
  // already-executed script nodes that cloneNode used to produce.
@@ -244,21 +520,59 @@ function cloneSnapshotTree(
244
520
  from: ParentNode,
245
521
  to: ParentNode,
246
522
  rules = pseudoRules,
523
+ localIds = ids,
247
524
  ) => {
248
525
  for (const node of from.childNodes) {
249
526
  to.appendChild(
250
527
  node instanceof Element
251
- ? cloneSnapshotTree(node, freezeStyles, rules)
528
+ ? cloneSnapshotTree(node, localIds, rules, svgMarker, cleanups)
252
529
  : node.cloneNode(false),
253
530
  );
254
531
  }
255
532
  };
256
- copyChildren(from, to);
533
+ copyChildren(
534
+ from,
535
+ to,
536
+ pseudoRules,
537
+ source instanceof HTMLTemplateElement ? snapshotIds(from) : ids,
538
+ );
539
+ if (source instanceof HTMLStyleElement && source.sheet) {
540
+ const root = source.getRootNode() as Document | ShadowRoot;
541
+ if (root.querySelector('svg')) {
542
+ let opaque = false;
543
+ const copy = copySnapshotSheet(source.sheet, ids, () => {
544
+ opaque = true;
545
+ });
546
+ // A real style element can retain opaque @imports; constructed sheets
547
+ // discard them. Serialize the original CSSOM with aliases in that case.
548
+ const sheet = opaque ? source.sheet : copy;
549
+ const dispose = installSnapshotSvgStyles(root, ids, svgMarker, [sheet]);
550
+ clone.textContent = snapshotUrls(
551
+ [...sheet.cssRules].map((rule) => rule.cssText).join('\n'),
552
+ ids,
553
+ source.sheet.href ?? document.baseURI,
554
+ );
555
+ dispose();
556
+ if (source.sheet.disabled) clone.setAttribute('media', 'not all');
557
+ }
558
+ }
257
559
  if (source.shadowRoot) {
258
560
  const shadow = clone.attachShadow({ mode: 'open' });
259
561
  const rules: string[] = [];
260
- copyChildren(source.shadowRoot, shadow, rules);
562
+ const shadowIds = snapshotIds(source.shadowRoot);
563
+ copyChildren(source.shadowRoot, shadow, rules, shadowIds);
564
+ shadow.adoptedStyleSheets = source.shadowRoot.adoptedStyleSheets.map(
565
+ (sheet) => copySnapshotSheet(sheet, shadowIds),
566
+ );
261
567
  copyLiveState(source.shadowRoot, shadow);
568
+ cleanups.push(
569
+ installSnapshotSvgStyles(
570
+ source.shadowRoot,
571
+ shadowIds,
572
+ svgMarker,
573
+ shadow.adoptedStyleSheets,
574
+ ),
575
+ );
262
576
  installSnapshotStyles(shadow, rules);
263
577
  }
264
578
  return clone;
@@ -285,16 +599,19 @@ function replaceEmbeddedContexts(source: ParentNode, clone: ParentNode): void {
285
599
  if (getComputedStyle(original).display === 'inline')
286
600
  placeholder.style.display = 'inline-block';
287
601
  // 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`;
602
+ placeholder.style.removeProperty('inline-size');
603
+ placeholder.style.removeProperty('block-size');
604
+ placeholder.style.setProperty('box-sizing', 'border-box', 'important');
605
+ placeholder.style.setProperty('width', `${rect.width}px`, 'important');
606
+ placeholder.style.setProperty('height', `${rect.height}px`, 'important');
291
607
  embedded.replaceWith(placeholder);
292
608
  });
293
609
  }
294
610
 
295
611
  /**
296
612
  * Create a snapshot clone of a .passage element for outgoing transitions.
297
- * - Strips IDs, action associations and event handlers from the clone tree
613
+ * - Strips authored IDs, action associations and event handlers; SVG IDs and
614
+ * their fragment references receive snapshot-local names
298
615
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
299
616
  * - Pauses/mutes any <audio>/<video>
300
617
  * - Copies what cloneNode leaves behind: canvas pixels, the state of form
@@ -307,18 +624,37 @@ function createSnapshot(
307
624
  transitionType: string,
308
625
  ): HTMLElement {
309
626
  const pseudoRules: string[] = [];
310
- const clone = cloneSnapshotTree(passageEl, false, pseudoRules) as HTMLElement;
627
+ const cleanups: (() => void)[] = [];
628
+ const ids = snapshotIds(passageEl);
629
+ const svgMarker = String(++snapshotPseudoId);
630
+ const clone = cloneSnapshotTree(
631
+ passageEl,
632
+ ids,
633
+ pseudoRules,
634
+ svgMarker,
635
+ cleanups,
636
+ ) as HTMLElement;
637
+ // These belong to the outgoing transition and container, not its frozen
638
+ // visual content. In particular, copied entrance animation must not win.
639
+ clone.style.removeProperty('animation');
640
+ clone.style.removeProperty('grid-area');
641
+ for (const name of ['opacity', 'transform']) {
642
+ // Normal declarations let the outgoing keyframes animate these values.
643
+ clone.style.setProperty(name, clone.style.getPropertyValue(name));
644
+ }
311
645
  copyLiveState(passageEl, clone);
312
646
  pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
313
647
 
314
648
  // A cloned browsing context would reload and execute scripts on insertion.
315
649
  // Keep its authored size/style as a passive placeholder instead.
316
650
  replaceEmbeddedContexts(passageEl, clone);
317
- const cleanup = installSnapshotStyles(
318
- passageEl.getRootNode() as Document | ShadowRoot,
319
- pseudoRules,
651
+ const root = passageEl.getRootNode() as Document | ShadowRoot;
652
+ cleanups.push(installSnapshotSvgStyles(root, ids, svgMarker));
653
+ const cleanup = installSnapshotStyles(root, pseudoRules);
654
+ if (cleanup) cleanups.push(cleanup);
655
+ snapshotStyleCleanup.set(clone, () =>
656
+ cleanups.forEach((dispose) => dispose()),
320
657
  );
321
- if (cleanup) snapshotStyleCleanup.set(clone, cleanup);
322
658
 
323
659
  // Disable interaction
324
660
  clone.style.pointerEvents = 'none';
@@ -1,17 +1,7 @@
1
+ import { sourcePositions } from '../markup/line-column';
2
+
1
3
  /** Index a source once; locate zero-based lines without rescanning its prefixes. */
2
4
  export function sourceLines(source: string): (offset: number) => number {
3
- const starts = [0];
4
- for (let i = 0; i < source.length; i++) {
5
- if (source[i] === '\n') starts.push(i + 1);
6
- }
7
- return (offset) => {
8
- let low = 0;
9
- let high = starts.length;
10
- while (low < high) {
11
- const middle = (low + high) >>> 1;
12
- if (starts[middle]! <= offset) low = middle + 1;
13
- else high = middle;
14
- }
15
- return Math.max(0, low - 1);
16
- };
5
+ const position = sourcePositions(source);
6
+ return (offset) => position(offset).line - 1;
17
7
  }