@rohal12/spindle 0.64.23 → 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.23",
3
+ "version": "0.64.25",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,11 @@
1
- import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';
1
+ import {
2
+ useCallback,
3
+ useContext,
4
+ useEffect,
5
+ useLayoutEffect,
6
+ useRef,
7
+ useState,
8
+ } from 'preact/hooks';
2
9
  import { parseMarkup } from '../markup/parse';
3
10
  import type { ASTNode } from '../markup/ast';
4
11
  import {
@@ -8,7 +15,11 @@ import {
8
15
  InterfaceContext,
9
16
  useViewScope,
10
17
  } from '../markup/render';
11
- import { useStoryFields } from '../hooks/use-story-fields';
18
+ import {
19
+ LateMountContext,
20
+ OutgoingContext,
21
+ useStoryFields,
22
+ } from '../hooks/use-story-fields';
12
23
  import type { Passage as PassageData } from '../parser';
13
24
  import { sourceLocationOf } from '../utils/source-location';
14
25
  import { emitFromRender } from '../event-emitter';
@@ -179,27 +190,42 @@ export function Passage({
179
190
  }
180
191
  }, [passage.name, navigationId]);
181
192
 
193
+ // The macros that mount after this passage was left must not run (see
194
+ // LateMountContext). Those of its first render are not late: that render
195
+ // may itself navigate away, and the macros after the navigation still run.
196
+ const hasLeft = useContext(OutgoingContext);
197
+ const committed = useRef(false);
198
+ useLayoutEffect(() => {
199
+ committed.current = true;
200
+ }, []);
201
+ const lateMount = useCallback(
202
+ () => committed.current && !!hasLeft?.(),
203
+ [hasLeft],
204
+ );
205
+
182
206
  const nobr = passage.tags.includes('nobr');
183
207
  const viewScope = useViewScope();
184
208
 
185
209
  const inner = (
186
210
  <InterfaceContext.Provider value={false}>
187
211
  <ViewScopeContext.Provider value={viewScope}>
188
- <div
189
- ref={elRef}
190
- class="passage"
191
- data-passage={passage.name}
192
- data-tags={passage.tags.join(' ')}
193
- data-transition={dataTransition}
194
- >
195
- {specialPassage('PassageHeader', 'header')}
196
- <PassageBody
197
- passage={passage}
198
- content={passage.content}
199
- />
200
- {specialPassage('PassageFooter', 'footer')}
201
- {doneReady && specialPassage('PassageDone', 'done')}
202
- </div>
212
+ <LateMountContext.Provider value={lateMount}>
213
+ <div
214
+ ref={elRef}
215
+ class="passage"
216
+ data-passage={passage.name}
217
+ data-tags={passage.tags.join(' ')}
218
+ data-transition={dataTransition}
219
+ >
220
+ {specialPassage('PassageHeader', 'header')}
221
+ <PassageBody
222
+ passage={passage}
223
+ content={passage.content}
224
+ />
225
+ {specialPassage('PassageFooter', 'footer')}
226
+ {doneReady && specialPassage('PassageDone', 'done')}
227
+ </div>
228
+ </LateMountContext.Provider>
203
229
  </ViewScopeContext.Provider>
204
230
  </InterfaceContext.Provider>
205
231
  );
@@ -7,7 +7,10 @@ import { defineMacro } from '../../define-macro';
7
7
  import { MacroError, logMacroError } from './MacroError';
8
8
  import { currentSourceLocation } from '../../utils/source-location';
9
9
  import { checkVariableName, ownValue } from '../../utils/namespace';
10
- import { PendingIterationContext } from '../../hooks/use-story-fields';
10
+ import {
11
+ LateMountContext,
12
+ PendingIterationContext,
13
+ } from '../../hooks/use-story-fields';
11
14
 
