@rohal12/spindle 0.61.7 → 0.62.1

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.
@@ -9656,34 +9656,6 @@ function parse$1(input, options) {
9656
9656
  }
9657
9657
  //#endregion
9658
9658
  //#region src/js-lexer.ts
9659
- /**
9660
- * The JavaScript in story markup, read with acorn.
9661
- *
9662
- * acorn reads the code: where string, template and regex literals and
9663
- * comments begin and end, whether `/` opens a regex, and (`parseCode`) the
9664
- * syntax tree. A plugin (`SigilParser`) teaches its tokenizer the two sigils
9665
- * that are no JavaScript: `@name` (locals) anywhere, and `%name`
9666
- * (transients) where an operand is expected, the same place acorn reads `/`
9667
- * as a regex; `%` elsewhere is the modulo operator. `$name` and `_name` are
9668
- * identifiers already; the syntax tree tells references from property names
9669
- * and declarations.
9670
- *
9671
- * - `parseCode`: the references and string text of well-formed code, or a
9672
- * `CodeSyntaxError` that says what is wrong and where. The expression
9673
- * engine (`expression.ts`) rewrites the references it finds, and the
9674
- * story-start check (`markup/validate.ts`) reports the errors.
9675
- * - `findCodeEnd`: where the code in a `{…}` ends, for the markup grammar
9676
- * (`markup/code-end.ts`). -1 when acorn can't read it: the grammar then
9677
- * scans it leniently, as prose-like macro arguments (`{link Don't go}`)
9678
- * need.
9679
- * - `lexJs`: a lenient token walk for the macro argument splitters
9680
- * (`components/macros/arg-utils.ts`), which also read text that is no
9681
- * JavaScript.
9682
- *
9683
- * Restrictions (docs/variables.md "Code in passages"): sigil variables can't
9684
- * be declared (`let _x`, `(_a) => …`) or be property names (`a.@x`), and
9685
- * code must be valid modern JavaScript (a non-strict script).
9686
- */
9687
9659
  /** Code runs through `new Function`: a non-strict script body. */
