@rohal12/spindle 0.59.23 → 0.59.24

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
  /**
@@ -11296,37 +11296,70 @@ function widgetDef({ name = "", parameters = "" }) {
11296
11296
  function parseWidgetDef(rawArgs) {
11297
11297
  return widgetDef(parseMacroArgs(rawArgs, WIDGET_PARAMETERS));
11298
11298
  }
11299
+ /** Where the name is written in the arguments, without its quotes. */
11300
+ function nameSpan(rawArgs) {
11301
+ const spans = /* @__PURE__ */ new Map();
11302
+ parseMacroArgs(rawArgs, WIDGET_PARAMETERS, spans);
11303
+ const [start, end] = spans.get(WIDGET_PARAMETERS[0]) ?? [0, 0];
11304
+ const quote = rawArgs[start];
11305
+ return (quote === "\"" || quote === "'") && end - start >= 2 ? [start + 1, rawArgs[end - 1] === quote ? end - 1 : end] : [start, end];
11306
+ }
11299
11307
  /**
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.
11308
+ * The widgets that StoryInit and the passages tagged `widget` define, in
11309
+ * source order: the ones the runtime registers, read tolerantly (a half-typed
11310
+ * definition is still reported, without a `closeStart`). Definitions whose
11311
+ * arguments cannot be read are left out.
11304
11312
  *
11305
11313
  * The passages are read as flat tokens, which need no block macros to be
11306
11314
  * 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).
11315
+ * here as it is to the parser, and does not make a block widget (#387). In
11316
+ * nested definitions, it belongs to the innermost.
11308
11317
  */
11309
- function blockWidgetNames(passages, parametersOf = registeredParameters) {
11310
- const names = [];
11318
+ function widgetDefinitions(passages, parametersOf = registeredParameters) {
11319
+ const found = [];
11311
11320
  for (const passage of passages) {
11312
11321
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
11313
11322
  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
- }
11323
+ const done = [];
11324
+ for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") if (!token.isClose) open.push({
11325
+ token,
11326
+ isBlock: false
11327
+ });
11328
+ else {
11322
11329
  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;
11330
+ if (def) done.push({
11331
+ ...def,
11332
+ closeStart: token.start
11333
+ });
11334
+ }
11335
+ else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11336
+ done.push(...open);
11337
+ const defs = [];
11338
+ for (const { token, isBlock, closeStart } of done) try {
11339
+ const [from, to] = nameSpan(token.rawArgs);
11340
+ defs.push({
11341
+ ...parseWidgetDef(token.rawArgs),
11342
+ block: isBlock,
11343
+ passage: passage.name,
11344
+ start: token.start,
11345
+ end: token.end,
11346
+ nameStart: token.argsStart + from,
11347
+ nameEnd: token.argsStart + to,
11348
+ ...closeStart === void 0 ? {} : { closeStart }
11349
+ });
11350
+ } catch {}
11351
+ found.push(...defs.sort((a, b) => a.start - b.start));
11328
11352
  }
11329
- return names;
11353
+ return found;
11354
+ }
11355
+ /**
11356
+ * The names of the block widgets (those whose body renders `{@children}`)
11357
+ * that StoryInit and the passages tagged `widget` define, closed. They must
11358
+ * be known as block macros before any passage is parsed, so that passages
11359
+ * invoking them nest their content whatever the passage order.
11360
+ */
11361
+ function blockWidgetNames(passages, parametersOf = registeredParameters) {
11362
+ return widgetDefinitions(passages, parametersOf).filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name);
11330
11363
  }
11331
11364
  //#endregion
11332
11365
  //#region src/widgets/register-widget-def.ts
@@ -12915,9 +12948,13 @@ function resolveAttributeValue(name, value, scope, errors) {
12915
12948
  for (const error of result.errors) errors.push([name, error]);
12916
12949
  return result.text;
12917
12950
  }
12951
+ /** Whether a node shows nothing as text: whitespace, or a closed HTML comment. */
12952
+ function isBlankText(n) {
12953
+ return n.type === "text" && (n.comment === true || n.value.trim() === "");
12954
+ }
12918
12955
  /** The index of the summary element opening `nodes`, or -1 when none does. */