12
15
  /**
13
16
  * The previous output before the first successful evaluation. Distinct from
@@ -130,6 +133,8 @@ defineMacro({
130
133
  const name = target.slice(1);
131
134
  const localsUpdate = isLocal ? ctx.update : null;
132
135
  const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
136
+ // In a passage that was left it must not compute (see LateMountContext)
137
+ const tooLate = ctx.hooks.useContext(LateMountContext)?.() ?? false;
133
138
 
134
139
  const prevOutput = ctx.hooks.useRef<unknown>(UNSET);
135
140
  // The navigation the target was last checked in
@@ -151,7 +156,7 @@ defineMacro({
151
156
  const ran = ctx.hooks.useRef(false);
152
157
  if (!ran.current) {
153
158
  ran.current = true;
154
- compute();
159
+ if (!tooLate) compute();
155
160
  }
156
161
 
157
162
  // The merged values only decide when to recompute; computeAndApply reads
@@ -160,7 +165,7 @@ defineMacro({
160
165
  ctx.hooks.useLayoutEffect(() => {
161
166
  // A queued effect can outlive the loop state its locals belong to.
162
167
  // Let the owner reconcile first, dropping any removed iterations.
163
- if (!pendingIteration?.(useStoryStore.getState())) compute();
168
+ if (!tooLate && !pendingIteration?.(useStoryStore.getState())) compute();
164
169
  }, [ctx.merged, pendingIteration]);
165
170
 
166
171
  return null;
@@ -1,4 +1,5 @@
1
1
  import { useStoryStore } from '../../store';
2
+ import { LateMountContext } from '../../hooks/use-story-fields';
2
3
  import { defineMacro } from '../../define-macro';
3
4
  import { evaluatePassageName } from './macro-args';
4
5
  import { logMacroError, MacroError } from './MacroError';
@@ -10,7 +11,11 @@ defineMacro({
10
11
  render(_props, ctx) {
11
12
  // Boxed: anything can be thrown, including null and other falsy values
12
13
  const [failure, setFailure] = ctx.hooks.useState<{ error: unknown }>();
14
+ // Mounting in a passage that was left: it must not navigate (see
15
+ // LateMountContext)
16
+ const tooLate = ctx.hooks.useContext(LateMountContext)?.() ?? false;
13
17
  ctx.hooks.useLayoutEffect(() => {
18
+ if (tooLate) return;
14
19
  // Reported like an error in {do}: thrown out of an effect, it would
15
20
  // abort the rest of the render's effects (e.g. the session could not
16
21
  // be written because the state holds a function). The location is
@@ -1,6 +1,6 @@
1
1
  import { DisplayOnlyContext } from '../../display-only';
2
2
  import { useStoryStore } from '../../store';
3
- import { useStoryFields } from '../../hooks/use-story-fields';
3
+ import { LateMountContext, useStoryFields } from '../../hooks/use-story-fields';
4
4
  import { parseMarkup } from '../../markup/parse';
5
5
  import { NobrContext } from '../../markup/render';
6
6
  import { defineMacro } from '../../define-macro';
@@ -15,6 +15,9 @@ defineMacro({
15
15
  parameters: INCLUDE_PARAMETERS,
16
16
  render(_props, ctx) {
17
17
  const displayOnly = ctx.hooks.useContext(DisplayOnlyContext);
18
+ // Mounting in a passage that was left: it must not count (see
19
+ // LateMountContext)
20
+ const tooLate = ctx.hooks.useContext(LateMountContext)?.() ?? false;
18
21
  const { storyData } = useStoryFields('storyData');
19
22
 
20
23
  const { inline } = ctx.args;
@@ -42,9 +45,10 @@ defineMacro({
42
45
 
43
46
  // Count the inclusion when its content mounts or the passage changes,
44
47
  // not on every render (an unrelated variable update re-renders it)
48
+ // (tooLate is read when the effect runs for the content that mounted)
45
49
  const included = !failure && !!passage;
46
50
  ctx.hooks.useEffect(() => {
47
- if (included && !displayOnly) {
51
+ if (included && !displayOnly && !tooLate) {
48
52
  useStoryStore.getState().trackRender(passageName);
49
53
  }
50
54
  }, [included, passageName, displayOnly]);
@@ -1,4 +1,5 @@
1
- import { useRef } from 'preact/hooks';
1
+ import { useContext, useRef } from 'preact/hooks';
2
+ import { LateMountContext } from '../../hooks/use-story-fields';
2
3
  import { currentSourceLocation } from '../../utils/source-location';
3
4
  import { errorMessage } from '../../utils/error-message';
4
5
 
@@ -34,7 +35,8 @@ export function logMacroError(
34
35
  }
35
36
 
36
37
  /**
37
- * Run `effect` once, during the macro's first render. If it throws, the
38
+ * Run `effect` once, during the macro's first render, unless that is in a
39
+ * passage already left (see LateMountContext). If it throws, the
38
40
  * error is logged under `{macro rawArgs}` and shown in place of the macro
39
41
  * from then on; otherwise the macro renders nothing.
40
42
  */
