@rohal12/spindle 0.59.31 → 0.59.33

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, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
2
+ import { useCallback, useContext, useEffect, useErrorBoundary, 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";
@@ -14847,7 +14847,7 @@ function encodePayload(payload) {
14847
14847
  /** Thrown for stored data that is not a payload this format can hold. */
14848
14848
  var invalid = () => /* @__PURE__ */ new Error("Invalid save data");
14849
14849
  /** A plain object or one without a prototype (a variable namespace). */
14850
- function isRecord$1(value) {
14850
+ function isRecord$2(value) {
14851
14851
  if (typeof value !== "object" || value === null) return false;
14852
14852
  const proto = Object.getPrototypeOf(value);
14853
14853
  return proto === Object.prototype || proto === null;
@@ -14855,10 +14855,10 @@ function isRecord$1(value) {
14855
14855
  /** Absent, null, or a `{ seed, pull }` PRNG snapshot. */
14856
14856
  function isOptionalPRNGSnapshot(value) {
14857
14857
  if (value == null) return true;
14858
- return isRecord$1(value) && typeof value.seed === "string" && typeof value.pull === "number" && Number.isInteger(value.pull) && value.pull >= 0;
14858
+ return isRecord$2(value) && typeof value.seed === "string" && typeof value.pull === "number" && Number.isInteger(value.pull) && value.pull >= 0;
14859
14859
  }
14860
- var isMoment = (value) => isRecord$1(value) && typeof value.passage === "string" && isRecord$1(value.variables) && typeof value.timestamp === "number" && isOptionalPRNGSnapshot(value.prng);
14861
- var isWatchers = (value) => value === void 0 || Array.isArray(value) && Array.from(value).every((w) => isRecord$1(w) && typeof w.condition === "string" && isRecord$1(w.options));
14860
+ var isMoment = (value) => isRecord$2(value) && typeof value.passage === "string" && isRecord$2(value.variables) && typeof value.timestamp === "number" && isOptionalPRNGSnapshot(value.prng);
14861
+ var isWatchers = (value) => value === void 0 || Array.isArray(value) && Array.from(value).every((w) => isRecord$2(w) && typeof w.condition === "string" && isRecord$2(w.options));
14862
14862
  var isCountsMap = (value) => value === void 0 || value instanceof Map && [...value.keys()].every((k) => typeof k === "string");
14863
14863
  /**
14864
14864
  * Whether a deserialized payload is well formed: every history moment is,
@@ -14866,8 +14866,8 @@ var isCountsMap = (value) => value === void 0 || value instanceof Map && [...val
14866
14866
  * passage.
14867
14867
  */
14868
14868
  function isPayload(value) {
14869
- if (!isRecord$1(value)) return false;
14870
- if (typeof value.passage !== "string" || !isRecord$1(value.variables)) return false;
14869
+ if (!isRecord$2(value)) return false;
14870
+ if (typeof value.passage !== "string" || !isRecord$2(value.variables)) return false;
14871
14871
  const { history, historyIndex } = value;
14872
14872
  if (!Array.isArray(history) || history.length === 0) return false;
14873
14873
  if (!Array.from(history).every(isMoment)) return false;
@@ -14900,7 +14900,7 @@ function decodePayload(encoded) {
14900
14900
  //#endregion
14901
14901
  //#region src/saves/types.ts
14902
14902
  var INVALID_FILE = "Invalid save file format";
14903
- function isRecord(value) {
14903
+ function isRecord$1(value) {
14904
14904
  return typeof value === "object" && value !== null && !Array.isArray(value);
14905
14905
  }
14906
14906
  var META_STRINGS = [
@@ -14931,12 +14931,12 @@ function decodeQuietly(encoded) {
14931
14931
  * Anything that passes can be stored and later loaded.
14932
14932
  */
14933
14933
  function checkSaveExport(value) {
14934
- if (!isRecord(value)) throw new Error(INVALID_FILE);
14934
+ if (!isRecord$1(value)) throw new Error(INVALID_FILE);
14935
14935
  if (!hasOwn(value, "formatVersion")) throw value.version === 1 ? new IncompatibleSaveError() : /* @__PURE__ */ new Error(INVALID_FILE);
14936
14936
  checkFormatVersion(value.formatVersion);
14937
14937
  if (typeof value.ifid !== "string") throw new Error(INVALID_FILE);
14938
14938
  const save = value.save;
14939
- if (!isRecord(save) || !isRecord(save.meta)) throw new Error(INVALID_FILE);
14939
+ if (!isRecord$1(save) || !isRecord$1(save.meta)) throw new Error(INVALID_FILE);
14940
14940
  const meta = save.meta;
14941
14941
  if (META_STRINGS.some((key) => typeof meta[key] !== "string")) throw new Error(INVALID_FILE);
14942
14942
  try {
@@ -17788,26 +17788,42 @@ function registerDialogHost(callbacks) {
17788
17788
  /**
17789
17789
  * The dialogs on display, bottom first, whoever opened them: the trigger
17790
17790
  * host, `{dialog}` or a menubar button (each PassageDialog registers itself
17791
- * while mounted), as the function that closes each.
17791
+ * while mounted).
17792
17792
  */
17793
17793
  var openDialogs = [];
17794
- /** Register a displayed dialog; returns the function that unregisters it. */
17795
- function registerOpenDialog(close) {
17796
- openDialogs.push(close);
17794
+ /**
17795
+ * Register a displayed dialog, as the function that closes it (its
17796
+ * DialogCloseContext value) and its panel element; returns the function
17797
+ * that unregisters it.
17798
+ */
17799
+ function registerOpenDialog(close, panel = null) {
17800
+ const entry = {
17801
+ close,
17802
+ panel
17803
+ };
17804
+ openDialogs.push(entry);
17797
17805
  return () => {
17798
- const i = openDialogs.lastIndexOf(close);
17806
+ const i = openDialogs.lastIndexOf(entry);
17799
17807
  if (i >= 0) openDialogs.splice(i, 1);
17800
17808
  };
17801
17809
  }
17810
+ /** The close function of the topmost dialog, or undefined when none is open. */
17811
+ function innermostOpenDialog() {
17812
+ return openDialogs[openDialogs.length - 1]?.close;
17813
+ }
17814
+ /** The panels of the dialogs on display, in opening order (innermost last). */
17815
+ function openDialogPanels() {
17816
+ return openDialogs.flatMap((d) => d.panel ? [d.panel] : []);
17817
+ }
17802
17818
  /** Close the topmost dialog. */
17803
17819
  function closeCurrentDialog() {
17804
- const top = openDialogs[openDialogs.length - 1];
17820
+ const top = innermostOpenDialog();
17805
17821
  if (top) top();
17806
17822
  else dialogHostCallbacks?.close();
17807
17823
  }
17808
17824
  function closeAllOpenDialogs() {
17809
17825
  clearDialogQueue();
17810
- for (const close of [...openDialogs].reverse()) close();
17826
+ for (const { close } of [...openDialogs].reverse()) close();
17811
17827
  dialogHostCallbacks?.closeAll();
17812
17828
  }
17813
17829
  function isDialogShowing() {
@@ -17827,7 +17843,8 @@ var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
17827
17843
  "PassageReady",
17828
17844
  "PassageHeader",
17829
17845
  "PassageFooter",
17830
- "PassageDone"
17846
+ "PassageDone",
17847
+ "StoryContext"
17831
17848
  ]);
17832
17849
  /** Full variable snapshot at history index 0. */
17833
17850
  var variableBase = createNamespace();
@@ -19357,8 +19374,254 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
19357
19374
  }, [dismissible, onClose]);
19358
19375
  }
19359
19376
  //#endregion
19360
- //#region src/components/PassageDialog.tsx
19377
+ //#region src/utils/field-checks.ts
19378
+ function isRecord(value) {
19379
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19380
+ }
19381
+ /** `value` as an object whose keys are all in `allowed`. */
19382
+ function checkObject(value, what, allowed, fail) {
19383
+ if (!isRecord(value)) fail(`${what} must be an object`);
19384
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(`${what} has an unknown field "${key}" (${allowed.join(", ")})`);
19385
+ return value;
19386
+ }
19387
+ var isString = (v) => typeof v === "string";
19388
+ var isBoolean = (v) => typeof v === "boolean";
19389
+ /** Each field of `obj` named in `checks` passes its check. */
19390
+ function checkFields(obj, what, checks, fail) {
19391
+ for (const [key, [valid, expected]] of Object.entries(checks)) if (key in obj && !valid(obj[key])) fail(`"${key}" of ${what} must be ${expected}`);
19392
+ }
19393
+ //#endregion
19394
+ //#region src/action-registry.ts
19395
+ /** The fields of a StoryAction that are left out when unset. */
19396
+ var OPTIONAL_ACTION_FIELDS = [
19397
+ "target",
19398
+ "variable",
19399
+ "options",
19400
+ "value",
19401
+ "disabled"
19402
+ ];
19403
+ /** The matcher fields compared with the action field of the same name. */
19404
+ var MATCHED_FIELDS = [
19405
+ "id",
19406
+ "type",
19407
+ "target",
19408
+ "variable",
19409
+ "label"
19410
+ ];
19411
+ /**
19412
+ * Whether an action satisfies every field the matcher sets. Unset matcher
19413
+ * fields match anything.
19414
+ */
19415
+ function actionMatches(action, matcher) {
19416
+ return MATCHED_FIELDS.every((field) => matcher[field] === void 0 || action[field] === matcher[field]) && (matcher.disabled === void 0 || !!action.disabled === matcher.disabled);
19417
+ }
19418
+ var MATCHER_FIELDS = {
19419
+ type: [isString, "a string"],
19420
+ id: [isString, "a string"],
19421
+ target: [isString, "a string"],
19422
+ variable: [isString, "a string"],
19423
+ label: [isString, "a string"],
19424
+ disabled: [isBoolean, "true or false"]
19425
+ };
19426
+ /**
19427
+ * A copy of `value` as an ActionMatcher, or `fail` naming `what` when it is not an
19428
+ * object of matcher fields with the right types. The automation YAML and
19429
+ * Story.setObservedActions() take matchers from authors.
19430
+ */
19431
+ function checkActionMatcher(value, what, fail) {
19432
+ const matcher = checkObject(value, what, Object.keys(MATCHER_FIELDS), fail);
19433
+ checkFields(matcher, what, MATCHER_FIELDS, fail);
19434
+ return { ...matcher };
19435
+ }
19436
+ /**
19437
+ * The registrations holding each ID, oldest first; the newest is the one
19438
+ * listed. Generated IDs don't collide, but author IDs can, and one control's
19439
+ * cleanup must not remove another control holding the same ID (#233).
19440
+ */
19441
+ var actions = /* @__PURE__ */ new Map();
19442
+ var idCounters = /* @__PURE__ */ new Map();
19443
+ /**
19444
+ * IDs handed out and not yet registered, or registered: a control registers
19445
+ * in a layout effect, after every control of the same render has allocated its
19446
+ * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
19447
+ * Released when the last registration of an ID goes.
19448
+ */
19449
+ var reserved = /* @__PURE__ */ new Set();
19450
+ /**
19451
+ * The counters reset on every navigation, so a passage's controls get the
19452
+ * same IDs each time it is shown. Controls that stay mounted across
19453
+ * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19454
+ * ID still registered (#233) and every one allocated but not registered yet
19455
+ * (#486).
19456
+ */
19457
+ function generateActionId(type, key, authorId) {
19458
+ if (authorId) {
19459
+ reserved.add(authorId);
19460
+ return authorId;
19461
+ }
19462
+ const base = `${type}:${key}`;
19463
+ let count = idCounters.get(base) ?? 0;
19464
+ let id;
19465
+ do {
19466
+ count++;
19467
+ id = count === 1 ? base : `${base}:${count}`;
19468
+ } while (actions.has(id) || reserved.has(id));
19469
+ idCounters.set(base, count);
19470
+ reserved.add(id);
19471
+ return id;
19472
+ }
19473
+ /**
19474
+ * Register `action`, of a control rendered in the dialog `dialog` (the
19475
+ * dialog's DialogCloseContext value), or outside any when null.
19476
+ */
19477
+ function registerAction(action, dialog = null) {
19478
+ const id = action.id;
19479
+ const entry = {
19480
+ action,
19481
+ dialog
19482
+ };
19483
+ const entries = actions.get(id);
19484
+ if (entries) {
19485
+ console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
19486
+ entries.push(entry);
19487
+ } else actions.set(id, [entry]);
19488
+ notify();
19489
+ return {
19490
+ update(next) {
19491
+ const current = actions.get(id);
19492
+ if (!current?.includes(entry)) return;
19493
+ entry.action = next;
19494
+ if (current[current.length - 1] === entry) notify();
19495
+ },
19496
+ unregister() {
19497
+ const current = actions.get(id);
19498
+ const index = current ? current.indexOf(entry) : -1;
19499
+ if (!current || index === -1) return;
19500
+ current.splice(index, 1);
19501
+ if (current.length === 0) {
19502
+ actions.delete(id);
19503
+ reserved.delete(id);
19504
+ }
19505
+ if (index === current.length) notify();
19506
+ }
19507
+ };
19508
+ }
19509
+ /** The promises of the performed actions that have not settled yet. */
19510
+ var running = /* @__PURE__ */ new Set();
19511
+ /**
19512
+ * Perform an action, as `Story.performAction()` does. One that returns a
19513
+ * promise is tracked until it settles, for `settleRunningActions()`, and the
19514
+ * promise is returned for the caller to await (its rejection stays the
19515
+ * caller's to handle).
19516
+ */
19517
+ function performRegisteredAction(action, value) {
19518
+ const result = action.perform(value);
19519
+ if (!result || typeof result.then !== "function") return result;
19520
+ const done = () => void running.delete(result);
19521
+ running.add(result);
19522
+ result.then(done, done);
19523
+ return result.then((v) => v);
19524
+ }
19525
+ /** Wait until every performed action has finished, whether or not it failed. */
19526
+ async function settleRunningActions() {
19527
+ while (running.size > 0) await Promise.allSettled(running);
19528
+ }
19529
+ function getActions() {
19530
+ return Array.from(actions.values(), listed);
19531
+ }
19532
+ /**
19533
+ * The actions of the controls rendered in the dialog `dialog` (its close
19534
+ * function, see registerAction), its nested dialogs' left out.
19535
+ */
19536
+ function getDialogActions(dialog) {
19537
+ return Array.from(actions.values()).map((entries) => entries[entries.length - 1]).filter((entry) => entry.dialog === dialog).map((entry) => entry.action);
19538
+ }
19539
+ function getAction(id) {
19540
+ const entries = actions.get(id);
19541
+ return entries && listed(entries);
19542
+ }
19543
+ function listed(entries) {
19544
+ return entries[entries.length - 1].action;
19545
+ }
19546
+ function resetIdCounters() {
19547
+ idCounters.clear();
19548
+ for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
19549
+ }
19550
+ function notify() {
19551
+ emit("actionsChanged");
19552
+ }
19553
+ //#endregion
19554
+ //#region src/components/dialog-close-context.ts
19555
+ /**
19556
+ * The function that closes the dialog the content renders in, or null
19557
+ * outside any dialog. Each PassageDialog provides its own stable one, so it
19558
+ * also identifies the dialog: the dialog stack (registerOpenDialog) holds
19559
+ * it, and useAction records it with the action, so Story.observe() can
19560
+ * offer only the innermost dialog's actions.
19561
+ */
19361
19562
  var DialogCloseContext = createContext(null);
19563
+ //#endregion
19564
+ //#region src/hooks/use-action.ts
19565
+ /**
19566
+ * While true, controls rendered underneath do not register actions or reserve
19567
+ * IDs. Used for display-only content mounted off-screen, so it never shows up
19568
+ * in `getActions()` or shifts the IDs of the visible passage's controls.
19569
+ */
19570
+ var ActionsDisabledContext = createContext(false);
19571
+ function useAction(opts) {
19572
+ const disabled = useContext(ActionsDisabledContext);
19573
+ const dialog = useContext(DialogCloseContext);
19574
+ const idRef = useRef("");
19575
+ const performRef = useRef(opts.perform);
19576
+ performRef.current = opts.perform;
19577
+ if (!disabled && !idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19578
+ const id = idRef.current;
19579
+ const buildAction = () => {
19580
+ const action = {
19581
+ id,
19582
+ type: opts.type,
19583
+ label: opts.label,
19584
+ perform: (...args) => performRef.current(...args)
19585
+ };
19586
+ for (const field of OPTIONAL_ACTION_FIELDS) if (opts[field] !== void 0) Object.assign(action, { [field]: opts[field] });
19587
+ return action;
19588
+ };
19589
+ const registration = useRef(null);
19590
+ const fresh = useRef(false);
19591
+ useLayoutEffect(() => {
19592
+ if (disabled) return;
19593
+ const own = registerAction(buildAction(), dialog);
19594
+ registration.current = own;
19595
+ fresh.current = true;
19596
+ return () => own.unregister();
19597
+ }, [
19598
+ id,
19599
+ disabled,
19600
+ dialog
19601
+ ]);
19602
+ useLayoutEffect(() => {
19603
+ if (disabled) return;
19604
+ if (fresh.current) {
19605
+ fresh.current = false;
19606
+ return;
19607
+ }
19608
+ registration.current?.update(buildAction());
19609
+ }, [
19610
+ id,
19611
+ disabled,
19612
+ dialog,
19613
+ opts.type,
19614
+ opts.label,
19615
+ opts.target,
19616
+ opts.variable,
19617
+ opts.disabled,
19618
+ opts.value,
19619
+ JSON.stringify(opts.options)
19620
+ ]);
19621
+ return disabled ? "" : id;
19622
+ }
19623
+ //#endregion
19624
+ //#region src/components/PassageDialog.tsx
19362
19625
  function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
19363
19626
  const onCloseRef = useRef(onClose);
19364
19627
  onCloseRef.current = onClose;
@@ -19389,7 +19652,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19389
19652
  const labelId = useId();
19390
19653
  const viewScope = useViewScope();
19391
19654
  useModalFocus(panelRef, ".dialog-body", dismissible, stableOnClose);
19392
- useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
19655
+ useLayoutEffect(() => registerOpenDialog(stableOnClose, panelRef.current), [stableOnClose]);
19393
19656
  useLayoutEffect(() => {
19394
19657
  const panel = panelRef.current;
19395
19658
  if (!panel || label) return;
@@ -19416,15 +19679,14 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19416
19679
  ref: panelRef,
19417
19680
  class: cls,
19418
19681
  role: "dialog",
19682
+ "data-dialog-passage": passageName,
19419
19683
  "aria-modal": "true",
19420
19684
  "aria-label": label ?? passageName,
19421
19685
  tabIndex: -1,
19422
- children: [showCloseButton && /* @__PURE__ */ jsx("button", {
19423
- type: "button",
19424
- class: "dialog-close",
19425
- "aria-label": "Close",
19426
- onClick: stableOnClose,
19427
- children: "✕"
19686
+ children: [showCloseButton && /* @__PURE__ */ jsx(DialogCloseButton, {
19687
+ dialogName: passageName ?? label ?? "dialog",
19688
+ passageName,
19689
+ onClose: stableOnClose
19428
19690
  }), /* @__PURE__ */ jsx("div", {
19429
19691
  class: "dialog-body",
19430
19692
  children: /* @__PURE__ */ jsx(ViewScopeContext.Provider, {
@@ -19436,6 +19698,26 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19436
19698
  })
19437
19699
  });
19438
19700
  }
19701
+ /**
19702
+ * The `✕` button, registered as a `close-dialog` action while the dialog is
19703
+ * shown, so whatever opened it through the API can close it too (#540).
19704
+ */
19705
+ function DialogCloseButton({ dialogName, passageName, onClose }) {
19706
+ useAction({
19707
+ type: "close-dialog",
19708
+ key: dialogName,
19709
+ label: "Close",
19710
+ target: passageName,
19711
+ perform: onClose
19712
+ });
19713
+ return /* @__PURE__ */ jsx("button", {
19714
+ type: "button",
19715
+ class: "dialog-close",
19716
+ "aria-label": "Close",
19717
+ onClick: onClose,
19718
+ children: "✕"
19719
+ });
19720
+ }
19439
19721
  //#endregion
19440
19722
  //#region src/components/TriggerDialogHost.tsx
19441
19723
  function TriggerDialogHost() {
@@ -19923,167 +20205,38 @@ function editedItems(since, state) {
19923
20205
  return (list, item, index) => typeof item === "object" && item !== null ? through.has(item) : ends.get(list)?.has(String(index)) === true;
19924
20206
  }
19925
20207
  //#endregion
19926
- //#region src/action-registry.ts
19927
- /** The fields of a StoryAction that are left out when unset. */
19928
- var OPTIONAL_ACTION_FIELDS = [
19929
- "target",
19930
- "variable",
19931
- "options",
19932
- "value",
19933
- "disabled"
19934
- ];
19935
- /**
19936
- * The registrations holding each ID, oldest first; the newest is the one
19937
- * listed. Generated IDs don't collide, but author IDs can, and one control's
19938
- * cleanup must not remove another control holding the same ID (#233).
19939
- */
19940
- var actions = /* @__PURE__ */ new Map();
19941
- var idCounters = /* @__PURE__ */ new Map();
19942
- /**
19943
- * IDs handed out and not yet registered, or registered: a control registers
19944
- * in a layout effect, after every control of the same render has allocated its
19945
- * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
19946
- * Released when the last registration of an ID goes.
19947
- */
19948
- var reserved = /* @__PURE__ */ new Set();
20208
+ //#region src/utils/extract-text.ts
19949
20209
  /**
19950
- * The counters reset on every navigation, so a passage's controls get the
19951
- * same IDs each time it is shown. Controls that stay mounted across
19952
- * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19953
- * ID still registered (#233) and every one allocated but not registered yet
19954
- * (#486).
20210
+ * Collect plain text from AST nodes, ignoring non-text nodes.
19955
20211
  */
19956
- function generateActionId(type, key, authorId) {
19957
- if (authorId) {
19958
- reserved.add(authorId);
19959
- return authorId;
19960
- }
19961
- const base = `${type}:${key}`;
19962
- let count = idCounters.get(base) ?? 0;
19963
- let id;
19964
- do {
19965
- count++;
19966
- id = count === 1 ? base : `${base}:${count}`;
19967
- } while (actions.has(id) || reserved.has(id));
19968
- idCounters.set(base, count);
19969
- reserved.add(id);
19970
- return id;
19971
- }
19972
- function registerAction(action) {
19973
- const id = action.id;
19974
- const entry = { action };
19975
- const entries = actions.get(id);
19976
- if (entries) {
19977
- console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
19978
- entries.push(entry);
19979
- } else actions.set(id, [entry]);
19980
- notify();
19981
- return {
19982
- update(next) {
19983
- const current = actions.get(id);
19984
- if (!current?.includes(entry)) return;
19985
- entry.action = next;
19986
- if (current[current.length - 1] === entry) notify();
19987
- },
19988
- unregister() {
19989
- const current = actions.get(id);
19990
- const index = current ? current.indexOf(entry) : -1;
19991
- if (!current || index === -1) return;
19992
- current.splice(index, 1);
19993
- if (current.length === 0) {
19994
- actions.delete(id);
19995
- reserved.delete(id);
19996
- }
19997
- if (index === current.length) notify();
19998
- }
19999
- };
20212
+ function collectText(nodes) {
20213
+ return nodes.map((n) => n.type === "text" ? n.value : "").join("");
20000
20214
  }
20001
- /** The promises of the performed actions that have not settled yet. */
20002
- var running = /* @__PURE__ */ new Set();
20215
+ //#endregion
20216
+ //#region src/display-only.ts
20003
20217
  /**
20004
- * Perform an action, as `Story.performAction()` does. One that returns a
20005
- * promise is tracked until it settles, for `settleRunningActions()`, and the
20006
- * promise is returned for the caller to await (its rejection stays the
20007
- * caller's to handle).
20218
+ * The macros that change the story, or act when they mount. A display-only
20219
+ * passage may not use them (see storyContextErrors), and under
20220
+ * DisplayOnlyContext they render an error instead of running.
20008
20221
  */
20009
- function performRegisteredAction(action, value) {
20010
- const result = action.perform(value);
20011
- if (!result || typeof result.then !== "function") return result;
20012
- const done = () => void running.delete(result);
20013
- running.add(result);
20014
- result.then(done, done);
20015
- return result.then((v) => v);
20016
- }
20017
- /** Wait until every performed action has finished, whether or not it failed. */
20018
- async function settleRunningActions() {
20019
- while (running.size > 0) await Promise.allSettled(running);
20020
- }
20021
- function getActions() {
20022
- return Array.from(actions.values(), listed);
20023
- }
20024
- function getAction(id) {
20025
- const entries = actions.get(id);
20026
- return entries && listed(entries);
20027
- }
20028
- function listed(entries) {
20029
- return entries[entries.length - 1].action;
20030
- }
20031
- function resetIdCounters() {
20032
- idCounters.clear();
20033
- for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
20034
- }
20035
- function notify() {
20036
- emit("actionsChanged");
20037
- }
20038
- //#endregion
20039
- //#region src/hooks/use-action.ts
20040
- function useAction(opts) {
20041
- const idRef = useRef("");
20042
- const performRef = useRef(opts.perform);
20043
- performRef.current = opts.perform;
20044
- if (!idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
20045
- const id = idRef.current;
20046
- const buildAction = () => {
20047
- const action = {
20048
- id,
20049
- type: opts.type,
20050
- label: opts.label,
20051
- perform: (...args) => performRef.current(...args)
20052
- };
20053
- for (const field of OPTIONAL_ACTION_FIELDS) if (opts[field] !== void 0) Object.assign(action, { [field]: opts[field] });
20054
- return action;
20055
- };
20056
- const registration = useRef(null);
20057
- useLayoutEffect(() => {
20058
- const own = registerAction(buildAction());
20059
- registration.current = own;
20060
- return () => own.unregister();
20061
- }, [id]);
20062
- const registered = useRef(false);
20063
- useLayoutEffect(() => {
20064
- if (!registered.current) {
20065
- registered.current = true;
20066
- return;
20067
- }
20068
- registration.current?.update(buildAction());
20069
- }, [
20070
- opts.type,
20071
- opts.label,
20072
- opts.target,
20073
- opts.variable,
20074
- opts.disabled,
20075
- opts.value,
20076
- JSON.stringify(opts.options)
20077
- ]);
20078
- return id;
20079
- }
20080
- //#endregion
20081
- //#region src/utils/extract-text.ts
20222
+ var ACTING_MACROS = [
20223
+ "set",
20224
+ "do",
20225
+ "unset",
20226
+ "computed",
20227
+ "goto",
20228
+ "watch"
20229
+ ];
20082
20230
  /**
20083
- * Collect plain text from AST nodes, ignoring non-text nodes.
20231
+ * While true, the macros rendered underneath change nothing: the acting
20232
+ * macros and every macro's `ctx.mutate`, `ctx.update` and `ctx.setValue`
20233
+ * fail with displayOnlyError(). Provided around the `StoryContext` tree,
20234
+ * which its static check can't see into ({include}, widget bodies).
20084
20235
  */
20085
- function collectText(nodes) {
20086
- return nodes.map((n) => n.type === "text" ? n.value : "").join("");
20236
+ var DisplayOnlyContext = createContext(false);
20237
+ /** The error of the macro `{name}` trying to change a display-only passage. */
20238
+ function displayOnlyError(name) {
20239
+ return /* @__PURE__ */ new Error(`StoryContext is display-only: {${name}} cannot change the story`);
20087
20240
  }
20088
20241
  //#endregion
20089
20242
  //#region src/define-macro.ts
@@ -20091,6 +20244,7 @@ function macroClass(type, className) {
20091
20244
  const base = `macro-${type}`;
20092
20245
  return className ? `${base} ${className}` : base;
20093
20246
  }
20247
+ var actingMacros = new NameSet(ACTING_MACROS);
20094
20248
  var sharedHooks = {
20095
20249
  useState,
20096
20250
  useRef,
@@ -20103,7 +20257,16 @@ var sharedHooks = {
20103
20257
  function defineMacro(config, source = "builtin") {
20104
20258
  const parameters = config.parameters ?? [];
20105
20259
  checkParameterTypes(config.name, parameters);
20260
+ const acts = actingMacros.has(config.name);
20106
20261
  function Wrapper(props) {
20262
+ const displayOnly = useContext(DisplayOnlyContext);
20263
+ if (displayOnly && acts) return h(MacroError, {
20264
+ macro: config.name,
20265
+ error: displayOnlyError(config.name)
20266
+ });
20267
+ const refuse = () => {
20268
+ throw displayOnlyError(config.name);
20269
+ };
20107
20270
  let className = props.className;
20108
20271
  let id = props.id;
20109
20272
  let resolve;
@@ -20144,8 +20307,8 @@ function defineMacro(config, source = "builtin") {
20144
20307
  id,
20145
20308
  resolve,
20146
20309
  cls: macroClass(config.name, className),
20147
- mutate: inIteration ? (code) => runAsItemEdit(() => executeMutation(code, getValues(), update)) : (code) => executeMutation(code, getValues(), update),
20148
- update,
20310
+ mutate: displayOnly ? refuse : inIteration ? (code) => runAsItemEdit(() => executeMutation(code, getValues(), update)) : (code) => executeMutation(code, getValues(), update),
20311
+ update: displayOnly ? refuse : update,
20149
20312
  getValues,
20150
20313
  wrap: (content) => wrapContent(className, id, content)
20151
20314
  };
@@ -20168,7 +20331,7 @@ function defineMacro(config, source = "builtin") {
20168
20331
  ctx.varName = varExpr;
20169
20332
  ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
20170
20333
  ctx.getValue = () => getByPath(readState().variables, segments);
20171
- ctx.setValue = (value) => {
20334
+ ctx.setValue = displayOnly ? refuse : (value) => {
20172
20335
  noteControlEdit(segments);
20173
20336
  mutateState((work, adopt) => {
20174
20337
  setByPath(work.variables, segments, adopt(value), { createMissing: true });
@@ -20222,6 +20385,286 @@ function getRenderedNavigationId() {
20222
20385
  return renderedNavigationId;
20223
20386
  }
20224
20387
  //#endregion
20388
+ //#region src/story-context-passage.ts
20389
+ /**
20390
+ * The macros a display-only passage may not use besides the input macros:
20391
+ * they change the story, act when they mount, or are controls.
20392
+ */
20393
+ var REJECTED_MACROS = [
20394
+ ...ACTING_MACROS,
20395
+ "link",
20396
+ "button",
20397
+ "dialog"
20398
+ ];
20399
+ /**
20400
+ * Why `StoryContext` (the passage an agent reads for stats and
20401
+ * instructions) may not use what it uses: it is display-only, so no macro
20402
+ * that changes the story or acts on mount, no input and no `[[link]]`.
20403
+ * `inputMacros` are the names of the macros that bind a variable. Each
20404
+ * name is reported once. Malformed markup is left to the markup validation.
20405
+ */
20406
+ function storyContextErrors(content, inputMacros) {
20407
+ const rejected = new NameSet([...REJECTED_MACROS, ...inputMacros]);
20408
+ let tokens;
20409
+ try {
20410
+ tokens = tokenizeMarkup(content);
20411
+ } catch (err) {
20412
+ if (err instanceof MarkupError) return [];
20413
+ throw err;
20414
+ }
20415
+ const found = /* @__PURE__ */ new Set();
20416
+ for (const token of tokens) if (token.type === "link") found.add("[[links]]");
20417
+ else if (token.type === "macro" && !token.isClose && rejected.has(token.name)) found.add(`{${token.name.toLowerCase()}}`);
20418
+ return [...found].map((what) => `StoryContext: ${what} is not allowed; StoryContext is display-only`);
20419
+ }
20420
+ /** The element the mounted StoryContext tree renders into. */
20421
+ var container = null;
20422
+ /** The hidden element the container was put in. */
20423
+ var wrapper = null;
20424
+ /** What shows in place of a StoryContext that can't be rendered. */
20425
+ function contextError(err) {
20426
+ return h("span", { class: "error" }, `StoryContext: ${errorMessage(err)}`);
20427
+ }
20428
+ /** The passage's tree, or the error that stops it from rendering. */
20429
+ function StoryContextView({ ast }) {
20430
+ const [error] = useErrorBoundary();
20431
+ return error ? contextError(error) : renderNodes(ast);
20432
+ }
20433
+ /**
20434
+ * The element holding the rendered `StoryContext` passage, or null when the
20435
+ * story has none. It is mounted on the first call, hidden from the page and
20436
+ * with its controls registering no actions, and stays mounted: it follows the
20437
+ * story's variables, also across a restart. The element itself is not hidden
20438
+ * (its parent is), so observableText() reads it. A passage that can't be
20439
+ * parsed or rendered shows its error as text in the element; this never
20440
+ * throws.
20441
+ */
20442
+ function storyContextElement() {
20443
+ if (container?.isConnected) return container;
20444
+ if (container) {
20445
+ render(null, container);
20446
+ wrapper?.remove();
20447
+ container = wrapper = null;
20448
+ }
20449
+ const passage = useStoryStore.getState().storyData?.passages.get("StoryContext");
20450
+ if (!passage) return null;
20451
+ const hidden = document.createElement("div");
20452
+ hidden.style.display = "none";
20453
+ const el = document.createElement("div");
20454
+ hidden.appendChild(el);
20455
+ document.body.appendChild(hidden);
20456
+ container = el;
20457
+ wrapper = hidden;
20458
+ let view;
20459
+ try {
20460
+ view = h(StoryContextView, { ast: parseMarkup(passage.content) });
20461
+ } catch (err) {
20462
+ view = contextError(err);
20463
+ }
20464
+ const mount = () => render(h(ActionsDisabledContext.Provider, { value: true }, h(DisplayOnlyContext.Provider, { value: true }, view)), el);
20465
+ try {
20466
+ mount();
20467
+ mount();
20468
+ } catch (err) {
20469
+ render(contextError(err), el);
20470
+ }
20471
+ return el;
20472
+ }
20473
+ //#endregion
20474
+ //#region src/observe/observable-text.ts
20475
+ /** Elements that start and end a line. */
20476
+ var BLOCKS = /* @__PURE__ */ new Set([
20477
+ "P",
20478
+ "DIV",
20479
+ "LI",
20480
+ "H1",
20481
+ "H2",
20482
+ "H3",
20483
+ "H4",
20484
+ "H5",
20485
+ "H6",
20486
+ "BLOCKQUOTE",
20487
+ "PRE",
20488
+ "TR",
20489
+ "SECTION",
20490
+ "ARTICLE",
20491
+ "HEADER",
20492
+ "FOOTER"
20493
+ ]);
20494
+ /** Elements whose content is never text the reader reads. */
20495
+ var NOT_TEXT = /* @__PURE__ */ new Set([
20496
+ "SCRIPT",
20497
+ "STYLE",
20498
+ "TEMPLATE",
20499
+ "NOSCRIPT"
20500
+ ]);
20501
+ /**
20502
+ * Whether the reader can't see the element. Headless DOMs compute no layout,
20503
+ * so only what the markup says counts: the `hidden` attribute, an inline
20504
+ * `display: none` and `aria-hidden="true"`.
20505
+ */
20506
+ function isHidden(el) {
20507
+ return el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true" || /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute("style") ?? "") || NOT_TEXT.has(el.tagName);
20508
+ }
20509
+ function formatValue(value) {
20510
+ return JSON.stringify(value) ?? String(value);
20511
+ }
20512
+ /** What a control with an action shows: its type, variable and value. */
20513
+ function controlMarker(el) {
20514
+ const own = el;
20515
+ const action = getAction(el.getAttribute("data-action") ?? "");
20516
+ const type = action?.type ?? el.getAttribute("type") ?? el.localName;
20517
+ const isCheckbox = type === "checkbox";
20518
+ const value = action?.value !== void 0 ? action.value : isCheckbox ? !!own.checked : own.value ?? "";
20519
+ const shown = isCheckbox ? value ? "checked" : "unchecked" : formatValue(value);
20520
+ const variable = action?.variable;
20521
+ const name = variable && !variable.startsWith("$") ? `$${variable}` : variable;
20522
+ if (type === "radiobutton" && own.value !== void 0) {
20523
+ const state = action?.value === own.value ? "selected" : "unselected";
20524
+ return `[${type}${name ? ` ${name}` : ""} = ${formatValue(own.value)}: ${state}]`;
20525
+ }
20526
+ return `[${type}${name ? ` ${name}` : ""}: ${shown}]`;
20527
+ }
20528
+ /**
20529
+ * The text a reader sees in the element, as lines: blocks and `<br>` break
20530
+ * lines, hidden elements are left out, and a control with a `data-action`
20531
+ * becomes a marker such as `[textbox $name: "Alice"]`. Elements inside `el`
20532
+ * that match `skip` are left out with their content.
20533
+ */
20534
+ function observableText(el, skip) {
20535
+ let out = "";
20536
+ const endLine = () => {
20537
+ if (out !== "" && !out.endsWith("\n")) out += "\n";
20538
+ };
20539
+ const walk = (node, inPre) => {
20540
+ if (node.nodeType === 3) {
20541
+ const data = node.textContent ?? "";
20542
+ if (inPre) out += data;
20543
+ else {
20544
+ const collapsed = data.replace(/\s+/g, " ");
20545
+ out += out === "" || out.endsWith("\n") ? collapsed.trimStart() : collapsed;
20546
+ }
20547
+ return;
20548
+ }
20549
+ if (node.nodeType !== 1) return;
20550
+ const child = node;
20551
+ if (isHidden(child) || skip && child !== el && child.matches(skip)) return;
20552
+ if (child.hasAttribute("data-action")) {
20553
+ out += controlMarker(child);
20554
+ return;
20555
+ }
20556
+ if (child.tagName === "BR") {
20557
+ out += "\n";
20558
+ return;
20559
+ }
20560
+ const block = BLOCKS.has(child.tagName);
20561
+ if (block) endLine();
20562
+ for (const c of Array.from(child.childNodes)) walk(c, inPre || child.tagName === "PRE");
20563
+ if (block) endLine();
20564
+ };
20565
+ walk(el, false);
20566
+ return out.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\s+$/g, "");
20567
+ }
20568
+ /**
20569
+ * The trimmed text of each error shown in the element, leaving out those
20570
+ * the reader can't see (inside a hidden element, as observableText() does)
20571
+ * and those inside an element within `el` that matches `skip`.
20572
+ */
20573
+ function observableErrors(el, skip) {
20574
+ const left = (e) => {
20575
+ for (let at = e; at; at = at.parentElement) {
20576
+ if (isHidden(at)) return true;
20577
+ if (at === el) return false;
20578
+ if (skip && at.matches(skip)) return true;
20579
+ }
20580
+ return false;
20581
+ };
20582
+ return Array.from(el.querySelectorAll(".error")).filter((e) => !left(e)).map((e) => (e.textContent ?? "").trim());
20583
+ }
20584
+ //#endregion
20585
+ //#region src/observe/observe.ts
20586
+ /**
20587
+ * Leaving the story's history, restarting, saving and loading, and the
20588
+ * menubar's Saves and Settings dialogs (`dialog`) are not moves in the story.
20589
+ */
20590
+ var DEFAULT_EXCLUDED = /* @__PURE__ */ new Set([
20591
+ "back",
20592
+ "forward",
20593
+ "restart",
20594
+ "save",
20595
+ "load",
20596
+ "dialog"
20597
+ ]);
20598
+ /**
20599
+ * The actions an observation offers: without the default exclusions unless
20600
+ * an `include` rule puts them back, and without what an `exclude` rule
20601
+ * matches (exclude wins over include).
20602
+ */
20603
+ function filterObservedActions(actions, rules) {
20604
+ const matchesAny = (action, matchers) => matchers?.some((m) => actionMatches(action, m)) ?? false;
20605
+ return actions.filter((action) => !matchesAny(action, rules.exclude) && (!DEFAULT_EXCLUDED.has(action.type) || matchesAny(action, rules.include))).map(({ perform: _perform, ...rest }) => rest);
20606
+ }
20607
+ var observedRules = {};
20608
+ /**
20609
+ * Replace the rules for which actions observe() offers. Each matcher is
20610
+ * checked as the automation YAML checks its matchers; a bad one throws,
20611
+ * naming the rule.
20612
+ */
20613
+ function setObservedActions(rules) {
20614
+ const fail = (message) => {
20615
+ throw new Error(`spindle: Story.setObservedActions(): ${message}`);
20616
+ };
20617
+ const r = checkObject(rules, "the rules", ["exclude", "include"], fail);
20618
+ const next = {};
20619
+ for (const key of ["exclude", "include"]) {
20620
+ const list = r[key];
20621
+ if (list === void 0) continue;
20622
+ if (!Array.isArray(list)) fail(`"${key}" must be a list of action matchers`);
20623
+ next[key] = list.map((m, i) => checkActionMatcher(m, `the rule ${key}[${i}]`, fail));
20624
+ }
20625
+ observedRules = next;
20626
+ }
20627
+ /** A dialog, from its backdrop down. */
20628
+ var DIALOG = ".dialog-overlay";
20629
+ /**
20630
+ * The actions a reader can reach: while a dialog is open (it is modal) only
20631
+ * those in the innermost one, its close button included.
20632
+ */
20633
+ function offeredActions() {
20634
+ const dialog = innermostOpenDialog();
20635
+ return dialog ? getDialogActions(dialog) : getActions();
20636
+ }
20637
+ /** What the story shows and offers now. */
20638
+ function observe() {
20639
+ if (getRenderedNavigationId() === null) throw new Error("spindle: Story.observe() needs a mounted story");
20640
+ const { currentPassage, navigationId } = useStoryStore.getState();
20641
+ const contextEl = storyContextElement();
20642
+ const passageEl = document.querySelector(".passage");
20643
+ const bodies = openDialogPanels().map((el) => ({
20644
+ passage: el.getAttribute("data-dialog-passage") ?? "",
20645
+ body: el.querySelector(":scope > .dialog-body")
20646
+ }));
20647
+ const dialogs = bodies.map(({ passage, body }) => ({
20648
+ passage,
20649
+ text: body ? observableText(body, DIALOG) : ""
20650
+ }));
20651
+ const errors = [
20652
+ passageEl,
20653
+ ...bodies.map((d) => d.body),
20654
+ contextEl
20655
+ ].flatMap((el) => el ? observableErrors(el, DIALOG) : []);
20656
+ for (const { context, message } of getRuntimeErrors()) errors.push(`${context.replace(/:$/, "")}: ${message}`);
20657
+ return {
20658
+ passage: currentPassage,
20659
+ text: passageEl ? observableText(passageEl, DIALOG) : "",
20660
+ context: contextEl ? observableText(contextEl) : null,
20661
+ dialogs,
20662
+ actions: filterObservedActions(offeredActions(), observedRules),
20663
+ errors,
20664
+ turn: navigationId
20665
+ };
20666
+ }
20667
+ //#endregion
20225
20668
  //#region src/story-api.ts
20226
20669
  var readyResolve = null;
20227
20670
  var readyPromise = null;
@@ -20297,7 +20740,7 @@ function storeAction(name) {
20297
20740
  return ((...args) => useStoryStore.getState()[name](...args));
20298
20741
  }
20299
20742
  function createStoryAPI() {
20300
- return {
20743
+ const api = {
20301
20744
  get(name) {
20302
20745
  const { isTransient, key } = parseName(name);
20303
20746
  const scope = getActiveMutationScope();
@@ -20420,6 +20863,13 @@ function createStoryAPI() {
20420
20863
  });
20421
20864
  return getActions();
20422
20865
  },
20866
+ observe,
20867
+ async step(id, value) {
20868
+ await api.performAction(id, value);
20869
+ await api.waitForActions();
20870
+ return observe();
20871
+ },
20872
+ setObservedActions,
20423
20873
  watch(condition, callbackOrOptions) {
20424
20874
  return addTrigger(condition, callbackOrOptions);
20425
20875
  },
@@ -20515,6 +20965,7 @@ function createStoryAPI() {
20515
20965
  }
20516
20966
  }
20517
20967
  };
20968
+ return api;
20518
20969
  }
20519
20970
  function installStoryAPI() {
20520
20971
  window.Story = createStoryAPI();
@@ -22741,7 +23192,8 @@ function Settled({ onSettled }) {
22741
23192
  * through a live view, so a local assigned earlier in the body is visible),
22742
23193
  * nobr/inline rendering, the enclosing block widget's {@children}, the
22743
23194
  * enclosing {repeat}'s {stop} and the enclosing dialog's close callback and whether it runs in a {for} iteration
22744
- * (#411) and the owning passage's departure (#410).
23195
+ * (#411), the owning passage's departure (#410), and whether it renders in
23196
+ * display-only content (StoryContext), which a body may not change either.
22745
23197
  * The body then behaves as if it rendered in place.
22746
23198
  *
22747
23199
  * The body's macros read story state from the store. Run from mutation code
@@ -22758,6 +23210,8 @@ function useDetachedBody() {
22758
23210
  const closeDialog = useContext(DialogCloseContext);
22759
23211
  const inIteration = useContext(ItemEditContext);
22760
23212
  const hasLeft = useContext(OutgoingContext);
23213
+ const displayOnly = useContext(DisplayOnlyContext);
23214
+ const actionsDisabled = useContext(ActionsDisabledContext);
22761
23215
  const mounted = useRef([]);
22762
23216
  useEffect(() => {
22763
23217
  const unsubscribe = subscribeStateReplacement(() => {
@@ -22800,14 +23254,20 @@ function useDetachedBody() {
22800
23254
  value: closeDialog,
22801
23255
  children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
22802
23256
  value: inIteration,
22803
- children: /* @__PURE__ */ jsxs(OutgoingContext.Provider, {
23257
+ children: /* @__PURE__ */ jsx(OutgoingContext.Provider, {
22804
23258
  value: hasLeft,
22805
- children: [renderNodes(children, {
22806
- nobr,
22807
- inline,
22808
- structural,
22809
- locals
22810
- }), release && /* @__PURE__ */ jsx(Settled, { onSettled: release })]
23259
+ children: /* @__PURE__ */ jsx(DisplayOnlyContext.Provider, {
23260
+ value: displayOnly,
23261
+ children: /* @__PURE__ */ jsxs(ActionsDisabledContext.Provider, {
23262
+ value: actionsDisabled,
23263
+ children: [renderNodes(children, {
23264
+ nobr,
23265
+ inline,
23266
+ structural,
23267
+ locals
23268
+ }), release && /* @__PURE__ */ jsx(Settled, { onSettled: release })]
23269
+ })
23270
+ })
22811
23271
  })
22812
23272
  })
22813
23273
  })
@@ -23303,16 +23763,25 @@ defineMacro({
23303
23763
  name: "noclose",
23304
23764
  type: "flag"
23305
23765
  }],
23306
- render({ children = [] }, ctx) {
23766
+ render({ rawArgs, children = [] }, ctx) {
23307
23767
  const [open, setOpen] = ctx.hooks.useState(false);
23308
23768
  const { noclose } = ctx.args;
23309
- const label = ctx.resolve(ctx.args.label ?? "");
23769
+ const label = ctx.resolve(ctx.args.label ?? "") ?? "";
23310
23770
  const passageName = ctx.collectText(children).trim().replace(/^["']|["']$/g, "");
23771
+ const openDialog = () => setOpen(true);
23772
+ ctx.useAction({
23773
+ type: "open-dialog",
23774
+ key: rawArgs,
23775
+ authorId: ctx.id,
23776
+ label,
23777
+ target: passageName,
23778
+ perform: openDialog
23779
+ });
23311
23780
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
23312
23781
  type: "button",
23313
23782
  id: ctx.id,
23314
23783
  class: ctx.cls,
23315
- onClick: () => setOpen(true),
23784
+ onClick: openDialog,
23316
23785
  children: label
23317
23786
  }), open && /* @__PURE__ */ jsx(PassageDialog, {
23318
23787
  passageName,
@@ -23917,7 +24386,7 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
23917
24386
  }],
23918
24387
  render(_props, ctx) {
23919
24388
  const placeholder = ctx.args.placeholder ?? "";
23920
- useVariableAction(ctx, {
24389
+ const actionId = useVariableAction(ctx, {
23921
24390
  type: name,
23922
24391
  label: placeholder || ctx.varName,
23923
24392
  perform: (v) => ctx.setValue(toValue(v))
@@ -23927,6 +24396,7 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
23927
24396
  return h(type ? "input" : "textarea", {
23928
24397
  type,
23929
24398
  id: ctx.id,
24399
+ "data-action": actionId || void 0,
23930
24400
  class: ctx.cls,
23931
24401
  value: shown,
23932
24402
  placeholder,
@@ -23961,7 +24431,7 @@ defineMacro({
23961
24431
  }],
23962
24432
  render(_props, ctx) {
23963
24433
  const label = ctx.args.label ?? "";
23964
- useVariableAction(ctx, {
24434
+ const actionId = useVariableAction(ctx, {
23965
24435
  type: "checkbox",
23966
24436
  label: label || ctx.varName || "",
23967
24437
  value: !!ctx.value,
@@ -23972,6 +24442,7 @@ defineMacro({
23972
24442
  class: ctx.cls,
23973
24443
  children: [/* @__PURE__ */ jsx("input", {
23974
24444
  type: "checkbox",
24445
+ "data-action": actionId || void 0,
23975
24446
  checked: !!ctx.value,
23976
24447
  onChange: (e) => ctx.setValue(e.target.checked)
23977
24448
  }), label ? ` ${label}` : null]
@@ -24002,7 +24473,7 @@ defineMacro({
24002
24473
  const radioValue = ctx.args.value ?? "";
24003
24474
  const label = ctx.args.label ?? "";
24004
24475
  const view = ctx.hooks.useContext(ViewScopeContext);
24005
- useVariableAction(ctx, {
24476
+ const actionId = useVariableAction(ctx, {
24006
24477
  type: "radiobutton",
24007
24478
  key: `$${ctx.varName}:${radioValue}`,
24008
24479
  label: label || radioValue,
@@ -24013,6 +24484,8 @@ defineMacro({
24013
24484
  class: ctx.cls,
24014
24485
  children: [/* @__PURE__ */ jsx("input", {
24015
24486
  type: "radio",
24487
+ value: radioValue,
24488
+ "data-action": actionId || void 0,
24016
24489
  name: view ? `radio-${view}-${ctx.varName}` : `radio-${ctx.varName}`,
24017
24490
  checked: ctx.value === radioValue,
24018
24491
  onChange: () => ctx.setValue(radioValue)
@@ -24030,7 +24503,7 @@ defineMacro({
24030
24503
  parameters: [VARIABLE_PARAMETER],
24031
24504
  render({ children = [] }, ctx) {
24032
24505
  const options = ctx.extractOptions(children);
24033
- useVariableAction(ctx, {
24506
+ const actionId = useVariableAction(ctx, {
24034
24507
  type: "listbox",
24035
24508
  label: ctx.varName,
24036
24509
  options,
@@ -24040,6 +24513,7 @@ defineMacro({
24040
24513
  });
24041
24514
  return /* @__PURE__ */ jsx("select", {
24042
24515
  id: ctx.id,
24516
+ "data-action": actionId || void 0,
24043
24517
  class: ctx.cls,
24044
24518
  value: display(ctx.value),
24045
24519
  onChange: (e) => ctx.setValue(e.target.value),
@@ -24066,7 +24540,7 @@ defineMacro({
24066
24540
  const nextIndex = (options.indexOf(String(current)) + 1) % options.length;
24067
24541
  ctx.setValue(options[nextIndex]);
24068
24542
  };
24069
- useVariableAction(ctx, {
24543
+ const actionId = useVariableAction(ctx, {
24070
24544
  type: "cycle",
24071
24545
  label: ctx.value == null ? options[0] || "" : String(ctx.value),
24072
24546
  options,
@@ -24078,6 +24552,7 @@ defineMacro({
24078
24552
  return /* @__PURE__ */ jsx("button", {
24079
24553
  type: "button",
24080
24554
  id: ctx.id,
24555
+ "data-action": actionId || void 0,
24081
24556
  class: ctx.cls,
24082
24557
  onClick: handleClick,
24083
24558
  children: ctx.value == null ? options[0] || "" : String(ctx.value)
@@ -24223,14 +24698,17 @@ function orStop(parse, where = "") {
24223
24698
  function knownParameters() {
24224
24699
  return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
24225
24700
  }
24701
+ /** The names of the registered macros that bind a variable (the inputs). */
24702
+ function storeVarMacroNames() {
24703
+ return getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
24704
+ }
24226
24705
  /**
24227
24706
  * The undeclared variables the passages refer to, with the macros known now:
24228
24707
  * the input macros that bind a variable (registered by author JS or
24229
24708
  * StoryInit) and the roles of their parameters decide what is a reference.
24230
24709
  */
24231
24710
  function variableErrors(storyData, schema) {
24232
- const storeVarMacros = getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
24233
- return validatePassages(storyData.passages, schema, storeVarMacros, knownParameters());
24711
+ return validatePassages(storyData.passages, schema, storeVarMacroNames(), knownParameters());
24234
24712
  }
24235
24713
  /**
24236
24714
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -24298,6 +24776,8 @@ function boot() {
24298
24776
  for (const [, passage] of storyData.passages) if (passage.tags.includes("widget")) orStop(() => registerWidgetDefinitions(parseMarkup(passage.content), passage.name), `Passage "${passage.name}": `);
24299
24777
  initializeStory(loadSession(storyData.ifid));
24300
24778
  const markup = [...variableErrors(storyData, schema), ...markupErrors(storyData, (p) => p.name !== "StoryInit")];
24779
+ const storyContext = storyData.passages.get("StoryContext");
24780
+ if (storyContext) markup.push(...storyContextErrors(storyContext.content, storeVarMacroNames()));
24301
24781
  if (markup.length > 0) stopWithErrors(markup);
24302
24782
  let prevNavigationId = useStoryStore.getState().navigationId;
24303
24783
  useStoryStore.subscribe((state) => {
@@ -24357,5 +24837,39 @@ function bootStory(options) {
24357
24837
  }
24358
24838
  });
24359
24839
  }
24840
+ /**
24841
+ * Record a playthrough for stateless decision models, which need the last few
24842
+ * steps sent with every call. A step that rejects records nothing.
24843
+ */
24844
+ function createTranscript(story, options = {}) {
24845
+ const limit = options.limit ?? 10;
24846
+ if (limit !== Infinity && !(typeof limit === "number" && Number.isInteger(limit) && limit >= 0)) throw new Error(`spindle: createTranscript(): "limit" must be a non-negative integer or Infinity, got ${typeof limit === "string" ? JSON.stringify(limit) : String(limit)}`);
24847
+ const withText = options.include?.text ?? true;
24848
+ const withContext = options.include?.context ?? false;
24849
+ const entries = [];
24850
+ return {
24851
+ entries,
24852
+ async step(id, value) {
24853
+ const before = story.observe();
24854
+ const action = before.actions.find((a) => a.id === id) ?? story.getActions().find((a) => a.id === id);
24855
+ const next = await story.step(id, value);
24856
+ const chose = {
24857
+ id,
24858
+ label: action?.label ?? id
24859
+ };
24860
+ if (value !== void 0) chose.value = value;
24861
+ const entry = {
24862
+ turn: before.turn,
24863
+ passage: before.passage,
24864
+ chose
24865
+ };
24866
+ if (withText) entry.text = before.text;
24867
+ if (withContext) entry.context = before.context;
24868
+ entries.push(entry);
24869
+ if (entries.length > limit) entries.splice(0, entries.length - limit);
24870
+ return next;
24871
+ }
24872
+ };
24873
+ }
24360
24874
  //#endregion
24361
- export { bootStory };
24875
+ export { bootStory, createTranscript };