@rohal12/spindle 0.59.22 → 0.59.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.
@@ -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,
@@ -31,19 +37,21 @@ export {
31
37
  stripLooseQuotes,
32
38
  unescapeQuoted,
33
39
  splitIncludeFlag,
40
+ parseWidgetDef,
41
+ widgetDefinitions,
42
+ variableReferences,
43
+ validateVariableReferences,
34
44
  } from './story-variables.js';
35
45
 
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
- }
46
+ /**
47
+ * The built-in macros: what `getMacroRegistry()` returns before any
48
+ * `defineMacro`. Pass them (and your own) to `validateStoryMarkup`,
49
+ * `collectStoryPassageReferences` and `passagePieces`, which take the macros
50
+ * they check against and keep no state.
51
+ */
52
+ export const builtinMacros = Object.freeze([...builtinList]);
46
53
 
54
+ const builtins = builtinMacros;
47
55
  const metadata = new Map();
48
56
  for (const m of builtins) metadata.set(m.name.toLowerCase(), m);
49
57
 
@@ -80,14 +88,16 @@ export function getMacroRegistry() {
80
88
  * Validate the markup of a story's passages as Spindle does when the story
81
89
  * starts: malformed markup and unknown macros (checked against the built-in
82
90
  * macros and those registered with defineMacro), with passage, line and
83
- * column.
91
+ * column. It reads the process-global registry; `validateStoryMarkup` takes
92
+ * the macros to check against instead.
84
93
  */
85
94
  export function validateMarkup(passages, options) {
86
95
  return validateStoryMarkup(passages, metadata.values(), options);
87
96
  }
88
97
 
89
98
  /**
90
- * The passages the markup of `source` names, with where each is written:
99
+ * The passages the markup of `source` names, with where each is written (the
100
+ * process-global registry; `collectStoryPassageReferences` takes the macros):
91
101
  * `[[…]]` links and the passage of `{goto}`, `{include}`, `{link}`,
92
102
  * `{watch}` and `{dialog}`, as the macros registered here declare them.
93
103
  * 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.22",
3
+ "version": "0.59.25",
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,47 +307,37 @@ 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
- let from = 0;
285
- for (const part of splitSigilTemplate(value)) {
286
- if (!('expr' in part)) continue;
287
- const k = locate(value, part.expr, from);
288
- from = k + part.expr.length;
334
+ for (const { expr, at: k } of sigilExpressions(value)) {
289
335
  yield {
290
336
  kind: 'code',
291
- code: part.expr,
337
+ code: expr,
292
338
  offset: at + k,
293
339
  goal: 'expression',
294
- label: `{${part.expr}} in the ${name} attribute of <${token.tag}>`,
340
+ label: `{${expr}} in the ${name} attribute of <${token.tag}>`,
295
341
  };
296
342
  }
297
343
  }
@@ -331,9 +377,7 @@ export function* codeAndText(
331
377
  }
332
378
  if (!args) continue;
333
379
  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;
380
+ const argsAt = token.argsStart;
337
381
  if (CONDITION_MACROS.has(name)) {
338
382
  yield {
339
383
  kind: 'code',
@@ -350,6 +394,136 @@ export function* codeAndText(
350
394
  }
351
395
  }
352
396
 
397
+ /** What reading the pieces of a passage depends on. */
398
+ export interface PieceOptions {
399
+ /**
400
+ * Whether a macro takes a body, for the markup in labels and attribute
401
+ * values (default: the registered block macros).
402
+ */
403
+ isBlock?(name: string): boolean;
404
+ }
405
+
406
+ /**
407
+ * `codeAndText`, with the markup in the texts read too: a text piece (a label,
408
+ * an attribute value) with a `{` in it carries its tokens and errors, and is
409
+ * followed by the pieces of that markup, `nested`, in the offsets of the whole
410
+ * `src`. In source order, a nested piece after the text it is in.
411
+ */
412
+ export function* passagePiecesOf(
413
+ src: string,
414
+ tokens: readonly Token[],
415
+ parametersOf: ParametersOf,
416
+ options: PieceOptions = {},
417
+ ): Generator<Piece> {
418
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, undefined);
419
+ }
420
+
421
+ /**
422
+ * The pieces of `tokens`, the tokens of `src`, which is the text described by
423
+ * `where` (none for `root`, the markup of the whole passage), and whose
424
+ * offsets `toRoot` turns into offsets in `root`.
425
+ */
426
+ function* expand(
427
+ root: string,
428
+ src: string,
429
+ tokens: readonly Token[],
430
+ parametersOf: ParametersOf,
431
+ options: PieceOptions,
432
+ toRoot: (offset: number) => number,
433
+ where: string | undefined,
434
+ ): Generator<Piece> {
435
+ for (const flat of codeAndText(src, tokens, parametersOf)) {
436
+ const piece = where ? nestedPiece(flat, toRoot, where) : flat;
437
+ if (flat.kind !== 'text' || !flat.text.includes('{')) {
438
+ yield piece;
439
+ continue;
440
+ }
441
+ // The text may not be where its length says: a string with escapes
442
+ const toText = (i: number) => toRoot(pieceOffset(flat, i));
443
+ const inner = analyzeMarkup(flat.text, {
444
+ text: true,
445
+ hooks: options.isBlock && { isBlock: options.isBlock },
446
+ });
447
+ yield {
448
+ ...(piece as TextPiece),
449
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
450
+ errors: inner.errors.map((e) => {
451
+ const { line, column } = lineColumn(root, toText(e.offset));
452
+ return new MarkupError(
453
+ e.reason,
454
+ toText(e.offset),
455
+ line,
456
+ column,
457
+ e.code,
458
+ toText(e.end),
459
+ e.data,
460
+ );
461
+ }),
462
+ };
463
+ yield* expand(
464
+ root,
465
+ flat.text,
466
+ inner.tokens,
467
+ parametersOf,
468
+ options,
469
+ toText,
470
+ flat.where,
471
+ );
472
+ }
473
+ }
474
+
475
+ /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
476
+ function nestedPiece(
477
+ piece: Piece,
478
+ toRoot: (offset: number) => number,
479
+ where: string,
480
+ ): Piece {
481
+ const offset = toRoot(piece.offset);
482
+ const nested = { offset, nested: true as const, where };
483
+ if (piece.kind === 'passage' || piece.kind === 'argument-error') {
484
+ const length = toRoot(piece.offset + piece.length) - offset;
485
+ return { ...piece, ...nested, length };
486
+ }
487
+ const extent = extentOf(piece);
488
+ const sourceOffsets = piece.sourceOffsets
489
+ ? piece.sourceOffsets.map(toRoot)
490
+ : toRoot(piece.offset + extent) - offset !== extent
491
+ ? Array.from({ length: extent + 1 }, (_, i) => toRoot(piece.offset + i))
492
+ : undefined;
493
+ return sourceOffsets
494
+ ? { ...piece, ...nested, sourceOffsets }
495
+ : { ...piece, ...nested };
496
+ }
497
+
498
+ /**
499
+ * Where each character of `value`, the unescaped text of a quoted string
500
+ * written as `raw` from `at` on (a backslash before a quote or a backslash
501
+ * is dropped), is
502
+ * in the source, and where the text ends. None when the text is where its
503
+ * length says, or is not that string.
504
+ */
505
+ function escapeOffsets(
506
+ raw: string,
507
+ at: number,
508
+ value: string,
509
+ ): number[] | undefined {
510
+ const offsets: number[] = [];
511
+ let escaped = false;
512
+ let i = 0;
513
+ while (offsets.length < value.length) {
514
+ if (i >= raw.length) return undefined;
515
+ offsets.push(at + i);
516
+ if (raw[i] === '\\' && /["'\\]/.test(raw.charAt(i + 1))) {
517
+ escaped = true;
518
+ i += 2;
519
+ } else {
520
+ i++;
521
+ }
522
+ }
523
+ offsets.push(at + i);
524
+ return escaped ? offsets : undefined;
525
+ }
526
+
353
527
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
354
528
  export function* argPieces(
355
529
  args: string,
@@ -358,16 +532,23 @@ export function* argPieces(
358
532
  macro: string,
359
533
  label: string,
360
534
  ): Generator<Piece> {
535
+ const name = macro.toLowerCase();
361
536
  let values: Record<string, unknown>;
362
537
  const spans: ArgSpans = new Map();
363
538
  try {
364
539
  values = parseMacroArgs(args, params, spans) as Record<string, unknown>;
365
540
  } catch (error) {
366
541
  if (!(error instanceof MacroArgumentError)) throw error;
367
- yield { kind: 'argument-error', message: error.message, offset, label };
542
+ yield {
543
+ kind: 'argument-error',
544
+ message: error.message,
545
+ offset,
546
+ length: args.length,
547
+ label,
548
+ macro: name,
549
+ };
368
550
  return;
369
551
  }
370
- const name = macro.toLowerCase();
371
552
  /** The pieces of the parameters `list`, with their values in `from`. */
372
553
  function* visit(
373
554
  list: readonly ParameterDef[],
@@ -423,8 +604,9 @@ export function* argPieces(
423
604
  const at =
424
605
  offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
425
606
  const holds = stringHolds(param);
607
+ const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
426
608
  if (holds === 'expression' || holds === 'statements') {
427
- yield {
609
+ const piece: CodePiece = {
428
610
  kind: 'code',
429
611
  code: value,
430
612
  offset: at,
@@ -432,15 +614,18 @@ export function* argPieces(
432
614
  label,
433
615
  inString: true,
434
616
  };
617
+ if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
618
+ yield piece;
435
619
  } else if (holds === 'passage') {
436
620
  yield passage(value);
437
621
  } else if (holds === 'markup') {
438
- yield {
439
- kind: 'text',
440
- text: value,
441
- offset: at,
442
- where: `In the ${param.name} of {${macro}}: `,
443
- };
622
+ const piece = textPiece(
623
+ value,
624
+ at,
625
+ `In the ${param.name} of {${macro}}: `,
626
+ );
627
+ if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
628
+ yield piece;
444
629
  }
445
630
  }
446
631
  }
@@ -448,11 +633,72 @@ export function* argPieces(
448
633
  yield* [...visit(params, values)].sort((a, b) => a.offset - b.offset);
449
634
  }
450
635
 
636
+ /** A text that may hold markup, at `offset`; read when it is expanded. */
637
+ const textPiece = (text: string, offset: number, where: string): TextPiece => ({
638
+ kind: 'text',
639
+ text,
640
+ offset,
641
+ where,
642
+ tokens: [],
643
+ errors: [],
644
+ });
645
+
646
+ /**
647
+ * The attributes of an HTML tag by the values as written, with where each
648
+ * value is: the first of equal names, which is the one in effect. A token
649
+ * with no spans (made from an AST) has them found in `src`, in order.
650
+ */
651
+ export function attributeValues(
652
+ src: string,
653
+ token: HtmlToken,
654
+ ): { name: string; value: string; at: number }[] {
655
+ if (token.attributeSpans.length === 0) {
656
+ let cursor = token.start;
657
+ return Object.entries(token.attributes).map(([name, value]) => {
658
+ const at = locate(src, value, cursor);
659
+ cursor = at + value.length;
660
+ return { name, value, at };
661
+ });
662
+ }
663
+ const seen = new Set<string>();
664
+ const values = [];
665
+ for (const span of token.attributeSpans) {
666
+ const lower = span.name.toLowerCase();
667
+ if (seen.has(lower)) continue;
668
+ seen.add(lower);
669
+ if (span.valueStart === undefined) continue;
670
+ values.push({
671
+ name: span.name,
672
+ value: src.slice(span.valueStart, span.valueEnd),
673
+ at: span.valueStart,
674
+ });
675
+ }
676
+ return values;
677
+ }
678
+
679
+ /**
680
+ * The `{$…}` expressions in the value of a code attribute (`onclick`, see
681
+ * isCodeAttribute), with where each is in the value.
682
+ */
683
+ export function sigilExpressions(
684
+ value: string,
685
+ ): { expr: string; at: number }[] {
686
+ const found = [];
687
+ let from = 0;
688
+ for (const part of splitSigilTemplate(value)) {
689
+ if (!('expr' in part)) continue;
690
+ const at = locate(value, part.expr, from);
691
+ from = at + part.expr.length;
692
+ found.push({ expr: part.expr, at });
693
+ }
694
+ return found;
695
+ }
696
+
451
697
  /**
452
698
  * Index of `part` in `text` from `from` on, else anywhere, else `from`: the
453
699
  * place to report an error in `part` at.
454
700
  */
455
- function locate(text: string, part: string, from: number): number {
701
+ export function locate(text: string, part: string, from: number): number {
456
702
  const at = text.indexOf(part, from);
457
703
  if (at >= 0) return at;
458
704
  const anywhere = text.indexOf(part);
@@ -475,17 +721,22 @@ export interface PassageReference {
475
721
  * `[[…]]` links, the passage argument of `{goto}`, `{include}` and `{link}`
476
722
  * (and of macros that declare one), the `goto` and `dialog` actions of
477
723
  * `{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.
724
+ * they hold one) and the body of `{dialog}`, in source order, also in the
725
+ * labels and attribute values that hold markup. A name written out is a
726
+ * literal; the others are expressions, which name a passage when they run.
481
727
  */
482
728
  export function collectPassageReferences(
483
729
  src: string,
484
730
  tokens: readonly Token[],
485
731
  parametersOf: ParametersOf,
486
732
  ): PassageReference[] {
733
+ return referencesOf(passagePiecesOf(src, tokens, parametersOf));
734
+ }
735
+
736
+ /** The passage references among `pieces` (see collectPassageReferences). */
737
+ export function referencesOf(pieces: Iterable<Piece>): PassageReference[] {
487
738
  const refs: PassageReference[] = [];
488
- for (const piece of codeAndText(src, tokens, parametersOf)) {
739
+ for (const piece of pieces) {
489
740
  if (piece.kind === 'passage') {
490
741
  refs.push({
491
742
  macro: piece.macro,
@@ -1,5 +1,11 @@
1
1
  import { createContext } from 'preact';
2
- import { useCallback, useLayoutEffect, useMemo, useRef } from 'preact/hooks';
2
+ import {
3
+ useCallback,
4
+ useId,
5
+ useLayoutEffect,
6
+ useMemo,
7
+ useRef,
8
+ } from 'preact/hooks';
3
9
  import { parseMarkup } from '../markup/parse';
4
10
  import {
5
11
  renderNodes,
@@ -20,6 +26,11 @@ interface PassageDialogProps {
20
26
  fallbackMarkup?: string;
21
27
  panelClass?: string;
22
28
  onClose: () => void;
29
+ /**
30
+ * The dialog's accessible name. Without one, the first heading authored in
31
+ * the dialog names it, or else its passage.
32
+ */
33
+ label?: string;
23
34
  /** Show the default `✕` button. Defaults to `dismissible`. */
24
35
  showCloseButton?: boolean;
25
36
  /**
@@ -35,6 +46,7 @@ export function PassageDialog({
35
46
  fallbackMarkup,
36
47
  panelClass,
37
48
  onClose,
49
+ label,
38
50
  dismissible = true,
39
51
  showCloseButton = dismissible,
40
52
  }: PassageDialogProps) {
@@ -71,6 +83,7 @@ export function PassageDialog({
71
83
  }, [markup, nobr]);
72
84
 
73
85
  const panelRef = useRef<HTMLDivElement>(null);
86
+ const labelId = useId();
74
87
  const viewScope = useViewScope();
75
88
 
76
89
  // Focus into the dialog, trap Tab, Escape to close, restore focus on close.
@@ -80,6 +93,19 @@ export function PassageDialog({
80
93
  // Be on the stack of displayed dialogs the Story dialog API works on.
81
94
  useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
82
95
 
96
+ // Name the dialog after its first heading when no label is given
97
+ useLayoutEffect(() => {
98
+ const panel = panelRef.current;
99
+ if (!panel || label) return;
100
+ const heading = panel.querySelector<HTMLElement>(
101
+ '.dialog-body :is(h1, h2, h3, h4, h5, h6)',
102
+ );
103
+ if (!heading) return;
104
+ heading.id ||= `${labelId}-heading`;
105
+ panel.setAttribute('aria-labelledby', heading.id);
106
+ return () => panel.removeAttribute('aria-labelledby');
107
+ }, [label, markup]);
108
+
83
109
  // Signal that the dialog's DOM is committed (once per open).
84
110
  useLayoutEffect(() => {
85
111
  if (panelRef.current) {
@@ -107,6 +133,7 @@ export function PassageDialog({
107
133
  class={cls}
108
134
  role="dialog"
109
135
  aria-modal="true"
136
+ aria-label={label ?? passageName}
110
137
  tabIndex={-1}
111
138
  >
112
139
  {showCloseButton && (
@@ -77,6 +77,9 @@ export function defineMenubarAction(config: MenubarActionConfig) {
77
77
  passageName={config.dialog.passageName}
78
78
  fallbackMarkup={config.dialog.fallbackMarkup}
79
79
  panelClass={config.dialog.panelClass}
80
+ label={
81
+ typeof config.label === 'string' ? config.label : config.name
82
+ }
80
83
  onClose={() => setDialogOpen(false)}
81
84
  showCloseButton={config.dialog.showCloseButton}
82
85
  />