@rohal12/spindle 0.64.16 → 0.64.17

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.
@@ -76,17 +76,17 @@ function* composedElements(root) {
76
76
  }
77
77
  /** Elements whose content is never text the reader reads. */
78
78
  var NOT_TEXT = /* @__PURE__ */ new Set([
79
- "SCRIPT",
80
- "STYLE",
81
- "TEMPLATE",
82
- "NOSCRIPT"
79
+ "script",
80
+ "style",
81
+ "template",
82
+ "noscript"
83
83
  ]);
84
84
  /**
85
85
  * Whether the element hides its whole subtree, including stylesheet rules.
86
86
  * This needs computed styles but no layout, so it also works headlessly.
87
87
  */
88
88
  function isHidden(el) {
89
- return el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true" || /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute("style") ?? "") || el.ownerDocument.defaultView?.getComputedStyle(el).display === "none" || NOT_TEXT.has(el.tagName) || el.parentElement?.tagName === "DETAILS" && !el.parentElement.hasAttribute("open") && el !== Array.from(el.parentElement.children).find((c) => c.tagName === "SUMMARY");
89
+ return el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true" || /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute("style") ?? "") || el.ownerDocument.defaultView?.getComputedStyle(el).display === "none" || NOT_TEXT.has(el.localName.toLowerCase()) || el.parentElement?.tagName === "DETAILS" && !el.parentElement.hasAttribute("open") && el !== Array.from(el.parentElement.children).find((c) => c.tagName === "SUMMARY");
90
90
  }
91
91
  /**
92
92
  * Whether `el` is in a closed `<details>`, other than in the summary that
@@ -16529,6 +16529,31 @@ function HtmlAnnotation({ attributes, children }) {
16529
16529
  }
16530
16530
  }, isHtmlEncoding(attributes.encoding) ? void 0 : children), container && isHtmlEncoding(attributes.encoding) && createPortal(children, container)] });
16531
16531
  }
16532
+ // src/components/macros/include-args.ts
16533
+ /**
16534
+ * The parameters of `{include}`. A standalone `inline` flag only counts
16535
+ * outside quotes and brackets, so passage names and expressions containing
16536
+ * the word stay intact (#201).
16537
+ */
16538
+ var INCLUDE_PARAMETERS = [{
16539
+ name: "inline",
16540
+ type: "flag"
16541
+ }, {
16542
+ name: "passage",
16543
+ type: "passage",
16544
+ required: true
16545
+ }];
16546
+ /**
16547
+ * The arguments of `{include}`: whether it has the `inline` flag, as its
16548
+ * first or last word, and the passage expression that is left.
16549
+ */
16550
+ function splitIncludeFlag(rawArgs) {
16551
+ const { inline, passage } = parseMacroArgs(rawArgs, INCLUDE_PARAMETERS);
16552
+ return {
16553
+ inline,
16554
+ passage
16555
+ };
16556
+ }
16532
16557
  // src/markup/render.tsx