@@ -42,8 +44,11 @@ export function useRunOnce(macro: string, rawArgs: string, effect: () => void) {
42
44
  // Unset until the effect has run. Boxed: anything can be thrown,
43
45
  // including null and other falsy values.
44
46
  const failure = useRef<{ error: unknown } | null | undefined>(undefined);
47
+ const lateMount = useContext(LateMountContext);
45
48
  if (failure.current === undefined) {
46
49
  failure.current = null;
50
+ // Mounting in a passage that was left: it must not run (see LateMountContext)
51
+ if (lateMount?.()) return null;
47
52
  const location = currentSourceLocation();
48
53
  try {
49
54
  effect();
@@ -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');
@@ -34,6 +34,11 @@ import { DialogCloseContext } from '../PassageDialog';
34
34
  import { defineMacro } from '../../define-macro';
35
35
  import { errorMessage } from '../../utils/error-message';
36
36
 
37
+ /** How long a Delete button stays armed without a second press. */
38
+ const ARMED_DELETE_MS = 5000;
39
+ const ARMED_DELETE_LABEL = 'Press again to delete';
40
+ const ARMED_DELETE_HINT = 'Press again to delete this save';
41
+
37
42
  function relativeTime(iso: string): string {
38
43
  const diff = Date.now() - new Date(iso).getTime();
39
44
  const secs = Math.floor(diff / 1000);
@@ -71,6 +76,8 @@ export function SaveManagerContent({
71
76
  } | null>(null);
72
77
  const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());
73
78
  const [renamingId, setRenamingId] = useState<string | null>(null);
79
+ // The save whose Delete button has been pressed once (see handleDelete)
80
+ const [armedId, setArmedId] = useState<string | null>(null);
74
81
  const renameCancelled = useRef(false);
75
82
  const [renameValue, setRenameValue] = useState('');
76
83
  const renameInputRef = useRef<HTMLInputElement>(null);
@@ -137,6 +144,38 @@ export function SaveManagerContent({
137
144
  };
138
145
  }, []);
139
146
 
147
+ // While a Delete button is armed, anything else the player does (a press
148
+ // elsewhere, a key, Escape) or a pause puts it back. Blur and Tab are
149
+ // covered by the button's onBlur; the document listeners cover browsers
150
+ // that do not focus a button on click. Escape disarms only: the dialog
151
+ // stays open.
152
+ useEffect(() => {
153
+ if (armedId === null) return;
154
+ const disarm = () => setArmedId(null);
155
+ const onArmedButton = (e: Event) =>
156
+ e.target instanceof Element && !!e.target.closest('[data-armed]');
157
+ const onPointerDown = (e: Event) => {
158
+ if (!onArmedButton(e)) disarm();
159
+ };
160
+ const onKeyDown = (e: KeyboardEvent) => {
161
+ if (e.key === 'Escape') {
162
+ e.preventDefault();
163
+ e.stopPropagation();
164
+ disarm();
165
+ } else if (!onArmedButton(e)) {
166
+ disarm();
167
+ }
168
+ };
169
+ const timer = window.setTimeout(disarm, ARMED_DELETE_MS);
170
+ document.addEventListener('pointerdown', onPointerDown, true);
171
+ document.addEventListener('keydown', onKeyDown, true);
172
+ return () => {
173
+ clearTimeout(timer);
174
+ document.removeEventListener('pointerdown', onPointerDown, true);
175
+ document.removeEventListener('keydown', onKeyDown, true);
176
+ };
177
+ }, [armedId]);
178
+
140
179
  const toggleCollapse = (id: string) => {
141
180
  setCollapsed((prev) => {
142
181
  const next = new Set(prev);
@@ -229,8 +268,13 @@ export function SaveManagerContent({
229
268
  }
230
269
  };
231
270
 
271
+ /** The first press arms the button; a second press on it deletes. */
232
272
  const handleDelete = async (saveId: string) => {
233
- if (!confirm('Delete this save?')) return;
273
+ if (armedId !== saveId) {
274
+ setArmedId(saveId);
275
+ return;
276
+ }
277
+ setArmedId(null);
234
278
  await runAction('Save deleted', 'Failed to delete save', async () => {
235
279
  await deleteSaveById(saveId);
236
280
  // The save may have been held by a slot; hasSave() and QuickLoad
@@ -475,10 +519,34 @@ export function SaveManagerContent({
475
519
  </button>
476
520
  <button
477
521
  type="button"
478
- class="save-slot-action danger"
522
+ class={
523
+ armedId === save.meta.id
524
+ ? 'save-slot-action danger is-armed'
525
+ : 'save-slot-action danger'
526
+ }
527
+ data-armed={
528
+ armedId === save.meta.id ? 'true' : undefined
529
+ }
530
+ aria-label={
531
+ armedId === save.meta.id
532
+ ? ARMED_DELETE_HINT
533
+ : undefined
534
+ }
535
+ title={
536
+ armedId === save.meta.id
537
+ ? ARMED_DELETE_HINT
538
+ : undefined
539
+ }
479
540
  onClick={() => handleDelete(save.meta.id)}
541
+ onBlur={() =>
542
+ setArmedId((id) =>
543
+ id === save.meta.id ? null : id,
544
+ )
545
+ }
480
546
  >
481
- Delete
547
+ {armedId === save.meta.id
548
+ ? ARMED_DELETE_LABEL
549
+ : 'Delete'}
482
550
  </button>
483
551
  </div>
484
552
  </div>
@@ -517,6 +585,14 @@ export function SaveManagerContent({
517
585
  )}
518
586
  </div>
519
587
 
588
+ <div
589
+ class="saves-sr-only"
590
+ role="status"
591
+ aria-live="polite"
592
+ >
593
+ {armedId !== null ? ARMED_DELETE_HINT : ''}
594
+ </div>
595
+
520
596
  {status && (
521
597
  <div class={`saves-status ${status.type === 'error' ? 'error' : ''}`}>
522
598
  {status.text}
@@ -32,6 +32,19 @@ export const PendingIterationContext = createContext<
32
32
  */
33
33
  export const OutgoingContext = createContext<(() => boolean) | null>(null);
34
34
 
35
+ /**
36
+ * Tells the macros that run code as they mount ({set}, {do}, {unset},
37
+ * {goto}, {computed}, the count of an {include}) whether they come too late: the
38
+ * passage they belong to was on the page and has been left since. State
39
+ * that changed before the navigation can still render new content into the
40
+ * passage on its way out, and its code would run against the destination's
41
+ * state (#352, as #410 for timers). The macros that mount while the passage
42
+ * is first rendered are never late, whatever that render navigates. Null
43
+ * outside a displayed passage, and in a click body, which renders apart
44
+ * from the passage and runs as part of the click.
45
+ */
46
+ export const LateMountContext = createContext<(() => boolean) | null>(null);
47
+
35
48
  /**
36
49
  * Story state fields `keys`, re-rendering when any of them changes (as one
37
50
  * useStoryStore() selector per field would). The result keeps its identity
@@ -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;