@rohal12/spindle 0.64.24 → 0.64.26

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.26",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,4 @@
1
- import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
+ import { renderActionButton, useControlAction } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { useDetachedBody } from './detached-body';
4
4
 
@@ -25,14 +25,6 @@ defineMacro({
25
25
  perform: handleClick,
26
26
  });
27
27
 
28
- return (
29
- <button
30
- type="button"
31
- {...actionAttributes(action, ctx)}
32
- onClick={handleClick}
33
- >
34
- {label}
35
- </button>
36
- );
28
+ return renderActionButton(action, ctx, handleClick, label);
37
29
  },
38
30
  });
@@ -1,4 +1,4 @@
1
- import { actionAttributes } from '../../hooks/use-action';
1
+ import { renderActionButton } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
4
4
  import { OPTION_CLAUSE } from './option-clauses';
@@ -12,18 +12,20 @@ defineMacro({
12
12
  parameters: [VARIABLE_PARAMETER],
13
13
  render({ children = [] }, ctx) {
14
14
  const options = ctx.extractOptions(children);
15
+ const label = ctx.value == null ? 'Choose an option' : String(ctx.value);
15
16
 
16
17
  const handleClick = () => {
17
18
  if (options.length === 0) return;
18
19
  const current = ctx.getValue!();
19
- const currentIndex = options.indexOf(String(current));
20
+ const currentIndex =
21
+ current == null ? -1 : options.indexOf(String(current));
20
22
  const nextIndex = (currentIndex + 1) % options.length;
21
23
  ctx.setValue!(options[nextIndex]);
22
24
  };
23
25
 
24
26
  const action = useVariableAction(ctx, {
25
27
  type: 'cycle',
26
- label: ctx.value == null ? options[0] || '' : String(ctx.value),
28
+ label,
27
29
  options,
28
30
  perform: (v) => {
29
31
  if (v !== undefined) {
@@ -34,14 +36,6 @@ defineMacro({
34
36
  },
35
37
  });
36
38
 
37
- return (
38
- <button
39
- type="button"
40
- {...actionAttributes(action, ctx)}
41
- onClick={handleClick}
42
- >
43
- {ctx.value == null ? options[0] || '' : String(ctx.value)}
44
- </button>
45
- );
39
+ return renderActionButton(action, ctx, handleClick, label);
46
40
  },
47
41
  });
@@ -1,4 +1,4 @@
1
- import { actionAttributes, useControlAction } from '../../hooks/use-action';
1
+ import { renderActionButton, useControlAction } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { PassageDialog } from '../PassageDialog';
4
4
 
@@ -33,13 +33,7 @@ defineMacro({
33
33
 
34
34
  return (
35
35
  <>
36
- <button
37
- type="button"
38
- {...actionAttributes(action, ctx)}
39
- onClick={openDialog}
40
- >
41
- {label}
42
- </button>
36
+ {renderActionButton(action, ctx, openDialog, label)}
43
37
  {open && (
44
38
  <PassageDialog
45
39
  passageName={passageName}
@@ -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,24 @@ 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
+ // An explicit empty form reference prevents both external association and
529
+ // fallback to an ancestor form, including forms inside the snapshot.
530
+ // Inert controls otherwise still submit values and participate in validation.
531
+ if (
532
+ html &&
533
+ source.matches('button, fieldset, input, object, output, select, textarea')
534
+ )
535
+ clone.setAttribute('form', '');
536
+ // Passive radios and details must not join live or other snapshot groups.
537
+ // Removing the name preserves their state when either tree is inserted.
538
+ if (
539
+ html &&
540
+ (source.localName === 'details' ||
541
+ (source.localName === 'input' &&
542
+ (source as HTMLInputElement).type === 'radio'))
543
+ )
544
+ clone.removeAttribute('name');
497
545
  // IDs and the passage class are removed, and custom tags become spans.
498
546
  // Freeze native and custom content before those selectors stop matching.
499
547
  const computed = getComputedStyle(source);
@@ -533,7 +581,14 @@ function cloneSnapshotTree(
533
581
  for (const node of from.childNodes) {
534
582
  to.appendChild(
535
583
  node instanceof Element
536
- ? cloneSnapshotTree(node, localIds, rules, svgMarker, cleanups)
584
+ ? cloneSnapshotTree(
585
+ node,
586
+ localIds,
587
+ rules,
588
+ svgMarker,
589
+ cleanups,
590
+ svgState,
591
+ )
537
592
  : node.cloneNode(false),
538
593
  );
539
594
  }
@@ -544,24 +599,20 @@ function cloneSnapshotTree(
544
599
  pseudoRules,
545
600
  source instanceof HTMLTemplateElement ? snapshotIds(from) : ids,
546
601
  );
547
- if (source instanceof HTMLStyleElement && source.sheet) {
602
+ if (source.localName === 'style' || linkedSheet) {
603
+ const sourceSheet = (source as HTMLStyleElement | HTMLLinkElement).sheet;
604
+ // HTML and generated content are already frozen in computed declarations.
605
+ // Authored rules must never remain active against the incoming passage.
606
+ clone.textContent = '';
548
607
  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;
608
+ if (sourceSheet && root.querySelector('svg')) {
609
+ const copy = copySnapshotSheet(sourceSheet, ids, () => {
610
+ svgState.opaqueRoots.add(root);
553
611
  });
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
- );
612
+ const dispose = installSnapshotSvgStyles(root, ids, svgMarker, [copy]);
613
+ clone.textContent = snapshotRuleText(copy.cssRules);
563
614
  dispose();
564
- if (source.sheet.disabled) clone.setAttribute('media', 'not all');
615
+ if (sourceSheet.disabled) clone.setAttribute('media', 'not all');
565
616
  }
566
617
  }
567
618
  if (source.shadowRoot) {
@@ -635,13 +686,27 @@ function createSnapshot(
635
686
  const cleanups: (() => void)[] = [];
636
687
  const ids = snapshotIds(passageEl);
637
688
  const svgMarker = String(++snapshotPseudoId);
689
+ const svgState: SnapshotSvgState = { opaqueRoots: new Set(), copies: [] };
638
690
  const clone = cloneSnapshotTree(
639
691
  passageEl,
640
692
  ids,
641
693
  pseudoRules,
642
694
  svgMarker,
643
695
  cleanups,
696
+ svgState,
644
697
  ) as HTMLElement;
698
+ // Opaque imported CSS cannot be scoped through the CSSOM. Freeze rendered
699
+ // SVG nodes instead of re-importing global rules into the live document.
700
+ // Definitions must keep specified values: copying computed defaults there
701
+ // replaces the fill/currentColor inherited by each use instance.
702
+ for (const { source, clone: copy, ids: localIds } of svgState.copies) {
703
+ if (
704
+ svgState.opaqueRoots.has(source.getRootNode()) &&
705
+ !source.closest('defs, symbol, clipPath, mask, pattern, marker')
706
+ ) {
707
+ copyComputedStyle(getComputedStyle(source), copy.style, localIds);
708
+ }
709
+ }
645
710
  // These belong to the outgoing transition and container, not its frozen
646
711
  // visual content. In particular, copied entrance animation must not win.
647
712
  clone.style.removeProperty('animation');
@@ -1,5 +1,6 @@
1
1
  import { createContext } from 'preact';
2
2
  import { useCallback, useContext, useLayoutEffect, useRef } from 'preact/hooks';
3
+ import { h, type ComponentChildren } from 'preact';
3
4
  import {
4
5
  registerAction,
5
6
  generateActionId,
@@ -52,6 +53,20 @@ export function actionAttributes(
52
53
  };
53
54
  }
54
55
 
56
+ /** Render a native macro button with its registered action and label. */
57
+ export function renderActionButton(
58
+ action: ControlAction,
59
+ control: { id?: string; cls?: string },
60
+ onClick: () => void,
61
+ label: ComponentChildren,
62
+ ) {
63
+ return h(
64
+ 'button',
65
+ { type: 'button', ...actionAttributes(action, control), onClick },
66
+ label,
67
+ );
68
+ }
69
+
55
70
  /**
56
71
  * While true, controls rendered underneath do not register actions or reserve
57
72
  * IDs. Used for display-only content mounted off-screen, so it never shows up
@@ -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 !==