@rohal12/spindle 0.62.7 → 0.62.8

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.
@@ -30,6 +30,12 @@ var NameMap = class extends Map {
30
30
  return super.delete(name.toLowerCase());
31
31
  }
32
32
  };
33
+ /** The latest definition of each name, using runtime replacement precedence. */
34
+ function effectiveNamedDefinitions(definitions) {
35
+ const latest = new NameMap();
36
+ for (const definition of definitions) latest.set(definition.name, definition);
37
+ return [...latest.values()];
38
+ }
33
39
  /** A set of macro or widget names (see NameMap). */
34
40
  var NameSet = class {
35
41
  constructor(names = []) {
@@ -3630,6 +3636,98 @@ function peg$parse(input, options) {
3630
3636
  if (peg$success) return peg$result;
3631
3637
  else peg$throw();
3632
3638
  }
3639
+ new NameMap();
3640
+ new NameMap();
3641
+ new NameSet();
3642
+ /**
3643
+ * How a macro argument is read (see components/macros/macro-args.ts). Every
3644
+ * declared parameter names one: there is no default.
3645
+ * Quoted strings accept `\"`, `\'` and `\\` escapes.
3646
+ * - `expression`: code, as written.
3647
+ * - `statements`: code run as statements (`{set}`), as written.
3648
+ * - `passage`: a passage name: a quoted string or an expression, as written.
3649
+ * - `variable`: a variable reference such as `$name` or `"$name"`, as written.
3650
+ * - `string`: one quoted string; anything else leaves the argument unset.
3651
+ * - `text`: one quoted string, or text with any loose quotes stripped.
3652
+ * - `names`: a comma-separated list of names (`@item, @i`).
3653
+ * - `delay`: a duration (`2s`, `500ms`, `300`) in milliseconds.
3654
+ * - `number`: a number.
3655
+ * - `flag`: a keyword, the parameter's name, at the start or end; a boolean.
3656
+ * - `separator`: a word (`of`) or `=` separating the parameters before it
3657
+ * from those after it; a boolean.
3658
+ * - `options`: keywords, the names of its `parameters`, each followed by a
3659
+ * quoted string or a number unless it is a flag.
3660
+ */
3661
+ var PARAMETER_TYPES = [
3662
+ "expression",
3663
+ "statements",
3664
+ "passage",
3665
+ "variable",
3666
+ "string",
3667
+ "text",
3668
+ "names",
3669
+ "delay",
3670
+ "number",
3671
+ "flag",
3672
+ "separator",
3673
+ "options"
3674
+ ];
3675
+ /**
3676
+ * What the value of a `string` or `text` argument holds, for the check at
3677
+ * story start and for tooling (see code-check.ts):
3678
+ * - `markup`: markup the macro renders (`{button}`'s label): its markup
3679
+ * is checked.
3680
+ * - `text`: plain text the macro uses as written (`{checkbox}`'s label).
3681
+ * - `passage`: a passage name (`{watch}`'s `goto`): the passage must exist.
3682
+ * - `expression`, `statements`: code (`{watch}`'s condition and `run`): it
3683
+ * is checked as code, and its variable references against the schema.
3684
+ *
3685
+ * Without it, the argument of a macro with `interpolate` holds `markup`,
3686
+ * any other `text`.
3687
+ */
3688
+ var STRING_HOLDS = [
3689
+ "markup",
3690
+ "text",
3691
+ "passage",
3692
+ "expression",
3693
+ "statements"
3694
+ ];
3695
+ /**
3696
+ * Throw if a parameter `macro` declares (or an option of one) has no type,
3697
+ * or one that isn't a ParameterType: arguments are read by their type, and
3698
+ * there is no default. Throw too if it declares what it `holds` wrongly.
3699
+ */
3700
+ function checkParameterTypes(macro, parameters) {
3701
+ const holdsFix = `Give a \`string\` or \`text\` parameter one of ${STRING_HOLDS.join(", ")} to hold (see docs/custom-macros.md#what-a-string-holds).`;
3702
+ for (const param of parameters) {
3703
+ const type = param.type;
3704
+ if (!PARAMETER_TYPES.includes(type)) throw parameterError(macro, param, type === void 0 ? "has no type" : `has the unknown type ${JSON.stringify(type)}`, `Give it one of the types ${PARAMETER_TYPES.join(", ")} (see docs/custom-macros.md#parameter-types), or declare no parameters and read props.rawArgs.`);
3705
+ const holds = param.holds;
3706
+ if (holds !== void 0 && type !== "string" && type !== "text") throw parameterError(macro, param, `is of the type ${type}, which holds what it is`, holdsFix);
3707
+ if (holds !== void 0 && !STRING_HOLDS.includes(holds)) throw parameterError(macro, param, `holds the unknown ${JSON.stringify(holds)}`, holdsFix);
3708
+ if (param.parameters) checkParameterTypes(macro, param.parameters);
3709
+ }
3710
+ }
3711
+ /** The error for the parameter `param` of `macro`: what is wrong, and the fix. */
3712
+ function parameterError(macro, param, problem, fix) {
3713
+ return /* @__PURE__ */ new Error(`spindle: The parameter "${param.name}" of the macro {${macro}} ${problem}. ${fix}`);
3714
+ }
3715
+ var metadataRegistry = new NameMap();
3716
+ /** Indexed at registration, so parsing each tag does not scan every macro. */
3717
+ var companionParents = new NameMap();
3718
+ /** The parents declaring a branching companion (listbox options are values). */
3719
+ function branchParents(name, macros) {
3720
+ if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
3721
+ return effectiveNamedDefinitions(macros).filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3722
+ }
3723
+ /** The declared parameters of the macro `name`, if it declares any. */
3724
+ function getMacroParameters(name) {
3725
+ return metadataRegistry.get(name)?.parameters;
3726
+ }
3727
+ getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
3728
+ function getMacroRegistry() {
3729
+ return Array.from(metadataRegistry.values());
3730
+ }
3633
3731
  //#endregion
3634
3732
  //#region src/markup/ast.ts
3635
3733
  /**
@@ -3726,7 +3824,7 @@ function astNode({ token, body }) {
3726
3824
  };
3727
3825
  if (!body) return withSelectors$1(node, token);
3728
3826
  const children = buildAst(body.children);
3729
- const branching = BRANCHING.has(name) && !WIDGETS.has(name);
3827
+ const branching = BRANCHING.has(name) && !WIDGETS.has(name) && getMacroParameters.source(name) !== "user";
3730
3828
  if (!branching && body.branches.length === 0) {
3731
3829
  node.children = children;
3732
3830
  return withSelectors$1(node, token);
@@ -3741,97 +3839,18 @@ function astNode({ token, body }) {
3741
3839
  }
3742
3840
  }
3743
3841
  }
3744
- new NameMap();
3745
- new NameMap();
3746
- new NameSet();
3747
- /**
3748
- * How a macro argument is read (see components/macros/macro-args.ts). Every
3749
- * declared parameter names one: there is no default.
3750
- * Quoted strings accept `\"`, `\'` and `\\` escapes.
3751
- * - `expression`: code, as written.
3752
- * - `statements`: code run as statements (`{set}`), as written.
3753
- * - `passage`: a passage name: a quoted string or an expression, as written.
3754
- * - `variable`: a variable reference such as `$name` or `"$name"`, as written.
3755
- * - `string`: one quoted string; anything else leaves the argument unset.
3756
- * - `text`: one quoted string, or text with any loose quotes stripped.
3757
- * - `names`: a comma-separated list of names (`@item, @i`).
3758
- * - `delay`: a duration (`2s`, `500ms`, `300`) in milliseconds.
3759
- * - `number`: a number.
3760
- * - `flag`: a keyword, the parameter's name, at the start or end; a boolean.
3761
- * - `separator`: a word (`of`) or `=` separating the parameters before it
3762
- * from those after it; a boolean.
3763
- * - `options`: keywords, the names of its `parameters`, each followed by a
3764
- * quoted string or a number unless it is a flag.
3765
- */
3766
- var PARAMETER_TYPES = [
3767
- "expression",
3768
- "statements",
3769
- "passage",
3770
- "variable",
3771
- "string",
3772
- "text",
3773
- "names",
3774
- "delay",
3775
- "number",
3776
- "flag",
3777
- "separator",
3778
- "options"
3779
- ];
3780
- /**
3781
- * What the value of a `string` or `text` argument holds, for the check at
3782
- * story start and for tooling (see code-check.ts):
3783
- * - `markup`: markup the macro renders (`{button}`'s label): its markup
3784
- * is checked.
3785
- * - `text`: plain text the macro uses as written (`{checkbox}`'s label).
3786
- * - `passage`: a passage name (`{watch}`'s `goto`): the passage must exist.
3787
- * - `expression`, `statements`: code (`{watch}`'s condition and `run`): it
3788
- * is checked as code, and its variable references against the schema.
3789
- *
3790
- * Without it, the argument of a macro with `interpolate` holds `markup`,
3791
- * any other `text`.
3792
- */
3793
- var STRING_HOLDS = [
3794
- "markup",
3795
- "text",
3796
- "passage",
3797
- "expression",
3798
- "statements"
3799
- ];
3800
- /**
3801
- * Throw if a parameter `macro` declares (or an option of one) has no type,
3802
- * or one that isn't a ParameterType: arguments are read by their type, and
3803
- * there is no default. Throw too if it declares what it `holds` wrongly.
3804
- */
3805
- function checkParameterTypes(macro, parameters) {
3806
- const holdsFix = `Give a \`string\` or \`text\` parameter one of ${STRING_HOLDS.join(", ")} to hold (see docs/custom-macros.md#what-a-string-holds).`;
3807
- for (const param of parameters) {
3808
- const type = param.type;
3809
- if (!PARAMETER_TYPES.includes(type)) throw parameterError(macro, param, type === void 0 ? "has no type" : `has the unknown type ${JSON.stringify(type)}`, `Give it one of the types ${PARAMETER_TYPES.join(", ")} (see docs/custom-macros.md#parameter-types), or declare no parameters and read props.rawArgs.`);
3810
- const holds = param.holds;
3811
- if (holds !== void 0 && type !== "string" && type !== "text") throw parameterError(macro, param, `is of the type ${type}, which holds what it is`, holdsFix);
3812
- if (holds !== void 0 && !STRING_HOLDS.includes(holds)) throw parameterError(macro, param, `holds the unknown ${JSON.stringify(holds)}`, holdsFix);
3813
- if (param.parameters) checkParameterTypes(macro, param.parameters);
3814
- }
3815
- }
3816
- /** The error for the parameter `param` of `macro`: what is wrong, and the fix. */
3817
- function parameterError(macro, param, problem, fix) {
3818
- return /* @__PURE__ */ new Error(`spindle: The parameter "${param.name}" of the macro {${macro}} ${problem}. ${fix}`);
3819
- }
3820
- var metadataRegistry = new NameMap();
3821
- /** Indexed at registration, so parsing each tag does not scan every macro. */
3822
- var companionParents = new NameMap();
3823
- /** The parents declaring a branching companion (listbox options are values). */
3824
- function branchParents(name, macros) {
3825
- if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
3826
- return macros.filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3827
- }
3828
- /** The declared parameters of the macro `name`, if it declares any. */
3829
- function getMacroParameters(name) {
3830
- return metadataRegistry.get(name)?.parameters;
3831
- }
3832
- getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
3833
- function getMacroRegistry() {
3834
- return Array.from(metadataRegistry.values());
3842
+ //#endregion
3843
+ //#region src/utils/sorted.ts
3844
+ /** Index of the first sorted value greater than `value` (or the length). */
3845
+ function upperBound(sorted, value) {
3846
+ let low = 0;
3847
+ let high = sorted.length;
3848
+ while (low < high) {
3849
+ const mid = low + high >>> 1;
3850
+ if (sorted[mid] <= value) low = mid + 1;
3851
+ else high = mid;
3852
+ }
3853
+ return low;
3835
3854
  }
3836
3855
  //#endregion
3837
3856
  //#region src/markup/line-column.ts
@@ -3854,14 +3873,7 @@ function sourcePositions(text) {
3854
3873
  const starts = [0];
3855
3874
  for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
3856
3875
  return (offset) => {
3857
- let low = 0;
3858
- let high = starts.length;
3859
- while (low < high) {
3860
- const mid = low + high >>> 1;
3861
- if (starts[mid] <= offset) low = mid + 1;
3862
- else high = mid;
3863
- }
3864
- const line = Math.max(1, low);
3876
+ const line = Math.max(1, upperBound(starts, offset));
3865
3877
  return {
3866
3878
  line,
3867
3879
  column: offset - starts[line - 1] + 1
@@ -10314,7 +10326,7 @@ function isCodeAttribute(name) {
10314
10326
  * Split a code attribute value into literal text and its `{…}` blocks that
10315
10327
  * start with a sigil. Braces inside strings don't close a block; an
10316
10328
  * unclosed block, any other brace and backslashes are text. A block whose
10317
- * sigil is not followed by a word character (`{$(…)}`) is code, kept
10329
+ * sigil is not followed by an identifier (`{$(…)}`) is code, kept
10318
10330
  * verbatim: not resolved, and not decoded like text.
10319
10331
  */
10320
10332
  function splitSigilTemplate(template, incomplete = false) {
@@ -10339,7 +10351,11 @@ function splitSigilTemplate(template, incomplete = false) {
10339
10351
  if (text) parts.push({ text });
10340
10352
  text = "";
10341
10353
  const block = template.slice(i, end);
10342
- parts.push(/^.\w/.test(block) || incomplete && block.length === 1 && end === template.length ? { expr: block } : { verbatim: `{${block}}` });
10354
+ let reference = /^.\w/.test(block);
10355
+ if (!reference && block[1] === "\\") lexJs(block, { variable(_sigil, _name, start) {
10356
+ if (start === 0) reference = true;
10357
+ } });
10358
+ parts.push(reference || incomplete && block.length === 1 && end === template.length ? { expr: block } : { verbatim: `{${block}}` });
10343
10359
  i = end + 1;
10344
10360
  }
10345
10361
  if (text) parts.push({ text });
@@ -10421,7 +10437,12 @@ function analyzeMarkup(source, options = {}) {
10421
10437
  nodes: paired.nodes,
10422
10438
  errors
10423
10439
  };
10424
- const inDamage = (start) => errors.some((e, i) => start >= damage[i] && start <= e.offset);
10440
+ const damageEnds = [];
10441
+ for (const e of errors) damageEnds.push(Math.max(damageEnds[damageEnds.length - 1] ?? -1, e.offset));
10442
+ const inDamage = (start) => {
10443
+ const index = upperBound(damage, start) - 1;
10444
+ return index >= 0 && start <= damageEnds[index];
10445
+ };
10425
10446
  const noticed = errors.map((e, i) => [damage[i] + .5, e]);
10426
10447
  const position = paired.errors.length ? sourcePositions(source) : void 0;
10427
10448
  for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(position, error)]);
@@ -25773,9 +25794,14 @@ var transformCache = /* @__PURE__ */ new Map();
25773
25794
  * validator, with no Preact or DOM dependencies. pkg/tooling.js re-exports
25774
25795
  * them, binding the validator to its macro metadata.
25775
25796
  */
25797
+ /** Widgets take precedence over macros regardless of metadata input order. */
25798
+ function effectiveToolingMacros(macros) {
25799
+ const list = [...macros];
25800
+ return effectiveNamedDefinitions([...list.filter((m) => !m.widget), ...list.filter((m) => m.widget)]);
25801
+ }
25776
25802
  function tokenizationOptions(options) {
25777
25803
  if (!options.macros) return options;
25778
- const macros = [...options.macros];
25804
+ const macros = effectiveToolingMacros(options.macros);
25779
25805
  const parametersOf = parameterLookup(macros);
25780
25806
  return {
25781
25807
  ...options,
@@ -25803,7 +25829,7 @@ function tokenizeMarkupTolerant(source, options = {}) {
25803
25829
  */
25804
25830
  function validateStoryMarkup(passages, macros, options = {}) {
25805
25831
  const list = [...passages];
25806
- const all = [...macros];
25832
+ const all = effectiveToolingMacros(macros);
25807
25833
  const known = /* @__PURE__ */ new Set();
25808
25834
  const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(list, parameterLookup(all)));
25809
25835
  const blocks = new Set(widgets.filter((def) => def.block).map((def) => def.name.toLowerCase()));
@@ -25848,7 +25874,7 @@ function blockLookup(macros) {
25848
25874
  * The macros are those the markup may use, built-in and user-defined.
25849
25875
  */
25850
25876
  function passagePieces(source, macros = []) {
25851
- const all = [...macros];
25877
+ const all = effectiveToolingMacros(macros);
25852
25878
  const parametersOf = parameterLookup(all);
25853
25879
  return passagePiecesOfTokens(source, all, tokenizeMarkupTolerant(source, { hooks: { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) } }).tokens);
25854
25880
  }
@@ -25858,7 +25884,7 @@ function passagePieces(source, macros = []) {
25858
25884
  * part of the published tooling API.
25859
25885
  */
25860
25886
  function passagePiecesOfTokens(source, macros, tokens) {
25861
- const all = [...macros];
25887
+ const all = effectiveToolingMacros(macros);
25862
25888
  return [...passagePiecesOf(source, tokens, parameterLookup(all), { isBlock: blockLookup(all) })];
25863
25889
  }
25864
25890
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.7",
3
+ "version": "0.62.8",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,4 +1,5 @@
1
1
  import { isReaderVisible } from './utils/element-visibility';
2
+ import { readOnlyValue } from './execute-mutation';
2
3
  import { emit } from './event-emitter';
3
4
  import {
4
5
  checkFields,
@@ -250,7 +251,7 @@ export async function settleRunningActions(): Promise<void> {
250
251
  }
251
252
 
252
253
  export function getActions(): StoryAction[] {
253
- return Array.from(actions.values(), listed);
254
+ return readOnlyValue(Array.from(actions.values(), listed));
254
255
  }
255
256
 
256
257
  /**
@@ -258,15 +259,17 @@ export function getActions(): StoryAction[] {
258
259
  * function, see registerAction), its nested dialogs' left out.
259
260
  */
260
261
  export function getDialogActions(dialog: () => void): StoryAction[] {
261
- return Array.from(actions.values())
262
- .map((entries) => entries[entries.length - 1]!)
263
- .filter((entry) => entry.dialog === dialog)
264
- .map((entry) => effectiveAction(entry.action));
262
+ return readOnlyValue(
263
+ Array.from(actions.values())
264
+ .map((entries) => entries[entries.length - 1]!)
265
+ .filter((entry) => entry.dialog === dialog)
266
+ .map((entry) => effectiveAction(entry.action)),
267
+ );
265
268
  }
266
269
 
267
270
  export function getAction(id: string): StoryAction | undefined {
268
271
  const entries = actions.get(id);
269
- return entries && listed(entries);
272
+ return entries && readOnlyValue(listed(entries));
270
273
  }
271
274
 
272
275
  function listed(entries: Entry[]): StoryAction {
package/src/headless.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * same boot sequence directly.
9
9
  */
10
10
  import { boot } from './index';
11
+ import { readOnlyValue } from './execute-mutation';
11
12
  import { isSpecialPassage, useStoryStore } from './store';
12
13
  import { noPassageError, specialPassageError } from './runtime-errors';
13
14
  import type { StoryAPI } from './story-api';
@@ -87,11 +88,11 @@ export function bootStory(options: BootStoryOptions): Promise<StoryAPI> {
87
88
  }
88
89
 
89
90
  /**
90
- * The story's `$` variables: a shallow copy of the current values, keyed by
91
- * name without the `$`. Values are the store's own (frozen) objects.
91
+ * The story's `$` variables, keyed by name without the `$`. Mutable values
92
+ * are copied together, preserving aliases without exposing live state.
92
93
  */
93
94
  export function storyVariables(): Record<string, unknown> {
94
- return { ...useStoryStore.getState().variables };
95
+ return { ...readOnlyValue(useStoryStore.getState().variables) };
95
96
  }
96
97
 
97
98
  /**
@@ -1,4 +1,9 @@
1
- import { composedParent, isRendered } from '../utils/element-visibility';
1
+ import {
2
+ composedChildren,
3
+ composedElements,
4
+ composedParent,
5
+ isRendered,
6
+ } from '../utils/element-visibility';
2
7
  import { useLayoutEffect } from 'preact/hooks';
3
8
  import type { RefObject } from 'preact';
4
9
 
@@ -17,24 +22,6 @@ const FOCUSABLE = [
17
22
  '[tabindex]',
18
23
  ].join(',');
19
24
 
20
- function composedChildren(root: ParentNode): Element[] {
21
- if ((root as Element).localName === 'slot') {
22
- const assigned = (root as HTMLSlotElement).assignedNodes({
23
- flatten: true,
24
- });
25
- return assigned.filter((node): node is Element => node.nodeType === 1);
26
- }
27
- return Array.from(root.children);
28
- }
29
-
30
- /** Authored elements in rendered order; unassigned light DOM is not rendered. */
31
- function* composedElements(root: ParentNode): Generator<HTMLElement> {
32
- for (const el of composedChildren(root)) {
33
- yield el as HTMLElement;
34
- yield* composedElements(el.shadowRoot ?? el);
35
- }
36
- }
37
-
38
25
  /**
39
26
  * Whether `el` can be focused at all: shown, rendered, enabled (also by its
40
27
  * fieldset) and not inert.
package/src/markup/ast.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  import { withSelectors, type Selectors, type VariableScope } from './tokens';
6
6
  import type { PairedBranch, PairedNode } from './pair';
7
7
  import { NameSet } from '../utils/macro-names';
8
+ import { getMacroParameters } from '../registry';
8
9
 
9
10
  export interface TextNode {
10
11
  type: 'text';
@@ -184,7 +185,10 @@ function astNode({ token, body }: PairedNode): ASTNode {
184
185
  };
185
186
  if (!body) return withSelectors(node, token);
186
187
  const children = buildAst(body.children);
187
- const branching = BRANCHING.has(name) && !WIDGETS.has(name);
188
+ const branching =
189
+ BRANCHING.has(name) &&
190
+ !WIDGETS.has(name) &&
191
+ getMacroParameters.source(name) !== 'user';
188
192
  if (!branching && body.branches.length === 0) {
189
193
  node.children = children;
190
194
  return withSelectors(node, token);
@@ -1,5 +1,6 @@
1
1
  import { isSigil } from './tokens';
2
2
  import { indexCodeEnds } from './code-end';
3
+ import { lexJs } from '../js-lexer';
3
4
 
4
5
  /**
5
6
  * Attributes whose value is code with braces of its own, not text: event
@@ -23,7 +24,7 @@ export type SigilPart =
23
24
  * Split a code attribute value into literal text and its `{…}` blocks that
24
25
  * start with a sigil. Braces inside strings don't close a block; an
25
26
  * unclosed block, any other brace and backslashes are text. A block whose
26
- * sigil is not followed by a word character (`{$(…)}`) is code, kept
27
+ * sigil is not followed by an identifier (`{$(…)}`) is code, kept
27
28
  * verbatim: not resolved, and not decoded like text.
28
29
  */
29
30
  export function splitSigilTemplate(
@@ -52,9 +53,16 @@ export function splitSigilTemplate(
52
53
  if (text) parts.push({ text });
53
54
  text = '';
54
55
  const block = template.slice(i, end);
56
+ let reference = /^.\w/.test(block);
57
+ if (!reference && block[1] === '\\') {
58
+ lexJs(block, {
59
+ variable(_sigil, _name, start) {
60
+ if (start === 0) reference = true;
61
+ },
62
+ });
63
+ }
55
64
  parts.push(
56
- /^.\w/.test(block) ||
57
- (incomplete && block.length === 1 && end === template.length)
65
+ reference || (incomplete && block.length === 1 && end === template.length)
58
66
  ? { expr: block }
59
67
  : { verbatim: `{${block}}` },
60
68
  );
@@ -1,3 +1,5 @@
1
+ import { upperBound } from '../utils/sorted';
2
+
1
3
  /** 1-based line and column of `offset` in `text`. */
2
4
  export function lineColumn(
3
5
  text: string,
@@ -20,14 +22,7 @@ export function sourcePositions(text: string) {
20
22
  if (text[i] === '\n') starts.push(i + 1);
21
23
  }
22
24
  return (offset: number) => {
23
- let low = 0;
24
- let high = starts.length;
25
- while (low < high) {
26
- const mid = (low + high) >>> 1;
27
- if (starts[mid]! <= offset) low = mid + 1;
28
- else high = mid;
29
- }
30
- const line = Math.max(1, low);
25
+ const line = Math.max(1, upperBound(starts, offset));
31
26
  return { line, column: offset - starts[line - 1]! + 1 };
32
27
  };
33
28
  }
@@ -15,6 +15,7 @@ import type { Selectors, Token } from './tokens';
15
15
  import { isCodeAttribute } from './code-attributes';
16
16
  import { defaultCodeEnd, indexCodeEnds, type CodeEnd } from './code-end';
17
17
  import { lineColumn, sourcePositions } from './line-column';
18
+ import { upperBound } from '../utils/sorted';
18
19
 
19
20
  export { lineColumn };
20
21
 
@@ -163,8 +164,18 @@ export function analyzeMarkup(
163
164
  // A malformed tag is noticed where it starts, an unpaired tag where its
164
165
  // problem shows (see PairingError.noticedAt). Within a malformed tag the
165
166
  // markup is no markup: what the recovery pairs there is dropped.
166
- const inDamage = (start: number) =>
167
- errors.some((e, i) => start >= damage[i]! && start <= e.offset);
167
+ // Damage starts increase during recovery, but intervals can overlap. A
168
+ // prefix maximum keeps even nested damage searchable in logarithmic time.
169
+ const damageEnds: number[] = [];
170
+ for (const e of errors) {
171
+ damageEnds.push(
172
+ Math.max(damageEnds[damageEnds.length - 1] ?? -1, e.offset),
173
+ );
174
+ }
175
+ const inDamage = (start: number) => {
176
+ const index = upperBound(damage, start) - 1;
177
+ return index >= 0 && start <= damageEnds[index]!;
178
+ };
168
179
  const noticed: [number, MarkupError][] = errors.map((e, i) => [
169
180
  damage[i]! + 0.5,
170
181
  e,
@@ -651,7 +651,7 @@ function decodeText(text: string): string {
651
651
  }
652
652
 
653
653
  /** A `{` and a sigil starting a reference, in a code attribute. */
654
- const SIGIL_REFERENCE = /\{[$_@%]\w/;
654
+ const SIGIL_REFERENCE = /\{[$_@%][\w\\]/;
655
655
 
656
656
  const attributeNodes = new Map<string, ParsedText>();
657
657
  const ATTRIBUTE_CACHE_LIMIT = 2000;
@@ -1,4 +1,10 @@
1
- import { isHidden, isRendered } from '../utils/element-visibility';
1
+ import {
2
+ composedChildNodes,
3
+ composedElements,
4
+ composedParent,
5
+ isHidden,
6
+ isRendered,
7
+ } from '../utils/element-visibility';
2
8
  import { getAction } from '../action-registry';
3
9
 
4
10
  /** Elements that start and end a line. */
@@ -81,8 +87,11 @@ export function observableText(
81
87
 
82
88
  const walk = (node: Node, inPre: boolean) => {
83
89
  if (node.nodeType === 3) {
84
- if (node.parentElement && !isRendered(node.parentElement, visibilityRoot))
85
- return;
90
+ const parent =
91
+ (node as Text).assignedSlot ??
92
+ node.parentElement ??
93
+ (node.getRootNode() as ShadowRoot).host;
94
+ if (parent && !isRendered(parent, visibilityRoot)) return;
86
95
  const data = node.textContent ?? '';
87
96
  if (inPre) out += data;
88
97
  else {
@@ -114,9 +123,10 @@ export function observableText(
114
123
  if (block) endLine();
115
124
  const closedDetails =
116
125
  child.tagName === 'DETAILS' && !child.hasAttribute('open');
126
+ const rendered = composedChildNodes(child);
117
127
  const children = closedDetails
118
- ? Array.from(child.children).filter((c) => !isHidden(c))
119
- : Array.from(child.childNodes);
128
+ ? rendered.filter((c) => c.nodeType === 1 && !isHidden(c as Element))
129
+ : rendered;
120
130
  for (const c of children) {
121
131
  walk(c, inPre || child.tagName === 'PRE');
122
132
  }
@@ -148,14 +158,16 @@ export function observableErrors(
148
158
  visibilityRoot?: Element,
149
159
  ): string[] {
150
160
  const left = (e: Element) => {
151
- for (let at: Element | null = e; at; at = at.parentElement) {
161
+ for (let at: Element | null = e; at; at = composedParent(at)) {
152
162
  if (isHidden(at)) return true;
153
163
  if (at === el) return false;
154
164
  if (skip && at.matches(skip)) return true;
155
165
  }
156
166
  return false;
157
167
  };
158
- return Array.from(el.querySelectorAll('.error'))
159
- .filter((e) => !left(e) && isRendered(e, visibilityRoot))
168
+ return [...composedElements(el)]
169
+ .filter(
170
+ (e) => e.matches('.error') && !left(e) && isRendered(e, visibilityRoot),
171
+ )
160
172
  .map((e) => observableText(e, skip, visibilityRoot).trim());
161
173
  }
package/src/registry.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { ComponentType } from 'preact';
2
2
  import type { ASTNode, Branch } from './markup/ast';
3
- import { NameMap, NameSet } from './utils/macro-names';
3
+ import {
4
+ effectiveNamedDefinitions,
5
+ NameMap,
6
+ NameSet,
7
+ } from './utils/macro-names';
4
8
 
5
9
  export interface MacroProps {
6
10
  rawArgs: string;
@@ -260,7 +264,7 @@ export function branchParents(
260
264
  (parent) => parent !== 'listbox',
261
265
  );
262
266
  }
263
- return macros
267
+ return effectiveNamedDefinitions(macros)
264
268
  .filter(
265
269
  (macro) =>
266
270
  macro.name.toLowerCase() !== 'listbox' &&