@rohal12/spindle 0.59.22 → 0.59.24

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.
@@ -20,19 +20,67 @@ import { runWithCommittedMutations } from '../../execute-mutation';
20
20
  import { subscribeStateReplacement } from '../../store';
21
21
  import { RepeatContext } from './Repeat';
22
22
  import { DialogCloseContext } from '../PassageDialog';
23
+ import { NameSet } from '../../utils/macro-names';
23
24
  import { ItemEditContext } from '../../utils/control-edits';
24
25
 
25
26
  const frozenAlways = () => true;
26
27
 
28
+ /**
29
+ * Macros whose work is over once their effects have run: a body made of
30
+ * these alone has nothing left to wait for. Any other macro (a timer, a
31
+ * widget, an author's macro) may keep working after rendering.
32
+ */
33
+ const SETTLING_MACROS = new NameSet([
34
+ 'set',
35
+ 'unset',
36
+ 'if',
37
+ 'for',
38
+ 'switch',
39
+ 'do',
40
+ 'print',
41
+ 'goto',
42
+ 'nobr',
43
+ 'span',
44
+ ]);
45
+
46
+ /** Whether `nodes` use no macro outside SETTLING_MACROS (see above). */
47
+ function settlesAfterRender(nodes: ASTNode[]): boolean {
48
+ return nodes.every((n) => {
49
+ switch (n.type) {
50
+ case 'macro':
51
+ return (
52
+ SETTLING_MACROS.has(n.name) &&
53
+ settlesAfterRender(n.children) &&
54
+ (n.branches ?? []).every((b) => settlesAfterRender(b.children))
55
+ );
56
+ case 'html':
57
+ return settlesAfterRender(n.children);
58
+ default:
59
+ return true;
60
+ }
61
+ });
62
+ }
63
+
64
+ /** Calls `onSettled` once the effects of the content before it have run. */
65
+ function Settled({ onSettled }: { onSettled: () => void }) {
66
+ useEffect(() => {
67
+ // After the effects of the whole body, and what they render in turn
68
+ const timer = setTimeout(onSettled, 0);
69
+ return () => clearTimeout(timer);
70
+ }, []);
71
+ return null;
72
+ }
73
+
27
74
  /**
28
75
  * Return a function that runs a macro body once, outside the passage tree:
29
76
  * it renders `children` into a detached node, so the body's macros ({set},
30
77
  * {if}, {goto}, ...) fire their side effects through the normal Preact
31
78
  * pipeline. Used by {button} and {link} on click. The body's state is frozen
32
79
  * once it has rendered, so it runs once per click. It stays mounted
33
- * until the owning macro unmounts (its passage changes, say), so work it
34
- * starts in an effect, such as the timer of a {timed} or {repeat}, can
35
- * finish; the passage leaving cancels it, and so does a restart or a load
80
+ * until it has nothing left to do: a body of plain macros ({set}, {if},
81
+ * {goto}...) once its effects have run, any other (with the timer of a
82
+ * {timed} or {repeat}, say) until the owning macro unmounts, e.g. its
83
+ * passage changes, so that work it starts in an effect can finish; the passage leaving cancels it, and so does a restart or a load
36
84
  * replacing the game, which a control of the story interface outlives
37
85
  * (#401).
38
86
  *
@@ -80,6 +128,16 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
80
128
  const run = (children: ASTNode[]) => {
81
129
  const locals = liveLocalsView(updater.getValues);
82
130
  const container = document.createElement('div');
131
+ // A body that settles is released once it has: it is not kept (with its
132
+ // detached nodes) for every click until the control goes away
133
+ const release = settlesAfterRender(children)
134
+ ? () => {
135
+ const at = mounted.current.indexOf(container);
136
+ if (at === -1) return;
137
+ mounted.current.splice(at, 1);
138
+ render(null, container);
139
+ }
140
+ : null;
83
141
  render(
84
142
  <FrozenStateContext.Provider value={frozenAlways}>
85
143
  <LocalsUpdateContext.Provider value={updater}>
@@ -98,6 +156,7 @@ export function useDetachedBody(): (children: ASTNode[]) => void {
98
156
  structural,
99
157
  locals,
100
158
  })}
159
+ {release && <Settled onSettled={release} />}
101
160
  </OutgoingContext.Provider>
102
161
  </ItemEditContext.Provider>
103
162
  </DialogCloseContext.Provider>
@@ -147,6 +147,33 @@ const openModals: ModalEntry[] = [];
147
147
  * - closes the topmost dialog on Escape when it is dismissible;
148
148
  * - returns focus to the previously focused element on close.
149
149
  */