9688
9660
  var OPTIONS = {
9689
9661
  ecmaVersion: "latest",
@@ -10077,13 +10049,13 @@ function propertyName(node, src) {
10077
10049
  * identifiers here are declared (a `let`, a parameter), where a sigil
10078
10050
  * variable can't be. `shorthand`: the node is a shorthand property's value.
10079
10051
  */
10080
- function walk(node, src, out, binding, shorthand) {
10052
+ function walk(node, src, out, binding, shorthand, access = "read") {
10081
10053
  if (Array.isArray(node)) {
10082
- for (const n of node) walk(n, src, out, binding, false);
10054
+ for (const n of node) walk(n, src, out, binding, false, access);
10083
10055
  return;
10084
10056
  }
10085
10057
  if (!isNode(node)) return;
10086
- const sub = (child, bind = false, short = false) => walk(child, src, out, bind, short);
10058
+ const sub = (child, bind = false, short = false, role = "read") => walk(child, src, out, bind, short, role);
10087
10059
  switch (node.type) {
10088
10060
  case "Identifier": {
10089
10061
  const sigil = sigilOf(node, src);
@@ -10094,7 +10066,9 @@ function walk(node, src, out, binding, shorthand) {
10094
10066
  name: sigil[1],
10095
10067
  start: node.start,
10096
10068
  end: node.end,
10097
- shorthand
10069
+ shorthand,
10070
+ read: access !== "write",
10071
+ write: access !== "read"
10098
10072
  });
10099
10073
  return;
10100
10074
  }
@@ -10115,10 +10089,10 @@ function walk(node, src, out, binding, shorthand) {
10115
10089
  if (node.shorthand) {
10116
10090
  const value = node.value;
10117
10091
  if (value.type === "AssignmentPattern") {
10118
- sub(value.left, binding, true);
10092
+ sub(value.left, binding, true, access);
10119
10093
  sub(value.right);
10120
- } else sub(value, binding, true);
10121
- } else sub(node.value, binding);
10094
+ } else sub(value, binding, true, access);
10095
+ } else sub(node.value, binding, false, access);
10122
10096
  return;
10123
10097
  case "MethodDefinition":
10124
10098
  case "PropertyDefinition":
@@ -10154,8 +10128,24 @@ function walk(node, src, out, binding, shorthand) {
10154
10128
  sub(node.param, true);
10155
10129
  sub(node.body);
10156
10130
  return;
10131
+ case "AssignmentExpression":
10132
+ sub(node.left, false, false, node.operator === "=" ? "write" : "readwrite");
10133
+ sub(node.right);
10134
+ return;
10135
+ case "UnaryExpression":
10136
+ sub(node.argument, false, false, node.operator === "delete" ? "write" : "read");
10137
+ return;
10138
+ case "UpdateExpression":
10139
+ sub(node.argument, false, false, "readwrite");
10140
+ return;
10141
+ case "ForInStatement":
10142
+ case "ForOfStatement":
10143
+ sub(node.left, false, false, "write");
10144
+ sub(node.right);
10145
+ sub(node.body);
10146
+ return;
10157
10147
  case "AssignmentPattern":
10158
- sub(node.left, binding);
10148
+ sub(node.left, binding, false, access);
10159
10149
  sub(node.right);
10160
10150
  return;
10161
10151
  case "ObjectPattern":
@@ -10165,7 +10155,7 @@ function walk(node, src, out, binding, shorthand) {
10165
10155
  "properties",
10166
10156
  "elements",
10167
10157
  "argument"
10168
- ]) sub(node[key], binding);
10158
+ ]) sub(node[key], binding, false, access);
10169
10159
  return;
10170
10160
  default: for (const key in node) {
10171
10161
  if (key === "type" || key === "start" || key === "end") continue;
@@ -10371,6 +10361,14 @@ function* tokens(src, start, goal, options = {}) {
10371
10361
  function lexJs(src, handlers, goal = "expression") {
10372
10362
  return walkTokens(src, 0, handlers, 0, goal, false);
10373
10363
  }
10364
+ /**
10365
+ * Lex the template literal opening at `start` (a backtick) as `lexJs` does,
10366
+ * its interpolations one nesting level deeper. Returns the index just past
10367
+ * its closing backtick, or `src.length` if it is unterminated.
10368
+ */
10369
+ function lexTemplate(src, start, handlers = {}, nesting = 0) {
10370
+ return walkTokens(src, start, handlers, nesting, "expression", true);
10371
+ }
10374
10372
  function walkTokens(src, from, handlers, nesting, goal, oneTemplate) {
10375
10373
  const comments = [];
10376
10374
  const onComment = (_block, _text, s, e) => {
@@ -11150,6 +11148,17 @@ function isCloser(ch) {
11150
11148
  return ch === ")" || ch === "]" || ch === "}";
11151
11149
  }
11152
11150
  /**
11151
+ * Given the index of an opening quote (`"`, `'` or a backtick), return the
11152
+ * index just past its closing quote, or `src.length` if it is unterminated.
11153
+ * A backslash escapes the character after it, so a quote preceded by an even
11154
+ * run of backslashes still closes the string and one preceded by an odd run
11155
+ * does not. Inside a template literal, `${…}` interpolations are lexed as
11156
+ * code, so quotes, backticks, braces and regexes inside them do not end it.
11157
+ */
11158
+ function skipString(src, start) {
11159
+ return src[start] === "`" ? lexTemplate(src, start) : scanStringLiteral(src, start).end;
11160
+ }
11161
+ /**
11153
11162
  * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
11154
11163
  * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
11155
11164
  * are kept as written, so code and regex text inside the string survive.
@@ -11161,14 +11170,15 @@ function unescapeQuoted(body) {
11161
11170
  * Read the `"…"` or `'…'` string whose opening quote is at `start`.
11162
11171
  * Returns its unescaped value and the index just past the closing quote, or
11163
11172
  * `null` if there is no such quote at `start` or the string is unterminated.
11173
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
11164
11174
  */
11165
- function readQuoted(src, start) {
11175
+ function readQuoted(src, start, tolerant = false) {
11166
11176
  const quote = src[start];
11167
11177
  if (quote !== "\"" && quote !== "'") return null;
11168
11178
  const { end, closed } = scanStringLiteral(src, start);
11169
- if (!closed) return null;
11179
+ if (!closed && !tolerant) return null;
11170
11180
  return {
11171
- value: unescapeQuoted(src.slice(start + 1, end - 1)),
11181
+ value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
11172
11182
  end
11173
11183
  };
11174
11184
  }
@@ -11355,11 +11365,16 @@ var MacroArgumentError = class extends Error {
11355
11365
  };
11356
11366
  /** Read `src`, at `place`, as `param` says. */
11357
11367
  function readValue(param, src, place) {
11358
- place.spans?.set(param, [place.at, place.at + src.length]);
11368
+ const span = [place.at, place.at + src.length];
11369
+ place.spans?.set(param, span);
11370
+ place.toolingSpans?.set(param, span);
11359
11371
  switch (param.type) {
11360
11372
  case "string": {
11361
11373
  const value = readWholeQuoted(src);
11362
- if (value === null) throw new MacroArgumentError(param, src);
11374
+ if (value === null) {
11375
+ if (place.toolingSpans && (src[0] === "\"" || src[0] === "'")) return readText(src);
11376
+ throw new MacroArgumentError(param, src);
11377
+ }
11363
11378
  return value;
11364
11379
  }
11365
11380
  case "text": return readText(src);
@@ -11390,20 +11405,21 @@ function matchAt(re, src, pos) {
11390
11405
  * skipped. A keyword of a `string` parameter must be followed by a quoted
11391
11406
  * string.
11392
11407
  */
11393
- function readOptions(params, src, { at, spans }) {
11408
+ function readOptions(params, src, { at, spans, toolingSpans }) {
11394
11409
  const options = {};
11395
11410
  let i = 0;
11396
11411
  while (i < src.length) {
11397
11412
  const key = matchAt(WORD_RE, src, i);
11398
11413
  if (!key) {
11399
- i = readQuoted(src, i)?.end ?? i + 1;
11414
+ i = readQuoted(src, i, !!toolingSpans)?.end ?? i + 1;
11400
11415
  continue;
11401
11416
  }
11417
+ const keyAt = i;
11402
11418
  i += key.length;
11403
11419
  let val;
11404
11420
  let j = i;
11405
11421
  while (j < src.length && isWhitespace(src[j])) j++;
11406
- const quoted = readQuoted(src, j);
11422
+ const quoted = readQuoted(src, j, !!toolingSpans);
11407
11423
  const digits = quoted || j === i ? null : matchAt(NUMBER_RE$1, src, j);
11408
11424
  if (quoted) {
11409
11425
  val = quoted.value;
@@ -11414,7 +11430,8 @@ function readOptions(params, src, { at, spans }) {
11414
11430
  }
11415
11431
  const param = params.find((p) => p.name === key);
11416
11432
  if (param && param.type !== "flag" && val !== void 0) spans?.set(param, [at + j, at + i]);
11417
- if (param?.type === "string" && !quoted) throw new MacroArgumentError(param, matchAt(WORD_OR_PUNCT_RE, src, j) ?? "");
11433
+ if (param) toolingSpans?.set(param, [at + keyAt, at + i]);
11434
+ if (param?.type === "string" && !quoted && !toolingSpans) throw new MacroArgumentError(param, matchAt(WORD_OR_PUNCT_RE, src, j) ?? "");
11418
11435
  if (param?.type === "flag") options[key] = true;
11419
11436
  else if (param?.type === "number") options[key] = Number(val ?? 0);
11420
11437
  else if (param) options[key] = val;
@@ -11450,7 +11467,7 @@ function takeFlag(src, word, alone) {
11450
11467
  * term with terms on both sides; `=` is an assignment at depth 0, not part
11451
11468
  * of `==` or `!=`.
11452
11469
  */
11453
- function findSeparator(src, word) {
11470
+ function findSeparator(src, word, tolerant = false) {
11454
11471
  if (word === "=") {
11455
11472
  const indices = topLevelIndices(src, (ch) => ch === "=");
11456
11473
  for (let k = 0; k < indices.length; k++) {
@@ -11464,7 +11481,7 @@ function findSeparator(src, word) {
11464
11481
  return null;
11465
11482
  }
11466
11483
  const spans = terms(src);
11467
- for (let k = 1; k < spans.length - 1; k++) if (slice(src, spans[k]) === word) return [spans[k - 1][1], spans[k + 1][0]];
11484
+ for (let k = 1; k < spans.length - (tolerant ? 0 : 1); k++) if (slice(src, spans[k]) === word) return [spans[k - 1][1], spans[k + 1]?.[0] ?? src.length];
11468
11485
  return null;
11469
11486
  }
11470
11487
  var takesRest = (param) => param.type === "expression" || param.type === "statements" || param.type === "passage" || param.type === "text";
@@ -11477,23 +11494,36 @@ function trimmed(src, at) {
11477
11494
  * Read the parameters of one group from `src` (`null`: no text), which is
11478
11495
  * at `at` in the raw arguments, into `args`.
11479
11496
  */
11480
- function readGroup(params, src, args, { at: srcAt, spans }) {
11497
+ function readGroup(params, src, args, { at: srcAt, spans, toolingSpans }) {
11481
11498
  let [text, at] = trimmed(src ?? "", srcAt);
11482
11499
  const alone = !params.some((p) => p.type !== "flag" && p.required);
11483
11500
  for (const flag of params.filter((p) => p.type === "flag")) {
11484
11501
  const rest = src === null ? null : takeFlag(text, flag.name, alone);
11485
11502
  args[flag.name] = rest !== null;
11486
- if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
11503
+ if (rest) {
11504
+ const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
11505
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
11506
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
11507
+ }
11487
11508
  }
11488
11509
  const positional = params.filter((p) => p.type !== "flag");
11489
11510
  if (positional.length === 0) return;
11490
11511
  const lastText = positional.findIndex((p, i) => takesRest(p) && !positional.slice(i + 1).some(takesRest));
11491
11512
  const restIndex = lastText < 0 ? positional.length - 1 : lastText;
11492
11513
  /** Read `param` from the text from `start` to `end`. */
11493
- const read = (param, [start, end]) => start === end ? unset(param) : readValue(param, text.slice(start, end), {
11494
- at: at + start,
11495
- spans
11496
- });
11514
+ const read = (param, [start, end], tolerant = true) => {
11515
+ if (start === end) return unset(param);
11516
+ try {
11517
+ return readValue(param, text.slice(start, end), {
11518
+ at: at + start,
11519
+ spans,
11520
+ toolingSpans
11521
+ });
11522
+ } catch (error) {
11523
+ if (toolingSpans && tolerant && error instanceof MacroArgumentError) return;
11524
+ throw error;
11525
+ }
11526
+ };
11497
11527
  if (positional.length === 1) {
11498
11528
  args[positional[0].name] = read(positional[0], [0, text.length]);
11499
11529
  return;
@@ -11504,7 +11534,7 @@ function readGroup(params, src, args, { at: srcAt, spans }) {
11504
11534
  for (const param of positional.slice(0, restIndex)) args[param.name] = from < to ? read(param, parts[from++]) : unset(param);
11505
11535
  const readTrailing = (param, span) => {
11506
11536
  try {
11507
- return read(param, span);
11537
+ return read(param, span, false);
11508
11538
  } catch (error) {
11509
11539
  if (error instanceof MacroArgumentError) return void 0;
11510
11540
  throw error;
@@ -11514,7 +11544,10 @@ function readGroup(params, src, args, { at: srcAt, spans }) {
11514
11544
  const value = from < to && !endsWithOperator(text.slice(0, parts[to - 1][0])) ? readTrailing(param, parts[to - 1]) : void 0;
11515
11545
  args[param.name] = value ?? unset(param);
11516
11546
  if (value !== void 0) to--;
11517
- else spans?.delete(param);
11547
+ else {
11548
+ spans?.delete(param);
11549
+ toolingSpans?.delete(param);
11550
+ }
11518
11551
  }
11519
11552
  const rest = positional[restIndex];
11520
11553
  args[rest.name] = from < to ? read(rest, [parts[from][0], parts[to - 1][1]]) : unset(rest);
@@ -11529,18 +11562,23 @@ var DELAY_PARAMETER = {
11529
11562
  * Read `rawArgs` into the declared `parameters` (see above). With `spans`,
11530
11563
  * note there where each argument set was read.
11531
11564
  */
11532
- function parseMacroArgs(rawArgs, parameters, spans) {
11565
+ function parseMacroArgs(rawArgs, parameters, spans, toolingSpans) {
11533
11566
  const args = {};
11534
11567
  let [rest, restAt] = trimmed(rawArgs, 0);
11535
11568
  let groupStart = 0;
11536
11569
  parameters.forEach((separator, i) => {
11537
11570
  if (separator.type !== "separator") return;
11538
- const at = rest === null ? null : findSeparator(rest, separator.name);
11571
+ const at = rest === null ? null : findSeparator(rest, separator.name, !!toolingSpans);
11539
11572
  args[separator.name] = at !== null;
11573
+ if (at && toolingSpans) {
11574
+ const start = restAt + at[0] + rest.slice(at[0], at[1]).indexOf(separator.name);
11575
+ toolingSpans.set(separator, [start, start + separator.name.length]);
11576
+ }
11540
11577
  const before = at ? rest.slice(0, at[0]) : rest;
11541
11578
  readGroup(parameters.slice(groupStart, i), before, args, {
11542
11579
  at: restAt,
11543
- spans
11580
+ spans,
11581
+ toolingSpans
11544
11582
  });
11545
11583
  rest = at ? rest.slice(at[1]) : null;
11546
11584
  if (at) restAt += at[1];
@@ -11548,7 +11586,8 @@ function parseMacroArgs(rawArgs, parameters, spans) {
11548
11586
  });
11549
11587
  readGroup(parameters.slice(groupStart), rest, args, {
11550
11588
  at: restAt,
11551
- spans
11589
+ spans,
11590
+ toolingSpans
11552
11591
  });
11553
11592
  return args;
11554
11593
  }
@@ -11718,10 +11757,10 @@ function parameterLookup(macros) {
11718
11757
  const widgets = new NameMap();
11719
11758
  for (const { name, parameters: params, interpolate, widget } of macros) {
11720
11759
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11721
- const declared = widget && widgetParameters(widget.params, widget.holds);
11722
- if (declared) widgets.set(name, declared);
11760
+ if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11723
11761
  }
11724
11762
  const lookup = (name) => {
11763
+ if (widgets.has(name)) return void 0;
11725
11764
  let params = parameters.get(name);
11726
11765
  if (!params) {
11727
11766
  const sub = subMacroParameters(name);
@@ -11794,7 +11833,8 @@ function* codeAndText(src, tokens, parametersOf) {
11794
11833
  }
11795
11834
  else if (token.type === "macro" && !token.isClose) {
11796
11835
  const name = token.name.toLowerCase();
11797
- if (name === "do") {
11836
+ const widget = parametersOf.widget?.(name);
11837
+ if (name === "do" && !widget) {
11798
11838
  const close = closeOfTextBody(t, name);
11799
11839
  if (close < 0) continue;
11800
11840
  yield {
@@ -11808,7 +11848,7 @@ function* codeAndText(src, tokens, parametersOf) {
11808
11848
  continue;
11809
11849
  }
11810
11850
  const args = token.rawArgs;
11811
- if (PASSAGE_BODIES.has(name)) {
11851
+ if (PASSAGE_BODIES.has(name) && !widget) {
11812
11852
  const close = closeOfTextBody(t, name);
11813
11853
  if (close > t + 1) {
11814
11854
  const text = src.slice(token.end, tokens[close].start);
@@ -11826,7 +11866,7 @@ function* codeAndText(src, tokens, parametersOf) {
11826
11866
  if (!args) continue;
11827
11867
  const label = `{${token.name} ${args}}`;
11828
11868
  const argsAt = token.argsStart;
11829
- if (CONDITION_MACROS.has(name)) {
11869
+ if (CONDITION_MACROS.has(name) && !widget) {
11830
11870
  yield {
11831
11871
  kind: "code",
11832
11872
  code: args,
@@ -11838,7 +11878,6 @@ function* codeAndText(src, tokens, parametersOf) {
11838
11878
  }
11839
11879
  const params = parametersOf(name);
11840
11880
  if (params) yield* argPieces(args, argsAt, params, token.name, label);
11841
- const widget = parametersOf.widget?.(name);
11842
11881
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
11843
11882
  }
11844
11883
  }
@@ -22438,7 +22477,7 @@ function shapeSchema(shape) {
22438
22477
  function initializerSyntaxError(expr) {
22439
22478
  const prefix = "return (";
22440
22479
  try {
22441
- parse$1(prefix + expr + ")", {
22480
+ parse$1(prefix + expr + "\n)", {
22442
22481
  ecmaVersion: "latest",
22443
22482
  allowReturnOutsideFunction: true
22444
22483
  });
@@ -22547,7 +22586,7 @@ function parseStoryVariables(content, sigil = "$") {
22547
22586
  const expr = content.slice(valueStart, valueEnd);
22548
22587
  let value;
22549
22588
  try {
22550
- value = new Function("return (" + expr + ")")();
22589
+ value = new Function("return (" + expr + "\n)")();
22551
22590
  } catch (err) {
22552
22591
  throw new Error(`${passageName}: Failed to evaluate "${sigil}${name} = ${expr}": ${errorMessage(err)}`);
22553
22592
  }
@@ -22793,7 +22832,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
22793
22832
  else if (token.type === "macro" && !token.isClose) {
22794
22833
  scanArgs(token, parametersOf, at, emit, options);
22795
22834
  scanSelectors(content, token, at, emit, options);
22796
- if (storeVarMacros.has(token.name.toLowerCase())) {
22835
+ if (storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name)) {
22797
22836
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
22798
22837
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
22799
22838
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
@@ -22809,7 +22848,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
22809
22848
  });
22810
22849
  } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
22811
22850
  }
22812
- if (token.name.toLowerCase() === "do") {
22851
+ if (token.name.toLowerCase() === "do" && !parametersOf.widget?.(token.name)) {
22813
22852
  let close = t + 1;
22814
22853
  while (close < tokens.length) {
22815
22854
  const c = tokens[close];
@@ -23142,12 +23181,169 @@ function appendSnapshot(container, snapshot) {
23142
23181
  }
23143
23182
  pendingScrolls.delete(snapshot);
23144
23183
  }
23145
- function copyComputedStyle(style, target) {
23184
+ function copyComputedStyle(style, target, ids) {
23146
23185
  for (let i = 0; i < style.length; i++) {
23147
23186
  const name = style[i];
23148
- target.setProperty(name, style.getPropertyValue(name));
23187
+ target.setProperty(name, snapshotUrls(style.getPropertyValue(name), ids), "important");
23188
+ }
23189
+ }
23190
+ var snapshotFragmentId = 0;
23191
+ /** SVG definitions need local targets without sharing IDs with live passages. */
23192
+ function snapshotIds(root) {
23193
+ const ids = /* @__PURE__ */ new Map();
23194
+ if (root instanceof Element && root.id) ids.set(root.id, "");
23195
+ for (const element of root.querySelectorAll("[id]")) ids.set(element.id, "");
23196
+ for (const original of ids.keys()) {
23197
+ let id;
23198
+ do
23199
+ id = `spindle-snapshot-${++snapshotFragmentId}`;
23200
+ while (ids.has(id) || document.getElementById(id));
23201
+ ids.set(original, id);
23202
+ }
23203
+ return ids;
23204
+ }
23205
+ /** Rewrite only fragments in this document; external SVG URLs stay external. */
23206
+ function snapshotFragment(value, ids) {
23207
+ try {
23208
+ const url = new URL(value, document.baseURI);
23209
+ const current = new URL(document.URL);
23210
+ if (url.href.split("#")[0] !== current.href.split("#")[0]) return value;
23211
+ let fragment = url.hash.slice(1);
23212
+ try {
23213
+ fragment = decodeURIComponent(fragment);
23214
+ } catch {}
23215
+ const id = ids.get(fragment);
23216
+ return id ? `#${id}` : value;
23217
+ } catch {
23218
+ return value;
23149
23219
  }
23150
23220
  }
23221
+ /** URL-valued presentation attributes, inline CSS and computed CSS alike. */
23222
+ function snapshotUrls(value, ids, base) {
23223
+ return value.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi, (match, double, single, bare) => {
23224
+ const original = double ?? single ?? bare;
23225
+ try {
23226
+ const rewritten = snapshotFragment(base ? new URL(original, base).href : original, ids);
23227
+ return original === rewritten ? match : `url("${rewritten}")`;
23228
+ } catch {
23229
+ return match;
23230
+ }
23231
+ });
23232
+ }
23233
+ /** Keep SVG's specified CSS: a use instance inherits from its use element,
23234
+ * rather than from the definition's original parent. Computed defaults on
23235
+ * definitions would replace that inheritance (and resolve currentColor).
23236
+ */
23237
+ var snapshotSvgRules = /* @__PURE__ */ new WeakSet();
23238
+ /** A detached style element has no sheet yet. Carry its CSSOM, including
23239
+ * script-inserted rules and imported styles, into the passive tree.
23240
+ */
23241
+ function copySnapshotSheet(source, ids, onOpaque) {
23242
+ const seen = /* @__PURE__ */ new Set();
23243
+ const textOf = (sheet) => {
23244
+ if (seen.has(sheet)) return "";
23245
+ seen.add(sheet);
23246
+ let rules;
23247
+ try {
23248
+ rules = [...sheet.cssRules];
23249
+ } catch {
23250
+ onOpaque?.();
23251
+ return "";
23252
+ }
23253
+ return rules.filter((rule) => !snapshotSvgRules.has(rule)).map((rule) => {
23254
+ if (rule instanceof CSSImportRule && rule.styleSheet) {
23255
+ let css = textOf(rule.styleSheet);
23256
+ if (rule.layerName !== null) css = `@layer ${rule.layerName}{${css}}`;
23257
+ if (rule.supportsText) css = `@supports (${rule.supportsText}){${css}}`;
23258
+ if (rule.media.mediaText) css = `@media ${rule.media.mediaText}{${css}}`;
23259
+ return css;
23260
+ }
23261
+ return snapshotUrls(rule.cssText, ids, sheet.href ?? document.baseURI);
23262
+ }).join("\n");
23263
+ };
23264
+ const copy = new CSSStyleSheet({
23265
+ media: source.media.mediaText,
23266
+ disabled: source.disabled
23267
+ });
23268
+ copy.replaceSync(textOf(source));
23269
+ return copy;
23270
+ }
23271
+ function installSnapshotSvgStyles(root, ids, marker, targetSheets = [...root.styleSheets, ...root.adoptedStyleSheets]) {
23272
+ if (!root.querySelector("svg")) return () => {};
23273
+ const customTags = new Set([...root instanceof ShadowRoot ? [root.host] : [], ...root.querySelectorAll("*")].filter((element) => element.localName.includes("-")).map((element) => element.localName));
23274
+ const identity = /"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\[(?:\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\]"'\\])*\]|([#.])?((?:\\[0-9a-fA-F]{1,6}\s?|\\.|[\w-]|[^\x00-\x7f])+)/g;
23275
+ const selectorOf = (selector, scoped = true) => {
23276
+ const rewritten = selector.replace(identity, (written, sigil, escaped, at) => {
23277
+ if (!escaped) return written.replace(/^\[\s*id(?=[\s~|^$*=\]])/, "[data-spindle-snapshot-original-id");
23278
+ const name = escaped.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g, (_, hex, char) => hex ? String.fromCodePoint(parseInt(hex, 16)) : char);
23279
+ if (sigil === "." && name === "passage") return ":is(.passage,.passage-snapshot)";
23280
+ if (!sigil && customTags.has(name) && selector[at - 1] !== ":") return `:is(${CSS.escape(name)},:where([data-spindle-snapshot-tag="${name}"]))`;
23281
+ const id = sigil === "#" && ids.get(name);
23282
+ return id ? `:is(#${id},:where([data-spindle-snapshot-id="${id}"]))` : written;
23283
+ });
23284
+ if (!scoped) return rewritten;
23285
+ const selectors = [];
23286
+ let start = 0;
23287
+ let depth = 0;
23288
+ for (let i = 0; i <= rewritten.length; i++) {
23289
+ const ch = rewritten[i];
23290
+ if (ch === "\\") i++;
23291
+ else if (ch === "\"" || ch === "'") i = skipString(rewritten, i) - 1;
23292
+ else if (ch === "(" || ch === "[") depth++;
23293
+ else if (ch === ")" || ch === "]") depth--;
23294
+ else if (i === rewritten.length || ch === "," && depth === 0) {
23295
+ selectors.push(`:where([data-spindle-snapshot-svg="${marker}"]):is(${rewritten.slice(start, i)})`);
23296
+ start = i + 1;
23297
+ }
23298
+ }
23299
+ return selectors.join(",");
23300
+ };
23301
+ const rulesOf = (rules, base) => {
23302
+ const result = [];
23303
+ for (const rule of rules) if (rule instanceof CSSStyleRule) {
23304
+ const css = snapshotUrls(rule.style.cssText, ids, base);
23305
+ result.push(`${selectorOf(rule.selectorText)}{${css}}`);
23306
+ if (rule.cssRules.length) result.push(`${selectorOf(rule.selectorText, false)}{${rulesOf(rule.cssRules, base).join("\n")}}`);
23307
+ } else if ("cssRules" in rule && !(rule instanceof CSSKeyframesRule)) {
23308
+ const contents = rulesOf(rule.cssRules, base);
23309
+ result.push(`${rule.cssText.slice(0, rule.cssText.indexOf("{"))}{${contents.join("\n")}}`);
23310
+ }
23311
+ return result;
23312
+ };
23313
+ const inserted = [];
23314
+ const sheets = /* @__PURE__ */ new Set();
23315
+ const sheetRules = (sheet) => {
23316
+ if (sheets.has(sheet) || sheet.disabled || !matchMedia(sheet.media.mediaText || "all").matches) return;
23317
+ sheets.add(sheet);
23318
+ try {
23319
+ visit(sheet, sheet.href ?? document.baseURI);
23320
+ } catch {}
23321
+ };
23322
+ const visit = (parent, base) => {
23323
+ for (const rule of [...parent.cssRules]) {
23324
+ if (snapshotSvgRules.has(rule)) continue;
23325
+ if (rule instanceof CSSStyleRule) {
23326
+ let index = [...parent.cssRules].indexOf(rule) + 1;
23327
+ for (const css of rulesOf([rule], base)) {
23328
+ parent.insertRule(css, index);
23329
+ const insertedRule = parent.cssRules[index++];
23330
+ inserted.push([parent, insertedRule]);
23331
+ snapshotSvgRules.add(insertedRule);
23332
+ }
23333
+ } else if (rule instanceof CSSImportRule) {
23334
+ if (rule.styleSheet && matchMedia(rule.media.mediaText || "all").matches) sheetRules(rule.styleSheet);
23335
+ } else if ("cssRules" in rule && !(rule instanceof CSSKeyframesRule)) visit(rule, base);
23336
+ }
23337
+ };
23338
+ for (const sheet of targetSheets) sheetRules(sheet);
23339
+ return () => {
23340
+ for (const [parent, rule] of inserted) {
23341
+ const index = [...parent.cssRules].indexOf(rule);
23342
+ if (index >= 0) parent.deleteRule(index);
23343
+ snapshotSvgRules.delete(rule);
23344
+ }
23345
+ };
23346
+ }
23151
23347
  function installSnapshotStyles(root, rules) {
23152
23348
  if (!rules.length) return;
23153
23349
  const sheet = new CSSStyleSheet();
@@ -23165,44 +23361,67 @@ var snapshotPseudoId = 0;
23165
23361
  * as ordinary native elements, without an `is` option (even if the original
23166
23362
  * has since removed its `is` attribute).
23167
23363
  */
23168
- function cloneSnapshotTree(source, freezeStyles = false, pseudoRules = []) {
23169
- const custom = source.namespaceURI === "http://www.w3.org/1999/xhtml" && source.localName.includes("-");
23170
- freezeStyles ||= custom || source.hasAttribute("is");
23364
+ function cloneSnapshotTree(source, ids, pseudoRules = [], svgMarker = String(++snapshotPseudoId), cleanups = []) {
23365
+ const html = source.namespaceURI === "http://www.w3.org/1999/xhtml";
23366
+ const svg = source.namespaceURI === "http://www.w3.org/2000/svg";
23367
+ const custom = html && source.localName.includes("-");
23171
23368
  const clone = document.createElementNS(source.namespaceURI, custom ? "span" : source.localName);
23172
23369
  for (const attr of [...source.attributes]) {
23173
23370
  if (attr.name === "id" || attr.name === "data-action" || attr.name === "is" || attr.name.toLowerCase().startsWith("on")) continue;
23174
- if (attr.namespaceURI) clone.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
23175
- else clone.setAttribute(attr.name, attr.value);
23176
- }
23177
- if (freezeStyles) {
23178
- copyComputedStyle(getComputedStyle(source), clone.style);
23179
- let id;
23180
- for (const pseudo of [
23181
- "::before",
23182
- "::after",
23183
- "::marker"
23184
- ]) {
23185
- const style = getComputedStyle(source, pseudo);
23186
- if (!style.content || ["none", "normal"].includes(style.content)) continue;
23187
- id ??= String(++snapshotPseudoId);
23188
- clone.setAttribute("data-spindle-snapshot-pseudo", id);
23189
- const target = document.createElement("span").style;
23190
- copyComputedStyle(style, target);
23191
- pseudoRules.push(`[data-spindle-snapshot-pseudo="${id}"]${pseudo}{${target.cssText}}`);
23192
- }
23371
+ const value = svg && attr.localName === "href" ? snapshotFragment(attr.value, ids) : svg || attr.localName === "style" ? snapshotUrls(attr.value, ids) : attr.value;
23372
+ if (attr.namespaceURI) clone.setAttributeNS(attr.namespaceURI, attr.name, value);
23373
+ else clone.setAttribute(attr.name, value);
23374
+ }
23375
+ if (svg && source.id) clone.id = ids.get(source.id);
23376
+ if (source.id) clone.setAttribute("data-spindle-snapshot-id", ids.get(source.id));
23377
+ if (source.id) clone.setAttribute("data-spindle-snapshot-original-id", source.id);
23378
+ if (custom) clone.setAttribute("data-spindle-snapshot-tag", source.localName);
23379
+ if (svg) clone.setAttribute("data-spindle-snapshot-svg", svgMarker);
23380
+ const computed = getComputedStyle(source);
23381
+ if (!svg) copyComputedStyle(computed, clone.style, ids);
23382
+ let pseudoId;
23383
+ for (const pseudo of [
23384
+ "::before",
23385
+ "::after",
23386
+ "::marker"
23387
+ ]) {
23388
+ const style = getComputedStyle(source, pseudo);
23389
+ if (!(pseudo === "::marker" && computed.display === "list-item") && (!style.content || ["none", "normal"].includes(style.content))) continue;
23390
+ pseudoId ??= String(++snapshotPseudoId);
23391
+ clone.setAttribute("data-spindle-snapshot-pseudo", pseudoId);
23392
+ const target = document.createElement("span").style;
23393
+ copyComputedStyle(style, target, ids);
23394
+ pseudoRules.push(`[data-spindle-snapshot-pseudo="${pseudoId}"]${pseudo}{${target.cssText}}`);
23193
23395
  }
23194
23396
  if (source.localName === "script") clone.setAttribute("type", "application/x-spindle-snapshot");
23195
23397
  const from = source instanceof HTMLTemplateElement ? source.content : source;
23196
23398
  const to = clone instanceof HTMLTemplateElement ? clone.content : clone;
23197
- const copyChildren = (from, to, rules = pseudoRules) => {
23198
- for (const node of from.childNodes) to.appendChild(node instanceof Element ? cloneSnapshotTree(node, freezeStyles, rules) : node.cloneNode(false));
23399
+ const copyChildren = (from, to, rules = pseudoRules, localIds = ids) => {
23400
+ for (const node of from.childNodes) to.appendChild(node instanceof Element ? cloneSnapshotTree(node, localIds, rules, svgMarker, cleanups) : node.cloneNode(false));
23199
23401
  };
23200
- copyChildren(from, to);
23402
+ copyChildren(from, to, pseudoRules, source instanceof HTMLTemplateElement ? snapshotIds(from) : ids);
23403
+ if (source instanceof HTMLStyleElement && source.sheet) {
23404
+ const root = source.getRootNode();
23405
+ if (root.querySelector("svg")) {
23406
+ let opaque = false;
23407
+ const copy = copySnapshotSheet(source.sheet, ids, () => {
23408
+ opaque = true;
23409
+ });
23410
+ const sheet = opaque ? source.sheet : copy;
23411
+ const dispose = installSnapshotSvgStyles(root, ids, svgMarker, [sheet]);
23412
+ clone.textContent = snapshotUrls([...sheet.cssRules].map((rule) => rule.cssText).join("\n"), ids, source.sheet.href ?? document.baseURI);
23413
+ dispose();
23414
+ if (source.sheet.disabled) clone.setAttribute("media", "not all");
23415
+ }
23416
+ }
23201
23417
  if (source.shadowRoot) {
23202
23418
  const shadow = clone.attachShadow({ mode: "open" });
23203
23419
  const rules = [];
23204
- copyChildren(source.shadowRoot, shadow, rules);
23420
+ const shadowIds = snapshotIds(source.shadowRoot);
23421
+ copyChildren(source.shadowRoot, shadow, rules, shadowIds);
23422
+ shadow.adoptedStyleSheets = source.shadowRoot.adoptedStyleSheets.map((sheet) => copySnapshotSheet(sheet, shadowIds));
23205
23423
  copyLiveState(source.shadowRoot, shadow);
23424
+ cleanups.push(installSnapshotSvgStyles(source.shadowRoot, shadowIds, svgMarker, shadow.adoptedStyleSheets));
23206
23425
  installSnapshotStyles(shadow, rules);
23207
23426
  }
23208
23427
  return clone;
@@ -23227,15 +23446,18 @@ function replaceEmbeddedContexts(source, clone) {
23227
23446
  }
23228
23447
  const rect = original.getBoundingClientRect();
23229
23448
  if (getComputedStyle(original).display === "inline") placeholder.style.display = "inline-block";
23230
- placeholder.style.boxSizing = "border-box";
23231
- placeholder.style.width = `${rect.width}px`;
23232
- placeholder.style.height = `${rect.height}px`;
23449
+ placeholder.style.removeProperty("inline-size");
23450
+ placeholder.style.removeProperty("block-size");
23451
+ placeholder.style.setProperty("box-sizing", "border-box", "important");
23452
+ placeholder.style.setProperty("width", `${rect.width}px`, "important");
23453
+ placeholder.style.setProperty("height", `${rect.height}px`, "important");
23233
23454
  embedded.replaceWith(placeholder);
23234
23455
  });
23235
23456
  }
23236
23457
  /**
23237
23458
  * Create a snapshot clone of a .passage element for outgoing transitions.
23238
- * - Strips IDs, action associations and event handlers from the clone tree
23459
+ * - Strips authored IDs, action associations and event handlers; SVG IDs and
23460
+ * their fragment references receive snapshot-local names
23239
23461
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
23240
23462
  * - Pauses/mutes any <audio>/<video>
23241
23463
  * - Copies what cloneNode leaves behind: canvas pixels, the state of form
@@ -23245,12 +23467,21 @@ function replaceEmbeddedContexts(source, clone) {
23245
23467
  */
23246
23468
  function createSnapshot(passageEl, transitionType) {
23247
23469
  const pseudoRules = [];
23248
- const clone = cloneSnapshotTree(passageEl, false, pseudoRules);
23470
+ const cleanups = [];
23471
+ const ids = snapshotIds(passageEl);
23472
+ const svgMarker = String(++snapshotPseudoId);
23473
+ const clone = cloneSnapshotTree(passageEl, ids, pseudoRules, svgMarker, cleanups);
23474
+ clone.style.removeProperty("animation");
23475
+ clone.style.removeProperty("grid-area");
23476
+ for (const name of ["opacity", "transform"]) clone.style.setProperty(name, clone.style.getPropertyValue(name));
23249
23477
  copyLiveState(passageEl, clone);
23250
23478
  pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
23251
23479
  replaceEmbeddedContexts(passageEl, clone);
23252
- const cleanup = installSnapshotStyles(passageEl.getRootNode(), pseudoRules);
23253
- if (cleanup) snapshotStyleCleanup.set(clone, cleanup);
23480
+ const root = passageEl.getRootNode();
23481
+ cleanups.push(installSnapshotSvgStyles(root, ids, svgMarker));
23482
+ const cleanup = installSnapshotStyles(root, pseudoRules);
23483
+ if (cleanup) cleanups.push(cleanup);
23484
+ snapshotStyleCleanup.set(clone, () => cleanups.forEach((dispose) => dispose()));
23254
23485
  clone.style.pointerEvents = "none";
23255
23486
  clone.style.userSelect = "none";
23256
23487
  clone.setAttribute("inert", "");