@rohal12/spindle 0.59.23 → 0.59.25

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.
@@ -1,5 +1,5 @@
1
1
  import { Fragment, createContext, h, render } from "preact";
2
- import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
2
+ import { useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
3
3
  import { useSyncExternalStore } from "preact/compat";
4
4
  import { createStore } from "zustand/vanilla";
5
5
  import { immer } from "zustand/middleware/immer";
@@ -10149,10 +10149,10 @@ function createListeners() {
10149
10149
  //#region src/runtime-errors.ts
10150
10150
  var errors = [];
10151
10151
  var nextId = 1;
10152
- var listeners$1 = createListeners();
10152
+ var listeners$2 = createListeners();
10153
10153
  function update(next) {
10154
10154
  errors = next;
10155
- listeners$1.notify();
10155
+ listeners$2.notify();
10156
10156
  }
10157
10157
  /**
10158
10158
  * Show `error` on the page, after `context` (what failed). The same error
@@ -10188,7 +10188,7 @@ function getRuntimeErrors() {
10188
10188
  return errors;
10189
10189
  }
10190
10190
  /** Call `listener` whenever the shown errors change; returns unsubscribe. */
10191
- var subscribeRuntimeErrors = listeners$1.subscribe;
10191
+ var subscribeRuntimeErrors = listeners$2.subscribe;
10192
10192
  //#endregion
10193
10193
  //#region src/components/macros/arg-utils.ts
10194
10194
  /**
@@ -10801,19 +10801,13 @@ function* codeAndText(src, tokens, parametersOf) {
10801
10801
  yield textPiece(value, at, `In the ${name} attribute of <${token.tag}>: `);
10802
10802
  continue;
10803
10803
  }
10804
- let from = 0;
10805
- for (const part of splitSigilTemplate(value)) {
10806
- if (!("expr" in part)) continue;
10807
- const k = locate(value, part.expr, from);
10808
- from = k + part.expr.length;
10809
- yield {
10810
- kind: "code",
10811
- code: part.expr,
10812
- offset: at + k,
10813
- goal: "expression",
10814
- label: `{${part.expr}} in the ${name} attribute of <${token.tag}>`
10815
- };
10816
- }
10804
+ for (const { expr, at: k } of sigilExpressions(value)) yield {
10805
+ kind: "code",
10806
+ code: expr,
10807
+ offset: at + k,
10808
+ goal: "expression",
10809
+ label: `{${expr}} in the ${name} attribute of <${token.tag}>`
10810
+ };
10817
10811
  }
10818
10812
  else if (token.type === "macro" && !token.isClose) {
10819
10813
  const name = token.name.toLowerCase();
@@ -11081,6 +11075,24 @@ function attributeValues(src, token) {
11081
11075
  return values;
11082
11076
  }
11083
11077
  /**
11078
+ * The `{$…}` expressions in the value of a code attribute (`onclick`, see
11079
+ * isCodeAttribute), with where each is in the value.
11080
+ */
11081
+ function sigilExpressions(value) {
11082
+ const found = [];
11083
+ let from = 0;
11084
+ for (const part of splitSigilTemplate(value)) {
11085
+ if (!("expr" in part)) continue;
11086
+ const at = locate(value, part.expr, from);
11087
+ from = at + part.expr.length;
11088
+ found.push({
11089
+ expr: part.expr,
11090
+ at
11091
+ });
11092
+ }
11093
+ return found;
11094
+ }
11095
+ /**
11084
11096
  * Index of `part` in `text` from `from` on, else anywhere, else `from`: the
11085
11097
  * place to report an error in `part` at.
11086
11098
  */
@@ -11296,37 +11308,70 @@ function widgetDef({ name = "", parameters = "" }) {
11296
11308
  function parseWidgetDef(rawArgs) {
11297
11309
  return widgetDef(parseMacroArgs(rawArgs, WIDGET_PARAMETERS));
11298
11310
  }
11311
+ /** Where the name is written in the arguments, without its quotes. */
11312
+ function nameSpan(rawArgs) {
11313
+ const spans = /* @__PURE__ */ new Map();
11314
+ parseMacroArgs(rawArgs, WIDGET_PARAMETERS, spans);
11315
+ const [start, end] = spans.get(WIDGET_PARAMETERS[0]) ?? [0, 0];
11316
+ const quote = rawArgs[start];
11317
+ return (quote === "\"" || quote === "'") && end - start >= 2 ? [start + 1, rawArgs[end - 1] === quote ? end - 1 : end] : [start, end];
11318
+ }
11299
11319
  /**
11300
- * The names of the block widgets (those whose body renders `{@children}`)
11301
- * that StoryInit and the passages tagged `widget` define. They must be
11302
- * known as block macros before any passage is parsed, so that passages
11303
- * invoking them nest their content whatever the passage order.
11320
+ * The widgets that StoryInit and the passages tagged `widget` define, in
11321
+ * source order: the ones the runtime registers, read tolerantly (a half-typed
11322
+ * definition is still reported, without a `closeStart`). Definitions whose
11323
+ * arguments cannot be read are left out.
11304
11324
  *
11305
11325
  * The passages are read as flat tokens, which need no block macros to be
11306
11326
  * known, so a `{@children}` in an HTML comment or in a `{do}` body is text
11307
- * here as it is to the parser, and does not make a block widget (#387).
11327
+ * here as it is to the parser, and does not make a block widget (#387). In
11328
+ * nested definitions, it belongs to the innermost.
11308
11329
  */
11309
- function blockWidgetNames(passages, parametersOf = registeredParameters) {
11310
- const names = [];
11330
+ function widgetDefinitions(passages, parametersOf = registeredParameters) {
11331
+ const found = [];
11311
11332
  for (const passage of passages) {
11312
11333
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
11313
11334
  const open = [];
11314
- for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
11315
- if (!token.isClose) {
11316
- open.push({
11317
- rawArgs: token.rawArgs,
11318
- isBlock: false
11319
- });
11320
- continue;
11321
- }
11335
+ const done = [];
11336
+ for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") if (!token.isClose) open.push({
11337
+ token,
11338
+ isBlock: false
11339
+ });
11340
+ else {
11322
11341
  const def = open.pop();
11323
- if (!def?.isBlock) continue;
11324
- try {
11325
- names.push(parseWidgetDef(def.rawArgs).name);
11326
- } catch {}
11327
- } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11342
+ if (def) done.push({
11343
+ ...def,
11344
+ closeStart: token.start
11345
+ });
11346
+ }
11347
+ else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11348
+ done.push(...open);
11349
+ const defs = [];
11350
+ for (const { token, isBlock, closeStart } of done) try {
11351
+ const [from, to] = nameSpan(token.rawArgs);
11352
+ defs.push({
11353
+ ...parseWidgetDef(token.rawArgs),
11354
+ block: isBlock,
11355
+ passage: passage.name,
11356
+ start: token.start,
11357
+ end: token.end,
11358
+ nameStart: token.argsStart + from,
11359
+ nameEnd: token.argsStart + to,
11360
+ ...closeStart === void 0 ? {} : { closeStart }
11361
+ });
11362
+ } catch {}
11363
+ found.push(...defs.sort((a, b) => a.start - b.start));
11328
11364
  }
11329
- return names;
11365
+ return found;
11366
+ }
11367
+ /**
11368
+ * The names of the block widgets (those whose body renders `{@children}`)
11369
+ * that StoryInit and the passages tagged `widget` define, closed. They must
11370
+ * be known as block macros before any passage is parsed, so that passages
11371
+ * invoking them nest their content whatever the passage order.
11372
+ */
11373
+ function blockWidgetNames(passages, parametersOf = registeredParameters) {
11374
+ return widgetDefinitions(passages, parametersOf).filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name);
11330
11375
  }
