@rohal12/spindle 0.64.24 → 0.64.25

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.24",
3
+ "version": "0.64.25",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -236,6 +236,31 @@ function snapshotUrls(
236
236
  */
237
237
  const snapshotSvgRules = new WeakSet<CSSRule>();
238
238
 
239
+ /** Keep only snapshot aliases, retaining their media/layer/nesting context. */
240
+ function snapshotRuleText(rules: Iterable<CSSRule>): string {
241
+ const text: string[] = [];
242
+ for (const rule of rules) {
243
+ if (snapshotSvgRules.has(rule)) text.push(rule.cssText);
244
+ else if ('cssRules' in rule && !(rule instanceof CSSKeyframesRule)) {
245
+ const body = snapshotRuleText((rule as CSSGroupingRule).cssRules);
246
+ if (body)
247
+ text.push(
248
+ `${rule.cssText.slice(0, rule.cssText.indexOf('{'))}{${body}}`,
249
+ );
250
+ }
251
+ }
252
+ return text.join('\n');
253
+ }
254
+
255
+ interface SnapshotSvgState {
256
+ opaqueRoots: Set<Node>;
257
+ copies: {
258
+ source: Element;
259
+ clone: SVGElement;
260
+ ids: ReadonlyMap<string, string>;
261
+ }[];
262
+ }
263
+
239
264
  /** A detached style element has no sheet yet. Carry its CSSOM, including
240
265
  * script-inserted rules and imported styles, into the passive tree.
241
266
  */
@@ -459,13 +484,18 @@ function cloneSnapshotTree(
459
484
  pseudoRules: string[] = [],
460
485
  svgMarker = String(++snapshotPseudoId),
461
486
  cleanups: (() => void)[] = [],
487
+ svgState: SnapshotSvgState = { opaqueRoots: new Set(), copies: [] },
462
488
  ): Element {
463
489
  const html = source.namespaceURI === 'http://www.w3.org/1999/xhtml';
464
490
  const svg = source.namespaceURI === 'http://www.w3.org/2000/svg';
465
491
  const custom = html && source.localName.includes('-');
492
+ const linkedSheet =
493
+ html &&
494
+ source.localName === 'link' &&
495
+ (source as HTMLLinkElement).relList.contains('stylesheet');
466
496
  const clone = document.createElementNS(
467
497
  source.namespaceURI,
468
- custom ? 'span' : source.localName,
498
+ linkedSheet ? 'style' : custom ? 'span' : source.localName,
469
499
  );
470
500
  for (const attr of [...source.attributes]) {
471
501
  if (
@@ -494,6 +524,17 @@ function cloneSnapshotTree(
494
524
  clone.setAttribute('data-spindle-snapshot-original-id', source.id);
495
525
  if (custom) clone.setAttribute('data-spindle-snapshot-tag', source.localName);
496
526
  if (svg) clone.setAttribute('data-spindle-snapshot-svg', svgMarker);
527
+ if (svg) svgState.copies.push({ source, clone: clone as SVGElement, ids });
528
+ // A passive radio must not join either a live form's group or another
529
+ // snapshot's group. With no name it cannot share checkedness at insertion.
530
+ if (
531
+ html &&
532
+ source.localName === 'input' &&
533
+ (source as HTMLInputElement).type === 'radio'
534
+ ) {
535
+ clone.removeAttribute('name');
536
+ clone.removeAttribute('form');
537
+ }
497
538
  // IDs and the passage class are removed, and custom tags become spans.
498
539
  // Freeze native and custom content before those selectors stop matching.
499
540
  const computed = getComputedStyle(source);
@@ -533,7 +574,14 @@ function cloneSnapshotTree(
533
574
  for (const node of from.childNodes) {
534
575
  to.appendChild(
535
576
  node instanceof Element
536
- ? cloneSnapshotTree(node, localIds, rules, svgMarker, cleanups)
577
+ ? cloneSnapshotTree(
578
+ node,
579
+ localIds,
580
+ rules,
581
+ svgMarker,
582
+ cleanups,
583
+ svgState,
584
+ )
537
585
  : node.cloneNode(false),
538
586
  );
539
587
  }
@@ -544,24 +592,20 @@ function cloneSnapshotTree(
544
592
  pseudoRules,
545
593
  source instanceof HTMLTemplateElement ? snapshotIds(from) : ids,
546
594
  );
547
- if (source instanceof HTMLStyleElement && source.sheet) {
595
+ if (source.localName === 'style' || linkedSheet) {
596
+ const sourceSheet = (source as HTMLStyleElement | HTMLLinkElement).sheet;
597
+ // HTML and generated content are already frozen in computed declarations.
598
+ // Authored rules must never remain active against the incoming passage.
599
+ clone.textContent = '';
548
600
  const root = source.getRootNode() as Document | ShadowRoot;
549
- if (root.querySelector('svg')) {
550
- let opaque = false;
551
- const copy = copySnapshotSheet(source.sheet, ids, () => {
552
- opaque = true;
601
+ if (sourceSheet && root.querySelector('svg')) {
602
+ const copy = copySnapshotSheet(sourceSheet, ids, () => {
603
+ svgState.opaqueRoots.add(root);
553
604
  });
554
- // A real style element can retain opaque @imports; constructed sheets
555
- // discard them. Serialize the original CSSOM with aliases in that case.
556
- const sheet = opaque ? source.sheet : copy;
557
- const dispose = installSnapshotSvgStyles(root, ids, svgMarker, [sheet]);
558
- clone.textContent = snapshotUrls(
559
- [...sheet.cssRules].map((rule) => rule.cssText).join('\n'),
560
- ids,
561
- source.sheet.href ?? document.baseURI,
562
- );
605
+ const dispose = installSnapshotSvgStyles(root, ids, svgMarker, [copy]);
606
+ clone.textContent = snapshotRuleText(copy.cssRules);
563
607
  dispose();
564
- if (source.sheet.disabled) clone.setAttribute('media', 'not all');
608
+ if (sourceSheet.disabled) clone.setAttribute('media', 'not all');
565
609
  }
566
610
  }
567
611
  if (source.shadowRoot) {
@@ -635,13 +679,27 @@ function createSnapshot(
635
679
  const cleanups: (() => void)[] = [];
636
680
  const ids = snapshotIds(passageEl);
637
681
  const svgMarker = String(++snapshotPseudoId);
682
+ const svgState: SnapshotSvgState = { opaqueRoots: new Set(), copies: [] };
638
683
  const clone = cloneSnapshotTree(
639
684
  passageEl,
640
685
  ids,
641
686
  pseudoRules,
642
687
  svgMarker,
643
688
  cleanups,
689
+ svgState,
644
690
  ) as HTMLElement;
691
+ // Opaque imported CSS cannot be scoped through the CSSOM. Freeze rendered
692
+ // SVG nodes instead of re-importing global rules into the live document.
693
+ // Definitions must keep specified values: copying computed defaults there
694
+ // replaces the fill/currentColor inherited by each use instance.
695
+ for (const { source, clone: copy, ids: localIds } of svgState.copies) {
696
+ if (
697
+ svgState.opaqueRoots.has(source.getRootNode()) &&
698
+ !source.closest('defs, symbol, clipPath, mask, pattern, marker')
699
+ ) {
700
+ copyComputedStyle(getComputedStyle(source), copy.style, localIds);
701
+ }
702
+ }
645
703
  // These belong to the outgoing transition and container, not its frozen
646
704
  // visual content. In particular, copied entrance animation must not win.
647
705
  clone.style.removeProperty('animation');
@@ -144,24 +144,19 @@ let attrCode = false;
144
144
  let rawName = '';
145
145
  /** The HTML text-only body being read; its own closer ends this context. */
146
146
  let htmlTextTag = '';
147
+ /** First bracket boundary of the current (non-nesting) link label. */
148
+ let linkTextEnd = -1;
147
149
 
148
150
  /**
149
151
  * The index in `inner` (at `at` in the input) of the first `separator` that
150
152
  * is not inside a {…} of the label: its code (`{if $a || $b}`, a string with
151
153
  * a pipe) belongs to the label, not to the link's syntax.
152
154
  */
153
- function linkSeparatorIndex(inner, at, separator) {
155
+ function linkSeparatorIndex(inner, at, separator, spans) {
156
+ let span = 0;
154
157
  for (let i = 0; i < inner.length; i++) {
155
- const c = inner.charAt(i);
156
- if (c === '\\' && /[{}]/.test(inner.charAt(i + 1))) {
157
- i++;
158
- } else if (c === LB) {
159
- // Selectors, then a macro name or the sigil of a variable or expression
160
- const head = /^(?:[.#][\w-]*)* ?(\/?[a-zA-Z][\w-]*|(?=[$_@%(!]))/.exec(inner.slice(i + 1));
161
- if (!head) continue;
162
- const close = hooks.closeBrace(input, at + i + 1 + head[0].length, at + i + 1);
163
- // One that does not end inside the label is no markup of it
164
- if (close !== -1 && close < at + inner.length) i = close - at;
158
+ if (span < spans.length && i === spans[span].start - at) {
159
+ i = spans[span++].end - at - 1;
165
160
  } else if (inner.startsWith(separator, i)) {
166
161
  return i;
167
162
  }
@@ -294,8 +289,8 @@ Literal
294
289
  / "[" { return lexeme('text', location(), { value: '[' }); }
295
290
 
296
291
  LinkLexeme
297
- = &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:$LinkText ("]]" / OpenEnd) {
298
- const link = lexeme('link', location(), parseLink(inner, at, (separator) => linkSeparatorIndex(inner, at, separator)));
292
+ = &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:LinkText ("]]" / OpenEnd) {
293
+ const link = lexeme('link', location(), parseLink(inner.value, at, (separator) => linkSeparatorIndex(inner.value, at, separator, inner.spans)));
299
294
  link.selectorSpan = selectorSpan(s, ss, at);
300
295
  return withSelectors(link, s);
301
296
  }
@@ -307,7 +302,25 @@ LinkLexeme
307
302
  * exponentially; a link's text can't hold [[ now.)
308
303
  */
309
304
  LinkText
310
- = (!("]]" / "[[") .)*
305
+ = start:Here &{
306
+ const close = input.indexOf(']]', start);
307
+ const nested = input.indexOf('[[', start);
308
+ linkTextEnd = Math.min(close < 0 ? input.length : close, nested < 0 ? input.length : nested);
309
+ return true;
310
+ }
311
+ parts:(!("]]" / "[[") part:(LinkLabelCode / .) { return typeof part === 'string' ? null : part; })* end:Here {
312
+ return { value: input.slice(start, end), spans: parts.filter(Boolean) };
313
+ }
314
+
315
+ /** Use the same selectors and macro names as the markup being skipped. */
316
+ LinkLabelCode
317
+ = start:Here "\\" [{}] end:Here { return { start, end }; }
318
+ / start:Here "{" Selectors codeStart:Here ("/"? MacroName / &[$_@%(!]) nameEnd:Here
319
+ &{
320
+ const close = hooks.closeBrace(input, nameEnd, codeStart);
321
+ return close >= 0 && close < linkTextEnd && skipTo(close);
322
+ }
323
+ $(.|{ return skipEnd - offset(); }|) "}" end:Here { return { start, end }; }
311
324
 
312
325
  /** `.class#id` selectors, and the one space after them. */
313
326
  Selectors
@@ -39,18 +39,33 @@ function formatValue(value: unknown): string {
39
39
  }
40
40
  }
41
41
 
42
- /** What a control with an action shows: its type, variable and value. */
42
+ function selectedLabels(el: HTMLSelectElement): string | string[] {
43
+ const labels = Array.from(el.options)
44
+ .filter((option) => option.selected)
45
+ .map(
46
+ (option) =>
47
+ // An empty label attribute falls back to the option's text.
48
+ option.getAttribute('label') ||
49
+ (option.textContent ?? '').trim().replace(/\s+/g, ' '),
50
+ );
51
+ return el.multiple ? labels : (labels[0] ?? '');
52
+ }
53
+
54
+ /** What a control shows: its type, optional action variable and live value. */
43
55
  function controlMarker(el: Element): string {
44
56
  const own = el as Partial<HTMLInputElement>;
45
57
  const action = getAction(el.getAttribute('data-action') ?? '');
46
- const type = action?.type ?? el.getAttribute('type') ?? el.localName;
58
+ const type =
59
+ action?.type ?? el.getAttribute('type')?.toLowerCase() ?? el.localName;
47
60
  const isCheckbox = type === 'checkbox';
48
61
  const value =
49
62
  action?.value !== undefined
50
63
  ? action.value
51
64
  : isCheckbox
52
65
  ? !!own.checked
53
- : (own.value ?? '');
66
+ : el.localName === 'select' && !el.hasAttribute('data-action')
67
+ ? selectedLabels(el as HTMLSelectElement)
68
+ : (own.value ?? '');
54
69
  const shown = isCheckbox
55
70
  ? value
56
71
  ? 'checked'
@@ -61,8 +76,10 @@ function controlMarker(el: Element): string {
61
76
  variable && !variable.startsWith('$') ? `$${variable}` : variable;
62
77
  // A radio is one choice of its variable: its own value, and whether it is
63
78
  // the one selected (the action's value is the variable's, shared by all)
64
- if (type === 'radiobutton' && own.value !== undefined) {
65
- const state = action?.value === own.value ? 'selected' : 'unselected';
79
+ if ((type === 'radiobutton' || type === 'radio') && own.value !== undefined) {
80
+ const selected =
81
+ action?.value !== undefined ? action.value === own.value : !!own.checked;
82
+ const state = selected ? 'selected' : 'unselected';
66
83
  return `[${type}${name ? ` ${name}` : ''} = ${formatValue(own.value)}: ${state}]`;
67
84
  }
68
85
  return `[${type}${name ? ` ${name}` : ''}: ${shown}]`;
@@ -70,7 +87,7 @@ function controlMarker(el: Element): string {
70
87
 
71
88
  /**
72
89
  * The text a reader sees in the element, as lines: blocks and `<br>` break
73
- * lines, hidden elements are left out, and a control with a `data-action`
90
+ * lines, hidden elements are left out, and a native or action-associated control
74
91
  * becomes a marker such as `[textbox $name: "Alice"]`. Elements inside `el`
75
92
  * that match `skip` are left out with their content. `visibilityRoot` bounds
76
93
  * ancestor checks when reading StoryContext inside its hidden host.
@@ -107,10 +124,11 @@ export function observableText(
107
124
  if (isHidden(child) || (skip && child !== el && child.matches(skip)))
108
125
  return;
109
126
  if (
110
- child.hasAttribute('data-action') &&
111
- (child.matches('input, textarea, select') ||
127
+ child.matches('input, textarea, select') ||
128
+ (child.hasAttribute('data-action') &&
112
129
  getAction(child.getAttribute('data-action')!)?.type === 'cycle')
113
130
  ) {
131
+ if (child.matches('input[type="hidden" i]')) return;
114
132
  if (!isRendered(child, visibilityRoot)) return;
115
133
  out += controlMarker(child);
116
134
  return;
@@ -35,6 +35,17 @@ export function* composedElements(root: ParentNode): Generator<HTMLElement> {
35
35
 
36
36
  /** Elements whose content is never text the reader reads. */
37
37
  const NOT_TEXT = new Set(['script', 'style', 'template', 'noscript']);
38
+ const SVG_NOT_TEXT = new Set([
39
+ 'title',
40
+ 'desc',
41
+ 'metadata',
42
+ 'defs',
43
+ 'symbol',
44
+ 'clippath',
45
+ 'mask',
46
+ 'pattern',
47
+ 'marker',
48
+ ]);
38
49
 
39
50
  /**
40
51
  * Whether the element hides its whole subtree, including stylesheet rules.
@@ -47,6 +58,8 @@ export function isHidden(el: Element): boolean {
47
58
  /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute('style') ?? '') ||
48
59
  el.ownerDocument.defaultView?.getComputedStyle(el).display === 'none' ||
49
60
  NOT_TEXT.has(el.localName.toLowerCase()) ||
61
+ (el.namespaceURI === 'http://www.w3.org/2000/svg' &&
62
+ SVG_NOT_TEXT.has(el.localName.toLowerCase())) ||
50
63
  (el.parentElement?.tagName === 'DETAILS' &&
51
64
  !el.parentElement.hasAttribute('open') &&
52
65
  el !==