@rohal12/spindle 0.59.32 → 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,6 +19374,23 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
19357
19374
  }, [dismissible, onClose]);
19358
19375
  }
19359
19376
  //#endregion
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
19360
19394
  //#region src/action-registry.ts
19361
19395
  /** The fields of a StoryAction that are left out when unset. */
19362
19396
  var OPTIONAL_ACTION_FIELDS = [
@@ -19366,6 +19400,39 @@ var OPTIONAL_ACTION_FIELDS = [
19366
19400
  "value",
19367
19401
  "disabled"
19368
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
+ }
19369
19436
  /**
19370
19437
  * The registrations holding each ID, oldest first; the newest is the one
19371
19438
  * listed. Generated IDs don't collide, but author IDs can, and one control's
@@ -19403,9 +19470,16 @@ function generateActionId(type, key, authorId) {
19403
19470
  reserved.add(id);
19404
19471
  return id;
19405
19472
  }
19406
- function registerAction(action) {
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) {
19407
19478
  const id = action.id;
19408
- const entry = { action };
19479
+ const entry = {
19480
+ action,
19481
+ dialog
19482
+ };
19409
19483
  const entries = actions.get(id);
19410
19484
  if (entries) {
19411
19485
  console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
@@ -19455,6 +19529,13 @@ async function settleRunningActions() {
19455
19529
  function getActions() {
19456
19530
  return Array.from(actions.values(), listed);
19457
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
+ }
19458
19539
  function getAction(id) {
19459
19540
  const entries = actions.get(id);
19460
19541
  return entries && listed(entries);
@@ -19470,12 +19551,30 @@ function notify() {
19470
19551
  emit("actionsChanged");
19471
19552
  }
19472
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
+ */
19562
+ var DialogCloseContext = createContext(null);
19563
+ //#endregion
19473
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);
19474
19571
  function useAction(opts) {
19572
+ const disabled = useContext(ActionsDisabledContext);
19573
+ const dialog = useContext(DialogCloseContext);
19475
19574
  const idRef = useRef("");
19476
19575
  const performRef = useRef(opts.perform);
19477
19576
  performRef.current = opts.perform;
19478
- if (!idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19577
+ if (!disabled && !idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19479
19578
  const id = idRef.current;
19480
19579
  const buildAction = () => {
19481
19580
  const action = {
@@ -19488,19 +19587,29 @@ function useAction(opts) {
19488
19587
  return action;
19489
19588
  };
19490
19589
  const registration = useRef(null);
19590
+ const fresh = useRef(false);
19491
19591
  useLayoutEffect(() => {
19492
- const own = registerAction(buildAction());
19592
+ if (disabled) return;
19593
+ const own = registerAction(buildAction(), dialog);
19493
19594
  registration.current = own;
19595
+ fresh.current = true;
19494
19596
  return () => own.unregister();
19495
- }, [id]);
19496
- const registered = useRef(false);
19597
+ }, [
19598
+ id,
19599
+ disabled,
19600
+ dialog
19601
+ ]);
19497
19602
  useLayoutEffect(() => {
19498
- if (!registered.current) {
19499
- registered.current = true;
19603
+ if (disabled) return;
19604
+ if (fresh.current) {
19605
+ fresh.current = false;
19500
19606
  return;
19501
19607
  }
19502
19608
  registration.current?.update(buildAction());
19503
19609
  }, [
19610
+ id,
19611
+ disabled,
19612
+ dialog,
19504
19613
  opts.type,
19505
19614
  opts.label,
19506
19615
  opts.target,
@@ -19509,11 +19618,10 @@ function useAction(opts) {
19509
19618
  opts.value,
19510
19619
  JSON.stringify(opts.options)
19511
19620
  ]);
19512
- return id;
19621
+ return disabled ? "" : id;
19513
19622
  }
19514
19623
  //#endregion
19515
19624
  //#region src/components/PassageDialog.tsx
19516
- var DialogCloseContext = createContext(null);
19517
19625
  function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
19518
19626
  const onCloseRef = useRef(onClose);
19519
19627
  onCloseRef.current = onClose;
@@ -19544,7 +19652,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19544
19652
  const labelId = useId();
19545
19653
  const viewScope = useViewScope();
19546
19654
  useModalFocus(panelRef, ".dialog-body", dismissible, stableOnClose);
19547
- useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
19655
+ useLayoutEffect(() => registerOpenDialog(stableOnClose, panelRef.current), [stableOnClose]);
19548
19656
  useLayoutEffect(() => {
19549
19657
  const panel = panelRef.current;
19550
19658
  if (!panel || label) return;
@@ -19571,6 +19679,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19571
19679
  ref: panelRef,
19572
19680
  class: cls,
19573
19681
  role: "dialog",
19682
+ "data-dialog-passage": passageName,
19574
19683
  "aria-modal": "true",
19575
19684
  "aria-label": label ?? passageName,
19576
19685
  tabIndex: -1,
@@ -20104,11 +20213,38 @@ function collectText(nodes) {
20104
20213
  return nodes.map((n) => n.type === "text" ? n.value : "").join("");
20105
20214
  }
20106
20215
  //#endregion
20216
+ //#region src/display-only.ts
20217
+ /**
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.
20221
+ */
20222
+ var ACTING_MACROS = [
20223
+ "set",
20224
+ "do",
20225
+ "unset",
20226
+ "computed",
20227
+ "goto",
20228
+ "watch"
20229
+ ];
20230
+ /**
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).
20235
+ */
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`);
20240
+ }
20241
+ //#endregion
20107
20242
  //#region src/define-macro.ts
20108
20243
  function macroClass(type, className) {
20109
20244
  const base = `macro-${type}`;
20110
20245
  return className ? `${base} ${className}` : base;
20111
20246
  }
20247
+ var actingMacros = new NameSet(ACTING_MACROS);
20112
20248
  var sharedHooks = {
20113
20249
  useState,
20114
20250
  useRef,
@@ -20121,7 +20257,16 @@ var sharedHooks = {
20121
20257
  function defineMacro(config, source = "builtin") {
20122
20258
  const parameters = config.parameters ?? [];
20123
20259
  checkParameterTypes(config.name, parameters);
20260
+ const acts = actingMacros.has(config.name);
20124
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
+ };
20125
20270
  let className = props.className;
20126
20271
  let id = props.id;
20127
20272
  let resolve;
@@ -20162,8 +20307,8 @@ function defineMacro(config, source = "builtin") {
20162
20307
  id,
20163
20308
  resolve,
20164
20309
  cls: macroClass(config.name, className),
20165
- mutate: inIteration ? (code) => runAsItemEdit(() => executeMutation(code, getValues(), update)) : (code) => executeMutation(code, getValues(), update),
20166
- update,
20310
+ mutate: displayOnly ? refuse : inIteration ? (code) => runAsItemEdit(() => executeMutation(code, getValues(), update)) : (code) => executeMutation(code, getValues(), update),
20311
+ update: displayOnly ? refuse : update,
20167
20312
  getValues,
20168
20313
  wrap: (content) => wrapContent(className, id, content)
20169
20314
  };
@@ -20186,7 +20331,7 @@ function defineMacro(config, source = "builtin") {
20186
20331
  ctx.varName = varExpr;
20187
20332
  ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
20188
20333
  ctx.getValue = () => getByPath(readState().variables, segments);
20189
- ctx.setValue = (value) => {
20334
+ ctx.setValue = displayOnly ? refuse : (value) => {
20190
20335
  noteControlEdit(segments);
20191
20336
  mutateState((work, adopt) => {
20192
20337
  setByPath(work.variables, segments, adopt(value), { createMissing: true });
@@ -20240,6 +20385,286 @@ function getRenderedNavigationId() {
20240
20385
  return renderedNavigationId;
20241
20386
  }
20242
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
20243
20668
  //#region src/story-api.ts
20244
20669
  var readyResolve = null;
20245
20670
  var readyPromise = null;
@@ -20315,7 +20740,7 @@ function storeAction(name) {
20315
20740
  return ((...args) => useStoryStore.getState()[name](...args));
20316
20741
  }
20317
20742
  function createStoryAPI() {
20318
- return {
20743
+ const api = {
20319
20744
  get(name) {
20320
20745
  const { isTransient, key } = parseName(name);
20321
20746
  const scope = getActiveMutationScope();
@@ -20438,6 +20863,13 @@ function createStoryAPI() {
20438
20863
  });
20439
20864
  return getActions();
20440
20865
  },
20866
+ observe,
20867
+ async step(id, value) {
20868
+ await api.performAction(id, value);
20869
+ await api.waitForActions();
20870
+ return observe();
20871
+ },
20872
+ setObservedActions,
20441
20873
  watch(condition, callbackOrOptions) {
20442
20874
  return addTrigger(condition, callbackOrOptions);
20443
20875
  },
@@ -20533,6 +20965,7 @@ function createStoryAPI() {
20533
20965
  }
20534
20966
  }
20535
20967
  };
20968
+ return api;
20536
20969
  }
20537
20970
  function installStoryAPI() {
20538
20971
  window.Story = createStoryAPI();
@@ -22759,7 +23192,8 @@ function Settled({ onSettled }) {
22759
23192
  * through a live view, so a local assigned earlier in the body is visible),
22760
23193
  * nobr/inline rendering, the enclosing block widget's {@children}, the
22761
23194
  * enclosing {repeat}'s {stop} and the enclosing dialog's close callback and whether it runs in a {for} iteration
22762
- * (#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.
22763
23197
  * The body then behaves as if it rendered in place.
22764
23198
  *
22765
23199
  * The body's macros read story state from the store. Run from mutation code
@@ -22776,6 +23210,8 @@ function useDetachedBody() {
22776
23210
  const closeDialog = useContext(DialogCloseContext);
22777
23211
  const inIteration = useContext(ItemEditContext);
22778
23212
  const hasLeft = useContext(OutgoingContext);
23213
+ const displayOnly = useContext(DisplayOnlyContext);
23214
+ const actionsDisabled = useContext(ActionsDisabledContext);
22779
23215
  const mounted = useRef([]);
22780
23216
  useEffect(() => {
22781
23217
  const unsubscribe = subscribeStateReplacement(() => {
@@ -22818,14 +23254,20 @@ function useDetachedBody() {
22818
23254
  value: closeDialog,
22819
23255
  children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
22820
23256
  value: inIteration,
22821
- children: /* @__PURE__ */ jsxs(OutgoingContext.Provider, {
23257
+ children: /* @__PURE__ */ jsx(OutgoingContext.Provider, {
22822
23258
  value: hasLeft,
22823
- children: [renderNodes(children, {
22824
- nobr,
22825
- inline,
22826
- structural,
22827
- locals
22828
- }), 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
+ })
22829
23271
  })
22830
23272
  })
22831
23273
  })
@@ -23944,7 +24386,7 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
23944
24386
  }],
23945
24387
  render(_props, ctx) {
23946
24388
  const placeholder = ctx.args.placeholder ?? "";
23947
- useVariableAction(ctx, {
24389
+ const actionId = useVariableAction(ctx, {
23948
24390
  type: name,
23949
24391
  label: placeholder || ctx.varName,
23950
24392
  perform: (v) => ctx.setValue(toValue(v))
@@ -23954,6 +24396,7 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
23954
24396
  return h(type ? "input" : "textarea", {
23955
24397
  type,
23956
24398
  id: ctx.id,
24399
+ "data-action": actionId || void 0,
23957
24400
  class: ctx.cls,
23958
24401
  value: shown,
23959
24402
  placeholder,
@@ -23988,7 +24431,7 @@ defineMacro({
23988
24431
  }],
23989
24432
  render(_props, ctx) {
23990
24433
  const label = ctx.args.label ?? "";
23991
- useVariableAction(ctx, {
24434
+ const actionId = useVariableAction(ctx, {
23992
24435
  type: "checkbox",
23993
24436
  label: label || ctx.varName || "",
23994
24437
  value: !!ctx.value,
@@ -23999,6 +24442,7 @@ defineMacro({
23999
24442
  class: ctx.cls,
24000
24443
  children: [/* @__PURE__ */ jsx("input", {
24001
24444
  type: "checkbox",
24445
+ "data-action": actionId || void 0,
24002
24446
  checked: !!ctx.value,
24003
24447
  onChange: (e) => ctx.setValue(e.target.checked)
24004
24448
  }), label ? ` ${label}` : null]
@@ -24029,7 +24473,7 @@ defineMacro({
24029
24473
  const radioValue = ctx.args.value ?? "";
24030
24474
  const label = ctx.args.label ?? "";
24031
24475
  const view = ctx.hooks.useContext(ViewScopeContext);
24032
- useVariableAction(ctx, {
24476
+ const actionId = useVariableAction(ctx, {
24033
24477
  type: "radiobutton",
24034
24478
  key: `$${ctx.varName}:${radioValue}`,
24035
24479
  label: label || radioValue,
@@ -24040,6 +24484,8 @@ defineMacro({
24040
24484
  class: ctx.cls,
24041
24485
  children: [/* @__PURE__ */ jsx("input", {
24042
24486
  type: "radio",
24487
+ value: radioValue,
24488
+ "data-action": actionId || void 0,
24043
24489
  name: view ? `radio-${view}-${ctx.varName}` : `radio-${ctx.varName}`,
24044
24490
  checked: ctx.value === radioValue,
24045
24491
  onChange: () => ctx.setValue(radioValue)
@@ -24057,7 +24503,7 @@ defineMacro({
24057
24503
  parameters: [VARIABLE_PARAMETER],
24058
24504
  render({ children = [] }, ctx) {
24059
24505
  const options = ctx.extractOptions(children);
24060
- useVariableAction(ctx, {
24506
+ const actionId = useVariableAction(ctx, {
24061
24507
  type: "listbox",
24062
24508
  label: ctx.varName,
24063
24509
  options,
@@ -24067,6 +24513,7 @@ defineMacro({
24067
24513
  });
24068
24514
  return /* @__PURE__ */ jsx("select", {
24069
24515
  id: ctx.id,
24516
+ "data-action": actionId || void 0,
24070
24517
  class: ctx.cls,
24071
24518
  value: display(ctx.value),
24072
24519
  onChange: (e) => ctx.setValue(e.target.value),
@@ -24093,7 +24540,7 @@ defineMacro({
24093
24540
  const nextIndex = (options.indexOf(String(current)) + 1) % options.length;
24094
24541
  ctx.setValue(options[nextIndex]);
24095
24542
  };
24096
- useVariableAction(ctx, {
24543
+ const actionId = useVariableAction(ctx, {
24097
24544
  type: "cycle",
24098
24545
  label: ctx.value == null ? options[0] || "" : String(ctx.value),
24099
24546
  options,
@@ -24105,6 +24552,7 @@ defineMacro({
24105
24552
  return /* @__PURE__ */ jsx("button", {
24106
24553
  type: "button",
24107
24554
  id: ctx.id,
24555
+ "data-action": actionId || void 0,
24108
24556
  class: ctx.cls,
24109
24557
  onClick: handleClick,
24110
24558
  children: ctx.value == null ? options[0] || "" : String(ctx.value)
@@ -24250,14 +24698,17 @@ function orStop(parse, where = "") {
24250
24698
  function knownParameters() {
24251
24699
  return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
24252
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
+ }
24253
24705
  /**
24254
24706
  * The undeclared variables the passages refer to, with the macros known now:
24255
24707
  * the input macros that bind a variable (registered by author JS or
24256
24708
  * StoryInit) and the roles of their parameters decide what is a reference.
24257
24709
  */
24258
24710
  function variableErrors(storyData, schema) {
24259
- const storeVarMacros = getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
24260
- return validatePassages(storyData.passages, schema, storeVarMacros, knownParameters());
24711
+ return validatePassages(storyData.passages, schema, storeVarMacroNames(), knownParameters());
24261
24712
  }
24262
24713
  /**
24263
24714
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -24325,6 +24776,8 @@ function boot() {
24325
24776
  for (const [, passage] of storyData.passages) if (passage.tags.includes("widget")) orStop(() => registerWidgetDefinitions(parseMarkup(passage.content), passage.name), `Passage "${passage.name}": `);
24326
24777
  initializeStory(loadSession(storyData.ifid));
24327
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()));
24328
24781
  if (markup.length > 0) stopWithErrors(markup);
24329
24782
  let prevNavigationId = useStoryStore.getState().navigationId;
24330
24783
  useStoryStore.subscribe((state) => {
@@ -24384,5 +24837,39 @@ function bootStory(options) {
24384
24837
  }
24385
24838
  });
24386
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
+ }
24387
24874
  //#endregion
24388
- export { bootStory };
24875
+ export { bootStory, createTranscript };