@rohal12/spindle 0.64.30 → 0.64.31

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.
@@ -9507,13 +9507,13 @@ function registerAction(action, dialog = null, panel = null, element = null) {
9507
9507
  console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
9508
9508
  entries.push(entry);
9509
9509
  } else actions.set(id, [entry]);
9510
- notify();
9510
+ notify$1();
9511
9511
  return {
9512
9512
  update(next) {
9513
9513
  const current = actions.get(id);
9514
9514
  if (!current?.includes(entry)) return;
9515
9515
  entry.action = next;
9516
- if (current[current.length - 1] === entry) notify();
9516
+ if (current[current.length - 1] === entry) notify$1();
9517
9517
  },
9518
9518
  unregister() {
9519
9519
  const current = actions.get(id);
@@ -9524,7 +9524,7 @@ function registerAction(action, dialog = null, panel = null, element = null) {
9524
9524
  actions.delete(id);
9525
9525
  reserved.delete(id);
9526
9526
  }
9527
- if (index === current.length) notify();
9527
+ if (index === current.length) notify$1();
9528
9528
  }
9529
9529
  };
9530
9530
  }
@@ -9594,7 +9594,7 @@ function resetIdCounters() {
9594
9594
  idCounters.clear();
9595
9595
  for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
9596
9596
  }
