@rohal12/spindle 0.62.0 → 0.62.2

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.
@@ -4045,6 +4045,8 @@ var BLOCK_MACROS = new NameSet([
4045
4045
  * definition is, whereas the macros in BLOCK_MACROS stay blocks.
4046
4046
  */
4047
4047
  var BLOCK_WIDGETS = new NameSet();
4048
+ /** All widgets, including inline ones, override built-in parsing semantics. */
4049
+ var WIDGETS = new NameSet();
4048
4050
  /** Classification owned by defineMacro, independent of explicit registrations. */
4049
4051
  var DEFINED_BLOCK_MACROS = new NameSet();
4050
4052
  function setDefinedBlockMacro(name, isBlock) {
@@ -4058,8 +4060,8 @@ function setClassification(names, name, block) {
4058
4060
  /** Macros whose body is JavaScript source, kept verbatim. */
4059
4061
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
4060
4062
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
4061
- function isRawMacro(name) {
4062
- return RAW_BODY_MACROS.has(name);
4063
+ function isRawMacro(name, widget = WIDGETS.has(name)) {
4064
+ return RAW_BODY_MACROS.has(name.toLowerCase()) && !widget;
4063
4065
  }
4064
4066
  /** Whether a macro takes a body closed by `{/name}`. */
4065
4067
  function isBlockMacro(name) {
@@ -4070,6 +4072,7 @@ function isBlockMacro(name) {
4070
4072
  * does. A block macro registered under the same name stays a block.
4071
4073
  */
4072
4074
  function setBlockWidget(name, isBlock) {
4075
+ WIDGETS.add(name);
4073
4076
  setClassification(BLOCK_WIDGETS, name, isBlock);
4074
4077
  }
4075
4078
  /** Macros whose branches render as one: the node holds one per branch. */
@@ -4125,7 +4128,8 @@ function astNode({ token, body }) {
4125
4128
  };
4126
4129
  if (!body) return withSelectors$1(node, token);
4127
4130
  const children = buildAst(body.children);
4128
- if (!BRANCHING.has(name) && body.branches.length === 0) {
4131
+ const branching = BRANCHING.has(name) && !WIDGETS.has(name);
4132
+ if (!branching && body.branches.length === 0) {
4129
4133
  node.children = children;
4130
4134
  return withSelectors$1(node, token);
4131
4135
  }
@@ -4133,9 +4137,9 @@ function astNode({ token, body }) {
4133
4137
  rawArgs: tag.rawArgs,
4134
4138
  children: branchChildren
4135
4139
  }, tag);
4136
- if (!BRANCHING.has(name)) node.children = children;
4137
- node.branches = [...BRANCHING.has(name) ? [branch(token, children)] : [], ...body.branches.map(({ tag, children: c }) => branch(tag, buildAst(c)))];
4138
- return BRANCHING.has(name) ? node : withSelectors$1(node, token);
4140
+ if (!branching) node.children = children;
4141
+ node.branches = [...branching ? [branch(token, children)] : [], ...body.branches.map(({ tag, children: c }) => branch(tag, buildAst(c)))];
4142
+ return branching ? node : withSelectors$1(node, token);
4139
4143
  }
4140
4144
  }
4141
4145
  }
@@ -4279,6 +4283,25 @@ function lineColumn(text, offset) {
4279
4283
  column: offset - lineStart + 1
4280
4284
  };
4281
4285
  }
4286
+ /** Index one source once; offsets and columns count UTF-16 code units. */
4287
+ function sourcePositions(text) {
4288
+ const starts = [0];
4289
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
4290
+ return (offset) => {
4291
+ let low = 0;
4292
+ let high = starts.length;
4293
+ while (low < high) {
4294
+ const mid = low + high >>> 1;
4295
+ if (starts[mid] <= offset) low = mid + 1;
4296
+ else high = mid;
4297
+ }
4298
+ const line = Math.max(1, low);
4299
+ return {
4300
+ line,
4301
+ column: offset - starts[line - 1] + 1
4302
+ };
4303
+ };
4304
+ }
4282
4305
  //#endregion
4283
4306
  //#region src/markup/pair.ts
4284
4307
  /**
@@ -4330,9 +4353,11 @@ function pairMarkup(tokens, options = {}) {
4330
4353
  };
4331
4354
  const errors = [];
4332
4355
  const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
4356
+ let position;
4333
4357
  const where = (offset) => {
4334
4358
  if (options.source === void 0) return `offset ${offset}`;
4335
- const { line, column } = lineColumn(options.source, offset);
4359
+ position ??= sourcePositions(options.source);
4360
+ const { line, column } = position(offset);
4336
4361
  return `line ${line}, column ${column}`;
4337
4362
  };
4338
4363
  const report = (code, token, message, noticedAt, data) => {
@@ -10361,6 +10386,14 @@ function* tokens(src, start, goal, options = {}) {
10361
10386
  function lexJs(src, handlers, goal = "expression") {
10362
10387
  return walkTokens(src, 0, handlers, 0, goal, false);
10363
10388
  }
10389
+ /**
10390
+ * Lex the template literal opening at `start` (a backtick) as `lexJs` does,
10391
+ * its interpolations one nesting level deeper. Returns the index just past
10392
+ * its closing backtick, or `src.length` if it is unterminated.
10393
+ */
10394
+ function lexTemplate(src, start, handlers = {}, nesting = 0) {
10395
+ return walkTokens(src, start, handlers, nesting, "expression", true);
10396
+ }
10364
10397
  function walkTokens(src, from, handlers, nesting, goal, oneTemplate) {
10365
10398
  const comments = [];
10366
10399
  const onComment = (_block, _text, s, e) => {
@@ -10770,7 +10803,8 @@ function analyzeMarkup(source, options = {}) {
10770
10803
  };
10771
10804
  const inDamage = (start) => errors.some((e, i) => start >= damage[i] && start <= e.offset);
10772
10805
  const noticed = errors.map((e, i) => [damage[i] + .5, e]);
10773
- for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(source, error)]);
10806
+ const position = paired.errors.length ? sourcePositions(source) : void 0;
10807
+ for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(position, error)]);
10774
10808
  noticed.sort((a, b) => a[0] - b[0]);
10775
10809
  return {
10776
10810
  tokens,
@@ -10789,8 +10823,8 @@ function parseMarkup(source, options = {}) {
10789
10823
  return buildAst(nodes);
10790
10824
  }
10791
10825
  /** A pairing problem as the MarkupError it is for `source`. */
10792
- function pairingError(source, error) {
10793
- const { line, column } = lineColumn(source, error.start);
10826
+ function pairingError(position, error) {
10827
+ const { line, column } = position(error.start);
10794
10828
  return new MarkupError(error.message, error.start, line, column, error.code, error.end, error.data);
10795
10829
  }
10796
10830
  /**
@@ -10825,6 +10859,7 @@ function scanMarkupTolerant(source, options = {}) {
10825
10859
  const tokens = [];
10826
10860
  const errors = [];
10827
10861
  const damage = [];
10862
+ let position;
10828
10863
  const lastBrace = source.lastIndexOf("}");
10829
10864
  const { closeBrace } = {
10830
10865
  ...defaultHooks,
@@ -10855,7 +10890,8 @@ function scanMarkupTolerant(source, options = {}) {
10855
10890
  break;
10856
10891
  }
10857
10892
  const at = base + result.offset;
10858
- const { line, column } = lineColumn(source, at);
10893
+ position ??= sourcePositions(source);
10894
+ const { line, column } = position(at);
10859
10895
  errors.push(new MarkupError(result.reason, at, line, column, result.code, base + result.end));
10860
10896
  let cut = result.offset;
10861
10897
  let prefix = attempt(rest.slice(0, cut), base);
@@ -11140,6 +11176,17 @@ function isCloser(ch) {
11140
11176
  return ch === ")" || ch === "]" || ch === "}";
11141
11177
  }
11142
11178
  /**
11179
+ * Given the index of an opening quote (`"`, `'` or a backtick), return the
11180
+ * index just past its closing quote, or `src.length` if it is unterminated.
11181
+ * A backslash escapes the character after it, so a quote preceded by an even
11182
+ * run of backslashes still closes the string and one preceded by an odd run
11183
+ * does not. Inside a template literal, `${…}` interpolations are lexed as
11184
+ * code, so quotes, backticks, braces and regexes inside them do not end it.
11185
+ */
11186
+ function skipString(src, start) {
11187
+ return src[start] === "`" ? lexTemplate(src, start) : scanStringLiteral(src, start).end;
11188
+ }
11189
+ /**
11143
11190
  * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
11144
11191
  * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
11145
11192
  * are kept as written, so code and regex text inside the string survive.
@@ -11738,10 +11785,10 @@ function parameterLookup(macros) {
11738
11785
  const widgets = new NameMap();
11739
11786
  for (const { name, parameters: params, interpolate, widget } of macros) {
11740
11787
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11741
- const declared = widget && widgetParameters(widget.params, widget.holds);
11742
- if (declared) widgets.set(name, declared);
11788
+ if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11743
11789
  }
11744
11790
  const lookup = (name) => {
11791
+ if (widgets.has(name)) return void 0;
11745
11792
  let params = parameters.get(name);
11746
11793
  if (!params) {
11747
11794
  const sub = subMacroParameters(name);
@@ -11814,7 +11861,8 @@ function* codeAndText(src, tokens, parametersOf) {
11814
11861
  }
11815
11862
  else if (token.type === "macro" && !token.isClose) {
11816
11863
  const name = token.name.toLowerCase();
11817
- if (name === "do") {
11864
+ const widget = parametersOf.widget?.(name);
11865
+ if (name === "do" && !widget) {
11818
11866
  const close = closeOfTextBody(t, name);
11819
11867
  if (close < 0) continue;
11820
11868
  yield {
@@ -11828,7 +11876,7 @@ function* codeAndText(src, tokens, parametersOf) {
11828
11876
  continue;
11829
11877
  }
11830
11878
  const args = token.rawArgs;
11831
- if (PASSAGE_BODIES.has(name)) {
11879
+ if (PASSAGE_BODIES.has(name) && !widget) {
11832
11880
  const close = closeOfTextBody(t, name);
11833
11881
  if (close > t + 1) {
11834
11882
  const text = src.slice(token.end, tokens[close].start);
@@ -11846,7 +11894,7 @@ function* codeAndText(src, tokens, parametersOf) {
11846
11894
  if (!args) continue;
11847
11895
  const label = `{${token.name} ${args}}`;
11848
11896
  const argsAt = token.argsStart;
11849
- if (CONDITION_MACROS.has(name)) {
11897
+ if (CONDITION_MACROS.has(name) && !widget) {
11850
11898
  yield {
11851
11899
  kind: "code",
11852
11900
  code: args,
@@ -11858,7 +11906,6 @@ function* codeAndText(src, tokens, parametersOf) {
11858
11906
  }
11859
11907
  const params = parametersOf(name);
11860
11908
  if (params) yield* argPieces(args, argsAt, params, token.name, label);
11861
- const widget = parametersOf.widget?.(name);
11862
11909
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
11863
11910
  }
11864
11911
  }
@@ -11870,14 +11917,16 @@ function* codeAndText(src, tokens, parametersOf) {
11870
11917
  * `src`. In source order, a nested piece after the text it is in.
11871
11918
  */
11872
11919
  function* passagePiecesOf(src, tokens, parametersOf, options = {}) {
11873
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0);
11920
+ let position;
11921
+ const locate = (offset) => (position ??= sourcePositions(src))(offset);
11922
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate);
11874
11923
  }
11875
11924
  /**
11876
11925
  * The pieces of `tokens`, the tokens of `src`, which is the text described by
11877
11926
  * `where` (none for `root`, the markup of the whole passage), and whose
11878
11927
  * offsets `toRoot` turns into offsets in `root`.
11879
11928
  */
11880
- function* expand(root, src, tokens, parametersOf, options, toRoot, where) {
11929
+ function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate) {
11881
11930
  for (const flat of codeAndText(src, tokens, parametersOf)) {
11882
11931
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
11883
11932
  if (flat.kind !== "text" || !flat.text.includes("{")) {
@@ -11887,17 +11936,20 @@ function* expand(root, src, tokens, parametersOf, options, toRoot, where) {
11887
11936
  const toText = (i) => toRoot(pieceOffset(flat, i));
11888
11937
  const inner = analyzeMarkup(flat.text, {
11889
11938
  text: true,
11890
- hooks: options.isBlock && { isBlock: options.isBlock }
11939
+ hooks: {
11940
+ ...options.isBlock && { isBlock: options.isBlock },
11941
+ isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
11942
+ }
11891
11943
  });
11892
11944
  yield {
11893
11945
  ...piece,
11894
11946
  tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
11895
11947
  errors: inner.errors.map((e) => {
11896
- const { line, column } = lineColumn(root, toText(e.offset));
11948
+ const { line, column } = locate(toText(e.offset));
11897
11949
  return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
11898
11950
  })
11899
11951
  };
11900
- yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where);
11952
+ yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate);
11901
11953
  }
11902
11954
  }
11903
11955
  /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
@@ -19996,12 +20048,34 @@ var FOCUSABLE = [
19996
20048
  "[contenteditable]",
19997
20049
  "[tabindex]"
19998
20050
  ].join(",");
20051
+ /** The parent in the rendered tree, including slots and shadow hosts. */
20052
+ function composedParent(el) {
20053
+ return el.assignedSlot ?? el.parentElement ?? el.getRootNode().host ?? null;
20054
+ }
20055
+ function composedChildren(root) {
20056
+ if (root.localName === "slot") return root.assignedNodes({ flatten: true }).filter((node) => node.nodeType === 1);
20057
+ return Array.from(root.children);
20058
+ }
20059
+ /** Authored elements in rendered order; unassigned light DOM is not rendered. */
20060
+ function* composedElements(root) {
20061
+ for (const el of composedChildren(root)) {
20062
+ yield el;
20063
+ yield* composedElements(el.shadowRoot ?? el);
20064
+ }
20065
+ }
19999
20066
  /**
20000
20067
  * Whether `el` can be focused at all: shown, rendered, enabled (also by its
20001
20068
  * fieldset) and not inert.
20002
20069
  */
20003
20070
  function isAvailable(el) {
20004
- return !el.hidden && !el.closest("[hidden], [inert]") && !el.matches(":disabled") && isRendered(el);
20071
+ if (!isRendered(el)) return false;
20072
+ for (let at = el; at; at = composedParent(at)) {
20073
+ if (at.hasAttribute("hidden") || at.hasAttribute("inert")) return false;
20074
+ if (at.ownerDocument.defaultView?.getComputedStyle(at).display === "none") return false;
20075
+ const parent = composedParent(at);
20076
+ if (parent?.localName === "details" && !parent.hasAttribute("open") && at !== Array.from(parent.children).find((child) => child.localName === "summary")) return false;
20077
+ }
20078
+ return !el.matches(":disabled");
20005
20079
  }
20006
20080
  /** The `tabindex` of `el` as an integer, or null when absent or invalid. */
20007
20081
  function tabIndexAttr(el) {
@@ -20036,9 +20110,30 @@ function isTabStop(el) {
20036
20110
  * others in document order.
20037
20111
  */
20038
20112
  function focusables(root) {
20039
- const stops = Array.from(root.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
20113
+ const scopes = [];
20114
+ const collect = (parent) => {
20115
+ for (const element of composedChildren(parent)) {
20116
+ const el = element;
20117
+ const nested = el.shadowRoot ?? (el.localName === "slot" ? el : null);
20118
+ const stop = el.matches(FOCUSABLE) && isAvailable(el) && isTabStop(el);
20119
+ if (nested) {
20120
+ if ((tabIndexAttr(el) ?? 0) < 0) continue;
20121
+ scopes.push({
20122
+ el,
20123
+ stops: [...stop && !el.shadowRoot?.delegatesFocus ? [el] : [], ...focusables(nested)]
20124
+ });
20125
+ } else {
20126
+ if (stop) scopes.push({
20127
+ el,
20128
+ stops: [el]
20129
+ });
20130
+ collect(el);
20131
+ }
20132
+ }
20133
+ };
20134
+ collect(root);
20040
20135
  const positive = (el) => Math.max(tabIndexAttr(el) ?? 0, 0);
20041
- return [...stops.filter((el) => positive(el) > 0).sort((a, b) => positive(a) - positive(b)), ...stops.filter((el) => positive(el) === 0)];
20136
+ return [...scopes.filter(({ el }) => positive(el) > 0).sort((a, b) => positive(a.el) - positive(b.el)), ...scopes.filter(({ el }) => positive(el) === 0)].flatMap(({ stops }) => stops);
20042
20137
  }
20043
20138
  /** Open modal dialogs, innermost last. Only the topmost handles keys. */
20044
20139
  var openModals = [];
@@ -20077,6 +20172,21 @@ function frameDocument(frame) {
20077
20172
  return null;
20078
20173
  }
20079
20174
  }
20175
+ /** Focus an element, entering accessible frames at the appropriate edge. */
20176
+ function enter(el, backwards) {
20177
+ if (isFrame(el)) {
20178
+ const doc = frameDocument(el);
20179
+ const inner = doc ? focusables(doc) : [];
20180
+ const edge = backwards ? inner[inner.length - 1] : inner[0];
20181
+ if (edge) return enter(edge, backwards);
20182
+ }
20183
+ el.focus();
20184
+ }
20185
+ /** document.activeElement exposes a shadow host; follow it to the control. */
20186
+ function activeElement(root) {
20187
+ const el = root.activeElement;
20188
+ return el?.shadowRoot?.activeElement ? activeElement(el.shadowRoot) : el;
20189
+ }
20080
20190
  /** The iframe element that holds `doc`, null for the top document. */
20081
20191
  function frameOf(doc) {
20082
20192
  try {
@@ -20093,8 +20203,10 @@ function frameOf(doc) {
20093
20203
  function nextStop(items, root, from, backwards) {
20094
20204
  const at = from ? items.indexOf(from) : -1;
20095
20205
  if (at !== -1) return items[at + (backwards ? -1 : 1)];
20096
- if (from && from !== root && root.contains(from)) {
20097
- const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
20206
+ const order = from ? [...composedElements(root)] : [];
20207
+ const position = order.indexOf(from);
20208
+ if (position !== -1) {
20209
+ const after = (el) => order.indexOf(el) > position;
20098
20210
  return backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
20099
20211
  }
20100
20212
  return backwards ? items[items.length - 1] : items[0];
@@ -20109,13 +20221,13 @@ function nextStop(items, root, from, backwards) {
20109
20221
  */
20110
20222
  function activeChain() {
20111
20223
  const chain = [];
20112
- let doc = document;
20113
- while (doc) {
20114
- const el = doc.activeElement;
20115
- if (!el || chain.length > 0 && el === doc.body) break;
20224
+ let root = document;
20225
+ while (root) {
20226
+ const el = root.activeElement;
20227
+ if (!el || chain.length > 0 && el === root.body) break;
20116
20228
  if (typeof el.focus !== "function") break;
20117
20229
  chain.push(el);
20118
- doc = isFrame(el) ? frameDocument(el) : null;
20230
+ root = el.shadowRoot?.activeElement ? el.shadowRoot : isFrame(el) ? frameDocument(el) : null;
20119
20231
  }
20120
20232
  return chain;
20121
20233
  }
@@ -20143,7 +20255,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
20143
20255
  };
20144
20256
  openModals.push(entry);
20145
20257
  const body = panel.querySelector(bodySelector) ?? panel;
20146
- (Array.from(panel.querySelectorAll("[autofocus]")).find(isAvailable) ?? focusables(body)[0] ?? panel).focus();
20258
+ enter([...composedElements(panel)].find((el) => el.hasAttribute("autofocus") && isAvailable(el)) ?? focusables(body)[0] ?? panel, false);
20147
20259
  return () => {
20148
20260
  const i = openModals.indexOf(entry);
20149
20261
  if (i !== -1) openModals.splice(i, 1);
@@ -20159,16 +20271,6 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
20159
20271
  const panel = panelRef.current;
20160
20272
  if (!panel) return;
20161
20273
  const top = () => openModals[openModals.length - 1]?.panel === panel;
20162
- /** Focus `el`; a frame is entered at its first (or last) control (#460). */
20163
- const enter = (el, backwards) => {
20164
- if (isFrame(el)) {
20165
- const doc = frameDocument(el);
20166
- const inner = doc ? focusables(doc) : [];
20167
- const edge = backwards ? inner[inner.length - 1] : inner[0];
20168
- if (edge) return enter(edge, backwards);
20169
- }
20170
- el.focus();
20171
- };
20172
20274
  /**
20173
20275
  * Move focus to the next (or previous) modal control from `from`. The
20174
20276
  * order is computed here, never left to the browser: its positive-tabindex
@@ -20193,8 +20295,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
20193
20295
  panel.focus();
20194
20296
  return;
20195
20297
  }
20196
- const next = nextStop(items, panel, from, backwards);
20197
- enter(next ?? (backwards ? last : first), backwards);
20298
+ enter(nextStop(items, panel, from, backwards) ?? (backwards ? last : first), backwards);
20198
20299
  };
20199
20300
  let steppingNative = null;
20200
20301
  const keyHandler = (doc, frame) => {
@@ -20208,7 +20309,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
20208
20309
  return;
20209
20310
  }
20210
20311
  if (e.key !== "Tab") return;
20211
- const active = doc.activeElement;
20312
+ const active = activeElement(doc);
20212
20313
  if (frame) {
20213
20314
  steppingNative = null;
20214
20315
  const inner = focusables(doc);
@@ -20231,20 +20332,20 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
20231
20332
  steppingNative = null;
20232
20333
  };
20233
20334
  const onFocusIn = (e) => {
20234
- const target = e.target;
20335
+ const target = e.composedPath()[0] ?? e.target;
20235
20336
  if (steppingNative && target !== steppingNative.el && top()) {
20236
20337
  const { from, backwards } = steppingNative;
20237
20338
  steppingNative = null;
20238
20339
  moveFocus(from, backwards);
20239
20340
  return;
20240
20341
  }
20241
- if (!top() || !(target instanceof Node) || panel.contains(target)) return;
20342
+ if (!top() || !(target instanceof Node) || target instanceof Element && [...composedElements(panel)].includes(target) || panel.contains(target)) return;
20242
20343
  if (target === document.body || target === document.documentElement) return;
20243
20344
  moveFocus(null, false);
20244
20345
  };
20245
20346
  const onFocusOut = (e) => {
20246
20347
  const pending = steppingNative;
20247
- if (!pending || e.target !== pending.el || e.relatedTarget || !top()) return;
20348
+ if (!pending || (e.composedPath()[0] ?? e.target) !== pending.el || e.relatedTarget || !top()) return;
20248
20349
  steppingNative = null;
20249
20350
  moveFocus(pending.from, pending.backwards);
20250
20351
  };
@@ -20260,15 +20361,25 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
20260
20361
  };
20261
20362
  const frameDocs = /* @__PURE__ */ new Map();
20262
20363
  const observers = [];
20364
+ const watched = /* @__PURE__ */ new WeakSet();
20263
20365
  const attachFrame = (frame) => {
20264
20366
  const doc = frameDocument(frame);
20265
20367
  if (!doc || frameDocs.get(frame) === doc) return;
20266
20368
  frameDocs.set(frame, doc);
20267
20369
  listen(doc, frame);
20268
20370
  watchFrames(doc);
20371
+ const chain = activeChain();
20372
+ if (top() && chain[chain.length - 1] === frame) enter(frame, false);
20269
20373
  };
20270
20374
  const watchFrames = (root) => {
20271
- const attachAll = () => root.querySelectorAll("iframe").forEach(attachFrame);
20375
+ if (watched.has(root)) return;
20376
+ watched.add(root);
20377
+ const attachAll = () => {
20378
+ for (const el of composedElements(root)) {
20379
+ if (el.shadowRoot) watchFrames(el.shadowRoot);
20380
+ if (isFrame(el)) attachFrame(el);
20381
+ }
20382
+ };
20272
20383
  root.addEventListener("load", (e) => {
20273
20384
  if (e.target && isFrame(e.target)) attachFrame(e.target);
20274
20385
  }, {
@@ -21805,14 +21916,23 @@ function distance(a, b) {
21805
21916
  }
21806
21917
  /** The known name closest to `name`, if one is close. */
21807
21918
  function closestName(name, names) {
21919
+ if (name.length > 256) return void 0;
21808
21920
  const lower = name.toLowerCase();
21809
21921
  let best;
21810
21922
  let bestDistance = Math.max(2, Math.floor(lower.length / 3)) + 1;
21923
+ let budget = 1e5;
21924
+ let candidates = 1e3;
21811
21925
  for (const candidate of names) {
21926
+ if (--candidates < 0) break;
21927
+ if (candidate.length > 256) continue;
21928
+ if (Math.abs(candidate.length - lower.length) >= bestDistance) continue;
21929
+ budget -= lower.length * candidate.length;
21930
+ if (budget < 0) break;
21812
21931
  const d = distance(lower, candidate.toLowerCase());
21813
21932
  if (d < bestDistance) {
21814
21933
  best = candidate;
21815
21934
  bestDistance = d;
21935
+ if (d === 0) break;
21816
21936
  }
21817
21937
  }
21818
21938
  return best;
@@ -21837,12 +21957,19 @@ function widgetName(rawArgs) {
21837
21957
  */
21838
21958
  function validateMarkup(passages, options) {
21839
21959
  const diagnostics = [];
21960
+ const positions = /* @__PURE__ */ new Map();
21840
21961
  const hooks = {
21841
21962
  ...options.isBlockMacro && { isBlock: options.isBlockMacro },
21842
- ...options.branchParents && { branchParents: options.branchParents }
21963
+ ...options.branchParents && { branchParents: options.branchParents },
21964
+ isRaw: (name) => isRawMacro(name, options.parametersOf ? options.parametersOf.widget?.(name) !== void 0 : void 0)
21843
21965
  };
21844
21966
  const report = (passage, start, end, code, message, data) => {
21845
- const { line, column } = lineColumn(passage.content, start);
21967
+ let position = positions.get(passage);
21968
+ if (!position) {
21969
+ position = sourcePositions(passage.content);
21970
+ positions.set(passage, position);
21971
+ }
21972
+ const { line, column } = position(start);
21846
21973
  const d = {
21847
21974
  passage: passage.name,
21848
21975
  line,
@@ -21888,7 +22015,7 @@ function validateMarkup(passages, options) {
21888
22015
  continue;
21889
22016
  }
21890
22017
  try {
21891
- const tokens = tokenizeMarkup(passage.content);
22018
+ const tokens = tokenizeMarkup(passage.content, { hooks });
21892
22019
  addWidgets(tokens);
21893
22020
  if (!reported) continue;
21894
22021
  parseMarkup(passage.content, { hooks });
@@ -22387,10 +22514,14 @@ var Reader = class {
22387
22514
  * The tokens of markup, or none if it is malformed (validateMarkup reports
22388
22515
  * that, with its position); in tolerant mode, those of the well-formed parts.
22389
22516
  */
22390
- function tokensOf(text, textMode, { tolerant } = {}) {
22391
- if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
22517
+ function tokensOf(text, textMode, { tolerant, parametersOf } = {}) {
22518
+ const options = {
22519
+ text: textMode,
22520
+ hooks: parametersOf && { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) }
22521
+ };
22522
+ if (tolerant) return tokenizeMarkupTolerant(text, options).tokens;
22392
22523
  try {
22393
- return tokenizeMarkup(text, { text: textMode });
22524
+ return tokenizeMarkup(text, options);
22394
22525
  } catch (err) {
22395
22526
  if (err instanceof MarkupError) return [];
22396
22527
  throw err;
@@ -22458,7 +22589,7 @@ function shapeSchema(shape) {
22458
22589
  function initializerSyntaxError(expr) {
22459
22590
  const prefix = "return (";
22460
22591
  try {
22461
- parse$1(prefix + expr + ")", {
22592
+ parse$1(prefix + expr + "\n)", {
22462
22593
  ecmaVersion: "latest",
22463
22594
  allowReturnOutsideFunction: true
22464
22595
  });
@@ -22567,7 +22698,7 @@ function parseStoryVariables(content, sigil = "$") {
22567
22698
  const expr = content.slice(valueStart, valueEnd);
22568
22699
  let value;
22569
22700
  try {
22570
- value = new Function("return (" + expr + ")")();
22701
+ value = new Function("return (" + expr + "\n)")();
22571
22702
  } catch (err) {
22572
22703
  throw new Error(`${passageName}: Failed to evaluate "${sigil}${name} = ${expr}": ${errorMessage(err)}`);
22573
22704
  }
@@ -22813,7 +22944,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
22813
22944
  else if (token.type === "macro" && !token.isClose) {
22814
22945
  scanArgs(token, parametersOf, at, emit, options);
22815
22946
  scanSelectors(content, token, at, emit, options);
22816
- if (storeVarMacros.has(token.name.toLowerCase())) {
22947
+ if (storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name)) {
22817
22948
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
22818
22949
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
22819
22950
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
@@ -22829,7 +22960,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
22829
22960
  });
22830
22961
  } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
22831
22962
  }
22832
- if (token.name.toLowerCase() === "do") {
22963
+ if (token.name.toLowerCase() === "do" && !parametersOf.widget?.(token.name)) {
22833
22964
  let close = t + 1;
22834
22965
  while (close < tokens.length) {
22835
22966
  const c = tokens[close];
@@ -23162,11 +23293,168 @@ function appendSnapshot(container, snapshot) {
23162
23293
  }
23163
23294
  pendingScrolls.delete(snapshot);
23164
23295
  }
23165
- function copyComputedStyle(style, target) {
23296
+ function copyComputedStyle(style, target, ids) {
23166
23297
  for (let i = 0; i < style.length; i++) {
23167
23298
  const name = style[i];
23168
- target.setProperty(name, style.getPropertyValue(name));
23299
+ target.setProperty(name, snapshotUrls(style.getPropertyValue(name), ids), "important");
23300
+ }
23301
+ }
23302
+ var snapshotFragmentId = 0;
23303
+ /** SVG definitions need local targets without sharing IDs with live passages. */
23304
+ function snapshotIds(root) {
23305
+ const ids = /* @__PURE__ */ new Map();
23306
+ if (root instanceof Element && root.id) ids.set(root.id, "");
23307
+ for (const element of root.querySelectorAll("[id]")) ids.set(element.id, "");
23308
+ for (const original of ids.keys()) {
23309
+ let id;
23310
+ do
23311
+ id = `spindle-snapshot-${++snapshotFragmentId}`;
23312
+ while (ids.has(id) || document.getElementById(id));
23313
+ ids.set(original, id);
23169
23314
  }
23315
+ return ids;
23316
+ }
23317
+ /** Rewrite only fragments in this document; external SVG URLs stay external. */
23318
+ function snapshotFragment(value, ids) {
23319
+ try {
23320
+ const url = new URL(value, document.baseURI);
23321
+ const current = new URL(document.URL);
23322
+ if (url.href.split("#")[0] !== current.href.split("#")[0]) return value;
23323
+ let fragment = url.hash.slice(1);
23324
+ try {
23325
+ fragment = decodeURIComponent(fragment);
23326
+ } catch {}
23327
+ const id = ids.get(fragment);
23328
+ return id ? `#${id}` : value;
23329
+ } catch {
23330
+ return value;
23331
+ }
23332
+ }
23333
+ /** URL-valued presentation attributes, inline CSS and computed CSS alike. */
23334
+ function snapshotUrls(value, ids, base) {
23335
+ return value.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi, (match, double, single, bare) => {
23336
+ const original = double ?? single ?? bare;
23337
+ try {
23338
+ const rewritten = snapshotFragment(base ? new URL(original, base).href : original, ids);
23339
+ return original === rewritten ? match : `url("${rewritten}")`;
23340
+ } catch {
23341
+ return match;
23342
+ }
23343
+ });
23344
+ }
23345
+ /** Keep SVG's specified CSS: a use instance inherits from its use element,
23346
+ * rather than from the definition's original parent. Computed defaults on
23347
+ * definitions would replace that inheritance (and resolve currentColor).
23348
+ */
23349
+ var snapshotSvgRules = /* @__PURE__ */ new WeakSet();
23350
+ /** A detached style element has no sheet yet. Carry its CSSOM, including
23351
+ * script-inserted rules and imported styles, into the passive tree.
23352
+ */
23353
+ function copySnapshotSheet(source, ids, onOpaque) {
23354
+ const seen = /* @__PURE__ */ new Set();
23355
+ const textOf = (sheet) => {
23356
+ if (seen.has(sheet)) return "";
23357
+ seen.add(sheet);
23358
+ let rules;
23359
+ try {
23360
+ rules = [...sheet.cssRules];
23361
+ } catch {
23362
+ onOpaque?.();
23363
+ return "";
23364
+ }
23365
+ return rules.filter((rule) => !snapshotSvgRules.has(rule)).map((rule) => {
23366
+ if (rule instanceof CSSImportRule && rule.styleSheet) {
23367
+ let css = textOf(rule.styleSheet);
23368
+ if (rule.layerName !== null) css = `@layer ${rule.layerName}{${css}}`;
23369
+ if (rule.supportsText) css = `@supports (${rule.supportsText}){${css}}`;
23370
+ if (rule.media.mediaText) css = `@media ${rule.media.mediaText}{${css}}`;
23371
+ return css;
23372
+ }
23373
+ return snapshotUrls(rule.cssText, ids, sheet.href ?? document.baseURI);
23374
+ }).join("\n");
23375
+ };
23376
+ const copy = new CSSStyleSheet({
23377
+ media: source.media.mediaText,
23378
+ disabled: source.disabled
23379
+ });
23380
+ copy.replaceSync(textOf(source));
23381
+ return copy;
23382
+ }
23383
+ function installSnapshotSvgStyles(root, ids, marker, targetSheets = [...root.styleSheets, ...root.adoptedStyleSheets]) {
23384
+ if (!root.querySelector("svg")) return () => {};
23385
+ const customTags = new Set([...root instanceof ShadowRoot ? [root.host] : [], ...root.querySelectorAll("*")].filter((element) => element.localName.includes("-")).map((element) => element.localName));
23386
+ const identity = /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\[(?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\]"'\\])*\]|([#.])?((?:\\[0-9a-fA-F]{1,6}\s?|\\.|[\w-]|[^\x00-\x7f])+)/g;
23387
+ const selectorOf = (selector, scoped = true) => {
23388
+ const rewritten = selector.replace(identity, (written, sigil, escaped, at) => {
23389
+ if (!escaped) return written.replace(/^\[\s*id(?=[\s~|^$*=\]])/, "[data-spindle-snapshot-original-id");
23390
+ const name = escaped.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g, (_, hex, char) => hex ? String.fromCodePoint(parseInt(hex, 16)) : char);
23391
+ if (sigil === "." && name === "passage") return ":is(.passage,.passage-snapshot)";
23392
+ if (!sigil && customTags.has(name) && selector[at - 1] !== ":") return `:is(${CSS.escape(name)},:where([data-spindle-snapshot-tag="${name}"]))`;
23393
+ const id = sigil === "#" && ids.get(name);
23394
+ return id ? `:is(#${id},:where([data-spindle-snapshot-id="${id}"]))` : written;
23395
+ });
23396
+ if (!scoped) return rewritten;
23397
+ const selectors = [];
23398
+ let start = 0;
23399
+ let depth = 0;
23400
+ for (let i = 0; i <= rewritten.length; i++) {
23401
+ const ch = rewritten[i];
23402
+ if (ch === "\\") i++;
23403
+ else if (ch === "\"" || ch === "'") i = skipString(rewritten, i) - 1;
23404
+ else if (ch === "(" || ch === "[") depth++;
23405
+ else if (ch === ")" || ch === "]") depth--;
23406
+ else if (i === rewritten.length || ch === "," && depth === 0) {
23407
+ selectors.push(`:where([data-spindle-snapshot-svg="${marker}"]):is(${rewritten.slice(start, i)})`);
23408
+ start = i + 1;
23409
+ }
23410
+ }
23411
+ return selectors.join(",");
23412
+ };
23413
+ const rulesOf = (rules, base) => {
23414
+ const result = [];
23415
+ for (const rule of rules) if (rule instanceof CSSStyleRule) {
23416
+ const css = snapshotUrls(rule.style.cssText, ids, base);
23417
+ result.push(`${selectorOf(rule.selectorText)}{${css}}`);
23418
+ if (rule.cssRules.length) result.push(`${selectorOf(rule.selectorText, false)}{${rulesOf(rule.cssRules, base).join("\n")}}`);
23419
+ } else if ("cssRules" in rule && !(rule instanceof CSSKeyframesRule)) {
23420
+ const contents = rulesOf(rule.cssRules, base);
23421
+ result.push(`${rule.cssText.slice(0, rule.cssText.indexOf("{"))}{${contents.join("\n")}}`);
23422
+ }
23423
+ return result;
23424
+ };
23425
+ const inserted = [];
23426
+ const sheets = /* @__PURE__ */ new Set();
23427
+ const sheetRules = (sheet) => {
23428
+ if (sheets.has(sheet) || sheet.disabled || !matchMedia(sheet.media.mediaText || "all").matches) return;
23429
+ sheets.add(sheet);
23430
+ try {
23431
+ visit(sheet, sheet.href ?? document.baseURI);
23432
+ } catch {}
23433
+ };
23434
+ const visit = (parent, base) => {
23435
+ for (const rule of [...parent.cssRules]) {
23436
+ if (snapshotSvgRules.has(rule)) continue;
23437
+ if (rule instanceof CSSStyleRule) {
23438
+ let index = [...parent.cssRules].indexOf(rule) + 1;
23439
+ for (const css of rulesOf([rule], base)) {
23440
+ parent.insertRule(css, index);
23441
+ const insertedRule = parent.cssRules[index++];
23442
+ inserted.push([parent, insertedRule]);
23443
+ snapshotSvgRules.add(insertedRule);
23444
+ }
23445
+ } else if (rule instanceof CSSImportRule) {
23446
+ if (rule.styleSheet && matchMedia(rule.media.mediaText || "all").matches) sheetRules(rule.styleSheet);
23447
+ } else if ("cssRules" in rule && !(rule instanceof CSSKeyframesRule)) visit(rule, base);
23448
+ }
23449
+ };
23450
+ for (const sheet of targetSheets) sheetRules(sheet);
23451
+ return () => {
23452
+ for (const [parent, rule] of inserted) {
23453
+ const index = [...parent.cssRules].indexOf(rule);
23454
+ if (index >= 0) parent.deleteRule(index);
23455
+ snapshotSvgRules.delete(rule);
23456
+ }
23457
+ };
23170
23458
  }
23171
23459
  function installSnapshotStyles(root, rules) {
23172
23460
  if (!rules.length) return;
@@ -23185,44 +23473,67 @@ var snapshotPseudoId = 0;
23185
23473
  * as ordinary native elements, without an `is` option (even if the original
23186
23474
  * has since removed its `is` attribute).
23187
23475
  */
23188
- function cloneSnapshotTree(source, freezeStyles = false, pseudoRules = []) {
23189
- const custom = source.namespaceURI === "http://www.w3.org/1999/xhtml" && source.localName.includes("-");
23190
- freezeStyles ||= custom || source.hasAttribute("is");
23476
+ function cloneSnapshotTree(source, ids, pseudoRules = [], svgMarker = String(++snapshotPseudoId), cleanups = []) {
23477
+ const html = source.namespaceURI === "http://www.w3.org/1999/xhtml";
23478
+ const svg = source.namespaceURI === "http://www.w3.org/2000/svg";
23479
+ const custom = html && source.localName.includes("-");
23191
23480
  const clone = document.createElementNS(source.namespaceURI, custom ? "span" : source.localName);
23192
23481
  for (const attr of [...source.attributes]) {
23193
23482
  if (attr.name === "id" || attr.name === "data-action" || attr.name === "is" || attr.name.toLowerCase().startsWith("on")) continue;
23194
- if (attr.namespaceURI) clone.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
23195
- else clone.setAttribute(attr.name, attr.value);
23196
- }
23197
- if (freezeStyles) {
23198
- copyComputedStyle(getComputedStyle(source), clone.style);
23199
- let id;
23200
- for (const pseudo of [
23201
- "::before",
23202
- "::after",
23203
- "::marker"
23204
- ]) {
23205
- const style = getComputedStyle(source, pseudo);
23206
- if (!style.content || ["none", "normal"].includes(style.content)) continue;
23207
- id ??= String(++snapshotPseudoId);
23208
- clone.setAttribute("data-spindle-snapshot-pseudo", id);
23209
- const target = document.createElement("span").style;
23210
- copyComputedStyle(style, target);
23211
- pseudoRules.push(`[data-spindle-snapshot-pseudo="${id}"]${pseudo}{${target.cssText}}`);
23212
- }
23483
+ const value = svg && attr.localName === "href" ? snapshotFragment(attr.value, ids) : svg || attr.localName === "style" ? snapshotUrls(attr.value, ids) : attr.value;
23484
+ if (attr.namespaceURI) clone.setAttributeNS(attr.namespaceURI, attr.name, value);
23485
+ else clone.setAttribute(attr.name, value);
23486
+ }
23487
+ if (svg && source.id) clone.id = ids.get(source.id);
23488
+ if (source.id) clone.setAttribute("data-spindle-snapshot-id", ids.get(source.id));
23489
+ if (source.id) clone.setAttribute("data-spindle-snapshot-original-id", source.id);
23490
+ if (custom) clone.setAttribute("data-spindle-snapshot-tag", source.localName);
23491
+ if (svg) clone.setAttribute("data-spindle-snapshot-svg", svgMarker);
23492
+ const computed = getComputedStyle(source);
23493
+ if (!svg) copyComputedStyle(computed, clone.style, ids);
23494
+ let pseudoId;
23495
+ for (const pseudo of [
23496
+ "::before",
23497
+ "::after",
23498
+ "::marker"
23499
+ ]) {
23500
+ const style = getComputedStyle(source, pseudo);
23501
+ if (!(pseudo === "::marker" && computed.display === "list-item") && (!style.content || ["none", "normal"].includes(style.content))) continue;
23502
+ pseudoId ??= String(++snapshotPseudoId);
23503
+ clone.setAttribute("data-spindle-snapshot-pseudo", pseudoId);
23504
+ const target = document.createElement("span").style;
23505
+ copyComputedStyle(style, target, ids);
23506
+ pseudoRules.push(`[data-spindle-snapshot-pseudo="${pseudoId}"]${pseudo}{${target.cssText}}`);
23213
23507
  }
23214
23508
  if (source.localName === "script") clone.setAttribute("type", "application/x-spindle-snapshot");
23215
23509
  const from = source instanceof HTMLTemplateElement ? source.content : source;
23216
23510
  const to = clone instanceof HTMLTemplateElement ? clone.content : clone;
23217
- const copyChildren = (from, to, rules = pseudoRules) => {
23218
- for (const node of from.childNodes) to.appendChild(node instanceof Element ? cloneSnapshotTree(node, freezeStyles, rules) : node.cloneNode(false));
23511
+ const copyChildren = (from, to, rules = pseudoRules, localIds = ids) => {
23512
+ for (const node of from.childNodes) to.appendChild(node instanceof Element ? cloneSnapshotTree(node, localIds, rules, svgMarker, cleanups) : node.cloneNode(false));
23219
23513
  };
23220
- copyChildren(from, to);
23514
+ copyChildren(from, to, pseudoRules, source instanceof HTMLTemplateElement ? snapshotIds(from) : ids);
23515
+ if (source instanceof HTMLStyleElement && source.sheet) {
23516
+ const root = source.getRootNode();
23517
+ if (root.querySelector("svg")) {
23518
+ let opaque = false;
23519
+ const copy = copySnapshotSheet(source.sheet, ids, () => {
23520
+ opaque = true;
23521
+ });
23522
+ const sheet = opaque ? source.sheet : copy;
23523
+ const dispose = installSnapshotSvgStyles(root, ids, svgMarker, [sheet]);
23524
+ clone.textContent = snapshotUrls([...sheet.cssRules].map((rule) => rule.cssText).join("\n"), ids, source.sheet.href ?? document.baseURI);
23525
+ dispose();
23526
+ if (source.sheet.disabled) clone.setAttribute("media", "not all");
23527
+ }
23528
+ }
23221
23529
  if (source.shadowRoot) {
23222
23530
  const shadow = clone.attachShadow({ mode: "open" });
23223
23531
  const rules = [];
23224
- copyChildren(source.shadowRoot, shadow, rules);
23532
+ const shadowIds = snapshotIds(source.shadowRoot);
23533
+ copyChildren(source.shadowRoot, shadow, rules, shadowIds);
23534
+ shadow.adoptedStyleSheets = source.shadowRoot.adoptedStyleSheets.map((sheet) => copySnapshotSheet(sheet, shadowIds));
23225
23535
  copyLiveState(source.shadowRoot, shadow);
23536
+ cleanups.push(installSnapshotSvgStyles(source.shadowRoot, shadowIds, svgMarker, shadow.adoptedStyleSheets));
23226
23537
  installSnapshotStyles(shadow, rules);
23227
23538
  }
23228
23539
  return clone;
@@ -23247,15 +23558,18 @@ function replaceEmbeddedContexts(source, clone) {
23247
23558
  }
23248
23559
  const rect = original.getBoundingClientRect();
23249
23560
  if (getComputedStyle(original).display === "inline") placeholder.style.display = "inline-block";
23250
- placeholder.style.boxSizing = "border-box";
23251
- placeholder.style.width = `${rect.width}px`;
23252
- placeholder.style.height = `${rect.height}px`;
23561
+ placeholder.style.removeProperty("inline-size");
23562
+ placeholder.style.removeProperty("block-size");
23563
+ placeholder.style.setProperty("box-sizing", "border-box", "important");
23564
+ placeholder.style.setProperty("width", `${rect.width}px`, "important");
23565
+ placeholder.style.setProperty("height", `${rect.height}px`, "important");
23253
23566
  embedded.replaceWith(placeholder);
23254
23567
  });
23255
23568
  }
23256
23569
  /**
23257
23570
  * Create a snapshot clone of a .passage element for outgoing transitions.
23258
- * - Strips IDs, action associations and event handlers from the clone tree
23571
+ * - Strips authored IDs, action associations and event handlers; SVG IDs and
23572
+ * their fragment references receive snapshot-local names
23259
23573
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
23260
23574
  * - Pauses/mutes any <audio>/<video>
23261
23575
  * - Copies what cloneNode leaves behind: canvas pixels, the state of form
@@ -23265,12 +23579,21 @@ function replaceEmbeddedContexts(source, clone) {
23265
23579
  */
23266
23580
  function createSnapshot(passageEl, transitionType) {
23267
23581
  const pseudoRules = [];
23268
- const clone = cloneSnapshotTree(passageEl, false, pseudoRules);
23582
+ const cleanups = [];
23583
+ const ids = snapshotIds(passageEl);
23584
+ const svgMarker = String(++snapshotPseudoId);
23585
+ const clone = cloneSnapshotTree(passageEl, ids, pseudoRules, svgMarker, cleanups);
23586
+ clone.style.removeProperty("animation");
23587
+ clone.style.removeProperty("grid-area");
23588
+ for (const name of ["opacity", "transform"]) clone.style.setProperty(name, clone.style.getPropertyValue(name));
23269
23589
  copyLiveState(passageEl, clone);
23270
23590
  pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
23271
23591
  replaceEmbeddedContexts(passageEl, clone);
23272
- const cleanup = installSnapshotStyles(passageEl.getRootNode(), pseudoRules);
23273
- if (cleanup) snapshotStyleCleanup.set(clone, cleanup);
23592
+ const root = passageEl.getRootNode();
23593
+ cleanups.push(installSnapshotSvgStyles(root, ids, svgMarker));
23594
+ const cleanup = installSnapshotStyles(root, pseudoRules);
23595
+ if (cleanup) cleanups.push(cleanup);
23596
+ snapshotStyleCleanup.set(clone, () => cleanups.forEach((dispose) => dispose()));
23274
23597
  clone.style.pointerEvents = "none";
23275
23598
  clone.style.userSelect = "none";
23276
23599
  clone.setAttribute("inert", "");
@@ -25473,8 +25796,15 @@ function orStop(parse, where = "") {
25473
25796
  * the declared parameters of macros and what the parameters of widgets hold.
25474
25797
  * (The markup and the variable references are read by the same.)
25475
25798
  */
25476
- function knownParameters() {
25477
- return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
25799
+ function knownParameters(declared = []) {
25800
+ return parameterLookup([
25801
+ ...getMacroRegistry(),
25802
+ ...declared.map((widget) => ({
25803
+ name: widget.name,
25804
+ widget
25805
+ })),
25806
+ ...widgetMacros()
25807
+ ]);
25478
25808
  }
25479
25809
  /** The names of the registered macros that bind a variable (the inputs). */
25480
25810
  function storeVarMacroNames() {
@@ -25485,19 +25815,19 @@ function storeVarMacroNames() {
25485
25815
  * the input macros that bind a variable (registered by author JS or
25486
25816
  * StoryInit) and the roles of their parameters decide what is a reference.
25487
25817
  */
25488
- function variableErrors(storyData, schema, only = () => true) {
25489
- return validatePassages(new Map([...storyData.passages].filter(([, passage]) => only(passage))), schema, storeVarMacroNames(), knownParameters());
25818
+ function variableErrors(storyData, schema, only = () => true, parametersOf = knownParameters()) {
25819
+ return validatePassages(new Map([...storyData.passages].filter(([, passage]) => only(passage))), schema, storeVarMacroNames(), parametersOf);
25490
25820
  }
25491
25821
  /**
25492
25822
  * The markup errors (malformed markup, unknown macros, syntax errors in
25493
25823
  * code) of the passages for which `only` holds, with the macros and widgets
25494
25824
  * known now.
25495
25825
  */
25496
- function markupErrors(storyData, only) {
25826
+ function markupErrors(storyData, only, parametersOf = knownParameters()) {
25497
25827
  return validateMarkup(storyData.passages.values(), {
25498
25828
  isKnownMacro: (name) => !!getMacro(name) || isSubMacro(name) || !!getWidget(name),
25499
25829
  macroNames: getMacroRegistry().map((m) => m.name),
25500
- parametersOf: knownParameters(),
25830
+ parametersOf,
25501
25831
  only
25502
25832
  }).map(formatDiagnostic);
25503
25833
  }
@@ -25536,9 +25866,11 @@ function boot() {
25536
25866
  throw new Error(`spindle: ${msg}`);
25537
25867
  }
25538
25868
  const schema = orStop(() => parseStoryVariables(storyVarsPassage.content));
25539
- for (const { name, block } of orStop(() => effectiveWidgets(storyData.passages.values()))) setBlockWidget(name, block);
25540
- const errors = variableErrors(storyData, schema, (p) => p.name === "StoryInit");
25541
- errors.push(...markupErrors(storyData, (p) => p.name === "StoryInit"));
25869
+ const widgets = orStop(() => effectiveWidgets(storyData.passages.values()));
25870
+ for (const { name, block } of widgets) setBlockWidget(name, block);
25871
+ const startupParameters = knownParameters(widgets);
25872
+ const errors = variableErrors(storyData, schema, (p) => p.name === "StoryInit", startupParameters);
25873
+ errors.push(...markupErrors(storyData, (p) => p.name === "StoryInit", startupParameters));
25542
25874
  let transientDefaults = {};
25543
25875
  const storyTransientsPassage = storyData.passages.get("StoryTransients");
25544
25876
  if (storyTransientsPassage) {