12919
12956
  function leadingSummaryIndex(nodes) {
12920
- const at = nodes.findIndex((n) => n.type !== "text" || n.value.trim() !== "");
12957
+ const at = nodes.findIndex((n) => !isBlankText(n));
12921
12958
  const first = nodes[at];
12922
12959
  return first?.type === "html" && first.tag.toLowerCase() === "summary" ? at : -1;
12923
12960
  }
@@ -12939,7 +12976,8 @@ function HtmlNodeRenderer({ node }) {
12939
12976
  const isInline = INLINE_ELEMENTS.has(tag);
12940
12977
  let children = void 0;
12941
12978
  let structural = false;
12942
- if (node.children.length > 0) if (inRaw || isRawRoot) children = renderInlineNodes(node.children);
12979
+ if (node.children.length > 0) if (tag === "style") children = node.children.map((n) => n.type === "text" ? n.value : renderSingleNode(n));
12980
+ else if (inRaw || isRawRoot) children = renderInlineNodes(node.children);
12943
12981
  else {
12944
12982
  const summaryAt = tag === "details" ? leadingSummaryIndex(node.children) : -1;
12945
12983
  const body = (nodes) => renderNodes(nodes, {
@@ -12947,7 +12985,7 @@ function HtmlNodeRenderer({ node }) {
12947
12985
  locals,
12948
12986
  inline: isInline
12949
12987
  });
12950
- structural = STRUCTURAL_ELEMENTS.has(tag) && node.children.every((n) => n.type !== "text" || n.value.trim() === "");
12988
+ structural = STRUCTURAL_ELEMENTS.has(tag) && node.children.every((n) => n.type !== "text" || isBlankText(n));
12951
12989
  children = structural ? node.children.filter((n) => n.type !== "text").map((n) => renderSingleNode(n)) : summaryAt === -1 ? body(node.children) : /* @__PURE__ */ jsxs(Fragment$1, { children: [
12952
12990
  body(node.children.slice(0, summaryAt)),
12953
12991
  renderSingleNode(node.children[summaryAt]),
@@ -13120,7 +13158,7 @@ function buildPlainTextVnodes(core, ph, unwrapParagraphs) {
13120
13158
  function renderNodes(nodes, options) {
13121
13159
  if (nodes.length === 0) return null;
13122
13160
  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);
13161
+ if (options?.structural && nodes.every((n) => n.type !== "text" || isBlankText(n))) return nodes.filter((n) => n.type !== "text").map(renderSingleNode);
13124
13162
  if (!nodes.some((n) => n.type === "text" && (n.value.trim() !== "" || BLANK_LINE_RE.test(n.value)))) return nodes.map((node) => renderSingleNode(node));
13125
13163
  const components = [];
13126
13164
  const ph = {
@@ -15726,13 +15764,13 @@ var VALID_EVENTS = new Set([
15726
15764
  "passagerender",
15727
15765
  "dialogrender"
15728
15766
  ]);
15729
- var listeners = /* @__PURE__ */ new Map();
15767
+ var listeners$1 = /* @__PURE__ */ new Map();
15730
15768
  function on(event, cb) {
15731
15769
  if (!VALID_EVENTS.has(event)) throw new Error(`spindle: Unknown event "${event}".`);
15732
- let set = listeners.get(event);
15770
+ let set = listeners$1.get(event);
15733
15771
  if (!set) {
15734
15772
  set = /* @__PURE__ */ new Set();
15735
- listeners.set(event, set);
15773
+ listeners$1.set(event, set);
15736
15774
  }
15737
15775
  set.add(cb);
15738
15776
  return () => {
@@ -15741,7 +15779,7 @@ function on(event, cb) {
15741
15779
  }
15742
15780
  /** Call `call` with each listener of `event`. */
15743
15781
  function forEachListener(event, call) {
15744
- const set = listeners.get(event);
15782
+ const set = listeners$1.get(event);
15745
15783
  if (!set) return;
15746
15784
  for (const cb of [...set]) call(cb);
15747
15785
  }
@@ -18562,6 +18600,24 @@ var openModals = [];
18562
18600
  * - closes the topmost dialog on Escape when it is dismissible;
18563
18601
  * - returns focus to the previously focused element on close.
18564
18602
  */
18603
+ /** The input types made of several segments, each a native Tab stop. */
18604
+ var SEGMENTED_INPUTS = new Set([
18605
+ "date",
18606
+ "time",
18607
+ "datetime-local",
18608
+ "month",
18609
+ "week"
18610
+ ]);
18611
+ /** Whether the element has native tab stops inside it, in its shadow tree. */
18612
+ function hasNativeStops(el) {
18613
+ if (el instanceof HTMLMediaElement) return el.controls;
18614
+ return el instanceof HTMLInputElement && SEGMENTED_INPUTS.has(el.type) && !el.readOnly;
18615
+ }
18616
+ /** The tab stops of an embedded document, in tab order. */
18617
+ function frameStops(doc) {
18618
+ if (!doc) return [];
18619
+ return Array.from(doc.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
18620
+ }
18565
18621
  function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18566
18622
  useLayoutEffect(() => {
18567
18623
  const panel = panelRef.current;
@@ -18589,6 +18645,21 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18589
18645
  * (#424). `from` may be an element of an embedded document, whose frame
18590
18646
  * element then stands in for it.
18591
18647
  */
18648
+ /** Focus `el`; a frame is entered at its first (or last) control (#460). */
18649
+ const enter = (el, backwards) => {
18650
+ if (el instanceof HTMLIFrameElement) {
18651
+ let inner = [];
18652
+ try {
18653
+ inner = frameStops(el.contentDocument);
18654
+ } catch {}
18655
+ const edge = backwards ? inner[inner.length - 1] : inner[0];
18656
+ if (edge) {
18657
+ edge.focus();
18658
+ return;
18659
+ }
18660
+ }
18661
+ el.focus();
18662
+ };
18592
18663
  const moveFocus = (from, backwards) => {
18593
18664
  const items = focusables(panel);
18594
18665
  const first = items[0];
@@ -18604,9 +18675,9 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18604
18675
  const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
18605
18676
  next = backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
18606
18677
  } else next = backwards ? last : first;
18607
- (next ?? (backwards ? last : first)).focus();
18678
+ enter(next ?? (backwards ? last : first), backwards);
18608
18679
  };
18609
- let steppingMedia = null;
18680
+ let steppingNative = null;
18610
18681
  const onKeyDown = (e) => {
18611
18682
  if (!top()) return;
18612
18683
  if (e.key === "Escape") {
@@ -18618,8 +18689,8 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18618
18689
  }
18619
18690
  if (e.key !== "Tab") return;
18620
18691
  const active = document.activeElement;
18621
- if (active instanceof HTMLMediaElement && active.controls) {
18622
- steppingMedia = {
18692
+ if (hasNativeStops(active)) {
18693
+ steppingNative = {
18623
18694
  el: active,
18624
18695
  backwards: e.shiftKey
18625
18696
  };
@@ -18629,7 +18700,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18629
18700
  moveFocus(active, e.shiftKey);
18630
18701
  };
18631
18702
  const onPointerDown = () => {
18632
- steppingMedia = null;
18703
+ steppingNative = null;
18633
18704
  };
18634
18705
  const controller = new AbortController();
18635
18706
  const { signal } = controller;
@@ -18644,7 +18715,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18644
18715
  const onFrameKeyDown = (e) => {
18645
18716
  if (!top()) return;
18646
18717
  if (e.key !== "Tab") return onKeyDown(e);
18647
- const inner = Array.from(doc.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
18718
+ const inner = frameStops(doc);
18648
18719
  const active = doc.activeElement;
18649
18720
  const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
18650
18721
  if (!edge || active === edge || active === doc.body) {
@@ -18672,9 +18743,9 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18672
18743
  attachFrames();
18673
18744
  const onFocusIn = (e) => {
18674
18745
  const target = e.target;
18675
- if (steppingMedia && target !== steppingMedia.el && top()) {
18676
- const { el, backwards } = steppingMedia;
18677
- steppingMedia = null;
18746
+ if (steppingNative && target !== steppingNative.el && top()) {
18747
+ const { el, backwards } = steppingNative;
18748
+ steppingNative = null;
18678
18749
  moveFocus(el, backwards);
18679
18750
  return;
18680
18751
  }
@@ -18688,9 +18759,9 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18688
18759
  signal
18689
18760
  });
18690
18761
  const onFocusOut = (e) => {
18691
- const pending = steppingMedia;
18762
+ const pending = steppingNative;
18692
18763
  if (!pending || e.target !== pending.el || e.relatedTarget || !top()) return;
18693
- steppingMedia = null;
18764
+ steppingNative = null;
18694
18765
  moveFocus(pending.el, pending.backwards);
18695
18766
  };
18696
18767
  document.addEventListener("focusout", onFocusOut, { signal });
@@ -18704,7 +18775,7 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18704
18775
  //#endregion
18705
18776
  //#region src/components/PassageDialog.tsx
18706
18777
  var DialogCloseContext = createContext(null);
18707
- function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, dismissible = true, showCloseButton = dismissible }) {
18778
+ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
18708
18779
  const onCloseRef = useRef(onClose);
18709
18780
  onCloseRef.current = onClose;
18710
18781
  const stableOnClose = useCallback(() => onCloseRef.current(), []);
@@ -18731,9 +18802,19 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, dismi
18731
18802
  }
18732
18803
  }, [markup, nobr]);
18733
18804
  const panelRef = useRef(null);
18805
+ const labelId = useId();
18734
18806
  const viewScope = useViewScope();
18735
18807
  useModalFocus(panelRef, ".dialog-body", dismissible, stableOnClose);
18736
18808
  useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
18809
+ useLayoutEffect(() => {
18810
+ const panel = panelRef.current;
18811
+ if (!panel || label) return;
18812
+ const heading = panel.querySelector(".dialog-body :is(h1, h2, h3, h4, h5, h6)");
18813
+ if (!heading) return;
18814
+ heading.id ||= `${labelId}-heading`;
18815
+ panel.setAttribute("aria-labelledby", heading.id);
18816
+ return () => panel.removeAttribute("aria-labelledby");
18817
+ }, [label, markup]);
18737
18818
  useLayoutEffect(() => {
18738
18819
  if (panelRef.current) emitFromRender("dialogrender", passageName ?? "", panelRef.current);
18739
18820
  }, []);
@@ -18752,6 +18833,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, dismi
18752
18833
  class: cls,
18753
18834
  role: "dialog",
18754
18835
  "aria-modal": "true",
18836
+ "aria-label": label ?? passageName,
18755
18837
  tabIndex: -1,
18756
18838
  children: [showCloseButton && /* @__PURE__ */ jsx("button", {
18757
18839
  type: "button",
@@ -19067,6 +19149,12 @@ var definitions = /* @__PURE__ */ new Map();
19067
19149
  var values = createNamespace();
19068
19150
  var storageLoaded = false;
19069
19151
  var unsubscribeStoryData = null;
19152
+ var listeners = /* @__PURE__ */ new Set();
19153
+ /** Call `listener` after a setting changes; returns the unsubscribe. */
19154
+ function subscribeSettings(listener) {
19155
+ listeners.add(listener);
19156
+ return () => listeners.delete(listener);
19157
+ }
19070
19158
  function storageKey() {
19071
19159
  return `spindle.${useStoryStore.getState().storyData?.ifid || "unknown"}.settings`;
19072
19160
  }
@@ -19140,6 +19228,7 @@ var settings = {
19140
19228
  set(name, value) {
19141
19229
  values[name] = value;
19142
19230
  persist();
19231
+ for (const listener of [...listeners]) listener();
19143
19232
  },
19144
19233
  getAll() {
19145
19234
  return { ...values };
@@ -21535,14 +21624,50 @@ defineMacro({
21535
21624
  //#region src/components/macros/detached-body.tsx
21536
21625
  var frozenAlways = () => true;
21537
21626
  /**
21627
+ * Macros whose work is over once their effects have run: a body made of
21628
+ * these alone has nothing left to wait for. Any other macro (a timer, a
21629
+ * widget, an author's macro) may keep working after rendering.
21630
+ */
21631
+ var SETTLING_MACROS = new NameSet([
21632
+ "set",
21633
+ "unset",
21634
+ "if",
21635
+ "for",
21636
+ "switch",
21637
+ "do",
21638
+ "print",
21639
+ "goto",
21640
+ "nobr",
21641
+ "span"
21642
+ ]);
21643
+ /** Whether `nodes` use no macro outside SETTLING_MACROS (see above). */
21644
+ function settlesAfterRender(nodes) {
21645
+ return nodes.every((n) => {
21646
+ switch (n.type) {
21647
+ case "macro": return SETTLING_MACROS.has(n.name) && settlesAfterRender(n.children) && (n.branches ?? []).every((b) => settlesAfterRender(b.children));
21648
+ case "html": return settlesAfterRender(n.children);
21649
+ default: return true;
21650
+ }
21651
+ });
21652
+ }
21653
+ /** Calls `onSettled` once the effects of the content before it have run. */
21654
+ function Settled({ onSettled }) {
21655
+ useEffect(() => {
21656
+ const timer = setTimeout(onSettled, 0);
21657
+ return () => clearTimeout(timer);
21658
+ }, []);
21659
+ return null;
21660
+ }
21661
+ /**
21538
21662
  * Return a function that runs a macro body once, outside the passage tree:
21539
21663
  * it renders `children` into a detached node, so the body's macros ({set},
21540
21664
  * {if}, {goto}, ...) fire their side effects through the normal Preact
21541
21665
  * pipeline. Used by {button} and {link} on click. The body's state is frozen
21542
21666
  * 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
21667
+ * until it has nothing left to do: a body of plain macros ({set}, {if},
21668
+ * {goto}...) once its effects have run, any other (with the timer of a
21669
+ * {timed} or {repeat}, say) until the owning macro unmounts, e.g. its
21670
+ * 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
21671
  * replacing the game, which a control of the story interface outlives
21547
21672
  * (#401).
21548
21673
  *
@@ -21584,6 +21709,12 @@ function useDetachedBody() {
21584
21709
  const run = (children) => {
21585
21710
  const locals = liveLocalsView(updater.getValues);
21586
21711
  const container = document.createElement("div");
21712
+ const release = settlesAfterRender(children) ? () => {
21713
+ const at = mounted.current.indexOf(container);
21714
+ if (at === -1) return;
21715
+ mounted.current.splice(at, 1);
21716
+ render(null, container);
21717
+ } : null;
21587
21718
  render(/* @__PURE__ */ jsx(FrozenStateContext.Provider, {
21588
21719
  value: frozenAlways,
21589
21720
  children: /* @__PURE__ */ jsx(LocalsUpdateContext.Provider, {
@@ -21604,14 +21735,14 @@ function useDetachedBody() {
21604
21735
  value: closeDialog,
21605
21736
  children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
21606
21737
  value: inIteration,
21607
- children: /* @__PURE__ */ jsx(OutgoingContext.Provider, {
21738
+ children: /* @__PURE__ */ jsxs(OutgoingContext.Provider, {
21608
21739
  value: hasLeft,
21609
- children: renderNodes(children, {
21740
+ children: [renderNodes(children, {
21610
21741
  nobr,
21611
21742
  inline,
21612
21743
  structural,
21613
21744
  locals
21614
- })
21745
+ }), release && /* @__PURE__ */ jsx(Settled, { onSettled: release })]
21615
21746
  })
21616
21747
  })
21617
21748
  })
@@ -21914,7 +22045,7 @@ defineMacro({
21914
22045
  visibility: measured === null ? "hidden" : "visible",
21915
22046
  clipPath: clip
21916
22047
  },
21917
- children: ctx.renderInlineNodes(children)
22048
+ children: ctx.renderNodes(children, { inline: true })
21918
22049
  }), !done && totalChars > 0 && /* @__PURE__ */ jsx("span", { class: "macro-type-cursor" })]
21919
22050
  });
21920
22051
  }
@@ -22007,6 +22138,7 @@ function defineMenubarAction(config) {
22007
22138
  passageName: config.dialog.passageName,
22008
22139
  fallbackMarkup: config.dialog.fallbackMarkup,
22009
22140
  panelClass: config.dialog.panelClass,
22141
+ label: typeof config.label === "string" ? config.label : config.name,
22010
22142
  onClose: () => setDialogOpen(false),
22011
22143
  showCloseButton: config.dialog.showCloseButton
22012
22144
  })] });
@@ -22488,10 +22620,12 @@ defineMacro({
22488
22620
  //#region src/components/macros/SettingsControls.tsx
22489
22621
  function SettingControl({ name, def }) {
22490
22622
  const [value, setValue] = useState(() => settings.get(name));
22491
- const update = (newValue) => {
22492
- setValue(newValue);
22493
- settings.set(name, newValue);
22494
- };
22623
+ useEffect(() => {
22624
+ const sync = () => setValue(settings.get(name));
22625
+ sync();
22626
+ return subscribeSettings(sync);
22627
+ }, [name]);
22628
+ const update = (newValue) => settings.set(name, newValue);
22495
22629
  switch (def.type) {
22496
22630
  case "toggle": return /* @__PURE__ */ jsxs("label", {
22497
22631
  class: "settings-row",
@@ -11071,37 +11071,70 @@ function widgetDef({ name = "", parameters = "" }) {
11071
11071
  function parseWidgetDef(rawArgs) {
11072
11072
  return widgetDef(parseMacroArgs(rawArgs, WIDGET_PARAMETERS));
11073
11073
  }
11074
+ /** Where the name is written in the arguments, without its quotes. */
11075
+ function nameSpan(rawArgs) {
11076
+ const spans = /* @__PURE__ */ new Map();
11077
+ parseMacroArgs(rawArgs, WIDGET_PARAMETERS, spans);
11078
+ const [start, end] = spans.get(WIDGET_PARAMETERS[0]) ?? [0, 0];
11079
+ const quote = rawArgs[start];
11080
+ return (quote === "\"" || quote === "'") && end - start >= 2 ? [start + 1, rawArgs[end - 1] === quote ? end - 1 : end] : [start, end];
11081
+ }
11074
11082
  /**
11075
- * The names of the block widgets (those whose body renders `{@children}`)
11076
- * that StoryInit and the passages tagged `widget` define. They must be
11077
- * known as block macros before any passage is parsed, so that passages
11078
- * invoking them nest their content whatever the passage order.
11083
+ * The widgets that StoryInit and the passages tagged `widget` define, in
11084
+ * source order: the ones the runtime registers, read tolerantly (a half-typed
11085
+ * definition is still reported, without a `closeStart`). Definitions whose
11086
+ * arguments cannot be read are left out.
11079
11087
  *
11080
11088
  * The passages are read as flat tokens, which need no block macros to be
11081
11089
  * known, so a `{@children}` in an HTML comment or in a `{do}` body is text
11082
- * here as it is to the parser, and does not make a block widget (#387).
11090
+ * here as it is to the parser, and does not make a block widget (#387). In
11091
+ * nested definitions, it belongs to the innermost.
11083
11092
  */
11084
- function blockWidgetNames(passages, parametersOf = registeredParameters) {
11085
- const names = [];
11093
+ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
11094
+ const found = [];
11086
11095
  for (const passage of passages) {
11087
11096
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
11088
11097
  const open = [];
11089
- for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
11090
- if (!token.isClose) {
11091
- open.push({
11092
- rawArgs: token.rawArgs,
11093
- isBlock: false
11094
- });
11095
- continue;
11096
- }
11098
+ const done = [];
11099
+ for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") if (!token.isClose) open.push({
11100
+ token,
11101
+ isBlock: false
11102
+ });
11103
+ else {
11097
11104
  const def = open.pop();
11098
- if (!def?.isBlock) continue;
11099
- try {
11100
- names.push(parseWidgetDef(def.rawArgs).name);
11101
- } catch {}
11102
- } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11105
+ if (def) done.push({
11106
+ ...def,
11107
+ closeStart: token.start
11108
+ });
11109
+ }
11110
+ else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11111
+ done.push(...open);
11112
+ const defs = [];
11113
+ for (const { token, isBlock, closeStart } of done) try {
11114
+ const [from, to] = nameSpan(token.rawArgs);
11115
+ defs.push({
11116
+ ...parseWidgetDef(token.rawArgs),
11117
+ block: isBlock,
11118
+ passage: passage.name,
11119
+ start: token.start,
11120
+ end: token.end,
11121
+ nameStart: token.argsStart + from,
11122
+ nameEnd: token.argsStart + to,
11123
+ ...closeStart === void 0 ? {} : { closeStart }
11124
+ });
11125
+ } catch {}
11126
+ found.push(...defs.sort((a, b) => a.start - b.start));
11103
11127
  }
11104
- return names;
11128
+ return found;
11129
+ }
11130
+ /**
11131
+ * The names of the block widgets (those whose body renders `{@children}`)
11132
+ * that StoryInit and the passages tagged `widget` define, closed. They must
11133
+ * be known as block macros before any passage is parsed, so that passages
11134
+ * invoking them nest their content whatever the passage order.
11135
+ */
11136
+ function blockWidgetNames(passages, parametersOf = registeredParameters) {
11137
+ return widgetDefinitions$1(passages, parametersOf).filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name);
11105
11138
  }
11106
11139
  //#endregion
11107
11140
  //#region src/markup/validate.ts
@@ -11860,5 +11893,16 @@ function passagePieces(source, macros = []) {
11860
11893
  function collectStoryPassageReferences(source, macros) {
11861
11894
  return referencesOf(passagePieces(source, macros));
11862
11895
  }
11896
+ /**
11897
+ * The widgets the story defines, as the runtime reads them: those of
11898
+ * StoryInit and of the passages tagged `widget`, with their parameters,
11899
+ * whether their body renders `{@children}` (a block widget) and where they
11900
+ * are written, in source order. Half-typed definitions are reported without a
11901
+ * `closeStart`. The macros are those the markup may use, built-in and
11902
+ * user-defined (a `{@children}` in an attribute or label counts).
11903
+ */
11904
+ function widgetDefinitions(passages, macros = []) {
11905
+ return widgetDefinitions$1(passages, parameterLookup([...macros]));
11906
+ }
11863
11907
  //#endregion
11864
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, passagePieces, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup };
11908
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, widgetDefinitions };
@@ -37,6 +37,8 @@ export {
37
37
  stripLooseQuotes,
38
38
  unescapeQuoted,
39
39
  splitIncludeFlag,
40
+ parseWidgetDef,
41
+ widgetDefinitions,
40
42
  } from './story-variables.js';
41
43
 
42
44
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.59.23",
3
+ "version": "0.59.24",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,5 +1,11 @@
1
1
  import { createContext } from 'preact';
2
- import { useCallback, useLayoutEffect, useMemo, useRef } from 'preact/hooks';
2
+ import {
3
+ useCallback,
4
+ useId,
5
+ useLayoutEffect,
6
+ useMemo,
7
+ useRef,
8
+ } from 'preact/hooks';
3
9
  import { parseMarkup } from '../markup/parse';
4
10
  import {
5
11
  renderNodes,
@@ -20,6 +26,11 @@ interface PassageDialogProps {
20
26
  fallbackMarkup?: string;
21
27
  panelClass?: string;
22
28
  onClose: () => void;
29
+ /**
30
+ * The dialog's accessible name. Without one, the first heading authored in
31
+ * the dialog names it, or else its passage.
32
+ */
33
+ label?: string;
23
34
  /** Show the default `✕` button. Defaults to `dismissible`. */
24
35
  showCloseButton?: boolean;
25
36
  /**
@@ -35,6 +46,7 @@ export function PassageDialog({
35
46
  fallbackMarkup,
36
47
  panelClass,
37
48
  onClose,
49
+ label,
38
50
  dismissible = true,
39
51
  showCloseButton = dismissible,
40
52
  }: PassageDialogProps) {
@@ -71,6 +83,7 @@ export function PassageDialog({
71
83
  }, [markup, nobr]);
72
84
 
73
85
  const panelRef = useRef<HTMLDivElement>(null);
86
+ const labelId = useId();
74
87
  const viewScope = useViewScope();
75
88
 
76
89
  // Focus into the dialog, trap Tab, Escape to close, restore focus on close.
@@ -80,6 +93,19 @@ export function PassageDialog({
80
93
  // Be on the stack of displayed dialogs the Story dialog API works on.
81
94
  useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
82
95
 
96
+ // Name the dialog after its first heading when no label is given
97
+ useLayoutEffect(() => {
98
+ const panel = panelRef.current;
99
+ if (!panel || label) return;
100
+ const heading = panel.querySelector<HTMLElement>(
101
+ '.dialog-body :is(h1, h2, h3, h4, h5, h6)',
102
+ );
103
+ if (!heading) return;
104
+ heading.id ||= `${labelId}-heading`;
105
+ panel.setAttribute('aria-labelledby', heading.id);
106
+ return () => panel.removeAttribute('aria-labelledby');
107
+ }, [label, markup]);
108
+
83
109
  // Signal that the dialog's DOM is committed (once per open).
84
110
  useLayoutEffect(() => {
85
111
  if (panelRef.current) {
@@ -107,6 +133,7 @@ export function PassageDialog({
107
133
  class={cls}
108
134
  role="dialog"
109
135
  aria-modal="true"
136
+ aria-label={label ?? passageName}
110
137
  tabIndex={-1}
111
138
  >
112
139
  {showCloseButton && (