150
+ /** The input types made of several segments, each a native Tab stop. */
151
+ const SEGMENTED_INPUTS = new Set([
152
+ 'date',
153
+ 'time',
154
+ 'datetime-local',
155
+ 'month',
156
+ 'week',
157
+ ]);
158
+
159
+ /** Whether the element has native tab stops inside it, in its shadow tree. */
160
+ function hasNativeStops(el: Element | null): el is HTMLElement {
161
+ if (el instanceof HTMLMediaElement) return el.controls;
162
+ return (
163
+ el instanceof HTMLInputElement &&
164
+ SEGMENTED_INPUTS.has(el.type) &&
165
+ !el.readOnly
166
+ );
167
+ }
168
+
169
+ /** The tab stops of an embedded document, in tab order. */
170
+ function frameStops(doc: Document | null): HTMLElement[] {
171
+ if (!doc) return [];
172
+ return Array.from(doc.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
173
+ (el) => isAvailable(el) && isTabStop(el),
174
+ );
175
+ }
176
+
150
177
  export function useModalFocus(
151
178
  panelRef: RefObject<HTMLElement>,
152
179
  bodySelector: string,
@@ -200,6 +227,24 @@ export function useModalFocus(
200
227
  * (#424). `from` may be an element of an embedded document, whose frame
201
228
  * element then stands in for it.
202
229
  */
230
+ /** Focus `el`; a frame is entered at its first (or last) control (#460). */
231
+ const enter = (el: HTMLElement, backwards: boolean) => {
232
+ if (el instanceof HTMLIFrameElement) {
233
+ let inner: HTMLElement[] = [];
234
+ try {
235
+ inner = frameStops(el.contentDocument);
236
+ } catch {
237
+ // Not accessible: the frame itself takes focus
238
+ }
239
+ const edge = backwards ? inner[inner.length - 1] : inner[0];
240
+ if (edge) {
241
+ edge.focus();
242
+ return;
243
+ }
244
+ }
245
+ el.focus();
246
+ };
247
+
203
248
  const moveFocus = (from: Element | null, backwards: boolean) => {
204
249
  const items = focusables(panel);
205
250
  const first = items[0];
@@ -224,12 +269,12 @@ export function useModalFocus(
224
269
  } else {
225
270
  next = backwards ? last : first;
226
271
  }
227
- (next ?? (backwards ? last : first)).focus();
272
+ enter(next ?? (backwards ? last : first), backwards);
228
273
  };
229
274
 
230
- // The media element whose native controls Tab is stepping through
231
- let steppingMedia: { el: HTMLMediaElement; backwards: boolean } | null =
232
- null;
275
+ // The element whose native inner controls (a media element's, a date
276
+ // input's segments) Tab is stepping through
277
+ let steppingNative: { el: HTMLElement; backwards: boolean } | null = null;
233
278
 
234
279
  const onKeyDown = (e: KeyboardEvent) => {
235
280
  if (!top()) return;
@@ -243,13 +288,13 @@ export function useModalFocus(
243
288
  }
244
289
 
245
290
  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).
291
+ // The controls of a media element and the segments of a date input are
292
+ // in its user-agent shadow tree, where the element stays the active
293
+ // one: they step through them natively, and onFocusIn takes over where
294
+ // focus leaves the element (#444, #461).
250
295
  const active = document.activeElement;
251
- if (active instanceof HTMLMediaElement && active.controls) {
252
- steppingMedia = { el: active, backwards: e.shiftKey };
296
+ if (hasNativeStops(active)) {
297
+ steppingNative = { el: active, backwards: e.shiftKey };
253
298
  return;
254
299
  }
255
300
  e.preventDefault();
@@ -257,7 +302,7 @@ export function useModalFocus(
257
302
  };
258
303
  // Clicking elsewhere ends the stepping through the controls
259
304
  const onPointerDown = () => {
260
- steppingMedia = null;
305
+ steppingNative = null;
261
306
  };
262
307
 
263
308
  // Key events inside an embedded document never reach this one (#425).
@@ -279,9 +324,7 @@ export function useModalFocus(
279
324
  const onFrameKeyDown = (e: KeyboardEvent) => {
280
325
  if (!top()) return;
281
326
  if (e.key !== 'Tab') return onKeyDown(e);
282
- const inner = Array.from(
283
- doc!.querySelectorAll<HTMLElement>(FOCUSABLE),
284
- ).filter((el) => isAvailable(el) && isTabStop(el));
327
+ const inner = frameStops(doc!);
285
328
  const active = doc!.activeElement;
286
329
  const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
287
330
  if (!edge || active === edge || active === doc!.body) {
@@ -307,10 +350,10 @@ export function useModalFocus(
307
350
  // document can't be reached, is brought back in.
308
351
  const onFocusIn = (e: FocusEvent) => {
309
352
  const target = e.target;
310
- if (steppingMedia && target !== steppingMedia.el && top()) {
353
+ if (steppingNative && target !== steppingNative.el && top()) {
311
354
  // Focus left the media controls: on to the modal's next control
312
- const { el, backwards } = steppingMedia;
313
- steppingMedia = null;
355
+ const { el, backwards } = steppingNative;
356
+ steppingNative = null;
314
357
  moveFocus(el, backwards);
315
358
  return;
316
359
  }
@@ -330,11 +373,11 @@ export function useModalFocus(
330
373
  // with no tab stop after it in the document) sends no focusin: the
331
374
  // modal's next control takes it at once.
332
375
  const onFocusOut = (e: FocusEvent) => {
333
- const pending = steppingMedia;
376
+ const pending = steppingNative;
334
377
  if (!pending || e.target !== pending.el || e.relatedTarget || !top()) {
335
378
  return;
336
379
  }
337
- steppingMedia = null;
380
+ steppingNative = null;
338
381
  moveFocus(pending.el, pending.backwards);
339
382
  };
340
383
  document.addEventListener('focusout', onFocusOut, { signal });
package/src/markup/ast.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  * The passage AST (built by parse.ts), and the registry of block macros:
3
3
  * those whose body the parser nests up to their `{/name}`.
4
4
  */
5
- import type { Selectors, VariableScope } from './tokens';
5
+ import { withSelectors, type Selectors, type VariableScope } from './tokens';
6
+ import type { PairedBranch, PairedNode } from './pair';
6
7
  import { NameSet } from '../utils/macro-names';
7
8
 
8
9
  export interface TextNode {
@@ -68,6 +69,14 @@ const BLOCK_MACROS = new NameSet([
68
69
  'nobr',
69
70
  ]);
70
71
 
72
+ /** Macros whose body is JavaScript source, kept verbatim. */
73
+ const RAW_BODY_MACROS = new Set(['do']);
74
+
75
+ /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
76
+ export function isRawMacro(name: string): boolean {
77
+ return RAW_BODY_MACROS.has(name);
78
+ }
79
+
71
80
  /** Whether a macro takes a body closed by `{/name}`. */
72
81
  export function isBlockMacro(name: string): boolean {
73
82
  return BLOCK_MACROS.has(name);
@@ -82,3 +91,81 @@ export function registerBlockMacro(name: string): void {
82
91
  export function unregisterBlockMacro(name: string): void {
83
92
  BLOCK_MACROS.delete(name);
84
93
  }
94
+
95
+ /** Macros whose branches render as one: the node holds one per branch. */
96
+ const BRANCHING = new Set(['if', 'switch', 'timed']);
97
+
98
+ /** `value` as a quoted macro argument. */
99
+ const quoteArg = (value: string) => `"${value.replace(/[\\"]/g, '\\$&')}"`;
100
+
101
+ /** The AST of paired markup (see pair.ts): what the renderer runs. */
102
+ export function buildAst(nodes: readonly PairedNode[]): ASTNode[] {
103
+ return nodes.map(astNode);
104
+ }
105
+
106
+ function astNode({ token, body }: PairedNode): ASTNode {
107
+ switch (token.type) {
108
+ case 'text':
109
+ return token.comment
110
+ ? { type: 'text', value: token.value, comment: true }
111
+ : { type: 'text', value: token.value };
112
+ case 'link':
113
+ return withSelectors<MacroNode>(
114
+ {
115
+ type: 'macro',
116
+ name: 'link',
117
+ rawArgs: `${quoteArg(token.display)} ${quoteArg(token.target)}`,
118
+ children: [],
119
+ },
120
+ token,
121
+ );
122
+ case 'variable':
123
+ return withSelectors<VariableNode>(
124
+ { type: 'variable', name: token.name, scope: token.scope },
125
+ token,
126
+ );
127
+ case 'expression':
128
+ return withSelectors<ExpressionNode>(
129
+ { type: 'expression', expression: token.expression },
130
+ token,
131
+ );
132
+ case 'html':
133
+ return {
134
+ type: 'html',
135
+ tag: token.tag,
136
+ attributes: token.attributes,
137
+ children: body ? buildAst(body.children) : [],
138
+ };
139
+ case 'macro': {
140
+ const name = token.name.toLowerCase();
141
+ const node: MacroNode = {
142
+ type: 'macro',
143
+ name,
144
+ rawArgs: token.rawArgs,
145
+ children: [],
146
+ };
147
+ if (!body) return withSelectors(node, token);
148
+ const children = buildAst(body.children);
149
+ if (!BRANCHING.has(name)) {
150
+ node.children = children;
151
+ return withSelectors(node, token);
152
+ }
153
+ // The node itself has no selectors: each branch has its own
154
+ const branch = (
155
+ tag: { rawArgs: string } & Selectors,
156
+ branchChildren: ASTNode[],
157
+ ): Branch =>
158
+ withSelectors<Branch>(
159
+ { rawArgs: tag.rawArgs, children: branchChildren },
160
+ tag,
161
+ );
162
+ node.branches = [
163
+ branch(token, children),
164
+ ...body.branches.map(({ tag, children: c }: PairedBranch) =>
165
+ branch(tag, buildAst(c)),
166
+ ),
167
+ ];
168
+ return node;
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,14 @@
1
+ /** 1-based line and column of `offset` in `text`. */
2
+ export function lineColumn(
3
+ text: string,
4
+ offset: number,
5
+ ): { line: number; column: number } {
6
+ let line = 1;
7
+ let lineStart = 0;
8
+ for (let i = text.indexOf('\n'); i !== -1 && i < offset; ) {
9
+ line++;
10
+ lineStart = i + 1;
11
+ i = text.indexOf('\n', lineStart);
12
+ }
13
+ return { line, column: offset - lineStart + 1 };
14
+ }
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Pairing: which closer closes which opener among the flat tokens of markup
3
+ * (parse.ts tokenizeMarkup), and which branch (`{else}`, `{case}`) belongs to
4
+ * which macro. The runtime AST (ast.ts) is built from this, and editor tooling
5
+ * reads the same tree (`pairMarkup` in tooling.ts), so both agree on where a
6
+ * block starts and ends.
7
+ *
8
+ * It never throws: a problem is an entry of `errors`, and the tree is
9
+ * recovered around it. A closer closes the innermost open element, as the
10
+ * runtime reads it, or, when it matches one further out, closes that one and
11
+ * what was open inside it stays unclosed.
12
+ */
13
+ import { lineColumn } from './line-column';
14
+ import { isBlockMacro, isRawMacro } from './ast';
15
+ import type { HtmlToken, MacroToken, Span, Token } from './tokens';
16
+
17
+ /** What is wrong with the pairing, by kind. */
18
+ export type PairingErrorCode =
19
+ | 'unclosed-block'
20
+ | 'mismatched-closer'
21
+ | 'stray-closer'
22
+ | 'misplaced-branch';
23
+
24
+ /**
25
+ * A problem in the pairing of the tokens, at the token from `start` up to
26
+ * `end` (offsets in the source).
27
+ */
28
+ export interface PairingError extends Span {
29
+ code: PairingErrorCode;
30
+ /** What is wrong, without the position. */
31
+ message: string;
32
+ /**
33
+ * The offset a parser reading left to right notices it at: where the
34
+ * closer ends, or past the end of the markup for what is left open there.
35
+ */
36
+ noticedAt: number;
37
+ /** The names involved, by code (see MarkupError.data). */
38
+ data: Record<string, string>;
39
+ }
40
+
41
+ /** A branch (`{else}`, `{case}`, …) of a macro, with what follows it. */
42
+ export interface PairedBranch {
43
+ tag: MacroToken;
44
+ children: PairedNode[];
45
+ }
46
+
47
+ /** What a macro or element holds, up to its closer. */
48
+ export interface PairedBody {
49
+ children: PairedNode[];
50
+ branches: PairedBranch[];
51
+ /** The closing tag; absent if it is never closed. */
52
+ close?: MacroToken | HtmlToken;
53
+ }
54
+
55
+ /**
56
+ * A node of the tree: a token that stands alone (text, a link, a variable, an
57
+ * expression, a macro without a body, a self-closing element), or the opening
58
+ * tag of a macro or element with its `body`.
59
+ */
60
+ export interface PairedNode {
61
+ /** The token, or the opening tag of the element. */
62
+ token: Token;
63
+ body?: PairedBody;
64
+ /** From the start of the token to the end of the closer (or of the body). */
65
+ start: number;
66
+ end: number;
67
+ }
68
+
69
+ export interface PairMarkupOptions {
70
+ /** Whether a macro takes a body (default: the registered block macros). */
71
+ isBlock?(name: string): boolean;
72
+ /**
73
+ * Whether a macro's body is JavaScript, kept verbatim as one text token
74
+ * (default: `{do}`). One that is never closed is a problem at its opening
75
+ * tag, where the body would start, and the markup after it is not its body.
76
+ */
77
+ isRaw?(name: string): boolean;
78
+ /**
79
+ * The markup the tokens are of: lets a message say at which line and column
80
+ * an element was opened (else it says at which offset).
81
+ */
82
+ source?: string;
83
+ }
84
+
85
+ export interface PairedMarkup {
86
+ nodes: PairedNode[];
87
+ errors: PairingError[];
88
+ }
89
+
90
+ /** The last of `items`. */
91
+ const last = <T>(items: readonly T[]): T | undefined => items[items.length - 1];
92
+
93
+ /** The macro each branch macro belongs to. */
94
+ export const BRANCH_PARENT: Readonly<Record<string, string>> = {
95
+ elseif: 'if',
96
+ else: 'if',
97
+ case: 'switch',
98
+ default: 'switch',
99
+ next: 'timed',
100
+ };
101
+
102
+ const isBranchTag = (token: Token): boolean =>
103
+ token.type === 'macro' &&
104
+ !token.isClose &&
105
+ Object.prototype.hasOwnProperty.call(BRANCH_PARENT, token.name.toLowerCase());
106
+
107
+ const lowerName = (token: MacroToken | HtmlToken) =>
108
+ nameOf(token).toLowerCase();
109
+
110
+ /** The macro name or HTML tag of `tag`, as written. */
111
+ const nameOf = (tag: MacroToken | HtmlToken): string =>
112
+ tag.type === 'macro' ? tag.name : tag.tag;
113
+
114
+ /** How a tag reads in an error message. */
115
+ export function tagLabel(tag: MacroToken | HtmlToken): string {
116
+ return tag.type === 'html'
117
+ ? `${tag.isClose ? '</' : '<'}${tag.tag}>`
118
+ : `{${tag.isClose ? '/' : ''}${tag.name}}`;
119
+ }
120
+
121
+ /** The tag that closes the element opened by `tag`. */
122
+ const closerOf = (tag: MacroToken | HtmlToken): string =>
123
+ tag.type === 'html' ? `</${tag.tag}>` : `{/${tag.name}}`;
124
+
125
+ /** An element being read: its opening tag, and what it holds so far. */
126
+ interface Frame {
127
+ node: PairedNode;
128
+ body: PairedBody;
129
+ /** Where the next child goes: the body, or its last branch. */
130
+ into: PairedNode[];
131
+ }
132
+
133
+ /** How an element ends: with its closer, or without. */
134
+ type Ending = 'closed' | 'unclosed' | 'mismatch' | 'cut';
135
+
136
+ /** Whether `close` is the closing tag of the element opened by `open`. */
137
+ const closes = (open: Token, close: MacroToken | HtmlToken): boolean =>
138
+ open.type === close.type &&
139
+ lowerName(open as MacroToken | HtmlToken) === lowerName(close);
140
+
141
+ /**
142
+ * Pair `tokens`, the tokens of `source`, into a tree: elements with their
143
+ * bodies and branches, and the problems found (unclosed, mismatched and
144
+ * stray closers, branches outside their macro) in the order a parser reading
145
+ * from left to right notices them.
146
+ */
147
+ export function pairMarkup(
148
+ tokens: readonly Token[],
149
+ options: PairMarkupOptions = {},
150
+ ): PairedMarkup {
151
+ const isBlock = options.isBlock ?? isBlockMacro;
152
+ const isRaw = options.isRaw ?? isRawMacro;
153
+ const errors: PairingError[] = [];
154
+ const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
155
+ const where = (offset: number) => {
156
+ if (options.source === undefined) return `offset ${offset}`;
157
+ const { line, column } = lineColumn(options.source, offset);
158
+ return `line ${line}, column ${column}`;
159
+ };
160
+ const report = (
161
+ code: PairingErrorCode,
162
+ token: Token,
163
+ message: string,
164
+ noticedAt: number,
165
+ data: Record<string, string>,
166
+ ) => {
167
+ errors.push({
168
+ code,
169
+ message,
170
+ start: token.start,
171
+ end: token.end,
172
+ noticedAt,
173
+ data,
174
+ });
175
+ };
176
+
177
+ /** A branch outside its macro, or inside another element `inside`. */
178
+ const misplaced = (
179
+ tag: MacroToken,
180
+ inside: MacroToken | HtmlToken | undefined,
181
+ noticedAt: number,
182
+ ) => {
183
+ const parent = BRANCH_PARENT[tag.name.toLowerCase()]!;
184
+ const where = inside ? `, not inside ${tagLabel(inside)}` : '';
185
+ report(
186
+ 'misplaced-branch',
187
+ tag,
188
+ `${tagLabel(tag)} must be directly inside {${parent}}${where}`,
189
+ noticedAt,
190
+ { name: tag.name, parent, ...(inside && { inside: nameOf(inside) }) },
191
+ );
192
+ };
193
+
194
+ const root: PairedNode[] = [];
195
+ const stack: Frame[] = [];
196
+ const add = (node: PairedNode) => (last(stack)?.into ?? root).push(node);
197
+
198
+ /**
199
+ * End the element on top of the stack, with `close` if it has one: its
200
+ * misplaced branches are reported first, then how it ends.
201
+ */
202
+ const end = (
203
+ ending: Ending,
204
+ close?: MacroToken | HtmlToken,
205
+ owns = ending === 'closed',
206
+ ) => {
207
+ const { node, body } = stack.pop()!;
208
+ const open = node.token as MacroToken | HtmlToken;
209
+ const noticedAt = close ? close.end : noticedAtEnd;
210
+ for (const { tag } of body.branches) {
211
+ const parent = BRANCH_PARENT[tag.name.toLowerCase()]!;
212
+ if (open.type !== 'macro' || lowerName(open) !== parent) {
213
+ misplaced(tag, open, noticedAt);
214
+ }
215
+ }
216
+ if (ending === 'unclosed') {
217
+ report(
218
+ 'unclosed-block',
219
+ open,
220
+ `Unclosed ${tagLabel(open)}: no ${closerOf(open)} closes it`,
221
+ noticedAt,
222
+ { name: nameOf(open) },
223
+ );
224
+ } else if (ending === 'mismatch') {
225
+ report(
226
+ 'mismatched-closer',
227
+ close!,
228
+ `${tagLabel(close!)} found where ${closerOf(open)} should close the ${tagLabel(open)} opened at ${where(open.start)}`,
229
+ noticedAt,
230
+ { name: nameOf(open), closer: nameOf(close!) },
231
+ );
232
+ }
233
+ if (owns) body.close = close;
234
+ node.end = body.close?.end ?? lastEnd(body) ?? open.end;
235
+ add(node);
236
+ };
237
+
238
+ for (let i = 0; i < tokens.length; i++) {
239
+ const token = tokens[i]!;
240
+ if ((token.type === 'macro' || token.type === 'html') && token.isClose) {
241
+ const top = last(stack);
242
+ if (!top) {
243
+ report(
244
+ 'stray-closer',
245
+ token,
246
+ `${tagLabel(token)} closes nothing: no ${token.type === 'html' ? `<${token.tag}>` : `{${token.name}}`} is open here`,
247
+ token.start,
248
+ { name: nameOf(token) },
249
+ );
250
+ } else if (closes(top.node.token, token)) {
251
+ end('closed', token);
252
+ } else {
253
+ // The closer ends the innermost element, as the runtime reads it;
254
+ // when it names one further out, it ends that one, and the elements
255
+ // inside it are left unclosed
256
+ let outer = stack.length - 1;
257
+ while (outer >= 0 && !closes(stack[outer]!.node.token, token)) outer--;
258
+ end('mismatch', token, outer === -1);
259
+ if (outer !== -1) {
260
+ while (stack.length > outer + 1) end('cut', token);
261
+ end('closed', token);
262
+ }
263
+ }
264
+ continue;
265
+ }
266
+ if (isBranchTag(token)) {
267
+ const tag = token as MacroToken;
268
+ const frame = last(stack);
269
+ if (!frame) {
270
+ misplaced(tag, undefined, tag.start);
271
+ continue;
272
+ }
273
+ const branch: PairedBranch = { tag, children: [] };
274
+ frame.body.branches.push(branch);
275
+ frame.into = branch.children;
276
+ continue;
277
+ }
278
+ const node: PairedNode = { token, start: token.start, end: token.end };
279
+ const opens =
280
+ token.type === 'html'
281
+ ? !token.isSelfClose
282
+ : token.type === 'macro' && isBlock(token.name.toLowerCase());
283
+ if (
284
+ opens &&
285
+ token.type === 'macro' &&
286
+ isRaw(token.name.toLowerCase()) &&
287
+ !closesRawBody(token, tokens[i + 1], tokens[i + 2])
288
+ ) {
289
+ // Its body is looked for as soon as the tag is read: the markup after
290
+ // it is not its body
291
+ report(
292
+ 'unclosed-block',
293
+ token,
294
+ `Unclosed ${tagLabel(token)}: no ${closerOf(token)} closes it`,
295
+ token.end,
296
+ { name: nameOf(token) },
297
+ );
298
+ add(node);
299
+ continue;
300
+ }
301
+ if (!opens) {
302
+ add(node);
303
+ continue;
304
+ }
305
+ const body: PairedBody = { children: [], branches: [] };
306
+ node.body = body;
307
+ stack.push({ node, body, into: body.children });
308
+ }
309
+ while (stack.length > 0) end('unclosed');
310
+ return { nodes: root, errors };
311
+ }
312
+
313
+ /**
314
+ * Whether the tokens after the opening tag `open` of a raw macro are its
315
+ * body (one text token, if it is not empty) and its closer.
316
+ */
317
+ function closesRawBody(
318
+ open: MacroToken,
319
+ next: Token | undefined,
320
+ after: Token | undefined,
321
+ ): boolean {
322
+ const closer = (t: Token | undefined) =>
323
+ t?.type === 'macro' && t.isClose && closes(open, t);
324
+ return closer(next) || (next?.type === 'text' && closer(after));
325
+ }
326
+
327
+ /** The end of the last thing in `body`. */
328
+ function lastEnd(body: PairedBody): number | undefined {
329
+ const branch = last(body.branches);
330
+ return last(branch?.children ?? body.children)?.end ?? branch?.tag.end;
331
+ }