11331
11376
  //#endregion
11332
11377
  //#region src/widgets/register-widget-def.ts
@@ -12915,9 +12960,13 @@ function resolveAttributeValue(name, value, scope, errors) {
12915
12960
  for (const error of result.errors) errors.push([name, error]);
12916
12961
  return result.text;
12917
12962
  }
12963
+ /** Whether a node shows nothing as text: whitespace, or a closed HTML comment. */
12964
+ function isBlankText(n) {
12965
+ return n.type === "text" && (n.comment === true || n.value.trim() === "");
12966
+ }
12918
12967
  /** The index of the summary element opening `nodes`, or -1 when none does. */
12919
12968
  function leadingSummaryIndex(nodes) {
12920
- const at = nodes.findIndex((n) => n.type !== "text" || n.value.trim() !== "");
12969
+ const at = nodes.findIndex((n) => !isBlankText(n));
12921
12970
  const first = nodes[at];
12922
12971
  return first?.type === "html" && first.tag.toLowerCase() === "summary" ? at : -1;
12923
12972
  }
@@ -12939,7 +12988,8 @@ function HtmlNodeRenderer({ node }) {
12939
12988
  const isInline = INLINE_ELEMENTS.has(tag);
12940
12989
  let children = void 0;
12941
12990
  let structural = false;
12942
- if (node.children.length > 0) if (inRaw || isRawRoot) children = renderInlineNodes(node.children);
12991
+ if (node.children.length > 0) if (tag === "style") children = node.children.map((n) => n.type === "text" ? n.value : renderSingleNode(n));
12992
+ else if (inRaw || isRawRoot) children = renderInlineNodes(node.children);
12943
12993
  else {
12944
12994
  const summaryAt = tag === "details" ? leadingSummaryIndex(node.children) : -1;
12945
12995
  const body = (nodes) => renderNodes(nodes, {
@@ -12947,7 +12997,7 @@ function HtmlNodeRenderer({ node }) {
12947
12997
  locals,
12948
12998
  inline: isInline
12949
12999
  });
12950
- structural = STRUCTURAL_ELEMENTS.has(tag) && node.children.every((n) => n.type !== "text" || n.value.trim() === "");
13000
+ structural = STRUCTURAL_ELEMENTS.has(tag) && node.children.every((n) => n.type !== "text" || isBlankText(n));
12951
13001
  children = structural ? node.children.filter((n) => n.type !== "text").map((n) => renderSingleNode(n)) : summaryAt === -1 ? body(node.children) : /* @__PURE__ */ jsxs(Fragment$1, { children: [
12952
13002
  body(node.children.slice(0, summaryAt)),
12953
13003
  renderSingleNode(node.children[summaryAt]),
@@ -13120,7 +13170,7 @@ function buildPlainTextVnodes(core, ph, unwrapParagraphs) {
13120
13170
  function renderNodes(nodes, options) {
13121
13171
  if (nodes.length === 0) return null;
13122
13172
  if (options?.raw) return renderInlineNodes(nodes);
13123
- if (options?.structural && nodes.every((n) => n.type !== "text" || n.value.trim() === "")) return nodes.filter((n) => n.type !== "text").map(renderSingleNode);
13173
+ if (options?.structural && nodes.every((n) => n.type !== "text" || isBlankText(n))) return nodes.filter((n) => n.type !== "text").map(renderSingleNode);
13124
13174
  if (!nodes.some((n) => n.type === "text" && (n.value.trim() !== "" || BLANK_LINE_RE.test(n.value)))) return nodes.map((node) => renderSingleNode(node));
13125
13175
  const components = [];
13126
13176
  const ph = {
@@ -15726,13 +15776,13 @@ var VALID_EVENTS = new Set([
15726
15776
  "passagerender",
15727
15777
  "dialogrender"
15728
15778
  ]);
15729
- var listeners = /* @__PURE__ */ new Map();
15779
+ var listeners$1 = /* @__PURE__ */ new Map();
15730
15780
  function on(event, cb) {
15731
15781
  if (!VALID_EVENTS.has(event)) throw new Error(`spindle: Unknown event "${event}".`);
15732
- let set = listeners.get(event);
15782
+ let set = listeners$1.get(event);
15733
15783
  if (!set) {
15734
15784
  set = /* @__PURE__ */ new Set();
15735
- listeners.set(event, set);
15785
+ listeners$1.set(event, set);
15736
15786
  }
15737
15787
  set.add(cb);
15738
15788
  return () => {
@@ -15741,7 +15791,7 @@ function on(event, cb) {
15741
15791
  }
15742
15792
  /** Call `call` with each listener of `event`. */
15743
15793
  function forEachListener(event, call) {
15744
- const set = listeners.get(event);
15794
+ const set = listeners$1.get(event);
15745
15795
  if (!set) return;
15746
15796
  for (const cb of [...set]) call(cb);
15747
15797
  }
@@ -18562,6 +18612,24 @@ var openModals = [];
18562
18612
  * - closes the topmost dialog on Escape when it is dismissible;
18563
18613
  * - returns focus to the previously focused element on close.
18564
18614
  */
18615
+ /** The input types made of several segments, each a native Tab stop. */
18616
+ var SEGMENTED_INPUTS = new Set([
18617
+ "date",
18618
+ "time",
18619
+ "datetime-local",
18620
+ "month",
18621
+ "week"
18622
+ ]);
18623
+ /** Whether the element has native tab stops inside it, in its shadow tree. */
18624
+ function hasNativeStops(el) {
18625
+ if (el instanceof HTMLMediaElement) return el.controls;
18626
+ return el instanceof HTMLInputElement && SEGMENTED_INPUTS.has(el.type) && !el.readOnly;
18627
+ }
18628
+ /** The tab stops of an embedded document, in tab order. */
18629
+ function frameStops(doc) {
18630
+ if (!doc) return [];
18631
+ return Array.from(doc.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
18632
+ }
18565
18633
  function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18566
18634
  useLayoutEffect(() => {
18567
18635
  const panel = panelRef.current;
@@ -18589,6 +18657,21 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18589
18657
  * (#424). `from` may be an element of an embedded document, whose frame
18590
18658
  * element then stands in for it.
18591
18659
  */
18660
+ /** Focus `el`; a frame is entered at its first (or last) control (#460). */
18661
+ const enter = (el, backwards) => {
18662
+ if (el instanceof HTMLIFrameElement) {
18663
+ let inner = [];
18664
+ try {
18665
+ inner = frameStops(el.contentDocument);
18666
+ } catch {}
18667
+ const edge = backwards ? inner[inner.length - 1] : inner[0];
18668
+ if (edge) {
18669
+ edge.focus();
18670
+ return;
18671
+ }
18672
+ }
18673
+ el.focus();
18674
+ };
18592
18675
  const moveFocus = (from, backwards) => {
18593
18676
  const items = focusables(panel);
18594
18677
  const first = items[0];
@@ -18604,9 +18687,9 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18604
18687
  const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
18605
18688
  next = backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
18606
18689
  } else next = backwards ? last : first;
18607
- (next ?? (backwards ? last : first)).focus();
18690
+ enter(next ?? (backwards ? last : first), backwards);
18608
18691
  };
18609
- let steppingMedia = null;
18692
+ let steppingNative = null;
18610
18693
  const onKeyDown = (e) => {
18611
18694
  if (!top()) return;
18612
18695
  if (e.key === "Escape") {
@@ -18618,8 +18701,8 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18618
18701
  }
18619
18702
  if (e.key !== "Tab") return;
18620
18703
  const active = document.activeElement;
18621
- if (active instanceof HTMLMediaElement && active.controls) {
18622
- steppingMedia = {
18704
+ if (hasNativeStops(active)) {
18705
+ steppingNative = {
18623
18706
  el: active,
18624
18707
  backwards: e.shiftKey
18625
18708
  };
@@ -18629,7 +18712,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18629
18712
  moveFocus(active, e.shiftKey);
18630
18713
  };
18631
18714
  const onPointerDown = () => {
18632
- steppingMedia = null;
18715
+ steppingNative = null;
18633
18716
  };
18634
18717
  const controller = new AbortController();
18635
18718
  const { signal } = controller;
@@ -18644,7 +18727,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18644
18727
  const onFrameKeyDown = (e) => {
18645
18728
  if (!top()) return;
18646
18729
  if (e.key !== "Tab") return onKeyDown(e);
18647
- const inner = Array.from(doc.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
18730
+ const inner = frameStops(doc);
18648
18731
  const active = doc.activeElement;
18649
18732
  const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
18650
18733
  if (!edge || active === edge || active === doc.body) {
@@ -18672,9 +18755,9 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18672
18755
  attachFrames();
18673
18756
  const onFocusIn = (e) => {
18674
18757
  const target = e.target;
18675
- if (steppingMedia && target !== steppingMedia.el && top()) {
18676
- const { el, backwards } = steppingMedia;
18677
- steppingMedia = null;
18758
+ if (steppingNative && target !== steppingNative.el && top()) {
18759
+ const { el, backwards } = steppingNative;
18760
+ steppingNative = null;
18678
18761
  moveFocus(el, backwards);
18679
18762
  return;
18680
18763
  }
@@ -18688,9 +18771,9 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18688
18771
  signal
18689
18772
  });
18690
18773
  const onFocusOut = (e) => {
18691
- const pending = steppingMedia;
18774
+ const pending = steppingNative;
18692
18775
  if (!pending || e.target !== pending.el || e.relatedTarget || !top()) return;
18693
- steppingMedia = null;
18776
+ steppingNative = null;
18694
18777
  moveFocus(pending.el, pending.backwards);
18695
18778
  };
18696
18779
  document.addEventListener("focusout", onFocusOut, { signal });
@@ -18704,7 +18787,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18704
18787
  //#endregion
18705
18788
  //#region src/components/PassageDialog.tsx
18706
18789
  var DialogCloseContext = createContext(null);
18707
- function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, dismissible = true, showCloseButton = dismissible }) {
18790
+ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
18708
18791
  const onCloseRef = useRef(onClose);
18709
18792
  onCloseRef.current = onClose;
18710
18793
  const stableOnClose = useCallback(() => onCloseRef.current(), []);
@@ -18731,9 +18814,19 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, dismi
18731
18814
  }
18732
18815
  }, [markup, nobr]);
18733
18816
  const panelRef = useRef(null);
18817
+ const labelId = useId();
18734
18818
  const viewScope = useViewScope();
18735
18819
  useModalFocus(panelRef, ".dialog-body", dismissible, stableOnClose);
18736
18820
  useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
18821
+ useLayoutEffect(() => {
18822
+ const panel = panelRef.current;
18823
+ if (!panel || label) return;
18824
+ const heading = panel.querySelector(".dialog-body :is(h1, h2, h3, h4, h5, h6)");
18825
+ if (!heading) return;
18826
+ heading.id ||= `${labelId}-heading`;
18827
+ panel.setAttribute("aria-labelledby", heading.id);
18828
+ return () => panel.removeAttribute("aria-labelledby");
18829
+ }, [label, markup]);
18737
18830
  useLayoutEffect(() => {
18738
18831
  if (panelRef.current) emitFromRender("dialogrender", passageName ?? "", panelRef.current);
18739
18832
  }, []);
@@ -18752,6 +18845,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, dismi
18752
18845
  class: cls,
18753
18846
  role: "dialog",
18754
18847
  "aria-modal": "true",
18848
+ "aria-label": label ?? passageName,
18755
18849
  tabIndex: -1,
18756
18850
  children: [showCloseButton && /* @__PURE__ */ jsx("button", {
18757
18851
  type: "button",
@@ -19067,6 +19161,12 @@ var definitions = /* @__PURE__ */ new Map();
19067
19161
  var values = createNamespace();
19068
19162
  var storageLoaded = false;
19069
19163
  var unsubscribeStoryData = null;
19164
+ var listeners = /* @__PURE__ */ new Set();
19165
+ /** Call `listener` after a setting changes; returns the unsubscribe. */
19166
+ function subscribeSettings(listener) {
19167
+ listeners.add(listener);
19168
+ return () => listeners.delete(listener);
19169
+ }
19070
19170
  function storageKey() {
19071
19171
  return `spindle.${useStoryStore.getState().storyData?.ifid || "unknown"}.settings`;
19072
19172
  }
@@ -19140,6 +19240,7 @@ var settings = {
19140
19240
  set(name, value) {
19141
19241
  values[name] = value;
19142
19242
  persist();
19243
+ for (const listener of [...listeners]) listener();
19143
19244
  },
19144
19245
  getAll() {
19145
19246
  return { ...values };
@@ -20231,10 +20332,11 @@ var Reader = class {
20231
20332
  //#endregion
20232
20333
  //#region src/story-variables.ts
20233
20334
  /**
20234
- * The tokens of markup, or none if it is malformed: validateMarkup reports
20235
- * that, with its position.
20335
+ * The tokens of markup, or none if it is malformed (validateMarkup reports
20336
+ * that, with its position); in tolerant mode, those of the well-formed parts.
20236
20337
  */
20237
- function tokensOf(text, textMode) {
20338
+ function tokensOf(text, textMode, { tolerant } = {}) {
20339
+ if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
20238
20340
  try {
20239
20341
  return tokenizeMarkup(text, { text: textMode });
20240
20342
  } catch (err) {
@@ -20246,8 +20348,8 @@ function declarationRegex(sigil) {
20246
20348
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20247
20349
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
20248
20350
  }
20249
- /** A `$name` reference with its dot path, at a `$` the lexer found. */
20250
- var VAR_PATH_RE = /\$(\w+(?:\.\w+)*)/y;
20351
+ /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
20352
+ var VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
20251
20353
  /** Quoted first argument of an input macro naming a story variable. */
20252
20354
  var QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
20253
20355
  var VALID_VAR_TYPES = new Set([
@@ -20401,19 +20503,30 @@ function parseStoryVariables(content, sigil = "$") {
20401
20503
  return schema;
20402
20504
  }
20403
20505
  /**
20404
- * Validate a single variable reference path (e.g. "player.health") against
20405
- * the schema. Returns an error message or null if valid.
20506
+ * Check a reference against the declarations: the error code and message, or
20507
+ * null if it is valid. (Unknown fields of objects are valid: classes
20508
+ * registered with Story.registerClass() can add members that are not in the
20509
+ * defaults.)
20406
20510
  */
20407
- function validateRef(ref, schema) {
20408
- const parts = ref.split(".");
20409
- const rootName = parts[0];
20410
- const nameError = variableNameError(rootName, "$" + rootName);
20411
- if (nameError) return nameError;
20412
- const rootSchema = schema.get(rootName);
20413
- if (!rootSchema) return `Undeclared variable: $${ref}`;
20414
- let current = rootSchema;
20415
- for (let i = 1; i < parts.length; i++) {
20416
- const part = parts[i];
20511
+ function checkReference(ref, declared) {
20512
+ const label = (path) => ref.sigil + [ref.name, ...path].join(".");
20513
+ const nameError = variableNameError(ref.name, ref.sigil + ref.name);
20514
+ if (nameError) return {
20515
+ code: "reserved-name",
20516
+ message: nameError
20517
+ };
20518
+ const schema = ref.sigil === "$" ? declared.variables : declared.transients;
20519
+ if (!schema) return null;
20520
+ if (!schema.has(ref.name)) return ref.sigil === "$" ? {
20521
+ code: "undeclared-variable",
20522
+ message: `Undeclared variable: ${label(ref.path)}`
20523
+ } : {
20524
+ code: "undeclared-transient",
20525
+ message: `Undeclared transient: ${label(ref.path)}`
20526
+ };
20527
+ let current = schema.get(ref.name);
20528
+ for (let i = 0; current && i < ref.path.length; i++) {
20529
+ const part = ref.path[i];
20417
20530
  if (current.type === "array") return null;
20418
20531
  if (current.type === "null") return null;
20419
20532
  const sample = PRIMITIVE_SAMPLES[current.type];
@@ -20423,10 +20536,11 @@ function validateRef(ref, schema) {
20423
20536
  current = { type: memberType };
20424
20537
  continue;
20425
20538
  }
20426
- if (current.type !== "object" || !current.fields) return `Cannot access field "${part}" on $${parts.slice(0, i).join(".")} (type: ${current.type})`;
20427
- const fieldSchema = current.fields.get(part);
20428
- if (!fieldSchema) return null;
20429
- current = fieldSchema;
20539
+ if (current.type !== "object" || !current.fields) return {
20540
+ code: "primitive-field",
20541
+ message: `Cannot access field "${part}" on ${label(ref.path.slice(0, i))} (type: ${current.type})`
20542
+ };
20543
+ current = current.fields.get(part);
20430
20544
  }
20431
20545
  return null;
20432
20546
  }
@@ -20444,12 +20558,27 @@ var BUILTIN_STORE_VAR_MACROS = [
20444
20558
  "textbox"
20445
20559
  ];
20446
20560
  var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
20561
+ /** A reference written at `index` of `code`, with its dot path. */
20562
+ function referenceAt(code, index, at) {
20563
+ VAR_PATH_RE.lastIndex = index;
20564
+ const match = VAR_PATH_RE.exec(code);
20565
+ if (!match) return void 0;
20566
+ const [name, ...path] = match[2].split(".");
20567
+ return {
20568
+ sigil: match[1],
20569
+ name,
20570
+ path,
20571
+ start: at(index),
20572
+ end: at(index + match[0].length)
20573
+ };
20574
+ }
20447
20575
  /**
20448
20576
  * Scan the value of a code attribute (`onclick`, see isCodeAttribute) for
20449
- * the `{$…}` references resolved in it; its other braces are code.
20577
+ * the `{$…}` references resolved in it; its other braces are code. `at` is
20578
+ * where the value is.
20450
20579
  */
20451
- function scanSigilReferences(value, onRef) {
20452
- for (const part of splitSigilTemplate(value)) if ("expr" in part) scanCode(part.expr, onRef);
20580
+ function scanSigilReferences(value, at, emit) {
20581
+ for (const { expr, at: k } of sigilExpressions(value)) scanCode(expr, (i) => at(k + i), emit);
20453
20582
  }
20454
20583
  /**
20455
20584
  * Scan literal text (string contents, HTML attribute values) for the markup
@@ -20457,9 +20586,9 @@ function scanSigilReferences(value, onRef) {
20457
20586
  * expressions and macros, read as in passage text. A bare `$word` in
20458
20587
  * literal text is not a reference.
20459
20588
  */
20460
- function scanInterpolations(text, onRef, storeVarMacros = NO_STORE_VAR_MACROS) {
20589
+ function scanInterpolations(text, at, emit, options) {
20461
20590
  if (!text.includes("{")) return;
20462
- collectTokenRefs(text, tokensOf(text, true), storeVarMacros, onRef);
20591
+ collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
20463
20592
  }
20464
20593
  /**
20465
20594
  * Report `$var` references in JavaScript code, lexed as the expression
@@ -20469,76 +20598,104 @@ function scanInterpolations(text, onRef, storeVarMacros = NO_STORE_VAR_MACROS) {
20469
20598
  * is literal text unless a macro argument that holds markup is read as such
20470
20599
  * (see scanArgs); the `${…}` parts of template literals are code.
20471
20600
  */
20472
- function scanCode(code, onRef, goal = "expression") {
20601
+ function scanCode(code, at, emit, goal = "expression") {
20473
20602
  const parsed = parseOrError(code, goal);
20474
20603
  if (parsed instanceof CodeSyntaxError) {
20475
- scanCodeLeniently(code, onRef, goal);
20604
+ scanCodeLeniently(code, at, emit, goal);
20476
20605
  return;
20477
20606
  }
20478
20607
  for (const ref of parsed.refs) {
20479
- if (ref.sigil !== "$") continue;
20480
- VAR_PATH_RE.lastIndex = ref.start;
20481
- onRef(VAR_PATH_RE.exec(code)[1]);
20608
+ if (ref.sigil !== "$" && ref.sigil !== "%") continue;
20609
+ const found = referenceAt(code, ref.start, at);
20610
+ if (found) emit(found);
20482
20611
  }
20483
20612
  }
20484
20613
  /** `scanCode` for code acorn can't parse: lexed leniently. */
20485
- function scanCodeLeniently(code, onRef, goal) {
20614
+ function scanCodeLeniently(code, at, emit, goal) {
20486
20615
  lexJs(code, {
20487
20616
  variable(sigil, _name, index) {
20488
- if (sigil !== "$") return;
20489
- VAR_PATH_RE.lastIndex = index;
20490
- onRef(VAR_PATH_RE.exec(code)[1]);
20617
+ if (sigil !== "$" && sigil !== "%") return;
20618
+ const found = referenceAt(code, index, at);
20619
+ if (found) emit(found);
20491
20620
  },
20492
20621
  literal() {}
20493
20622
  }, goal);
20494
20623
  }
20495
20624
  /**
20496
- * Report the `$var` references a passage evaluates at runtime: `{$var}`
20497
- * displays, `{$expr}` expressions, macro arguments and `{do}` bodies (as
20498
- * code), quoted variable names bound by input macros, and `{$…}`
20499
- * interpolations in HTML attributes. Prose is literal text and not scanned.
20500
- */
20501
- function collectPassageRefs(content, storeVarMacros, onRef, parametersOf) {
20502
- withParseCache(() => collectTokenRefs(content, tokensOf(content, false), storeVarMacros, onRef, parametersOf));
20503
- }
20504
- /**
20505
20625
  * Report the references in the arguments of a macro by what its parameters
20506
20626
  * say each holds (see ParameterDef.holds): code is scanned as code and
20507
20627
  * markup as markup, but literal text (a placeholder, a passage name) holds
20508
20628
  * none. A macro without declared parameters, or arguments that do not
20509
20629
  * parse, are scanned as code.
20510
20630
  */
20511
- function scanArgs(token, params, onRef) {
20631
+ function scanArgs(token, params, at, emit, options) {
20512
20632
  if (!token.rawArgs) return;
20513
20633
  if (params) {
20514
- const pieces = [...argPieces(token.rawArgs, 0, params, token.name, "")];
20634
+ const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
20515
20635
  if (!pieces.some((piece) => piece.kind === "argument-error")) {
20516
- for (const piece of pieces) if (piece.kind === "code") scanCode(piece.code, onRef, piece.goal);
20517
- else if (piece.kind === "text") scanInterpolations(piece.text, onRef);
20636
+ for (const piece of pieces) {
20637
+ const pieceAt = (i) => at(pieceOffset(piece, i));
20638
+ if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
20639
+ else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
20640
+ ...options,
20641
+ storeVarMacros: NO_STORE_VAR_MACROS
20642
+ });
20643
+ }
20518
20644
  return;
20519
20645
  }
20520
20646
  }
20521
- scanCode(token.rawArgs, onRef);
20647
+ scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
20522
20648
  }
20523
20649
  /** Report the `$var` references in the tokens of `content`. */
20524
- function collectTokenRefs(content, tokens, storeVarMacros, onRef, parametersOf = () => void 0) {
20650
+ function collectTokenRefs(content, tokens, at, emit, options) {
20651
+ const { storeVarMacros, parametersOf } = options;
20525
20652
  for (let t = 0; t < tokens.length; t++) {
20526
20653
  const token = tokens[t];
20527
20654
  if (token.type === "variable") {
20528
- if (token.scope === "variable" && token.name) onRef(token.name);
20529
- } else if (token.type === "link") scanInterpolations(token.display, onRef);
20530
- else if (token.type === "expression") scanCode(token.expression, onRef);
20531
- else if (token.type === "html") for (const [name, value] of Object.entries(token.attributes)) if (isCodeAttribute(name)) scanSigilReferences(value, onRef);
20532
- else scanInterpolations(value, onRef, storeVarMacros);
20655
+ if ((token.scope === "variable" || token.scope === "transient") && token.name) {
20656
+ const [name, ...path] = token.name.split(".");
20657
+ emit({
20658
+ sigil: token.scope === "variable" ? "$" : "%",
20659
+ name,
20660
+ path,
20661
+ start: at(token.nameStart - 1),
20662
+ end: at(token.nameEnd)
20663
+ });
20664
+ }
20665
+ } else if (token.type === "link") scanInterpolations(token.display, (i) => at(token.displayStart + i), emit, {
20666
+ ...options,
20667
+ storeVarMacros: NO_STORE_VAR_MACROS
20668
+ });
20669
+ else if (token.type === "expression") scanCode(token.expression, (i) => at(token.expressionStart + i), emit);
20670
+ else if (token.type === "html") for (const { name, value, at: valueAt } of attributeValues(content, token)) {
20671
+ const valueIn = (i) => at(valueAt + i);
20672
+ if (isCodeAttribute(name)) scanSigilReferences(value, valueIn, emit);
20673
+ else scanInterpolations(value, valueIn, emit, options);
20674
+ }
20533
20675
  else if (token.type === "macro" && !token.isClose) {
20534
- scanArgs(token, parametersOf(token.name), onRef);
20535
- if (token.className) scanInterpolations(token.className, onRef);
20536
- if (token.id) scanInterpolations(token.id, onRef);
20676
+ scanArgs(token, parametersOf(token.name), at, emit, options);
20677
+ if (token.selectorsStart !== void 0 && token.selectorsEnd !== void 0) {
20678
+ const from = token.selectorsStart;
20679
+ scanInterpolations(content.slice(from, token.selectorsEnd), (i) => at(from + i), emit, {
20680
+ ...options,
20681
+ storeVarMacros: NO_STORE_VAR_MACROS
20682
+ });
20683
+ }
20537
20684
  if (storeVarMacros.has(token.name.toLowerCase())) {
20685
+ const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
20538
20686
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
20539
20687
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
20540
- if (quoted) onRef(quoted[1]);
20541
- else if (!/^["'`]/.test(first)) scanCode(first, onRef);
20688
+ if (quoted) {
20689
+ const [name, ...path] = quoted[1].split(".");
20690
+ const start = token.argsStart + lead + 1;
20691
+ emit({
20692
+ sigil: "$",
20693
+ name,
20694
+ path,
20695
+ start: at(start),
20696
+ end: at(start + 1 + quoted[1].length)
20697
+ });
20698
+ } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
20542
20699
  }
20543
20700
  if (token.name.toLowerCase() === "do") {
20544
20701
  let close = t + 1;
@@ -20548,7 +20705,7 @@ function collectTokenRefs(content, tokens, storeVarMacros, onRef, parametersOf =
20548
20705
  close++;
20549
20706
  }
20550
20707
  if (close < tokens.length) {
20551
- scanCode(content.slice(token.end, tokens[close].start), onRef, "statements");
20708
+ scanCode(content.slice(token.end, tokens[close].start), (i) => at(token.end + i), emit, "statements");
20552
20709
  t = close;
20553
20710
  }
20554
20711
  }
@@ -20556,6 +20713,43 @@ function collectTokenRefs(content, tokens, storeVarMacros, onRef, parametersOf =
20556
20713
  }
20557
20714
  }
20558
20715
  /**
20716
+ * The `$` and `%` variable references a passage evaluates at runtime, in
20717
+ * source order: `{$var}` displays, `{$expr}` expressions, macro arguments and
20718
+ * `{do}` bodies (as code), quoted variable names bound by input macros, and
20719
+ * `{$…}` interpolations in labels and HTML attributes. Prose is literal text
20720
+ * and not scanned.
20721
+ */
20722
+ function collectVariableReferences(content, options) {
20723
+ const found = [];
20724
+ withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
20725
+ return found;
20726
+ }
20727
+ /**
20728
+ * The invalid variable references of the passages, against what is declared,
20729
+ * with their positions. The passages that hold no markup (the declarations
20730
+ * themselves, SaveTitle) are skipped.
20731
+ */
20732
+ function checkVariableReferences(passages, declared, options) {
20733
+ const diagnostics = [];
20734
+ for (const passage of passages) {
20735
+ if (NOT_MARKUP.has(passage.name)) continue;
20736
+ for (const ref of collectVariableReferences(passage.content, options)) {
20737
+ const error = checkReference(ref, declared);
20738
+ if (!error) continue;
20739
+ diagnostics.push({
20740
+ passage: passage.name,
20741
+ code: error.code,
20742
+ name: ref.name,
20743
+ ...ref.path.length > 0 ? { path: ref.path } : {},
20744
+ start: ref.start,
20745
+ end: ref.end,
20746
+ message: error.message
20747
+ });
20748
+ }
20749
+ }
20750
+ return diagnostics;
20751
+ }
20752
+ /**
20559
20753
  * Check the `$var` references of all passages against the schema, at story
20560
20754
  * start. Returns the error messages (empty = valid). (The syntax of their
20561
20755
  * code is checked with their markup: see markup/validate.ts.)
@@ -20564,16 +20758,10 @@ function collectTokenRefs(content, tokens, storeVarMacros, onRef, parametersOf =
20564
20758
  * variable; it defaults to the built-in ones.
20565
20759
  */
20566
20760
  function validatePassages(passages, schema, storeVarMacros = BUILTIN_STORE_VAR_MACROS, parametersOf = getMacroParameters) {
20567
- const errors = [];
20568
- const storeVarSet = new Set(Array.from(storeVarMacros, (m) => m.toLowerCase()));
20569
- for (const [name, passage] of passages) {
20570
- if (NOT_MARKUP.has(name)) continue;
20571
- collectPassageRefs(passage.content, storeVarSet, (ref) => {
20572
- const error = validateRef(ref, schema);
20573
- if (error) errors.push(`Passage "${name}": ${error}`);
20574
- }, parametersOf);
20575
- }
20576
- return errors;
20761
+ return checkVariableReferences(passages.values(), { variables: schema }, {
20762
+ storeVarMacros: new Set(Array.from(storeVarMacros, (m) => m.toLowerCase())),
20763
+ parametersOf
20764
+ }).map((d) => `Passage "${d.passage}": ${d.message}`);
20577
20765
  }
20578
20766
  /**
20579
20767
  * Extract default values from the schema as a record without a prototype,
@@ -21535,14 +21723,50 @@ defineMacro({
21535
21723
  //#region src/components/macros/detached-body.tsx
21536
21724
  var frozenAlways = () => true;
21537
21725
  /**
21726
+ * Macros whose work is over once their effects have run: a body made of
21727
+ * these alone has nothing left to wait for. Any other macro (a timer, a
21728
+ * widget, an author's macro) may keep working after rendering.
21729
+ */
21730
+ var SETTLING_MACROS = new NameSet([
21731
+ "set",
21732
+ "unset",
21733
+ "if",
21734
+ "for",
21735
+ "switch",
21736
+ "do",
21737
+ "print",
21738
+ "goto",
21739
+ "nobr",
21740
+ "span"
21741
+ ]);
21742
+ /** Whether `nodes` use no macro outside SETTLING_MACROS (see above). */
21743
+ function settlesAfterRender(nodes) {
21744
+ return nodes.every((n) => {
21745
+ switch (n.type) {
21746
+ case "macro": return SETTLING_MACROS.has(n.name) && settlesAfterRender(n.children) && (n.branches ?? []).every((b) => settlesAfterRender(b.children));
21747
+ case "html": return settlesAfterRender(n.children);
21748
+ default: return true;
21749
+ }
21750
+ });
21751
+ }
21752
+ /** Calls `onSettled` once the effects of the content before it have run. */
21753
+ function Settled({ onSettled }) {
21754
+ useEffect(() => {
21755
+ const timer = setTimeout(onSettled, 0);
21756
+ return () => clearTimeout(timer);
21757
+ }, []);
21758
+ return null;
21759
+ }
21760
+ /**
21538
21761
  * Return a function that runs a macro body once, outside the passage tree:
21539
21762
  * it renders `children` into a detached node, so the body's macros ({set},
21540
21763
  * {if}, {goto}, ...) fire their side effects through the normal Preact
21541
21764
  * pipeline. Used by {button} and {link} on click. The body's state is frozen
21542
21765
  * once it has rendered, so it runs once per click. It stays mounted
21543
- * until the owning macro unmounts (its passage changes, say), so work it
21544
- * starts in an effect, such as the timer of a {timed} or {repeat}, can
21545
- * finish; the passage leaving cancels it, and so does a restart or a load
21766
+ * until it has nothing left to do: a body of plain macros ({set}, {if},
21767
+ * {goto}...) once its effects have run, any other (with the timer of a
21768
+ * {timed} or {repeat}, say) until the owning macro unmounts, e.g. its
21769
+ * passage changes, so that work it starts in an effect can finish; the passage leaving cancels it, and so does a restart or a load
21546
21770
  * replacing the game, which a control of the story interface outlives
21547
21771
  * (#401).
21548
21772
  *
@@ -21584,6 +21808,12 @@ function useDetachedBody() {
21584
21808
  const run = (children) => {
21585
21809
  const locals = liveLocalsView(updater.getValues);
21586
21810
  const container = document.createElement("div");
21811
+ const release = settlesAfterRender(children) ? () => {
21812
+ const at = mounted.current.indexOf(container);
21813
+ if (at === -1) return;
21814
+ mounted.current.splice(at, 1);
21815
+ render(null, container);
21816
+ } : null;
21587
21817
  render(/* @__PURE__ */ jsx(FrozenStateContext.Provider, {
21588
21818
  value: frozenAlways,
21589
21819
  children: /* @__PURE__ */ jsx(LocalsUpdateContext.Provider, {
@@ -21604,14 +21834,14 @@ function useDetachedBody() {
21604
21834
  value: closeDialog,
21605
21835
  children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
21606
21836
  value: inIteration,
21607
- children: /* @__PURE__ */ jsx(OutgoingContext.Provider, {
21837
+ children: /* @__PURE__ */ jsxs(OutgoingContext.Provider, {
21608
21838
  value: hasLeft,
21609
- children: renderNodes(children, {
21839
+ children: [renderNodes(children, {
21610
21840
  nobr,
21611
21841
  inline,
21612
21842
  structural,
21613
21843
  locals
21614
- })
21844
+ }), release && /* @__PURE__ */ jsx(Settled, { onSettled: release })]
21615
21845
  })
21616
21846
  })
21617
21847
  })
@@ -21914,7 +22144,7 @@ defineMacro({
21914
22144
  visibility: measured === null ? "hidden" : "visible",
21915
22145
  clipPath: clip
21916
22146
  },
21917
- children: ctx.renderInlineNodes(children)
22147
+ children: ctx.renderNodes(children, { inline: true })
21918
22148
  }), !done && totalChars > 0 && /* @__PURE__ */ jsx("span", { class: "macro-type-cursor" })]
21919
22149
  });
21920
22150
  }
@@ -22007,6 +22237,7 @@ function defineMenubarAction(config) {
22007
22237
  passageName: config.dialog.passageName,
22008
22238
  fallbackMarkup: config.dialog.fallbackMarkup,
22009
22239
  panelClass: config.dialog.panelClass,
22240
+ label: typeof config.label === "string" ? config.label : config.name,
22010
22241
  onClose: () => setDialogOpen(false),
22011
22242
  showCloseButton: config.dialog.showCloseButton
22012
22243
  })] });
@@ -22488,10 +22719,12 @@ defineMacro({
22488
22719
  //#region src/components/macros/SettingsControls.tsx
22489
22720
  function SettingControl({ name, def }) {
22490
22721
  const [value, setValue] = useState(() => settings.get(name));
22491
- const update = (newValue) => {
22492
- setValue(newValue);
22493
- settings.set(name, newValue);
22494
- };
22722
+ useEffect(() => {
22723
+ const sync = () => setValue(settings.get(name));
22724
+ sync();
22725
+ return subscribeSettings(sync);
22726
+ }, [name]);
22727
+ const update = (newValue) => settings.set(name, newValue);
22495
22728
  switch (def.type) {
22496
22729
  case "toggle": return /* @__PURE__ */ jsxs("label", {
22497
22730
  class: "settings-row",