9597
- function notify() {
9597
+ function notify$1() {
9598
9598
  emit("actionsChanged");
9599
9599
  }
9600
9600
  // src/components/dialog-close-context.ts
@@ -14055,12 +14055,13 @@ function jsCodeEnd(onOpenEnd) {
14055
14055
  var defaultCodeEnd = jsCodeEnd();
14056
14056
  /**
14057
14057
  * Index possible brace ends for repeated recovery attempts in one template.
14058
- * Within plain code, nested braces must close first. At a quote, slash or
14059
- * escape we stop making lexical assumptions, but the remaining raw `}`s
14060
- * still bound how many pending braces could close. Indexing visits each
14061
- * opener once, so unmatched plain-code openers can skip suffix scans.
14058
+ * Within plain code, nested braces must close first. At a quote, slash,
14059
+ * escape or HTML-style comment we stop making lexical assumptions, but the
14060
+ * remaining raw `}`s still bound how many pending braces could close.
14061
+ * Indexing visits each opener once, so unmatched plain-code openers can
14062
+ * skip suffix scans.
14062
14063
  */
14063
- function indexCodeEnds(input) {
14064
+ function indexCodeEnds(input, closeBrace = defaultCodeEnd.closeBrace) {
14064
14065
  const possible = /* @__PURE__ */ new Set();
14065
14066
  const pending = [];
14066
14067
  let remaining = 0;
@@ -14080,12 +14081,12 @@ function indexCodeEnds(input) {
14080
14081
  remaining--;
14081
14082
  const open = pending.pop();
14082
14083
  if (open !== void 0) possible.add(open);
14083
- } else if (/['"`/\\]/.test(c)) uncertain();
14084
+ } else if (/['"`/\\]/.test(c) || input.startsWith("<!--", i) || input.startsWith("-->", i)) uncertain();
14084
14085
  }
14085
14086
  return (start, codeStart = start, limit = input.length) => {
14086
14087
  if (start > lastBrace || codeStart >= limit) return -1;
14087
14088
  const source = limit === input.length ? input : input.slice(0, limit);
14088
- if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return defaultCodeEnd.closeBrace(source, codeStart, start);
14089
+ if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return closeBrace(source, codeStart, start);
14089
14090
  const base = Math.max(0, codeStart - 1);
14090
14091
  const end = parsedCodeEnd(source.slice(base), codeStart - base, "expression");
14091
14092
  return end < 0 ? -1 : base + end;
@@ -15690,9 +15691,8 @@ function locate(text, part, from) {
15690
15691
  return anywhere >= 0 ? anywhere : from;
15691
15692
  }
15692
15693
  // src/widgets/ast-scanner.ts
15693
- /** The declared parameters of the macros registered so far. */
15694
- var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
15695
- registeredParameters.source = getMacroParameters.source;
15694
+ /** Snapshot effective macro metadata once per scan. */
15695
+ var registeredParameters = () => parameterLookup(getMacroRegistry());
15696
15696
  /**
15697
15697
  * Whether the text of an attribute value or macro label renders a
15698
15698
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -15719,7 +15719,7 @@ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpa
15719
15719
  * are read from it); a token made from an AST has none. Discovery hooks
15720
15720
  * also apply inside these texts, before widgets have been registered.
15721
15721
  */
15722
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
15722
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters(), src = "", hooks, budget) {
15723
15723
  for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
15724
15724
  return false;
15725
15725
  }
@@ -15730,7 +15730,7 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
15730
15730
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
15731
15731
  * reads it), and a definition renders nothing of its own.
15732
15732
  */
15733
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
15733
+ function astContainsChildren(nodes, parametersOf = registeredParameters(), hooks, budget) {
15734
15734
  const pending = [...nodes];
15735
15735
  while (pending.length) {
15736
15736
  const node = pending.pop();
@@ -15837,7 +15837,7 @@ function nameSpan(rawArgs) {
15837
15837
  * here as it is to the parser, and does not make a block widget (#387). In
15838
15838
  * nested definitions, it belongs to the innermost.
15839
15839
  */
15840
- function widgetDefinitions(passages, parametersOf = registeredParameters) {
15840
+ function widgetDefinitions(passages, parametersOf = registeredParameters()) {
15841
15841
  const list = [...passages];
15842
15842
  const scan = (replacesDo) => {
15843
15843
  const found = [];
@@ -15902,7 +15902,7 @@ function effectiveWidgetDefinitions(definitions) {
15902
15902
  * takes a body must be known before any passage is parsed, so that passages
15903
15903
  * invoking them nest their content (or don't) whatever the passage order.
15904
15904
  */
15905
- function effectiveWidgets(passages, parametersOf = registeredParameters) {
15905
+ function effectiveWidgets(passages, parametersOf = registeredParameters()) {
15906
15906
  return effectiveWidgetDefinitions(widgetDefinitions(passages, parametersOf));
15907
15907
  }
15908
15908
  // src/widgets/register-widget-def.ts
@@ -21940,7 +21940,13 @@ var values = createNamespace();
21940
21940
  var storageLoaded = false;
21941
21941
  var unsubscribeStoryData = null;
21942
21942
  var listeners = /* @__PURE__ */ new Set();
21943
- /** Call `listener` after a setting changes; returns the unsubscribe. */
21943
+ var revision = 0;
21944
+ var getSettingsRevision = () => revision;
21945
+ function notify() {
21946
+ revision++;
21947
+ for (const listener of [...listeners]) listener();
21948
+ }
21949
+ /** Call `listener` after a definition or value changes; returns the unsubscribe. */
21944
21950
  function subscribeSettings(listener) {
21945
21951
  listeners.add(listener);
21946
21952
  return () => listeners.delete(listener);
@@ -21978,6 +21984,7 @@ function define(name, def) {
21978
21984
  definitions.set(name, def);
21979
21985
  if (!hasOwn(values, name)) values[name] = def.config.default;
21980
21986
  loadFromStorage();
21987
+ notify();
21981
21988
  }
21982
21989
  /** The value of setting `name` if it has the type of `fallback`, else that. */
21983
21990
  function valueOf(name, fallback) {
@@ -22025,7 +22032,7 @@ var settings = {
22025
22032
  values[name] = value;
22026
22033
  persist();
22027
22034
  if (unchanged) return;
22028
- for (const listener of [...listeners]) listener();
22035
+ notify();
22029
22036
  emit("settingchanged", name, value);
22030
22037
  },
22031
22038
  getAll() {
@@ -22467,10 +22474,14 @@ function observableText(el, skip, visibilityRoot) {
22467
22474
  const localTarget = (use) => {
22468
22475
  use = instances.source(use);
22469
22476
  const href = use.getAttribute("href") ?? use.getAttributeNS("http://www.w3.org/1999/xlink", "href");
22470
- if (!href?.startsWith("#") || href.length === 1) return;
22477
+ if (!href) return;
22471
22478
  let id;
22472
22479
  try {
22473
- id = decodeURIComponent(href.slice(1));
22480
+ const url = new URL(href, use.baseURI);
22481
+ const current = new URL(use.ownerDocument.URL);
22482
+ if (url.href.split("#")[0] !== current.href.split("#")[0]) return;
22483
+ if (url.hash.length <= 1) return;
22484
+ id = decodeURIComponent(url.hash.slice(1));
22474
22485
  } catch {
22475
22486
  return;
22476
22487
  }
@@ -25119,7 +25130,10 @@ defineMacro({
25119
25130
  class: ctx.className ?? "story",
25120
25131
  children: [!renderDeferred && readyPassage && /* @__PURE__ */ jsx("div", {
25121
25132
  hidden: true,
25122
- children: renderPassageContent(readyPassage)
25133
+ children: /* @__PURE__ */ jsx(InterfaceContext.Provider, {
25134
+ value: false,
25135
+ children: renderPassageContent(readyPassage)
25136
+ })
25123
25137
  }, `ready-${navigationId}`), /* @__PURE__ */ jsx("div", {
25124
25138
  class: "passage-container",
25125
25139
  ref: containerRef,
@@ -26054,44 +26068,49 @@ function hotkeyTitle(label, key) {
26054
26068
  return key ? `${label} (${key})` : label;
26055
26069
  }
26056
26070
  function defineMenubarAction(config) {
26071
+ function Button({ className, id }) {
26072
+ const [dialogOpen, setDialogOpen] = useState(false);
26073
+ const setup = config.setup?.() ?? { perform: () => {} };
26074
+ const { disabled, title = config.title } = setup;
26075
+ const cls = className ? `menubar-button ${className}` : "menubar-button";
26076
+ const perform = config.dialog ? () => setDialogOpen(true) : config.confirm ? () => {
26077
+ if (confirm(config.confirm)) setup.perform();
26078
+ } : setup.perform;
26079
+ const action = useControlAction({
26080
+ type: config.actionType,
26081
+ key: config.name,
26082
+ authorId: id,
26083
+ label: typeof config.label === "string" ? config.label : config.name,
26084
+ disabled,
26085
+ perform: config.dialog ? () => setDialogOpen(true) : setup.perform
26086
+ });
26087
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
26088
+ type: "button",
26089
+ ...actionAttributes(action, {
26090
+ id,
26091
+ cls
26092
+ }),
26093
+ onClick: perform,
26094
+ disabled,
26095
+ title,
26096
+ children: config.label
26097
+ }), config.dialog && dialogOpen && /* @__PURE__ */ jsx(PassageDialog, {
26098
+ passageName: config.dialog.passageName,
26099
+ fallbackMarkup: config.dialog.fallbackMarkup,
26100
+ panelClass: config.dialog.panelClass,
26101
+ label: typeof config.label === "string" ? config.label : config.name,
26102
+ onClose: () => setDialogOpen(false),
26103
+ showCloseButton: config.dialog.showCloseButton
26104
+ })] });
26105
+ }
26057
26106
  defineMacro({
26058
26107
  name: config.name,
26059
26108
  interpolate: true,
26060
26109
  render(_, ctx) {
26061
- if (config.hidden?.()) return null;
26062
- const [dialogOpen, setDialogOpen] = useState(false);
26063
- const setup = config.setup?.() ?? { perform: () => {} };
26064
- const { disabled, title = config.title } = setup;
26065
- const cls = ctx.className ? `menubar-button ${ctx.className}` : "menubar-button";
26066
- const perform = config.dialog ? () => setDialogOpen(true) : config.confirm ? () => {
26067
- if (confirm(config.confirm)) setup.perform();
26068
- } : setup.perform;
26069
- const action = useControlAction({
26070
- type: config.actionType,
26071
- key: config.name,
26072
- authorId: ctx.id,
26073
- label: typeof config.label === "string" ? config.label : config.name,
26074
- disabled,
26075
- perform: config.dialog ? () => setDialogOpen(true) : setup.perform
26110
+ return config.useHidden?.() ? null : /* @__PURE__ */ jsx(Button, {
26111
+ className: ctx.className,
26112
+ id: ctx.id
26076
26113
  });
26077
- return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
26078
- type: "button",
26079
- ...actionAttributes(action, {
26080
- id: ctx.id,
26081
- cls
26082
- }),
26083
- onClick: perform,
26084
- disabled,
26085
- title,
26086
- children: config.label
26087
- }), config.dialog && dialogOpen && /* @__PURE__ */ jsx(PassageDialog, {
26088
- passageName: config.dialog.passageName,
26089
- fallbackMarkup: config.dialog.fallbackMarkup,
26090
- panelClass: config.dialog.panelClass,
26091
- label: typeof config.label === "string" ? config.label : config.name,
26092
- onClose: () => setDialogOpen(false),
26093
- showCloseButton: config.dialog.showCloseButton
26094
- })] });
26095
26114
  }
26096
26115
  });
26097
26116
  }
@@ -26160,7 +26179,7 @@ defineMenubarAction({
26160
26179
  name: "settings",
26161
26180
  label: "Settings",
26162
26181
  actionType: "dialog",
26163
- hidden: () => !settings.hasAny(),
26182
+ useHidden: () => !useSyncExternalStore(subscribeSettings, settings.hasAny),
26164
26183
  dialog: {
26165
26184
  passageName: "Settings",
26166
26185
  fallbackMarkup: "{settings-controls}",
@@ -26688,6 +26707,7 @@ function SettingControl({ name, def }) {
26688
26707
  });
26689
26708
  }
26690
26709
  function SettingsControlsContent({ className, id }) {
26710
+ useSyncExternalStore(subscribeSettings, getSettingsRevision);
26691
26711
  const defs = settings.getDefinitions();
26692
26712
  return /* @__PURE__ */ jsx("div", {
26693
26713
  id,
@@ -10516,12 +10516,13 @@ function jsCodeEnd(onOpenEnd) {
10516
10516
  var defaultCodeEnd = jsCodeEnd();
10517
10517
  /**
10518
10518
  * Index possible brace ends for repeated recovery attempts in one template.
10519
- * Within plain code, nested braces must close first. At a quote, slash or
10520
- * escape we stop making lexical assumptions, but the remaining raw `}`s
10521
- * still bound how many pending braces could close. Indexing visits each
10522
- * opener once, so unmatched plain-code openers can skip suffix scans.
10519
+ * Within plain code, nested braces must close first. At a quote, slash,
10520
+ * escape or HTML-style comment we stop making lexical assumptions, but the
10521
+ * remaining raw `}`s still bound how many pending braces could close.
10522
+ * Indexing visits each opener once, so unmatched plain-code openers can
10523
+ * skip suffix scans.
10523
10524
  */
10524
- function indexCodeEnds(input) {
10525
+ function indexCodeEnds(input, closeBrace = defaultCodeEnd.closeBrace) {
10525
10526
  const possible = /* @__PURE__ */ new Set();
10526
10527
  const pending = [];
10527
10528
  let remaining = 0;
@@ -10541,17 +10542,39 @@ function indexCodeEnds(input) {
10541
10542
  remaining--;
10542
10543
  const open = pending.pop();
10543
10544
  if (open !== void 0) possible.add(open);
10544
- } else if (/['"`/\\]/.test(c)) uncertain();
10545
+ } else if (/['"`/\\]/.test(c) || input.startsWith("<!--", i) || input.startsWith("-->", i)) uncertain();
10545
10546
  }
10546
10547
  return (start, codeStart = start, limit = input.length) => {
10547
10548
  if (start > lastBrace || codeStart >= limit) return -1;
10548
10549
  const source = limit === input.length ? input : input.slice(0, limit);
10549
- if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return defaultCodeEnd.closeBrace(source, codeStart, start);
10550
+ if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return closeBrace(source, codeStart, start);
10550
10551
  const base = Math.max(0, codeStart - 1);
10551
10552
  const end = parsedCodeEnd(source.slice(base), codeStart - base, "expression");
10552
10553
  return end < 0 ? -1 : base + end;
10553
10554
  };
10554
10555
  }
10556
+ /**
10557
+ * Reusable strict expression-boundary queries over one immutable source.
10558
+ * Results match `findCodeEnd(input, start)`, without markup's lenient
10559
+ * fallback. The shared brace index prunes unmatched plain-code prefixes;
10560
+ * each queried start is cached independently, including failed queries.
10561
+ */
10562
+ function indexStrictCodeEnds(input) {
10563
+ const read = indexCodeEnds(input, (source, start) => {
10564
+ const base = Math.max(0, start - 1);
10565
+ const end = findCodeEnd(source.slice(base), start - base);
10566
+ return end < 0 ? -1 : base + end;
10567
+ });
10568
+ const ends = /* @__PURE__ */ new Map();
10569
+ return (start) => {
10570
+ let end = ends.get(start);
10571
+ if (end === void 0) {
10572
+ end = read(start);
10573
+ ends.set(start, end);
10574
+ }
10575
+ return end;
10576
+ };
10577
+ }
10555
10578
  // src/markup/code-attributes.ts
10556
10579
  /**
10557
10580
  * Attributes whose value is code with braces of its own, not text: event
@@ -12288,9 +12311,8 @@ function readCompletion(source, cursor, macros, full, sourceLength = source.leng
12288
12311
  return read(source, (i) => i);
12289
12312
  }
12290
12313
  // src/widgets/ast-scanner.ts
12291
- /** The declared parameters of the macros registered so far. */
12292
- var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
12293
- registeredParameters.source = getMacroParameters.source;
12314
+ /** Snapshot effective macro metadata once per scan. */
12315
+ var registeredParameters = () => parameterLookup(getMacroRegistry());
12294
12316
  /**
12295
12317
  * Whether the text of an attribute value or macro label renders a
12296
12318
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -12317,7 +12339,7 @@ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpa
12317
12339
  * are read from it); a token made from an AST has none. Discovery hooks
12318
12340
  * also apply inside these texts, before widgets have been registered.
12319
12341
  */
12320
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
12342
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters(), src = "", hooks, budget) {
12321
12343
  for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
12322
12344
  return false;
12323
12345
  }
@@ -12328,7 +12350,7 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
12328
12350
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
12329
12351
  * reads it), and a definition renders nothing of its own.
12330
12352
  */
12331
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
12353
+ function astContainsChildren(nodes, parametersOf = registeredParameters(), hooks, budget) {
12332
12354
  const pending = [...nodes];
12333
12355
  while (pending.length) {
12334
12356
  const node = pending.pop();
@@ -12429,7 +12451,7 @@ function nameSpan(rawArgs) {
12429
12451
  * here as it is to the parser, and does not make a block widget (#387). In
12430
12452
  * nested definitions, it belongs to the innermost.
12431
12453
  */
12432
- function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
12454
+ function widgetDefinitions$1(passages, parametersOf = registeredParameters()) {
12433
12455
  const list = [...passages];
12434
12456
  const scan = (replacesDo) => {
12435
12457
  const found = [];
@@ -26558,4 +26580,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
26558
26580
  const list = [...passages];
26559
26581
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
26560
26582
  }
26561
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, completionTarget, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCallAt, macroCalls, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
26583
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, completionTarget, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, indexStrictCodeEnds, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCallAt, macroCalls, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
@@ -27,6 +27,7 @@ export {
27
27
  parseBoundVariable,
28
28
  effectiveWidgetDefinitions,
29
29
  findCodeEnd,
30
+ indexStrictCodeEnds,
30
31
  lexJs,
31
32
  lexTemplate,
32
33
  scanStringLiteral,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.30",
3
+ "version": "0.64.31",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,8 +1,9 @@
1
1
  import { actionAttributes, useControlAction } from '../../hooks/use-action';
2
2
  import { useState } from 'preact/hooks';
3
+ import { useSyncExternalStore } from 'preact/compat';
3
4
  import { useStoryStore } from '../../store';
4
5
  import { useStoryFields } from '../../hooks/use-story-fields';
5
- import { settings } from '../../settings';
6
+ import { settings, subscribeSettings } from '../../settings';
6
7
  import { quickLoad, quickSave } from '../../quick-actions';
7
8
  import { defineMacro } from '../../define-macro';
8
9
  import { PassageDialog } from '../PassageDialog';
@@ -15,7 +16,7 @@ interface MenubarActionConfig {
15
16
  actionType: ActionType;
16
17
  title?: string;
17
18
  confirm?: string;
18
- hidden?: () => boolean;
19
+ useHidden?: () => boolean;
19
20
  setup?: () => {
20
21
  perform: () => void | Promise<void>;
21
22
  disabled?: boolean;
@@ -34,62 +35,69 @@ function hotkeyTitle(label: string, key: string | null): string {
34
35
  }
35
36
 
36
37
  export function defineMenubarAction(config: MenubarActionConfig) {
38
+ // Visibility can change after mount. Keep the button's hooks and action
39
+ // registration in a child whose lifetime follows that visibility.
40
+ function Button({ className, id }: { className?: string; id?: string }) {
41
+ const [dialogOpen, setDialogOpen] = useState(false);
42
+
43
+ const setup = config.setup?.() ?? { perform: () => {} };
44
+ const { disabled, title = config.title } = setup;
45
+
46
+ const cls = className ? `menubar-button ${className}` : 'menubar-button';
47
+
48
+ const perform = config.dialog
49
+ ? () => setDialogOpen(true)
50
+ : config.confirm
51
+ ? () => {
52
+ if (confirm(config.confirm!)) setup.perform();
53
+ }
54
+ : setup.perform;
55
+
56
+ const action = useControlAction({
57
+ type: config.actionType,
58
+ key: config.name,
59
+ authorId: id,
60
+ label: typeof config.label === 'string' ? config.label : config.name,
61
+ disabled,
62
+ perform: config.dialog ? () => setDialogOpen(true) : setup.perform,
63
+ });
64
+
65
+ return (
66
+ <>
67
+ <button
68
+ type="button"
69
+ {...actionAttributes(action, { id, cls })}
70
+ onClick={perform}
71
+ disabled={disabled}
72
+ title={title}
73
+ >
74
+ {config.label}
75
+ </button>
76
+ {config.dialog && dialogOpen && (
77
+ <PassageDialog
78
+ passageName={config.dialog.passageName}
79
+ fallbackMarkup={config.dialog.fallbackMarkup}
80
+ panelClass={config.dialog.panelClass}
81
+ label={
82
+ typeof config.label === 'string' ? config.label : config.name
83
+ }
84
+ onClose={() => setDialogOpen(false)}
85
+ showCloseButton={config.dialog.showCloseButton}
86
+ />
87
+ )}
88
+ </>
89
+ );
90
+ }
91
+
37
92
  defineMacro({
38
93
  name: config.name,
39
94
  interpolate: true,
40
95
  render(_, ctx) {
41
- if (config.hidden?.()) return null;
42
-
43
- const [dialogOpen, setDialogOpen] = useState(false);
44
-
45
- const setup = config.setup?.() ?? { perform: () => {} };
46
- const { disabled, title = config.title } = setup;
47
-
48
- const cls = ctx.className
49
- ? `menubar-button ${ctx.className}`
50
- : 'menubar-button';
51
-
52
- const perform = config.dialog
53
- ? () => setDialogOpen(true)
54
- : config.confirm
55
- ? () => {
56
- if (confirm(config.confirm!)) setup.perform();
57
- }
58
- : setup.perform;
59
-
60
- const action = useControlAction({
61
- type: config.actionType,
62
- key: config.name,
63
- authorId: ctx.id,
64
- label: typeof config.label === 'string' ? config.label : config.name,
65
- disabled,
66
- perform: config.dialog ? () => setDialogOpen(true) : setup.perform,
67
- });
68
-
69
- return (
70
- <>
71
- <button
72
- type="button"
73
- {...actionAttributes(action, { id: ctx.id, cls })}
74
- onClick={perform}
75
- disabled={disabled}
76
- title={title}
77
- >
78
- {config.label}
79
- </button>
80
- {config.dialog && dialogOpen && (
81
- <PassageDialog
82
- passageName={config.dialog.passageName}
83
- fallbackMarkup={config.dialog.fallbackMarkup}
84
- panelClass={config.dialog.panelClass}
85
- label={
86
- typeof config.label === 'string' ? config.label : config.name
87
- }
88
- onClose={() => setDialogOpen(false)}
89
- showCloseButton={config.dialog.showCloseButton}
90
- />
91
- )}
92
- </>
96
+ return config.useHidden?.() ? null : (
97
+ <Button
98
+ className={ctx.className}
99
+ id={ctx.id}
100
+ />
93
101
  );
94
102
  },
95
103
  });
@@ -173,7 +181,7 @@ defineMenubarAction({
173
181
  name: 'settings',
174
182
  label: 'Settings',
175
183
  actionType: 'dialog',
176
- hidden: () => !settings.hasAny(),
184
+ useHidden: () => !useSyncExternalStore(subscribeSettings, settings.hasAny),
177
185
  dialog: {
178
186
  passageName: 'Settings',
179
187
  fallbackMarkup: '{settings-controls}',
@@ -15,6 +15,7 @@ import { Passage, renderPassageContent, type PassageProps } from '../Passage';
15
15
  import { defineMacro } from '../../define-macro';
16
16
  import { resolveTransition, type ResolvedTransition } from '../../transition';
17
17
  import { skipString } from './arg-utils';
18
+ import { InterfaceContext } from '../../markup/render';
18
19
 
19
20
  /** Input types whose `value` is not what the user sees or edits. */
20
21
  const VALUELESS_INPUTS = new Set([
@@ -1107,7 +1108,9 @@ defineMacro({
1107
1108
  key={`ready-${navigationId}`}
1108
1109
  hidden
1109
1110
  >
1110
- {renderPassageContent(readyPassage)}
1111
+ <InterfaceContext.Provider value={false}>
1112
+ {renderPassageContent(readyPassage)}
1113
+ </InterfaceContext.Provider>
1111
1114
  </div>
1112
1115
  )}
1113
1116
  <div
@@ -1,5 +1,11 @@
1
1
  import { useEffect, useId, useState } from 'preact/hooks';
2
- import { settings, subscribeSettings, type SettingDef } from '../../settings';
2
+ import { useSyncExternalStore } from 'preact/compat';
3
+ import {
4
+ settings,
5
+ subscribeSettings,
6
+ getSettingsRevision,
7
+ type SettingDef,
8
+ } from '../../settings';
3
9
  import { defineMacro } from '../../define-macro';
4
10
 
5
11
  function SettingRow({
@@ -117,6 +123,7 @@ function SettingsControlsContent({
117
123
  className?: string;
118
124
  id?: string;
119
125
  }) {
126
+ useSyncExternalStore(subscribeSettings, getSettingsRevision);
120
127
  const defs = settings.getDefinitions();
121
128
 
122
129
  return (
@@ -206,13 +206,15 @@ export const defaultCodeEnd: CodeEnd = jsCodeEnd();
206
206
 
207
207
  /**
208
208
  * Index possible brace ends for repeated recovery attempts in one template.
209
- * Within plain code, nested braces must close first. At a quote, slash or
210
- * escape we stop making lexical assumptions, but the remaining raw `}`s
211
- * still bound how many pending braces could close. Indexing visits each
212
- * opener once, so unmatched plain-code openers can skip suffix scans.
209
+ * Within plain code, nested braces must close first. At a quote, slash,
210
+ * escape or HTML-style comment we stop making lexical assumptions, but the
211
+ * remaining raw `}`s still bound how many pending braces could close.
212
+ * Indexing visits each opener once, so unmatched plain-code openers can
213
+ * skip suffix scans.
213
214
  */
214
215
  export function indexCodeEnds(
215
216
  input: string,
217
+ closeBrace: CodeEnd['closeBrace'] = defaultCodeEnd.closeBrace,
216
218
  ): (start: number, codeStart?: number, limit?: number) => number {
217
219
  const possible = new Set<number>();
218
220
  const pending: number[] = [];
@@ -241,7 +243,16 @@ export function indexCodeEnds(
241
243
  remaining--;
242
244
  const open = pending.pop();
243
245
  if (open !== undefined) possible.add(open);
244
- } else if (/['"`/\\]/.test(c)) uncertain();
246
+ } else if (
247
+ /['"`/\\]/.test(c) ||
248
+ input.startsWith('<!--', i) ||
249
+ input.startsWith('-->', i)
250
+ ) {
251
+ // Acorn accepts HTML-style line comments in script code. Their
252
+ // braces are as uncertain as those after a slash; do not parse the
253
+ // comment here, or assume --> needs to be a comment at this start.
254
+ uncertain();
255
+ }
245
256
  }
246
257
  return (start, codeStart = start, limit = input.length) => {
247
258
  if (start > lastBrace || codeStart >= limit) return -1;
@@ -256,7 +267,7 @@ export function indexCodeEnds(
256
267
  possible.has(start - 1) ||
257
268
  input.slice(start, codeStart).includes('{')
258
269
  ) {
259
- return defaultCodeEnd.closeBrace(source, codeStart, start);
270
+ return closeBrace(source, codeStart, start);
260
271
  }
261
272
  // Acorn locates its starting line and syntax errors by scanning the
262
273
  // prefix. Recovery must not hand it the whole passage for every opener.
@@ -270,3 +281,28 @@ export function indexCodeEnds(
270
281
  return end < 0 ? -1 : base + end;
271
282
  };
272
283
  }
284
+
285
+ /**
286
+ * Reusable strict expression-boundary queries over one immutable source.
287
+ * Results match `findCodeEnd(input, start)`, without markup's lenient
288
+ * fallback. The shared brace index prunes unmatched plain-code prefixes;
289
+ * each queried start is cached independently, including failed queries.
290
+ */
291
+ export function indexStrictCodeEnds(input: string): (start: number) => number {
292
+ const read = indexCodeEnds(input, (source, start) => {
293
+ // Acorn computes error locations by reading the prefix. Keep just one
294
+ // preceding character so a leading #! does not become a hashbang.
295
+ const base = Math.max(0, start - 1);
296
+ const end = findCodeEnd(source.slice(base), start - base);
297
+ return end < 0 ? -1 : base + end;
298
+ });
299
+ const ends = new Map<number, number>();
300
+ return (start) => {
301
+ let end = ends.get(start);
302
+ if (end === undefined) {
303
+ end = read(start);
304
+ ends.set(start, end);
305
+ }
306
+ return end;
307
+ };
308
+ }