16533
16558
  var defaultUpdater = {
16534
16559
  update: (key) => {
@@ -17079,16 +17104,79 @@ var LEADING_PARTS = {
17079
17104
  details: "summary",
17080
17105
  fieldset: "legend"
17081
17106
  };
17107
+ var SETUP_MACROS = /* @__PURE__ */ new Set([
17108
+ "set",
17109
+ "unset",
17110
+ "do",
17111
+ "widget"
17112
+ ]);
17113
+ function isSetupMacro(node) {
17114
+ return SETUP_MACROS.has(node.name.toLowerCase()) && !getWidget(node.name) && getMacroParameters.source(node.name) === "builtin";
17115
+ }
17082
17116
  /**
17083
- * The index of the node opening `nodes` as the leading part of the `tag`
17084
- * container, or -1 when none does: the element itself, or a macro, which may
17085
- * render it ({if}, {include}, a widget: #474).
17117
+ * Only promote bodies whose first output is a literal part (or nothing).
17118
+ * Nested/dynamic macros stay at the existing boundary: inspecting their
17119
+ * possible output recursively can be expensive and cannot predict effects.
17086
17120
  */
17087
- function leadingPartIndex(tag, nodes) {
17121
+ function hasKnownLeadingPart(node, part) {
17122
+ if (node.className || node.id) return false;
17123
+ const widget = getWidget(node.name);
17124
+ let bodies;
17125
+ if (widget) bodies = [widget.body];
17126
+ else if (getMacroParameters.source(node.name) === "builtin") {
17127
+ const name = node.name.toLowerCase();
17128
+ if (name === "if" || name === "switch") {
17129
+ const branches = node.branches ?? [];
17130
+ if (branches.some((branch) => branch.className || branch.id)) return false;
17131
+ bodies = branches.map((branch) => branch.children);
17132
+ } else if (name === "for" || name === "nobr") bodies = [node.children];
17133
+ else if (name === "include") try {
17134
+ const target = passageTarget(splitIncludeFlag(node.rawArgs).passage ?? "");
17135
+ if (target.kind !== "name") return false;
17136
+ const passage = useStoryStore.getState().storyData?.passages.get(target.name);
17137
+ if (!passage) return false;
17138
+ bodies = [parseMarkup(passage.content)];
17139
+ } catch {
17140
+ return false;
17141
+ }
17142
+ else return false;
17143
+ } else return false;
17144
+ let found = false;
17145
+ for (const body of bodies) {
17146
+ if (body.some((n) => n.type === "text" && (n.value.trim() !== "" || BLANK_LINE_RE.test(n.value)))) return false;
17147
+ const first = body.find((n) => !isBlankText(n) && !(n.type === "macro" && isSetupMacro(n)));
17148
+ if (!first) continue;
17149
+ if (first.type !== "html" || first.tag.toLowerCase() !== part) return false;
17150
+ found = true;
17151
+ }
17152
+ return found;
17153
+ }
17154
+ /**
17155
+ * The end of the leading part of the `tag` container: preceding macros may
17156
+ * render nothing (setup), or produce the part themselves (#474, #739).
17157
+ * Keep the prefix through a literal part direct. Without one, preserve the
17158
+ * first macro boundary, extending past setup only for a known native part.
17159
+ */
17160
+ function leadingPartEnd(tag, nodes) {
17088
17161
  const part = LEADING_PARTS[tag];
17089
- const at = nodes.findIndex((n) => !isBlankText(n));
17090
- const first = nodes[at];
17091
- return part && (first?.type === "macro" || first?.type === "html" && first.tag.toLowerCase() === part) ? at : -1;
17162
+ if (!part) return 0;
17163
+ let end = 0;
17164
+ let setup = true;
17165
+ for (let at = 0; at < nodes.length; at++) {
17166
+ const node = nodes[at];
17167
+ if (isBlankText(node)) continue;
17168
+ if (node.type === "macro") {
17169
+ if (end === 0) end = at + 1;
17170
+ if (setup && !isSetupMacro(node)) {
17171
+ if (end < at + 1 && hasKnownLeadingPart(node, part)) end = at + 1;
17172
+ setup = false;
17173
+ }
17174
+ continue;
17175
+ }
17176
+ if (node.type === "html" && node.tag.toLowerCase() === part) return at + 1;
17177
+ break;
17178
+ }
17179
+ return end;
17092
17180
  }
17093
17181
  function HtmlNodeRenderer({ node }) {
17094
17182
  const scope = useTextScope();
@@ -17119,18 +17207,14 @@ function HtmlNodeRenderer({ node }) {
17119
17207
  if (RAW_TEXT_ELEMENTS.has(tag)) children = node.children.map((n) => n.type === "text" ? n.value : renderSingleNode(n));
17120
17208
  else if (rawContent || isRawRoot) children = renderInlineNodes(node.children);
17121
17209
  else {
17122
- const leadAt = leadingPartIndex(tag, node.children);
17210
+ const leadEnd = leadingPartEnd(tag, node.children);
17123
17211
  const body = (nodes) => renderNodes(nodes, {
17124
17212
  nobr,
17125
17213
  locals,
17126
17214
  inline: isInline
17127
17215
  });
17128
17216
  structural = STRUCTURAL_ELEMENTS.has(tag) && node.children.every((n) => n.type !== "text" || isBlankText(n));
17129
- children = structural ? node.children.filter((n) => n.type !== "text").map((n) => renderSingleNode(n)) : leadAt === -1 ? body(node.children) : /* @__PURE__ */ jsxs(Fragment$1, { children: [
17130
- body(node.children.slice(0, leadAt)),
17131
- renderSingleNode(node.children[leadAt]),
17132
- body(node.children.slice(leadAt + 1))
17133
- ] });
17217
+ children = structural ? node.children.filter((n) => n.type !== "text").map((n) => renderSingleNode(n)) : leadEnd === 0 ? body(node.children) : /* @__PURE__ */ jsxs(Fragment$1, { children: [renderInlineNodes(node.children.slice(0, leadEnd)), body(node.children.slice(leadEnd))] });
17134
17218
  if (isInline !== parentInline) children = /* @__PURE__ */ jsx(InlineContext.Provider, {
17135
17219
  value: isInline,
17136
17220
  children
@@ -23828,7 +23912,7 @@ function installSnapshotSvgStyles(root, ids, marker, targetSheets = [...root.sty
23828
23912
  }
23829
23913
  return result;
23830
23914
  };
23831
- const inserted = [];
23915
+ const inserted = /* @__PURE__ */ new Map();
23832
23916
  const sheets = /* @__PURE__ */ new Set();
23833
23917
  const sheetRules = (sheet) => {
23834
23918
  if (sheets.has(sheet) || sheet.disabled || !matchMedia(sheet.media.mediaText || "all").matches) return;
@@ -23838,14 +23922,17 @@ function installSnapshotSvgStyles(root, ids, marker, targetSheets = [...root.sty
23838
23922
  } catch {}
23839
23923
  };
23840
23924
  const visit = (parent, base) => {
23841
- for (const rule of [...parent.cssRules]) {
23925
+ for (let at = parent.cssRules.length - 1; at >= 0; at--) {
23926
+ const rule = parent.cssRules[at];
23842
23927
  if (snapshotSvgRules.has(rule)) continue;
23843
23928
  if (rule instanceof CSSStyleRule) {
23844
- let index = [...parent.cssRules].indexOf(rule) + 1;
23929
+ let index = at + 1;
23845
23930
  for (const css of rulesOf([rule], base)) {
23846
23931
  parent.insertRule(css, index);
23847
23932
  const insertedRule = parent.cssRules[index++];
23848
- inserted.push([parent, insertedRule]);
23933
+ let rules = inserted.get(parent);
23934
+ if (!rules) inserted.set(parent, rules = /* @__PURE__ */ new Set());
23935
+ rules.add(insertedRule);
23849
23936
  snapshotSvgRules.add(insertedRule);
23850
23937
  }
23851
23938
  } else if (rule instanceof CSSImportRule) {
@@ -23855,10 +23942,9 @@ function installSnapshotSvgStyles(root, ids, marker, targetSheets = [...root.sty
23855
23942
  };
23856
23943
  for (const sheet of targetSheets) sheetRules(sheet);
23857
23944
  return () => {
23858
- for (const [parent, rule] of inserted) {
23859
- const index = [...parent.cssRules].indexOf(rule);
23860
- if (index >= 0) parent.deleteRule(index);
23861
- snapshotSvgRules.delete(rule);
23945
+ for (const [parent, rules] of inserted) {
23946
+ for (let index = parent.cssRules.length - 1; index >= 0; index--) if (rules.has(parent.cssRules[index])) parent.deleteRule(index);
23947
+ for (const rule of rules) snapshotSvgRules.delete(rule);
23862
23948
  }
23863
23949
  };
23864
23950
  }
@@ -25760,14 +25846,7 @@ defineMacro({
25760
25846
  name: "include",
25761
25847
  interpolate: true,
25762
25848
  merged: true,
25763
- parameters: [{
25764
- name: "inline",
25765
- type: "flag"
25766
- }, {
25767
- name: "passage",
25768
- type: "passage",
25769
- required: true
25770
- }],
25849
+ parameters: INCLUDE_PARAMETERS,
25771
25850
  render(_props, ctx) {
25772
25851
  const displayOnly = ctx.hooks.useContext(DisplayOnlyContext);
25773
25852
  const { storyData } = useStoryFields("storyData");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.16",
3
+ "version": "0.64.17",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -369,7 +369,7 @@ function installSnapshotSvgStyles(
369
369
  return result;
370
370
  };
371
371
  type RuleContainer = CSSStyleSheet | CSSGroupingRule;
372
- const inserted: [RuleContainer, CSSRule][] = [];
372
+ const inserted = new Map<RuleContainer, Set<CSSRule>>();
373
373
  const sheets = new Set<CSSStyleSheet>();
374
374
  const sheetRules = (sheet: CSSStyleSheet) => {
375
375
  if (
@@ -387,14 +387,19 @@ function installSnapshotSvgStyles(
387
387
  }
388
388
  };
389
389
  const visit = (parent: RuleContainer, base: string) => {
390
- for (const rule of [...parent.cssRules]) {
390
+ // Work backwards so inserting adjacent aliases leaves the remaining
391
+ // original indexes intact, without copying the live list per rule.
392
+ for (let at = parent.cssRules.length - 1; at >= 0; at--) {
393
+ const rule = parent.cssRules[at]!;
391
394
  if (snapshotSvgRules.has(rule)) continue;
392
395
  if (rule instanceof CSSStyleRule) {
393
- let index = [...parent.cssRules].indexOf(rule) + 1;
396
+ let index = at + 1;
394
397
  for (const css of rulesOf([rule], base)) {
395
398
  parent.insertRule(css, index);
396
399
  const insertedRule = parent.cssRules[index++]!;
397
- inserted.push([parent, insertedRule]);
400
+ let rules = inserted.get(parent);
401
+ if (!rules) inserted.set(parent, (rules = new Set()));
402
+ rules.add(insertedRule);
398
403
  snapshotSvgRules.add(insertedRule);
399
404
  }
400
405
  } else if (rule instanceof CSSImportRule) {
@@ -412,10 +417,13 @@ function installSnapshotSvgStyles(
412
417
  // including anonymous layers. They match snapshot elements only.
413
418
  for (const sheet of targetSheets) sheetRules(sheet);
414
419
  return () => {
415
- for (const [parent, rule] of inserted) {
416
- const index = [...parent.cssRules].indexOf(rule);
417
- if (index >= 0) parent.deleteRule(index);
418
- snapshotSvgRules.delete(rule);
420
+ for (const [parent, rules] of inserted) {
421
+ // Rules may have changed during the transition. Match identities in
422
+ // one backwards pass, preserving authored insertions and removals.
423
+ for (let index = parent.cssRules.length - 1; index >= 0; index--) {
424
+ if (rules.has(parent.cssRules[index]!)) parent.deleteRule(index);
425
+ }
426
+ for (const rule of rules) snapshotSvgRules.delete(rule);
419
427
  }
420
428
  };
421
429
  }
@@ -4,7 +4,7 @@ import { VarDisplay } from '../components/macros/VarDisplay';
4
4
  import { ExprDisplay } from '../components/macros/ExprDisplay';
5
5
  import { WidgetInvocation } from '../components/macros/WidgetInvocation';
6
6
  import { getWidget } from '../widgets/widget-registry';
7
- import { getMacro, isSubMacro } from '../registry';
7
+ import { getMacro, getMacroParameters, isSubMacro } from '../registry';
8
8
  import { markdownToHtml } from './markdown';
9
9
  import { h } from 'preact';
10
10
  import type { ASTNode, HtmlNode, MacroNode } from './ast';
@@ -27,6 +27,10 @@ import { isCodeAttribute } from './code-attributes';
27
27
  import { errorMessage } from '../utils/error-message';
28
28
  import { EMPTY_NAMESPACE } from '../utils/namespace';
29
29
  import { authorElement, isHtmlEncoding } from './html-integration';
30
+ import { parseMarkup } from './parse';
31
+ import { useStoryStore } from '../store';
32
+ import { passageTarget } from '../components/macros/macro-args';
33
+ import { splitIncludeFlag } from '../components/macros/include-args';
30
34
 
31
35
  export interface LocalsUpdater {
32
36
  update: (key: string, value: unknown) => void;
@@ -755,21 +759,102 @@ const LEADING_PARTS: Record<string, string> = {
755
759
  details: 'summary',
756
760
  fieldset: 'legend',
757
761
  };
762
+ const SETUP_MACROS = new Set(['set', 'unset', 'do', 'widget']);
763
+
764
+ function isSetupMacro(node: MacroNode): boolean {
765
+ return (
766
+ SETUP_MACROS.has(node.name.toLowerCase()) &&
767
+ !getWidget(node.name) &&
768
+ getMacroParameters.source(node.name) === 'builtin'
769
+ );
770
+ }
771
+
772
+ /**
773
+ * Only promote bodies whose first output is a literal part (or nothing).
774
+ * Nested/dynamic macros stay at the existing boundary: inspecting their
775
+ * possible output recursively can be expensive and cannot predict effects.
776
+ */
777
+ function hasKnownLeadingPart(node: MacroNode, part: string): boolean {
778
+ if (node.className || node.id) return false;
779
+ const widget = getWidget(node.name);
780
+ let bodies: ASTNode[][];
781
+ if (widget) {
782
+ bodies = [widget.body];
783
+ } else if (getMacroParameters.source(node.name) === 'builtin') {
784
+ const name = node.name.toLowerCase();
785
+ if (name === 'if' || name === 'switch') {
786
+ const branches = node.branches ?? [];
787
+ if (branches.some((branch) => branch.className || branch.id))
788
+ return false;
789
+ bodies = branches.map((branch) => branch.children);
790
+ } else if (name === 'for' || name === 'nobr') {
791
+ bodies = [node.children];
792
+ } else if (name === 'include') {
793
+ try {
794
+ const target = passageTarget(
795
+ splitIncludeFlag(node.rawArgs).passage ?? '',
796
+ );
797
+ if (target.kind !== 'name') return false;
798
+ const passage = useStoryStore
799
+ .getState()
800
+ .storyData?.passages.get(target.name);
801
+ if (!passage) return false;
802
+ bodies = [parseMarkup(passage.content)];
803
+ } catch {
804
+ // Let the include report its own argument or parsing error at render.
805
+ return false;
806
+ }
807
+ } else return false;
808
+ } else return false;
809
+ let found = false;
810
+ for (const body of bodies) {
811
+ // Prose makes renderNodes wrap even a literal part in a paragraph.
812
+ if (
813
+ body.some(
814
+ (n) =>
815
+ n.type === 'text' &&
816
+ (n.value.trim() !== '' || BLANK_LINE_RE.test(n.value)),
817
+ )
818
+ )
819
+ return false;
820
+ const first = body.find(
821
+ (n) => !isBlankText(n) && !(n.type === 'macro' && isSetupMacro(n)),
822
+ );
823
+ if (!first) continue;
824
+ if (first.type !== 'html' || first.tag.toLowerCase() !== part) return false;
825
+ found = true;
826
+ }
827
+ return found;
828
+ }
758
829
 
759
830
  /**
760
- * The index of the node opening `nodes` as the leading part of the `tag`
761
- * container, or -1 when none does: the element itself, or a macro, which may
762
- * render it ({if}, {include}, a widget: #474).
831
+ * The end of the leading part of the `tag` container: preceding macros may
832
+ * render nothing (setup), or produce the part themselves (#474, #739).
833
+ * Keep the prefix through a literal part direct. Without one, preserve the
834
+ * first macro boundary, extending past setup only for a known native part.
763
835
  */
764
- function leadingPartIndex(tag: string, nodes: ASTNode[]): number {
836
+ function leadingPartEnd(tag: string, nodes: ASTNode[]): number {
765
837
  const part = LEADING_PARTS[tag];
766
- const at = nodes.findIndex((n) => !isBlankText(n));
767
- const first = nodes[at];
768
- return part &&
769
- (first?.type === 'macro' ||
770
- (first?.type === 'html' && first.tag.toLowerCase() === part))
771
- ? at
772
- : -1;
838
+ if (!part) return 0;
839
+ let end = 0;
840
+ let setup = true;
841
+ for (let at = 0; at < nodes.length; at++) {
842
+ const node = nodes[at]!;
843
+ if (isBlankText(node)) continue;
844
+ if (node.type === 'macro') {
845
+ if (end === 0) end = at + 1;
846
+ if (setup && !isSetupMacro(node)) {
847
+ if (end < at + 1 && hasKnownLeadingPart(node, part)) {
848
+ end = at + 1;
849
+ }
850
+ setup = false;
851
+ }
852
+ continue;
853
+ }
854
+ if (node.type === 'html' && node.tag.toLowerCase() === part) return at + 1;
855
+ break;
856
+ }
857
+ return end;
773
858
  }
774
859
 
775
860
  function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
@@ -833,7 +918,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
833
918
  // The summary of a details element and the legend of a fieldset stay
834
919
  // its direct children: rendered apart from the markdown of the rest of
835
920
  // the content.
836
- const leadAt = leadingPartIndex(tag, node.children);
921
+ const leadEnd = leadingPartEnd(tag, node.children);
837
922
  const body = (nodes: ASTNode[]) =>
838
923
  renderNodes(nodes, { nobr, locals, inline: isInline });
839
924
  structural =
@@ -843,13 +928,12 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
843
928
  node.children
844
929
  .filter((n) => n.type !== 'text')
845
930
  .map((n) => renderSingleNode(n))
846
- ) : leadAt === -1 ? (
931
+ ) : leadEnd === 0 ? (
847
932
  body(node.children)
848
933
  ) : (
849
934
  <>
850
- {body(node.children.slice(0, leadAt))}
851
- {renderSingleNode(node.children[leadAt]!)}
852
- {body(node.children.slice(leadAt + 1))}
935
+ {renderInlineNodes(node.children.slice(0, leadEnd))}
936
+ {body(node.children.slice(leadEnd))}
853
937
  </>
854
938
  );
855
939
  if (isInline !== parentInline) {
@@ -18,6 +18,7 @@ type ScannedMarkup = ReturnType<typeof scanMarkupTolerant>;
18
18
  import { jsCodeEnd } from '../markup/code-end';
19
19
  import { builtinMacros } from './builtin-macros';
20
20
  import { parameterLookup } from '../code-check';
21
+ import { upperBound } from '../utils/sorted';
21
22
 
22
23
  const pairing = parameterLookup(builtinMacros).pairing;
23
24
 
@@ -407,26 +408,39 @@ function spansOf(text: string, reading: Reading): StyledSpan[] {
407
408
  }
408
409
 
409
410
  /**
410
- * Where the construct starts whose code, starting at `at`, may end
411
- * elsewhere once text follows: the damage of an error the code is in, or
412
- * the tag holding the code (a raw body starts where its opener ends).
411
+ * Owners of code that may end elsewhere once text follows: the damage of
412
+ * an error the code is in, or the tag holding the code (a raw body starts
413
+ * where its opener ends). Index once for all open code positions.
413
414
  */
414
- function openCodeStart(scan: ScannedMarkup, at: number): number {
415
- const i = scan.errors.findIndex(
416
- (e, i) => scan.damage[i]! < at && at <= Math.max(e.offset, e.end),
417
- );
418
- if (i >= 0) return scan.damage[i]!;
419
- const token = scan.tokens.find(
420
- (t) => t.type !== 'text' && t.start < at && at <= t.end,
421
- );
422
- return token ? token.start : -1;
415
+ function openCodeStarts(scan: ScannedMarkup, ends: number[]): number[] {
416
+ if (!ends.length) return [];
417
+ // Damage starts are ordered but their ranges may overlap. Prefix maxima
418
+ // let each query find the first owning error, just as findIndex did.
419
+ const damageEnds: number[] = [];
420
+ for (const error of scan.errors) {
421
+ damageEnds.push(
422
+ Math.max(
423
+ damageEnds[damageEnds.length - 1] ?? -1,
424
+ error.offset,
425
+ error.end,
426
+ ),
427
+ );
428
+ }
429
+ const tokens = scan.tokens.filter((token) => token.type !== 'text');
430
+ const starts = tokens.map((token) => token.start);
431
+ return ends.map((at) => {
432
+ const i = upperBound(damageEnds, at - 1);
433
+ if (i < scan.damage.length && scan.damage[i]! < at) return scan.damage[i]!;
434
+ const token = tokens[upperBound(starts, at - 1) - 1];
435
+ return token && at <= token.end ? token.start : -1;
436
+ });
423
437
  }
424
438
 
425
439
  function openStartOf(text: string, reading: Reading): number {
426
440
  const { tokens } = reading;
427
441
  const starts = [
428
442
  ...unclosedStarts(text, reading),
429
- ...reading.openEnds.map((at) => openCodeStart(reading, at)),
443
+ ...openCodeStarts(reading, reading.openEnds),
430
444
  openComment(tokens),
431
445
  openDo(tokens)?.start ?? -1,
432
446
  openTag(text, tokens),
@@ -34,7 +34,7 @@ export function* composedElements(root: ParentNode): Generator<HTMLElement> {
34
34
  }
35
35
 
36
36
  /** Elements whose content is never text the reader reads. */
37
- const NOT_TEXT = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT']);
37
+ const NOT_TEXT = new Set(['script', 'style', 'template', 'noscript']);
38
38
 
39
39
  /**
40
40
  * Whether the element hides its whole subtree, including stylesheet rules.
@@ -46,7 +46,7 @@ export function isHidden(el: Element): boolean {
46
46
  el.getAttribute('aria-hidden') === 'true' ||
47
47
  /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute('style') ?? '') ||
48
48
  el.ownerDocument.defaultView?.getComputedStyle(el).display === 'none' ||
49
- NOT_TEXT.has(el.tagName) ||
49
+ NOT_TEXT.has(el.localName.toLowerCase()) ||
50
50
  (el.parentElement?.tagName === 'DETAILS' &&
51
51
  !el.parentElement.hasAttribute('open') &&
52
52
  el !==