@rohal12/spindle 0.59.21 → 0.59.23

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.
@@ -1,15 +1,21 @@
1
- import { readFileSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
-
5
1
  import {
6
2
  checkParameterTypes,
7
3
  collectStoryPassageReferences,
8
4
  validateStoryMarkup,
9
5
  } from './story-variables.js';
6
+ // The built-in macros, generated at build time (scripts/dump-macro-registry.ts)
7
+ // as a module, not read from a file: a bundler inlines it.
8
+ import builtinList from './macro-registry.js';
10
9
 
11
10
  export {
11
+ validateStoryMarkup,
12
+ collectStoryPassageReferences,
13
+ passagePieces,
14
+ pieceOffset,
15
+ pairMarkup,
16
+ isBlockMacro,
12
17
  parseStoryVariables,
18
+ parseDeclarations,
13
19
  formatDiagnostic,
14
20
  findCodeEnd,
15
21
  lexJs,
@@ -33,17 +39,15 @@ export {
33
39
  splitIncludeFlag,
34
40
  } from './story-variables.js';
35
41
 
36
- const __dirname = dirname(fileURLToPath(import.meta.url));
37
-
38
- // Load built-in macro metadata generated at build time
39
- const registryPath = join(__dirname, 'macro-registry.json');
40
- let builtins = [];
41
- try {
42
- builtins = JSON.parse(readFileSync(registryPath, 'utf-8'));
43
- } catch {
44
- // macro-registry.json not yet built — empty builtins
45
- }
42
+ /**
43
+ * The built-in macros: what `getMacroRegistry()` returns before any
44
+ * `defineMacro`. Pass them (and your own) to `validateStoryMarkup`,
45
+ * `collectStoryPassageReferences` and `passagePieces`, which take the macros
46
+ * they check against and keep no state.
47
+ */
48
+ export const builtinMacros = Object.freeze([...builtinList]);
46
49
 
50
+ const builtins = builtinMacros;
47
51
  const metadata = new Map();
48
52
  for (const m of builtins) metadata.set(m.name.toLowerCase(), m);
49
53
 
@@ -80,14 +84,16 @@ export function getMacroRegistry() {
80
84
  * Validate the markup of a story's passages as Spindle does when the story
81
85
  * starts: malformed markup and unknown macros (checked against the built-in
82
86
  * macros and those registered with defineMacro), with passage, line and
83
- * column.
87
+ * column. It reads the process-global registry; `validateStoryMarkup` takes
88
+ * the macros to check against instead.
84
89
  */
85
90
  export function validateMarkup(passages, options) {
86
91
  return validateStoryMarkup(passages, metadata.values(), options);
87
92
  }
88
93
 
89
94
  /**
90
- * The passages the markup of `source` names, with where each is written:
95
+ * The passages the markup of `source` names, with where each is written (the
96
+ * process-global registry; `collectStoryPassageReferences` takes the macros):
91
97
  * `[[…]]` links and the passage of `{goto}`, `{include}`, `{link}`,
92
98
  * `{watch}` and `{dialog}`, as the macros registered here declare them.
93
99
  * Malformed tags are skipped, so half-typed markup reads.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.59.21",
3
+ "version": "0.59.23",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -45,6 +45,7 @@
45
45
  "dist/pkg/headless.js",
46
46
  "dist/pkg/story-variables.js",
47
47
  "dist/pkg/macro-registry.json",
48
+ "dist/pkg/macro-registry.js",
48
49
  "types",
49
50
  "src"
50
51
  ],
package/src/code-check.ts CHANGED
@@ -26,8 +26,14 @@
26
26
  * The arguments of macros that declare no parameters may be anything:
27
27
  * they are not checked.
28
28
  */
29
- import type { Token } from './markup/tokens';
29
+ import type { HtmlToken, Token } from './markup/tokens';
30
30
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
31
+ import {
32
+ analyzeMarkup,
33
+ lineColumn,
34
+ MarkupError,
35
+ mapOffsets,
36
+ } from './markup/parse';
31
37
  import { CodeSyntaxError, parseCode, type JsGoal } from './js-lexer';
32
38
  import type { ParsedCode } from './js-lexer';
33
39
  import type { ParameterDef, StringHolds } from './registry';
@@ -76,14 +82,51 @@ export function parseOrError(
76
82
  return result;
77
83
  }
78
84
 
85
+ /**
86
+ * What every piece says of where it is: it is at `offset` in the markup (all
87
+ * offsets are UTF-16 code units into the source given). A piece in the markup
88
+ * of a text (a label, an attribute value) is `nested`, with `where` the
89
+ * description of that text, as in TextPiece.
90
+ */
91
+ export interface PieceBase {
92
+ offset: number;
93
+ nested?: true;
94
+ where?: string;
95
+ /**
96
+ * For the code or text of a quoted string with escapes (a `\"`), whose
97
+ * characters are not where `offset` plus their index says: the offset of
98
+ * each character in the source, and of the end of the text, so that
99
+ * `sourceOffsets[i]` is where character `i` of `code` or `text` is. Absent
100
+ * when `offset + i` is (see {@link pieceOffset}).
101
+ */
102
+ sourceOffsets?: readonly number[];
103
+ }
104
+
105
+ /** Where character `index` of the code or text of `piece` is in the source. */
106
+ export function pieceOffset(piece: PieceBase, index: number): number {
107
+ return piece.sourceOffsets?.[index] ?? piece.offset + index;
108
+ }
109
+
110
+ /** How much of a piece's own text or code there is (not its source extent). */
111
+ function extentOf(piece: Piece): number {
112
+ return piece.kind === 'code'
113
+ ? piece.code.length
114
+ : piece.kind === 'text'
115
+ ? piece.text.length
116
+ : piece.length;
117
+ }
118
+
119
+ /** A piece found in a markup that is written out, for an error to point at. */
120
+ interface LabeledPiece extends PieceBase {
121
+ /** The markup it is in, for the error: `{print $a +}`, `[[Go->Hall]]`. */
122
+ label: string;
123
+ }
124
+
79
125
  /** A piece of code in markup, at `offset` in it. */
80
- export interface CodePiece {
126
+ export interface CodePiece extends LabeledPiece {
81
127
  kind: 'code';
82
128
  code: string;
83
- offset: number;
84
129
  goal: JsGoal;
85
- /** The markup it is in, for the error: `{print $a +}`. */
86
- label: string;
87
130
  /**
88
131
  * Whether it names a passage: a `passage` argument that is an
89
132
  * expression (one that is a string literal is a PassagePiece).
@@ -95,35 +138,47 @@ export interface CodePiece {
95
138
  macro?: string;
96
139
  }
97
140
 
98
- /** A passage name written out in markup, at `offset` in it. */
99
- export interface PassagePiece {
100
- kind: 'passage';
101
- name: string;
102
- offset: number;
103
- /** The markup it is in, for the error: `[[Go->Hall]]`. */
104
- label: string;
105
- /** How much of the markup is the name, as written (quotes included). */
141
+ /** A piece that takes `length` of the markup, as written, for macro `macro`. */
142
+ interface MacroPiece extends LabeledPiece {
106
143
  length: number;
107
- /** The macro it is the argument of; `link` for `[[…]]` links. */
108
144
  macro: string;
109
145
  }
110
146
 
111
- /** Macro arguments that don't have their parameters' forms. */
112
- export interface ArgumentErrorPiece {
147
+ /**
148
+ * A passage name written out in markup, at `offset` in it: `length` of the
149
+ * markup is the name as written (quotes included), and `macro` the macro it
150
+ * is the argument of; `link` for `[[…]]` links.
151
+ */
152
+ export interface PassagePiece extends MacroPiece {
153
+ kind: 'passage';
154
+ name: string;
155
+ }
156
+
157
+ /**
158
+ * Macro arguments that don't have their parameters' forms: `length` of the
159
+ * markup is the arguments, of `macro`.
160
+ */
161
+ export interface ArgumentErrorPiece extends MacroPiece {
113
162
  kind: 'argument-error';
114
163
  message: string;
115
- offset: number;
116
- /** The markup it is in, for the error: `{link Go}`. */
117
- label: string;
118
164
  }
119
165
 
120
166
  /** Text in markup that may hold markup of its own, at `offset` in it. */
121
- export interface TextPiece {
167
+ export interface TextPiece extends PieceBase {
122
168
  kind: 'text';
123
169
  text: string;
124
- offset: number;
125
170
  /** Where it is, for the error: `In the label of {button}: `. */
126
171
  where: string;
172
+ /**
173
+ * The tokens of the markup in it, with offsets in the source given (none
174
+ * for a text with no `{`, which has no markup in it).
175
+ */
176
+ tokens: Token[];
177
+ /**
178
+ * Its malformed markup, in the order a parser reading from left to right
179
+ * meets it, with offsets in the source given.
180
+ */
181
+ errors: MarkupError[];
127
182
  }
128
183
 
129
184
  /** Macros whose whole argument text is one expression: branch conditions. */
@@ -132,7 +187,8 @@ const CONDITION_MACROS = new Set(['if', 'elseif', 'case']);
132
187
  /** Block macros whose body is the name of a passage. */
133
188
  const PASSAGE_BODIES = new Set(['dialog']);
134
189
 
135
- type Piece = CodePiece | TextPiece | PassagePiece | ArgumentErrorPiece;
190
+ /** What a passage runs and names, and where (see passagePieces). */
191
+ export type Piece = CodePiece | TextPiece | PassagePiece | ArgumentErrorPiece;
136
192
 
137
193
  /** The declared parameters of a macro, if it has any. */
138
194
  export type ParametersOf = (
@@ -251,34 +307,28 @@ export function* codeAndText(
251
307
  };
252
308
  // The label is markup too (the link renders as `{link}`)
253
309
  if (token.display.includes('{')) {
254
- yield {
255
- kind: 'text',
256
- text: token.display,
257
- offset: locate(src, token.display, token.start),
258
- where: 'In the label of a link: ',
259
- };
310
+ yield textPiece(
311
+ token.display,
312
+ token.displayStart,
313
+ 'In the label of a link: ',
314
+ );
260
315
  }
261
316
  } else if (token.type === 'expression') {
262
317
  yield {
263
318
  kind: 'code',
264
319
  code: token.expression,
265
- offset: token.end - 1 - token.expression.length,
320
+ offset: token.expressionStart,
266
321
  goal: 'expression',
267
322
  label: `{${token.expression}}`,
268
323
  };
269
324
  } else if (token.type === 'html') {
270
- // The values are the source text between their quotes, in order
271
- let cursor = token.start;
272
- for (const [name, value] of Object.entries(token.attributes)) {
273
- const at = locate(src, value, cursor);
274
- cursor = at + value.length;
325
+ for (const { name, value, at } of attributeValues(src, token)) {
275
326
  if (!isCodeAttribute(name)) {
276
- yield {
277
- kind: 'text',
278
- text: value,
279
- offset: at,
280
- where: `In the ${name} attribute of <${token.tag}>: `,
281
- };
327
+ yield textPiece(
328
+ value,
329
+ at,
330
+ `In the ${name} attribute of <${token.tag}>: `,
331
+ );
282
332
  continue;
283
333
  }
284
334
  let from = 0;
@@ -331,9 +381,7 @@ export function* codeAndText(
331
381
  }
332
382
  if (!args) continue;
333
383
  const label = `{${token.name} ${args}}`;
334
- // The arguments end the tag, but for the whitespace before its }
335
- const tag = src.slice(token.start, token.end - 1);
336
- const argsAt = token.start + tag.trimEnd().length - args.length;
384
+ const argsAt = token.argsStart;
337
385
  if (CONDITION_MACROS.has(name)) {
338
386
  yield {
339
387
  kind: 'code',
@@ -350,6 +398,136 @@ export function* codeAndText(
350
398
  }
351
399
  }
352
400
 
401
+ /** What reading the pieces of a passage depends on. */
402
+ export interface PieceOptions {
403
+ /**
404
+ * Whether a macro takes a body, for the markup in labels and attribute
405
+ * values (default: the registered block macros).
406
+ */
407
+ isBlock?(name: string): boolean;
408
+ }
409
+
410
+ /**
411
+ * `codeAndText`, with the markup in the texts read too: a text piece (a label,
412
+ * an attribute value) with a `{` in it carries its tokens and errors, and is
413
+ * followed by the pieces of that markup, `nested`, in the offsets of the whole
414
+ * `src`. In source order, a nested piece after the text it is in.
415
+ */
416
+ export function* passagePiecesOf(
417
+ src: string,
418
+ tokens: readonly Token[],
419
+ parametersOf: ParametersOf,
420
+ options: PieceOptions = {},
421
+ ): Generator<Piece> {
422
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, undefined);
423
+ }
424
+
425
+ /**
426
+ * The pieces of `tokens`, the tokens of `src`, which is the text described by
427
+ * `where` (none for `root`, the markup of the whole passage), and whose
428
+ * offsets `toRoot` turns into offsets in `root`.
429
+ */
430
+ function* expand(
431
+ root: string,
432
+ src: string,
433
+ tokens: readonly Token[],
434
+ parametersOf: ParametersOf,
435
+ options: PieceOptions,
436
+ toRoot: (offset: number) => number,
437
+ where: string | undefined,
438
+ ): Generator<Piece> {
439
+ for (const flat of codeAndText(src, tokens, parametersOf)) {
440
+ const piece = where ? nestedPiece(flat, toRoot, where) : flat;
441
+ if (flat.kind !== 'text' || !flat.text.includes('{')) {
442
+ yield piece;
443
+ continue;
444
+ }
445
+ // The text may not be where its length says: a string with escapes
446
+ const toText = (i: number) => toRoot(pieceOffset(flat, i));
447
+ const inner = analyzeMarkup(flat.text, {
448
+ text: true,
449
+ hooks: options.isBlock && { isBlock: options.isBlock },
450
+ });
451
+ yield {
452
+ ...(piece as TextPiece),
453
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
454
+ errors: inner.errors.map((e) => {
455
+ const { line, column } = lineColumn(root, toText(e.offset));
456
+ return new MarkupError(
457
+ e.reason,
458
+ toText(e.offset),
459
+ line,
460
+ column,
461
+ e.code,
462
+ toText(e.end),
463
+ e.data,
464
+ );
465
+ }),
466
+ };
467
+ yield* expand(
468
+ root,
469
+ flat.text,
470
+ inner.tokens,
471
+ parametersOf,
472
+ options,
473
+ toText,
474
+ flat.where,
475
+ );
476
+ }
477
+ }
478
+
479
+ /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
480
+ function nestedPiece(
481
+ piece: Piece,
482
+ toRoot: (offset: number) => number,
483
+ where: string,
484
+ ): Piece {
485
+ const offset = toRoot(piece.offset);
486
+ const nested = { offset, nested: true as const, where };
487
+ if (piece.kind === 'passage' || piece.kind === 'argument-error') {
488
+ const length = toRoot(piece.offset + piece.length) - offset;
489
+ return { ...piece, ...nested, length };
490
+ }
491
+ const extent = extentOf(piece);
492
+ const sourceOffsets = piece.sourceOffsets
493
+ ? piece.sourceOffsets.map(toRoot)
494
+ : toRoot(piece.offset + extent) - offset !== extent
495
+ ? Array.from({ length: extent + 1 }, (_, i) => toRoot(piece.offset + i))
496
+ : undefined;
497
+ return sourceOffsets
498
+ ? { ...piece, ...nested, sourceOffsets }
499
+ : { ...piece, ...nested };
500
+ }
501
+
502
+ /**
503
+ * Where each character of `value`, the unescaped text of a quoted string
504
+ * written as `raw` from `at` on (a backslash before a quote or a backslash
505
+ * is dropped), is
506
+ * in the source, and where the text ends. None when the text is where its
507
+ * length says, or is not that string.
508
+ */
509
+ function escapeOffsets(
510
+ raw: string,
511
+ at: number,
512
+ value: string,
513
+ ): number[] | undefined {
514
+ const offsets: number[] = [];
515
+ let escaped = false;
516
+ let i = 0;
517
+ while (offsets.length < value.length) {
518
+ if (i >= raw.length) return undefined;
519
+ offsets.push(at + i);
520
+ if (raw[i] === '\\' && /["'\\]/.test(raw.charAt(i + 1))) {
521
+ escaped = true;
522
+ i += 2;
523
+ } else {
524
+ i++;
525
+ }
526
+ }
527
+ offsets.push(at + i);
528
+ return escaped ? offsets : undefined;
529
+ }
530
+
353
531
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
354
532
  export function* argPieces(
355
533
  args: string,
@@ -358,16 +536,23 @@ export function* argPieces(
358
536
  macro: string,
359
537
  label: string,
360
538
  ): Generator<Piece> {
539
+ const name = macro.toLowerCase();
361
540
  let values: Record<string, unknown>;
362
541
  const spans: ArgSpans = new Map();
363
542
  try {
364
543
  values = parseMacroArgs(args, params, spans) as Record<string, unknown>;
365
544
  } catch (error) {
366
545
  if (!(error instanceof MacroArgumentError)) throw error;
367
- yield { kind: 'argument-error', message: error.message, offset, label };
546
+ yield {
547
+ kind: 'argument-error',
548
+ message: error.message,
549
+ offset,
550
+ length: args.length,
551
+ label,
552
+ macro: name,
553
+ };
368
554
  return;
369
555
  }
370
- const name = macro.toLowerCase();
371
556
  /** The pieces of the parameters `list`, with their values in `from`. */
372
557
  function* visit(
373
558
  list: readonly ParameterDef[],
@@ -423,8 +608,9 @@ export function* argPieces(
423
608
  const at =
424
609
  offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
425
610
  const holds = stringHolds(param);
611
+ const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
426
612
  if (holds === 'expression' || holds === 'statements') {
427
- yield {
613
+ const piece: CodePiece = {
428
614
  kind: 'code',
429
615
  code: value,
430
616
  offset: at,
@@ -432,15 +618,18 @@ export function* argPieces(
432
618
  label,
433
619
  inString: true,
434
620
  };
621
+ if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
622
+ yield piece;
435
623
  } else if (holds === 'passage') {
436
624
  yield passage(value);
437
625
  } else if (holds === 'markup') {
438
- yield {
439
- kind: 'text',
440
- text: value,
441
- offset: at,
442
- where: `In the ${param.name} of {${macro}}: `,
443
- };
626
+ const piece = textPiece(
627
+ value,
628
+ at,
629
+ `In the ${param.name} of {${macro}}: `,
630
+ );
631
+ if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
632
+ yield piece;
444
633
  }
445
634
  }
446
635
  }
@@ -448,6 +637,49 @@ export function* argPieces(
448
637
  yield* [...visit(params, values)].sort((a, b) => a.offset - b.offset);
449
638
  }
450
639
 
640
+ /** A text that may hold markup, at `offset`; read when it is expanded. */
641
+ const textPiece = (text: string, offset: number, where: string): TextPiece => ({
642
+ kind: 'text',
643
+ text,
644
+ offset,
645
+ where,
646
+ tokens: [],
647
+ errors: [],
648
+ });
649
+
650
+ /**
651
+ * The attributes of an HTML tag by the values as written, with where each
652
+ * value is: the first of equal names, which is the one in effect. A token
653
+ * with no spans (made from an AST) has them found in `src`, in order.
654
+ */
655
+ function attributeValues(
656
+ src: string,
657
+ token: HtmlToken,
658
+ ): { name: string; value: string; at: number }[] {
659
+ if (token.attributeSpans.length === 0) {
660
+ let cursor = token.start;
661
+ return Object.entries(token.attributes).map(([name, value]) => {
662
+ const at = locate(src, value, cursor);
663
+ cursor = at + value.length;
664
+ return { name, value, at };
665
+ });
666
+ }
667
+ const seen = new Set<string>();
668
+ const values = [];
669
+ for (const span of token.attributeSpans) {
670
+ const lower = span.name.toLowerCase();
671
+ if (seen.has(lower)) continue;
672
+ seen.add(lower);
673
+ if (span.valueStart === undefined) continue;
674
+ values.push({
675
+ name: span.name,
676
+ value: src.slice(span.valueStart, span.valueEnd),
677
+ at: span.valueStart,
678
+ });
679
+ }
680
+ return values;
681
+ }
682
+
451
683
  /**
452
684
  * Index of `part` in `text` from `from` on, else anywhere, else `from`: the
453
685
  * place to report an error in `part` at.
@@ -475,17 +707,22 @@ export interface PassageReference {
475
707
  * `[[…]]` links, the passage argument of `{goto}`, `{include}` and `{link}`
476
708
  * (and of macros that declare one), the `goto` and `dialog` actions of
477
709
  * `{watch}` (and the `string` and `text` arguments of macros that declare
478
- * they hold one) and the body of `{dialog}`, in source order. A name written
479
- * out is a literal; the others are expressions, which name a passage when
480
- * they run.
710
+ * they hold one) and the body of `{dialog}`, in source order, also in the
711
+ * labels and attribute values that hold markup. A name written out is a
712
+ * literal; the others are expressions, which name a passage when they run.
481
713
  */
482
714
  export function collectPassageReferences(
483
715
  src: string,
484
716
  tokens: readonly Token[],
485
717
  parametersOf: ParametersOf,
486
718
  ): PassageReference[] {
719
+ return referencesOf(passagePiecesOf(src, tokens, parametersOf));
720
+ }
721
+
722
+ /** The passage references among `pieces` (see collectPassageReferences). */
723
+ export function referencesOf(pieces: Iterable<Piece>): PassageReference[] {
487
724
  const refs: PassageReference[] = [];
488
- for (const piece of codeAndText(src, tokens, parametersOf)) {
725
+ for (const piece of pieces) {
489
726
  if (piece.kind === 'passage') {
490
727
  refs.push({
491
728
  macro: piece.macro,
@@ -188,6 +188,7 @@ export function SaveManagerContent() {
188
188
  decodeSavePayload(current.payload),
189
189
  undefined,
190
190
  current.meta.playthroughId,
191
+ replacement,
191
192
  );
192
193
  showStatus('Game loaded');
193
194
  if (closeDialog) {
@@ -227,6 +227,10 @@ export function useModalFocus(
227
227
  (next ?? (backwards ? last : first)).focus();
228
228
  };
229
229
 
230
+ // The media element whose native controls Tab is stepping through
231
+ let steppingMedia: { el: HTMLMediaElement; backwards: boolean } | null =
232
+ null;
233
+
230
234
  const onKeyDown = (e: KeyboardEvent) => {
231
235
  if (!top()) return;
232
236
 
@@ -239,8 +243,21 @@ export function useModalFocus(
239
243
  }
240
244
 
241
245
  if (e.key !== 'Tab') return;
246
+ // The controls of a media element are in its user-agent shadow tree,
247
+ // where the element stays the active one: they step through them
248
+ // natively, and onFocusIn takes over where focus leaves the element
249
+ // (#444).
250
+ const active = document.activeElement;
251
+ if (active instanceof HTMLMediaElement && active.controls) {
252
+ steppingMedia = { el: active, backwards: e.shiftKey };
253
+ return;
254
+ }
242
255
  e.preventDefault();
243
- moveFocus(document.activeElement, e.shiftKey);
256
+ moveFocus(active, e.shiftKey);
257
+ };
258
+ // Clicking elsewhere ends the stepping through the controls
259
+ const onPointerDown = () => {
260
+ steppingMedia = null;
244
261
  };
245
262
 
246
263
  // Key events inside an embedded document never reach this one (#425).
@@ -290,6 +307,13 @@ export function useModalFocus(
290
307
  // document can't be reached, is brought back in.
291
308
  const onFocusIn = (e: FocusEvent) => {
292
309
  const target = e.target;
310
+ if (steppingMedia && target !== steppingMedia.el && top()) {
311
+ // Focus left the media controls: on to the modal's next control
312
+ const { el, backwards } = steppingMedia;
313
+ steppingMedia = null;
314
+ moveFocus(el, backwards);
315
+ return;
316
+ }
293
317
  if (!top() || !(target instanceof Node) || panel.contains(target)) return;
294
318
  if (target === document.body || target === document.documentElement) {
295
319
  return;
@@ -298,6 +322,22 @@ export function useModalFocus(
298
322
  };
299
323
 
300
324
  document.addEventListener('keydown', onKeyDown, { signal });
325
+ document.addEventListener('pointerdown', onPointerDown, {
326
+ capture: true,
327
+ signal,
328
+ });
329
+ // Focus that leaves the media element for nothing (past its last control,
330
+ // with no tab stop after it in the document) sends no focusin: the
331
+ // modal's next control takes it at once.
332
+ const onFocusOut = (e: FocusEvent) => {
333
+ const pending = steppingMedia;
334
+ if (!pending || e.target !== pending.el || e.relatedTarget || !top()) {
335
+ return;
336
+ }
337
+ steppingMedia = null;
338
+ moveFocus(pending.el, pending.backwards);
339
+ };
340
+ document.addEventListener('focusout', onFocusOut, { signal });
301
341
  document.addEventListener('focusin', onFocusIn, { signal });
302
342
  return () => {
303
343
  controller.abort();