@rohal12/spindle 0.59.32 → 0.60.0

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.
Files changed (51) hide show
  1. package/README.md +20 -18
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +635 -98
  4. package/dist/pkg/story-variables.js +830 -54
  5. package/dist/pkg/tooling.js +1 -0
  6. package/package.json +4 -2
  7. package/src/action-registry.ts +84 -2
  8. package/src/automation/load-yaml.ts +10 -55
  9. package/src/automation/runner.ts +2 -14
  10. package/src/automation/types.ts +2 -8
  11. package/src/components/PassageDialog.tsx +8 -3
  12. package/src/components/dialog-close-context.ts +10 -0
  13. package/src/components/macros/Checkbox.tsx +2 -1
  14. package/src/components/macros/Cycle.tsx +2 -1
  15. package/src/components/macros/Listbox.tsx +2 -1
  16. package/src/components/macros/Radiobutton.tsx +3 -1
  17. package/src/components/macros/detached-body.tsx +19 -8
  18. package/src/components/macros/input-macro.ts +2 -1
  19. package/src/define-macro.ts +42 -16
  20. package/src/display-only.ts +30 -0
  21. package/src/format/format-passage.ts +626 -0
  22. package/src/format/placeholders.ts +316 -0
  23. package/src/format/prettier.ts +62 -0
  24. package/src/format/segment.ts +126 -0
  25. package/src/headless.ts +81 -1
  26. package/src/hooks/use-action.ts +31 -9
  27. package/src/index.tsx +16 -4
  28. package/src/js-lexer.ts +36 -6
  29. package/src/markup/code-end.ts +97 -41
  30. package/src/markup/parse.ts +6 -6
  31. package/src/observe/observable-text.ts +147 -0
  32. package/src/observe/observe.ts +160 -0
  33. package/src/store.ts +1 -0
  34. package/src/story-api.ts +21 -1
  35. package/src/story-context-passage.ts +132 -0
  36. package/src/tooling.ts +23 -1
  37. package/src/triggers.ts +32 -8
  38. package/src/twine-editor/builtin-macros.ts +11 -0
  39. package/src/twine-editor/commands.ts +173 -0
  40. package/src/twine-editor/highlight.ts +471 -0
  41. package/src/twine-editor/icons.ts +35 -0
  42. package/src/twine-editor/index.ts +19 -0
  43. package/src/twine-editor/mode.ts +137 -0
  44. package/src/twine-editor/references.ts +34 -0
  45. package/src/twine-editor/snippets.ts +74 -0
  46. package/src/twine-editor/toolbar.ts +85 -0
  47. package/src/types-drift-check.ts +12 -0
  48. package/src/utils/field-checks.ts +46 -0
  49. package/types/headless.d.ts +43 -2
  50. package/types/index.d.ts +71 -0
  51. package/types/tooling.d.ts +68 -0
@@ -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";
@@ -9443,8 +9443,8 @@ var WORDS_BEFORE_STRING = /* @__PURE__ */ new Set([
9443
9443
  * string may span lines, as quoted macro labels may: the parse reports
9444
9444
  * what in it is no JavaScript.
9445
9445
  */
9446
- function findCodeEnd(src, start, { goal = "expression", stop } = {}) {
9447
- const end = scanCodeEnd(src, start, goal, stop);
9446
+ function findCodeEnd(src, start, { goal = "expression", stop, onRunOut } = {}) {
9447
+ const end = scanCodeEnd(src, start, goal, stop, onRunOut);
9448
9448
  return end < 0 && !stop ? parsedCodeEnd(src, start, goal) : end;
9449
9449
  }
9450
9450
  /**
@@ -9470,7 +9470,12 @@ function parsedCodeEnd(src, start, goal) {
9470
9470
  return -1;
9471
9471
  }
9472
9472
  /** `findCodeEnd` by the tokens: see there. */
9473
- function scanCodeEnd(src, start, goal, stop) {
9473
+ function scanCodeEnd(src, start, goal, stop, onRunOut) {
9474
+ /** No end: the code runs to the end of `src`. */
9475
+ const ranOut = () => {
9476
+ onRunOut?.();
9477
+ return -1;
9478
+ };
9474
9479
  const stack = [];
9475
9480
  let prevEnd = -1;
9476
9481
  let prevWord = false;
@@ -9486,11 +9491,12 @@ function scanCodeEnd(src, start, goal, stop) {
9486
9491
  if (!/^Unterminated/.test(message) && !inTemplate) {
9487
9492
  resumeAt = Math.max(tok.pos, from) + 1;
9488
9493
  afterOperand = false;
9489
- if (resumeAt >= src.length) return -1;
9494
+ if (resumeAt >= src.length) return ranOut();
9490
9495
  break;
9491
9496
  }
9492
9497
  const k = stack.lastIndexOf("${");
9493
- if (!/^Unterminated template/.test(message) || k < 0 || templateSlip || stop) return -1;
9498
+ if (!/^Unterminated template/.test(message) || k < 0 || templateSlip || stop) return /^Unterminated/.test(message) && !/^Unterminated regular/.test(message) && !(/^Unterminated string/.test(message) && prevWord && tok.pos === prevEnd) ? ranOut() : -1;
9499
+ onRunOut?.();
9494
9500
  templateSlip = true;
9495
9501
  stack.length = k;
9496
9502
  resumeAt = tok.pos;
@@ -9499,7 +9505,7 @@ function scanCodeEnd(src, start, goal, stop) {
9499
9505
  }
9500
9506
  if (tok.restarted && stack.includes("${")) return -1;
9501
9507
  const t = tok.type;
9502
- if (t === types$1.eof) return -1;
9508
+ if (t === types$1.eof) return ranOut();
9503
9509
  if (t === types$1.string && prevWord && tok.start === prevEnd) return -1;
9504
9510
  prevWord = t === types$1.name && !WORDS_BEFORE_STRING.has(tok.value) || t === types$1.num;
9505
9511
  prevEnd = tok.end;
@@ -9771,80 +9777,124 @@ var NON_STRING_QUOTE_PREFIX = /[\p{L}\p{N}_\\]/u;
9771
9777
  function skipLiteral(input, i) {
9772
9778
  const quote = input[i];
9773
9779
  const template = quote === "`";
9780
+ let ranOut = false;
9774
9781
  for (let j = i + 1; j < input.length;) {
9775
9782
  const c = input[j];
9776
9783
  if (c === "\\") j += 2;
9777
- else if (c === quote) return j + 1;
9778
- else if (!template && c === "\n") return -1;
9784
+ else if (c === quote) return {
9785
+ end: j + 1,
9786
+ ranOut
9787
+ };
9788
+ else if (!template && c === "\n") return {
9789
+ end: -1,
9790
+ ranOut
9791
+ };
9779
9792
  else if (template && c === "$" && input[j + 1] === "{") {
9780
- const close = lenientClose(input, j + 2);
9781
- if (close === -1) return -1;
9782
- j = close + 1;
9793
+ const close = lenientRead(input, j + 2);
9794
+ ranOut ||= close.ranOut;
9795
+ if (close.end === -1) return {
9796
+ end: -1,
9797
+ ranOut
9798
+ };
9799
+ j = close.end + 1;
9783
9800
  } else j++;
9784
9801
  }
9785
- return -1;
9802
+ return {
9803
+ end: -1,
9804
+ ranOut: ranOut || template
9805
+ };
9786
9806
  }
9787
9807
  /**
9788
9808
  * The closing `}` of braces read leniently from `i` (just past a `{`): braces
9789
9809
  * count except inside string and template literals, and a quote that can't
9790
9810
  * start a string (an apostrophe, or one not closed on its line) is text, as
9791
- * is a backtick without a closing one.
9811
+ * is a backtick without a closing one. `onRunOut` is called when a line
9812
+ * appended to `input` could change the result (see `Lenient`).
9792
9813
  */
9793
- function lenientClose(input, i) {
9814
+ function lenientClose(input, i, onRunOut) {
9815
+ const { end, ranOut } = lenientRead(input, i);
9816
+ if (ranOut) onRunOut?.();
9817
+ return end;
9818
+ }
9819
+ function lenientRead(input, i) {
9794
9820
  if (memoInput !== input) {
9795
9821
  memoInput = input;
9796
9822
  memo.clear();
9797
9823
  }
9798
- let end = memo.get(i);
9799
- if (end === void 0) {
9800
- end = scanLenient(input, i);
9801
- memo.set(i, end);
9824
+ let read = memo.get(i);
9825
+ if (read === void 0) {
9826
+ read = scanLenient(input, i);
9827
+ memo.set(i, read);
9802
9828
  }
9803
- return end;
9829
+ return read;
9804
9830
  }
9805
9831
  var memoInput = "";
9806
9832
  var memo = /* @__PURE__ */ new Map();
9807
9833
  function scanLenient(input, i) {
9808
9834
  let depth = 0;
9835
+ let ranOut = false;
9809
9836
  while (i < input.length) {
9810
9837
  const c = input[i];
9811
9838
  if (c === "{") {
9812
9839
  depth++;
9813
9840
  i++;
9814
9841
  } else if (c === "}") {
9815
- if (depth === 0) return i;
9842
+ if (depth === 0) return {
9843
+ end: i,
9844
+ ranOut
9845
+ };
9816
9846
  depth--;
9817
9847
  i++;
9818
9848
  } else if (c === "`" || (c === "\"" || c === "'") && !(i > 0 && NON_STRING_QUOTE_PREFIX.test(input[i - 1]))) {
9819
9849
  const close = skipLiteral(input, i);
9820
- i = close === -1 ? i + 1 : close;
9850
+ ranOut ||= close.ranOut;
9851
+ i = close.end === -1 ? i + 1 : close.end;
9821
9852
  } else i++;
9822
9853
  }
9823
- return -1;
9854
+ return {
9855
+ end: -1,
9856
+ ranOut: true
9857
+ };
9858
+ }
9859
+ /**
9860
+ * The JavaScript reader Spindle uses: js-lexer, then a lenient scan. With
9861
+ * `onOpenEnd`, it also reports code whose end depends on what follows the
9862
+ * input (see `OnOpenCodeEnd`); the ends it finds are the same.
9863
+ */
9864
+ function jsCodeEnd(onOpenEnd) {
9865
+ return {
9866
+ closeBrace(input, codeStart, lenientStart) {
9867
+ let ranOut = false;
9868
+ const onRunOut = () => ranOut = true;
9869
+ const strict = findCodeEnd(input, codeStart, { onRunOut });
9870
+ const end = strict !== -1 ? strict : lenientClose(input, lenientStart, onRunOut);
9871
+ if (ranOut) onOpenEnd?.(input, codeStart);
9872
+ return end;
9873
+ },
9874
+ rawBodyEnd(input, bodyStart, name) {
9875
+ const closer = `\\{/${name}\\s*\\}`;
9876
+ const first = new RegExp(closer, "gi");
9877
+ first.lastIndex = bodyStart;
9878
+ const firstAt = first.exec(input)?.index ?? -1;
9879
+ if (firstAt === -1) return -1;
9880
+ const at = new RegExp(closer, "iy");
9881
+ let ranOut = false;
9882
+ const end = findCodeEnd(input, bodyStart, {
9883
+ goal: "statements",
9884
+ stop: (k) => {
9885
+ at.lastIndex = k;
9886
+ return at.test(input);
9887
+ },
9888
+ onRunOut: () => ranOut = true
9889
+ });
9890
+ if (end !== -1) return end;
9891
+ if (onOpenEnd && (ranOut || new RegExp(`\\{/${name}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
9892
+ return firstAt;
9893
+ }
9894
+ };
9824
9895
  }
9825
9896
  /** The JavaScript reader Spindle uses today: js-lexer, then a lenient scan. */
9826
- var defaultCodeEnd = {
9827
- closeBrace(input, codeStart, lenientStart) {
9828
- const end = findCodeEnd(input, codeStart);
9829
- return end !== -1 ? end : lenientClose(input, lenientStart);
9830
- },
9831
- rawBodyEnd(input, bodyStart, name) {
9832
- const closer = `\\{/${name}\\s*\\}`;
9833
- const first = new RegExp(closer, "gi");
9834
- first.lastIndex = bodyStart;
9835
- const firstAt = first.exec(input)?.index ?? -1;
9836
- if (firstAt === -1) return -1;
9837
- const at = new RegExp(closer, "iy");
9838
- const end = findCodeEnd(input, bodyStart, {
9839
- goal: "statements",
9840
- stop: (k) => {
9841
- at.lastIndex = k;
9842
- return at.test(input);
9843
- }
9844
- });
9845
- return end === -1 ? firstAt : end;
9846
- }
9847
- };
9897
+ var defaultCodeEnd = jsCodeEnd();
9848
9898
  //#endregion
9849
9899
  //#region src/markup/code-attributes.ts
9850
9900
  /**
@@ -9947,7 +9997,7 @@ function run$2(source, startRule, options) {
9947
9997
  * so it has no errors of its own.
9948
9998
  */
9949
9999
  function analyzeMarkup(source, options = {}) {
9950
- const { tokens, errors, damage } = scan(source, options);
10000
+ const { tokens, errors, damage } = scanMarkupTolerant(source, options);
9951
10001
  const hooks = {
9952
10002
  ...defaultHooks,
9953
10003
  ...options.hooks
@@ -10004,7 +10054,7 @@ function tokenizeMarkup(source, options = {}) {
10004
10054
  * markup the tokens are those of `tokenizeMarkup` and there are no errors.
10005
10055
  */
10006
10056
  function tokenizeMarkupTolerant(source, options = {}) {
10007
- const { tokens, errors } = scan(source, options);
10057
+ const { tokens, errors } = scanMarkupTolerant(source, options);
10008
10058
  return {
10009
10059
  tokens,
10010
10060
  errors
@@ -10012,10 +10062,10 @@ function tokenizeMarkupTolerant(source, options = {}) {
10012
10062
  }
10013
10063
  /**
10014
10064
  * The tokens of tolerant tokenizing, the errors, and where the damage of
10015
- * each error starts: the tag that is malformed, which an error inside it
10016
- * (an attribute value) is after.
10065
+ * each error starts (`damage[i]` for `errors[i]`): the tag that is
10066
+ * malformed, which an error inside it (an attribute value) is after.
10017
10067
  */
10018
- function scan(source, options) {
10068
+ function scanMarkupTolerant(source, options = {}) {
10019
10069
  const tokens = [];
10020
10070
  const errors = [];
10021
10071
  const damage = [];
@@ -14847,7 +14897,7 @@ function encodePayload(payload) {
14847
14897
  /** Thrown for stored data that is not a payload this format can hold. */
14848
14898
  var invalid = () => /* @__PURE__ */ new Error("Invalid save data");
14849
14899
  /** A plain object or one without a prototype (a variable namespace). */
14850
- function isRecord$1(value) {
14900
+ function isRecord$2(value) {
14851
14901
  if (typeof value !== "object" || value === null) return false;
14852
14902
  const proto = Object.getPrototypeOf(value);
14853
14903
  return proto === Object.prototype || proto === null;
@@ -14855,10 +14905,10 @@ function isRecord$1(value) {
14855
14905
  /** Absent, null, or a `{ seed, pull }` PRNG snapshot. */
14856
14906
  function isOptionalPRNGSnapshot(value) {
14857
14907
  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;
14908
+ return isRecord$2(value) && typeof value.seed === "string" && typeof value.pull === "number" && Number.isInteger(value.pull) && value.pull >= 0;
14859
14909
  }
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));
14910
+ var isMoment = (value) => isRecord$2(value) && typeof value.passage === "string" && isRecord$2(value.variables) && typeof value.timestamp === "number" && isOptionalPRNGSnapshot(value.prng);
14911
+ 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
14912
  var isCountsMap = (value) => value === void 0 || value instanceof Map && [...value.keys()].every((k) => typeof k === "string");
14863
14913
  /**
14864
14914
  * Whether a deserialized payload is well formed: every history moment is,
@@ -14866,8 +14916,8 @@ var isCountsMap = (value) => value === void 0 || value instanceof Map && [...val
14866
14916
  * passage.
14867
14917
  */
14868
14918
  function isPayload(value) {
14869
- if (!isRecord$1(value)) return false;
14870
- if (typeof value.passage !== "string" || !isRecord$1(value.variables)) return false;
14919
+ if (!isRecord$2(value)) return false;
14920
+ if (typeof value.passage !== "string" || !isRecord$2(value.variables)) return false;
14871
14921
  const { history, historyIndex } = value;
14872
14922
  if (!Array.isArray(history) || history.length === 0) return false;
14873
14923
  if (!Array.from(history).every(isMoment)) return false;
@@ -14900,7 +14950,7 @@ function decodePayload(encoded) {
14900
14950
  //#endregion
14901
14951
  //#region src/saves/types.ts
14902
14952
  var INVALID_FILE = "Invalid save file format";
14903
- function isRecord(value) {
14953
+ function isRecord$1(value) {
14904
14954
  return typeof value === "object" && value !== null && !Array.isArray(value);
14905
14955
  }
14906
14956
  var META_STRINGS = [
@@ -14931,12 +14981,12 @@ function decodeQuietly(encoded) {
14931
14981
  * Anything that passes can be stored and later loaded.
14932
14982
  */
14933
14983
  function checkSaveExport(value) {
14934
- if (!isRecord(value)) throw new Error(INVALID_FILE);
14984
+ if (!isRecord$1(value)) throw new Error(INVALID_FILE);
14935
14985
  if (!hasOwn(value, "formatVersion")) throw value.version === 1 ? new IncompatibleSaveError() : /* @__PURE__ */ new Error(INVALID_FILE);
14936
14986
  checkFormatVersion(value.formatVersion);
14937
14987
  if (typeof value.ifid !== "string") throw new Error(INVALID_FILE);
14938
14988
  const save = value.save;
14939
- if (!isRecord(save) || !isRecord(save.meta)) throw new Error(INVALID_FILE);
14989
+ if (!isRecord$1(save) || !isRecord$1(save.meta)) throw new Error(INVALID_FILE);
14940
14990
  const meta = save.meta;
14941
14991
  if (META_STRINGS.some((key) => typeof meta[key] !== "string")) throw new Error(INVALID_FILE);
14942
14992
  try {
@@ -17788,26 +17838,42 @@ function registerDialogHost(callbacks) {
17788
17838
  /**
17789
17839
  * The dialogs on display, bottom first, whoever opened them: the trigger
17790
17840
  * host, `{dialog}` or a menubar button (each PassageDialog registers itself
17791
- * while mounted), as the function that closes each.
17841
+ * while mounted).
17792
17842
  */
17793
17843
  var openDialogs = [];
17794
- /** Register a displayed dialog; returns the function that unregisters it. */
17795
- function registerOpenDialog(close) {
17796
- openDialogs.push(close);
17844
+ /**
17845
+ * Register a displayed dialog, as the function that closes it (its
17846
+ * DialogCloseContext value) and its panel element; returns the function
17847
+ * that unregisters it.
17848
+ */
17849
+ function registerOpenDialog(close, panel = null) {
17850
+ const entry = {
17851
+ close,
17852
+ panel
17853
+ };
17854
+ openDialogs.push(entry);
17797
17855
  return () => {
17798
- const i = openDialogs.lastIndexOf(close);
17856
+ const i = openDialogs.lastIndexOf(entry);
17799
17857
  if (i >= 0) openDialogs.splice(i, 1);
17800
17858
  };
17801
17859
  }
17860
+ /** The close function of the topmost dialog, or undefined when none is open. */
17861
+ function innermostOpenDialog() {
17862
+ return openDialogs[openDialogs.length - 1]?.close;
17863
+ }
17864
+ /** The panels of the dialogs on display, in opening order (innermost last). */
17865
+ function openDialogPanels() {
17866
+ return openDialogs.flatMap((d) => d.panel ? [d.panel] : []);
17867
+ }
17802
17868
  /** Close the topmost dialog. */
17803
17869
  function closeCurrentDialog() {
17804
- const top = openDialogs[openDialogs.length - 1];
17870
+ const top = innermostOpenDialog();
17805
17871
  if (top) top();
17806
17872
  else dialogHostCallbacks?.close();
17807
17873
  }
17808
17874
  function closeAllOpenDialogs() {
17809
17875
  clearDialogQueue();
17810
- for (const close of [...openDialogs].reverse()) close();
17876
+ for (const { close } of [...openDialogs].reverse()) close();
17811
17877
  dialogHostCallbacks?.closeAll();
17812
17878
  }
17813
17879
  function isDialogShowing() {
@@ -17827,7 +17893,8 @@ var SPECIAL_PASSAGES = /* @__PURE__ */ new Set([
17827
17893
  "PassageReady",
17828
17894
  "PassageHeader",
17829
17895
  "PassageFooter",
17830
- "PassageDone"
17896
+ "PassageDone",
17897
+ "StoryContext"
17831
17898
  ]);
17832
17899
  /** Full variable snapshot at history index 0. */
17833
17900
  var variableBase = createNamespace();
@@ -19357,6 +19424,23 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
19357
19424
  }, [dismissible, onClose]);
19358
19425
  }
19359
19426
  //#endregion
19427
+ //#region src/utils/field-checks.ts
19428
+ function isRecord(value) {
19429
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19430
+ }
19431
+ /** `value` as an object whose keys are all in `allowed`. */
19432
+ function checkObject(value, what, allowed, fail) {
19433
+ if (!isRecord(value)) fail(`${what} must be an object`);
19434
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(`${what} has an unknown field "${key}" (${allowed.join(", ")})`);
19435
+ return value;
19436
+ }
19437
+ var isString = (v) => typeof v === "string";
19438
+ var isBoolean = (v) => typeof v === "boolean";
19439
+ /** Each field of `obj` named in `checks` passes its check. */
19440
+ function checkFields(obj, what, checks, fail) {
19441
+ for (const [key, [valid, expected]] of Object.entries(checks)) if (key in obj && !valid(obj[key])) fail(`"${key}" of ${what} must be ${expected}`);
19442
+ }
19443
+ //#endregion
19360
19444
  //#region src/action-registry.ts
19361
19445
  /** The fields of a StoryAction that are left out when unset. */
19362
19446
  var OPTIONAL_ACTION_FIELDS = [
@@ -19366,6 +19450,39 @@ var OPTIONAL_ACTION_FIELDS = [
19366
19450
  "value",
19367
19451
  "disabled"
19368
19452
  ];
19453
+ /** The matcher fields compared with the action field of the same name. */
19454
+ var MATCHED_FIELDS = [
19455
+ "id",
19456
+ "type",
19457
+ "target",
19458
+ "variable",
19459
+ "label"
19460
+ ];
19461
+ /**
19462
+ * Whether an action satisfies every field the matcher sets. Unset matcher
19463
+ * fields match anything.
19464
+ */
19465
+ function actionMatches(action, matcher) {
19466
+ return MATCHED_FIELDS.every((field) => matcher[field] === void 0 || action[field] === matcher[field]) && (matcher.disabled === void 0 || !!action.disabled === matcher.disabled);
19467
+ }
19468
+ var MATCHER_FIELDS = {
19469
+ type: [isString, "a string"],
19470
+ id: [isString, "a string"],
19471
+ target: [isString, "a string"],
19472
+ variable: [isString, "a string"],
19473
+ label: [isString, "a string"],
19474
+ disabled: [isBoolean, "true or false"]
19475
+ };
19476
+ /**
19477
+ * A copy of `value` as an ActionMatcher, or `fail` naming `what` when it is not an
19478
+ * object of matcher fields with the right types. The automation YAML and
19479
+ * Story.setObservedActions() take matchers from authors.
19480
+ */
19481
+ function checkActionMatcher(value, what, fail) {
19482
+ const matcher = checkObject(value, what, Object.keys(MATCHER_FIELDS), fail);
19483
+ checkFields(matcher, what, MATCHER_FIELDS, fail);
19484
+ return { ...matcher };
19485
+ }
19369
19486
  /**
19370
19487
  * The registrations holding each ID, oldest first; the newest is the one
19371
19488
  * listed. Generated IDs don't collide, but author IDs can, and one control's
@@ -19403,9 +19520,16 @@ function generateActionId(type, key, authorId) {
19403
19520
  reserved.add(id);
19404
19521
  return id;
19405
19522
  }
19406
- function registerAction(action) {
19523
+ /**
19524
+ * Register `action`, of a control rendered in the dialog `dialog` (the
19525
+ * dialog's DialogCloseContext value), or outside any when null.
19526
+ */
19527
+ function registerAction(action, dialog = null) {
19407
19528
  const id = action.id;
19408
- const entry = { action };
19529
+ const entry = {
19530
+ action,
19531
+ dialog
19532
+ };
19409
19533
  const entries = actions.get(id);
19410
19534
  if (entries) {
19411
19535
  console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
@@ -19455,6 +19579,13 @@ async function settleRunningActions() {
19455
19579
  function getActions() {
19456
19580
  return Array.from(actions.values(), listed);
19457
19581
  }
19582
+ /**
19583
+ * The actions of the controls rendered in the dialog `dialog` (its close
19584
+ * function, see registerAction), its nested dialogs' left out.
19585
+ */
19586
+ function getDialogActions(dialog) {
19587
+ return Array.from(actions.values()).map((entries) => entries[entries.length - 1]).filter((entry) => entry.dialog === dialog).map((entry) => entry.action);
19588
+ }
19458
19589
  function getAction(id) {
19459
19590
  const entries = actions.get(id);
19460
19591
  return entries && listed(entries);
@@ -19470,12 +19601,30 @@ function notify() {
19470
19601
  emit("actionsChanged");
19471
19602
  }
19472
19603
  //#endregion
19604
+ //#region src/components/dialog-close-context.ts
19605
+ /**
19606
+ * The function that closes the dialog the content renders in, or null
19607
+ * outside any dialog. Each PassageDialog provides its own stable one, so it
19608
+ * also identifies the dialog: the dialog stack (registerOpenDialog) holds
19609
+ * it, and useAction records it with the action, so Story.observe() can
19610
+ * offer only the innermost dialog's actions.
19611
+ */
19612
+ var DialogCloseContext = createContext(null);
19613
+ //#endregion
19473
19614
  //#region src/hooks/use-action.ts
19615
+ /**
19616
+ * While true, controls rendered underneath do not register actions or reserve
19617
+ * IDs. Used for display-only content mounted off-screen, so it never shows up
19618
+ * in `getActions()` or shifts the IDs of the visible passage's controls.
19619
+ */
19620
+ var ActionsDisabledContext = createContext(false);
19474
19621
  function useAction(opts) {
19622
+ const disabled = useContext(ActionsDisabledContext);
19623
+ const dialog = useContext(DialogCloseContext);
19475
19624
  const idRef = useRef("");
19476
19625
  const performRef = useRef(opts.perform);
19477
19626
  performRef.current = opts.perform;
19478
- if (!idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19627
+ if (!disabled && !idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19479
19628
  const id = idRef.current;
19480
19629
  const buildAction = () => {
19481
19630
  const action = {
@@ -19488,19 +19637,29 @@ function useAction(opts) {
19488
19637
  return action;
19489
19638
  };
19490
19639
  const registration = useRef(null);
19640
+ const fresh = useRef(false);
19491
19641
  useLayoutEffect(() => {
19492
- const own = registerAction(buildAction());
19642
+ if (disabled) return;
19643
+ const own = registerAction(buildAction(), dialog);
19493
19644
  registration.current = own;
19645
+ fresh.current = true;
19494
19646
  return () => own.unregister();
19495
- }, [id]);
19496
- const registered = useRef(false);
19647
+ }, [
19648
+ id,
19649
+ disabled,
19650
+ dialog
19651
+ ]);
19497
19652
  useLayoutEffect(() => {
19498
- if (!registered.current) {
19499
- registered.current = true;
19653
+ if (disabled) return;
19654
+ if (fresh.current) {
19655
+ fresh.current = false;
19500
19656
  return;
19501
19657
  }
19502
19658
  registration.current?.update(buildAction());
19503
19659
  }, [
19660
+ id,
19661
+ disabled,
19662
+ dialog,
19504
19663
  opts.type,
19505
19664
  opts.label,
19506
19665
  opts.target,
@@ -19509,11 +19668,10 @@ function useAction(opts) {
19509
19668
  opts.value,
19510
19669
  JSON.stringify(opts.options)
19511
19670
  ]);
19512
- return id;
19671
+ return disabled ? "" : id;
19513
19672
  }
19514
19673
  //#endregion
19515
19674
  //#region src/components/PassageDialog.tsx
19516
- var DialogCloseContext = createContext(null);
19517
19675
  function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
19518
19676
  const onCloseRef = useRef(onClose);
19519
19677
  onCloseRef.current = onClose;
@@ -19544,7 +19702,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19544
19702
  const labelId = useId();
19545
19703
  const viewScope = useViewScope();
19546
19704
  useModalFocus(panelRef, ".dialog-body", dismissible, stableOnClose);
19547
- useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
19705
+ useLayoutEffect(() => registerOpenDialog(stableOnClose, panelRef.current), [stableOnClose]);
19548
19706
  useLayoutEffect(() => {
19549
19707
  const panel = panelRef.current;
19550
19708
  if (!panel || label) return;
@@ -19571,6 +19729,7 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19571
19729
  ref: panelRef,
19572
19730
  class: cls,
19573
19731
  role: "dialog",
19732
+ "data-dialog-passage": passageName,
19574
19733
  "aria-modal": "true",
19575
19734
  "aria-label": label ?? passageName,
19576
19735
  tabIndex: -1,
@@ -20104,11 +20263,38 @@ function collectText(nodes) {
20104
20263
  return nodes.map((n) => n.type === "text" ? n.value : "").join("");
20105
20264
  }
20106
20265
  //#endregion
20266
+ //#region src/display-only.ts
20267
+ /**
20268
+ * The macros that change the story, or act when they mount. A display-only
20269
+ * passage may not use them (see storyContextErrors), and under
20270
+ * DisplayOnlyContext they render an error instead of running.
20271
+ */
20272
+ var ACTING_MACROS = [
20273
+ "set",
20274
+ "do",
20275
+ "unset",
20276
+ "computed",
20277
+ "goto",
20278
+ "watch"
20279
+ ];
20280
+ /**
20281
+ * While true, the macros rendered underneath change nothing: the acting
20282
+ * macros and every macro's `ctx.mutate`, `ctx.update` and `ctx.setValue`
20283
+ * fail with displayOnlyError(). Provided around the `StoryContext` tree,
20284
+ * which its static check can't see into ({include}, widget bodies).
20285
+ */
20286
+ var DisplayOnlyContext = createContext(false);
20287
+ /** The error of the macro `{name}` trying to change a display-only passage. */
20288
+ function displayOnlyError(name) {
20289
+ return /* @__PURE__ */ new Error(`StoryContext is display-only: {${name}} cannot change the story`);
20290
+ }
20291
+ //#endregion
20107
20292
  //#region src/define-macro.ts
20108
20293
  function macroClass(type, className) {
20109
20294
  const base = `macro-${type}`;
20110
20295
  return className ? `${base} ${className}` : base;
20111
20296
  }
20297
+ var actingMacros = new NameSet(ACTING_MACROS);
20112
20298
  var sharedHooks = {
20113
20299
  useState,
20114
20300
  useRef,
@@ -20121,7 +20307,16 @@ var sharedHooks = {
20121
20307
  function defineMacro(config, source = "builtin") {
20122
20308
  const parameters = config.parameters ?? [];
20123
20309
  checkParameterTypes(config.name, parameters);
20310
+ const acts = actingMacros.has(config.name);
20124
20311
  function Wrapper(props) {
20312
+ const displayOnly = useContext(DisplayOnlyContext);
20313
+ if (displayOnly && acts) return h(MacroError, {
20314
+ macro: config.name,
20315
+ error: displayOnlyError(config.name)
20316
+ });
20317
+ const refuse = () => {
20318
+ throw displayOnlyError(config.name);
20319
+ };
20125
20320
  let className = props.className;
20126
20321
  let id = props.id;
20127
20322
  let resolve;
@@ -20162,8 +20357,8 @@ function defineMacro(config, source = "builtin") {
20162
20357
  id,
20163
20358
  resolve,
20164
20359
  cls: macroClass(config.name, className),
20165
- mutate: inIteration ? (code) => runAsItemEdit(() => executeMutation(code, getValues(), update)) : (code) => executeMutation(code, getValues(), update),
20166
- update,
20360
+ mutate: displayOnly ? refuse : inIteration ? (code) => runAsItemEdit(() => executeMutation(code, getValues(), update)) : (code) => executeMutation(code, getValues(), update),
20361
+ update: displayOnly ? refuse : update,
20167
20362
  getValues,
20168
20363
  wrap: (content) => wrapContent(className, id, content)
20169
20364
  };
@@ -20186,7 +20381,7 @@ function defineMacro(config, source = "builtin") {
20186
20381
  ctx.varName = varExpr;
20187
20382
  ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
20188
20383
  ctx.getValue = () => getByPath(readState().variables, segments);
20189
- ctx.setValue = (value) => {
20384
+ ctx.setValue = displayOnly ? refuse : (value) => {
20190
20385
  noteControlEdit(segments);
20191
20386
  mutateState((work, adopt) => {
20192
20387
  setByPath(work.variables, segments, adopt(value), { createMissing: true });
@@ -20240,6 +20435,286 @@ function getRenderedNavigationId() {
20240
20435
  return renderedNavigationId;
20241
20436
  }
20242
20437
  //#endregion
20438
+ //#region src/story-context-passage.ts
20439
+ /**
20440
+ * The macros a display-only passage may not use besides the input macros:
20441
+ * they change the story, act when they mount, or are controls.
20442
+ */
20443
+ var REJECTED_MACROS = [
20444
+ ...ACTING_MACROS,
20445
+ "link",
20446
+ "button",
20447
+ "dialog"
20448
+ ];
20449
+ /**
20450
+ * Why `StoryContext` (the passage an agent reads for stats and
20451
+ * instructions) may not use what it uses: it is display-only, so no macro
20452
+ * that changes the story or acts on mount, no input and no `[[link]]`.
20453
+ * `inputMacros` are the names of the macros that bind a variable. Each
20454
+ * name is reported once. Malformed markup is left to the markup validation.
20455
+ */
20456
+ function storyContextErrors(content, inputMacros) {
20457
+ const rejected = new NameSet([...REJECTED_MACROS, ...inputMacros]);
20458
+ let tokens;
20459
+ try {
20460
+ tokens = tokenizeMarkup(content);
20461
+ } catch (err) {
20462
+ if (err instanceof MarkupError) return [];
20463
+ throw err;
20464
+ }
20465
+ const found = /* @__PURE__ */ new Set();
20466
+ for (const token of tokens) if (token.type === "link") found.add("[[links]]");
20467
+ else if (token.type === "macro" && !token.isClose && rejected.has(token.name)) found.add(`{${token.name.toLowerCase()}}`);
20468
+ return [...found].map((what) => `StoryContext: ${what} is not allowed; StoryContext is display-only`);
20469
+ }
20470
+ /** The element the mounted StoryContext tree renders into. */
20471
+ var container = null;
20472
+ /** The hidden element the container was put in. */
20473
+ var wrapper = null;
20474
+ /** What shows in place of a StoryContext that can't be rendered. */
20475
+ function contextError(err) {
20476
+ return h("span", { class: "error" }, `StoryContext: ${errorMessage(err)}`);
20477
+ }
20478
+ /** The passage's tree, or the error that stops it from rendering. */
20479
+ function StoryContextView({ ast }) {
20480
+ const [error] = useErrorBoundary();
20481
+ return error ? contextError(error) : renderNodes(ast);
20482
+ }
20483
+ /**
20484
+ * The element holding the rendered `StoryContext` passage, or null when the
20485
+ * story has none. It is mounted on the first call, hidden from the page and
20486
+ * with its controls registering no actions, and stays mounted: it follows the
20487
+ * story's variables, also across a restart. The element itself is not hidden
20488
+ * (its parent is), so observableText() reads it. A passage that can't be
20489
+ * parsed or rendered shows its error as text in the element; this never
20490
+ * throws.
20491
+ */
20492
+ function storyContextElement() {
20493
+ if (container?.isConnected) return container;
20494
+ if (container) {
20495
+ render(null, container);
20496
+ wrapper?.remove();
20497
+ container = wrapper = null;
20498
+ }
20499
+ const passage = useStoryStore.getState().storyData?.passages.get("StoryContext");
20500
+ if (!passage) return null;
20501
+ const hidden = document.createElement("div");
20502
+ hidden.style.display = "none";
20503
+ const el = document.createElement("div");
20504
+ hidden.appendChild(el);
20505
+ document.body.appendChild(hidden);
20506
+ container = el;
20507
+ wrapper = hidden;
20508
+ let view;
20509
+ try {
20510
+ view = h(StoryContextView, { ast: parseMarkup(passage.content) });
20511
+ } catch (err) {
20512
+ view = contextError(err);
20513
+ }
20514
+ const mount = () => render(h(ActionsDisabledContext.Provider, { value: true }, h(DisplayOnlyContext.Provider, { value: true }, view)), el);
20515
+ try {
20516
+ mount();
20517
+ mount();
20518
+ } catch (err) {
20519
+ render(contextError(err), el);
20520
+ }
20521
+ return el;
20522
+ }
20523
+ //#endregion
20524
+ //#region src/observe/observable-text.ts
20525
+ /** Elements that start and end a line. */
20526
+ var BLOCKS = /* @__PURE__ */ new Set([
20527
+ "P",
20528
+ "DIV",
20529
+ "LI",
20530
+ "H1",
20531
+ "H2",
20532
+ "H3",
20533
+ "H4",
20534
+ "H5",
20535
+ "H6",
20536
+ "BLOCKQUOTE",
20537
+ "PRE",
20538
+ "TR",
20539
+ "SECTION",
20540
+ "ARTICLE",
20541
+ "HEADER",
20542
+ "FOOTER"
20543
+ ]);
20544
+ /** Elements whose content is never text the reader reads. */
20545
+ var NOT_TEXT = /* @__PURE__ */ new Set([
20546
+ "SCRIPT",
20547
+ "STYLE",
20548
+ "TEMPLATE",
20549
+ "NOSCRIPT"
20550
+ ]);
20551
+ /**
20552
+ * Whether the reader can't see the element. Headless DOMs compute no layout,
20553
+ * so only what the markup says counts: the `hidden` attribute, an inline
20554
+ * `display: none` and `aria-hidden="true"`.
20555
+ */
20556
+ function isHidden(el) {
20557
+ 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);
20558
+ }
20559
+ function formatValue(value) {
20560
+ return JSON.stringify(value) ?? String(value);
20561
+ }
20562
+ /** What a control with an action shows: its type, variable and value. */
20563
+ function controlMarker(el) {
20564
+ const own = el;
20565
+ const action = getAction(el.getAttribute("data-action") ?? "");
20566
+ const type = action?.type ?? el.getAttribute("type") ?? el.localName;
20567
+ const isCheckbox = type === "checkbox";
20568
+ const value = action?.value !== void 0 ? action.value : isCheckbox ? !!own.checked : own.value ?? "";
20569
+ const shown = isCheckbox ? value ? "checked" : "unchecked" : formatValue(value);
20570
+ const variable = action?.variable;
20571
+ const name = variable && !variable.startsWith("$") ? `$${variable}` : variable;
20572
+ if (type === "radiobutton" && own.value !== void 0) {
20573
+ const state = action?.value === own.value ? "selected" : "unselected";
20574
+ return `[${type}${name ? ` ${name}` : ""} = ${formatValue(own.value)}: ${state}]`;
20575
+ }
20576
+ return `[${type}${name ? ` ${name}` : ""}: ${shown}]`;
20577
+ }
20578
+ /**
20579
+ * The text a reader sees in the element, as lines: blocks and `<br>` break
20580
+ * lines, hidden elements are left out, and a control with a `data-action`
20581
+ * becomes a marker such as `[textbox $name: "Alice"]`. Elements inside `el`
20582
+ * that match `skip` are left out with their content.
20583
+ */
20584
+ function observableText(el, skip) {
20585
+ let out = "";
20586
+ const endLine = () => {
20587
+ if (out !== "" && !out.endsWith("\n")) out += "\n";
20588
+ };
20589
+ const walk = (node, inPre) => {
20590
+ if (node.nodeType === 3) {
20591
+ const data = node.textContent ?? "";
20592
+ if (inPre) out += data;
20593
+ else {
20594
+ const collapsed = data.replace(/\s+/g, " ");
20595
+ out += out === "" || out.endsWith("\n") ? collapsed.trimStart() : collapsed;
20596
+ }
20597
+ return;
20598
+ }
20599
+ if (node.nodeType !== 1) return;
20600
+ const child = node;
20601
+ if (isHidden(child) || skip && child !== el && child.matches(skip)) return;
20602
+ if (child.hasAttribute("data-action")) {
20603
+ out += controlMarker(child);
20604
+ return;
20605
+ }
20606
+ if (child.tagName === "BR") {
20607
+ out += "\n";
20608
+ return;
20609
+ }
20610
+ const block = BLOCKS.has(child.tagName);
20611
+ if (block) endLine();
20612
+ for (const c of Array.from(child.childNodes)) walk(c, inPre || child.tagName === "PRE");
20613
+ if (block) endLine();
20614
+ };
20615
+ walk(el, false);
20616
+ return out.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\s+$/g, "");
20617
+ }
20618
+ /**
20619
+ * The trimmed text of each error shown in the element, leaving out those
20620
+ * the reader can't see (inside a hidden element, as observableText() does)
20621
+ * and those inside an element within `el` that matches `skip`.
20622
+ */
20623
+ function observableErrors(el, skip) {
20624
+ const left = (e) => {
20625
+ for (let at = e; at; at = at.parentElement) {
20626
+ if (isHidden(at)) return true;
20627
+ if (at === el) return false;
20628
+ if (skip && at.matches(skip)) return true;
20629
+ }
20630
+ return false;
20631
+ };
20632
+ return Array.from(el.querySelectorAll(".error")).filter((e) => !left(e)).map((e) => (e.textContent ?? "").trim());
20633
+ }
20634
+ //#endregion
20635
+ //#region src/observe/observe.ts
20636
+ /**
20637
+ * Leaving the story's history, restarting, saving and loading, and the
20638
+ * menubar's Saves and Settings dialogs (`dialog`) are not moves in the story.
20639
+ */
20640
+ var DEFAULT_EXCLUDED = /* @__PURE__ */ new Set([
20641
+ "back",
20642
+ "forward",
20643
+ "restart",
20644
+ "save",
20645
+ "load",
20646
+ "dialog"
20647
+ ]);
20648
+ /**
20649
+ * The actions an observation offers: without the default exclusions unless
20650
+ * an `include` rule puts them back, and without what an `exclude` rule
20651
+ * matches (exclude wins over include).
20652
+ */
20653
+ function filterObservedActions(actions, rules) {
20654
+ const matchesAny = (action, matchers) => matchers?.some((m) => actionMatches(action, m)) ?? false;
20655
+ return actions.filter((action) => !matchesAny(action, rules.exclude) && (!DEFAULT_EXCLUDED.has(action.type) || matchesAny(action, rules.include))).map(({ perform: _perform, ...rest }) => rest);
20656
+ }
20657
+ var observedRules = {};
20658
+ /**
20659
+ * Replace the rules for which actions observe() offers. Each matcher is
20660
+ * checked as the automation YAML checks its matchers; a bad one throws,
20661
+ * naming the rule.
20662
+ */
20663
+ function setObservedActions(rules) {
20664
+ const fail = (message) => {
20665
+ throw new Error(`spindle: Story.setObservedActions(): ${message}`);
20666
+ };
20667
+ const r = checkObject(rules, "the rules", ["exclude", "include"], fail);
20668
+ const next = {};
20669
+ for (const key of ["exclude", "include"]) {
20670
+ const list = r[key];
20671
+ if (list === void 0) continue;
20672
+ if (!Array.isArray(list)) fail(`"${key}" must be a list of action matchers`);
20673
+ next[key] = list.map((m, i) => checkActionMatcher(m, `the rule ${key}[${i}]`, fail));
20674
+ }
20675
+ observedRules = next;
20676
+ }
20677
+ /** A dialog, from its backdrop down. */
20678
+ var DIALOG = ".dialog-overlay";
20679
+ /**
20680
+ * The actions a reader can reach: while a dialog is open (it is modal) only
20681
+ * those in the innermost one, its close button included.
20682
+ */
20683
+ function offeredActions() {
20684
+ const dialog = innermostOpenDialog();
20685
+ return dialog ? getDialogActions(dialog) : getActions();
20686
+ }
20687
+ /** What the story shows and offers now. */
20688
+ function observe() {
20689
+ if (getRenderedNavigationId() === null) throw new Error("spindle: Story.observe() needs a mounted story");
20690
+ const { currentPassage, navigationId } = useStoryStore.getState();
20691
+ const contextEl = storyContextElement();
20692
+ const passageEl = document.querySelector(".passage");
20693
+ const bodies = openDialogPanels().map((el) => ({
20694
+ passage: el.getAttribute("data-dialog-passage") ?? "",
20695
+ body: el.querySelector(":scope > .dialog-body")
20696
+ }));
20697
+ const dialogs = bodies.map(({ passage, body }) => ({
20698
+ passage,
20699
+ text: body ? observableText(body, DIALOG) : ""
20700
+ }));
20701
+ const errors = [
20702
+ passageEl,
20703
+ ...bodies.map((d) => d.body),
20704
+ contextEl
20705
+ ].flatMap((el) => el ? observableErrors(el, DIALOG) : []);
20706
+ for (const { context, message } of getRuntimeErrors()) errors.push(`${context.replace(/:$/, "")}: ${message}`);
20707
+ return {
20708
+ passage: currentPassage,
20709
+ text: passageEl ? observableText(passageEl, DIALOG) : "",
20710
+ context: contextEl ? observableText(contextEl) : null,
20711
+ dialogs,
20712
+ actions: filterObservedActions(offeredActions(), observedRules),
20713
+ errors,
20714
+ turn: navigationId
20715
+ };
20716
+ }
20717
+ //#endregion
20243
20718
  //#region src/story-api.ts
20244
20719
  var readyResolve = null;
20245
20720
  var readyPromise = null;
@@ -20315,7 +20790,7 @@ function storeAction(name) {
20315
20790
  return ((...args) => useStoryStore.getState()[name](...args));
20316
20791
  }
20317
20792
  function createStoryAPI() {
20318
- return {
20793
+ const api = {
20319
20794
  get(name) {
20320
20795
  const { isTransient, key } = parseName(name);
20321
20796
  const scope = getActiveMutationScope();
@@ -20438,6 +20913,13 @@ function createStoryAPI() {
20438
20913
  });
20439
20914
  return getActions();
20440
20915
  },
20916
+ observe,
20917
+ async step(id, value) {
20918
+ await api.performAction(id, value);
20919
+ await api.waitForActions();
20920
+ return observe();
20921
+ },
20922
+ setObservedActions,
20441
20923
  watch(condition, callbackOrOptions) {
20442
20924
  return addTrigger(condition, callbackOrOptions);
20443
20925
  },
@@ -20533,6 +21015,7 @@ function createStoryAPI() {
20533
21015
  }
20534
21016
  }
20535
21017
  };
21018
+ return api;
20536
21019
  }
20537
21020
  function installStoryAPI() {
20538
21021
  window.Story = createStoryAPI();
@@ -22759,7 +23242,8 @@ function Settled({ onSettled }) {
22759
23242
  * through a live view, so a local assigned earlier in the body is visible),
22760
23243
  * nobr/inline rendering, the enclosing block widget's {@children}, the
22761
23244
  * 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).
23245
+ * (#411), the owning passage's departure (#410), and whether it renders in
23246
+ * display-only content (StoryContext), which a body may not change either.
22763
23247
  * The body then behaves as if it rendered in place.
22764
23248
  *
22765
23249
  * The body's macros read story state from the store. Run from mutation code
@@ -22776,6 +23260,8 @@ function useDetachedBody() {
22776
23260
  const closeDialog = useContext(DialogCloseContext);
22777
23261
  const inIteration = useContext(ItemEditContext);
22778
23262
  const hasLeft = useContext(OutgoingContext);
23263
+ const displayOnly = useContext(DisplayOnlyContext);
23264
+ const actionsDisabled = useContext(ActionsDisabledContext);
22779
23265
  const mounted = useRef([]);
22780
23266
  useEffect(() => {
22781
23267
  const unsubscribe = subscribeStateReplacement(() => {
@@ -22818,14 +23304,20 @@ function useDetachedBody() {
22818
23304
  value: closeDialog,
22819
23305
  children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
22820
23306
  value: inIteration,
22821
- children: /* @__PURE__ */ jsxs(OutgoingContext.Provider, {
23307
+ children: /* @__PURE__ */ jsx(OutgoingContext.Provider, {
22822
23308
  value: hasLeft,
22823
- children: [renderNodes(children, {
22824
- nobr,
22825
- inline,
22826
- structural,
22827
- locals
22828
- }), release && /* @__PURE__ */ jsx(Settled, { onSettled: release })]
23309
+ children: /* @__PURE__ */ jsx(DisplayOnlyContext.Provider, {
23310
+ value: displayOnly,
23311
+ children: /* @__PURE__ */ jsxs(ActionsDisabledContext.Provider, {
23312
+ value: actionsDisabled,
23313
+ children: [renderNodes(children, {
23314
+ nobr,
23315
+ inline,
23316
+ structural,
23317
+ locals
23318
+ }), release && /* @__PURE__ */ jsx(Settled, { onSettled: release })]
23319
+ })
23320
+ })
22829
23321
  })
22830
23322
  })
22831
23323
  })
@@ -23944,7 +24436,7 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
23944
24436
  }],
23945
24437
  render(_props, ctx) {
23946
24438
  const placeholder = ctx.args.placeholder ?? "";
23947
- useVariableAction(ctx, {
24439
+ const actionId = useVariableAction(ctx, {
23948
24440
  type: name,
23949
24441
  label: placeholder || ctx.varName,
23950
24442
  perform: (v) => ctx.setValue(toValue(v))
@@ -23954,6 +24446,7 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
23954
24446
  return h(type ? "input" : "textarea", {
23955
24447
  type,
23956
24448
  id: ctx.id,
24449
+ "data-action": actionId || void 0,
23957
24450
  class: ctx.cls,
23958
24451
  value: shown,
23959
24452
  placeholder,
@@ -23988,7 +24481,7 @@ defineMacro({
23988
24481
  }],
23989
24482
  render(_props, ctx) {
23990
24483
  const label = ctx.args.label ?? "";
23991
- useVariableAction(ctx, {
24484
+ const actionId = useVariableAction(ctx, {
23992
24485
  type: "checkbox",
23993
24486
  label: label || ctx.varName || "",
23994
24487
  value: !!ctx.value,
@@ -23999,6 +24492,7 @@ defineMacro({
23999
24492
  class: ctx.cls,
24000
24493
  children: [/* @__PURE__ */ jsx("input", {
24001
24494
  type: "checkbox",
24495
+ "data-action": actionId || void 0,
24002
24496
  checked: !!ctx.value,
24003
24497
  onChange: (e) => ctx.setValue(e.target.checked)
24004
24498
  }), label ? ` ${label}` : null]
@@ -24029,7 +24523,7 @@ defineMacro({
24029
24523
  const radioValue = ctx.args.value ?? "";
24030
24524
  const label = ctx.args.label ?? "";
24031
24525
  const view = ctx.hooks.useContext(ViewScopeContext);
24032
- useVariableAction(ctx, {
24526
+ const actionId = useVariableAction(ctx, {
24033
24527
  type: "radiobutton",
24034
24528
  key: `$${ctx.varName}:${radioValue}`,
24035
24529
  label: label || radioValue,
@@ -24040,6 +24534,8 @@ defineMacro({
24040
24534
  class: ctx.cls,
24041
24535
  children: [/* @__PURE__ */ jsx("input", {
24042
24536
  type: "radio",
24537
+ value: radioValue,
24538
+ "data-action": actionId || void 0,
24043
24539
  name: view ? `radio-${view}-${ctx.varName}` : `radio-${ctx.varName}`,
24044
24540
  checked: ctx.value === radioValue,
24045
24541
  onChange: () => ctx.setValue(radioValue)
@@ -24057,7 +24553,7 @@ defineMacro({
24057
24553
  parameters: [VARIABLE_PARAMETER],
24058
24554
  render({ children = [] }, ctx) {
24059
24555
  const options = ctx.extractOptions(children);
24060
- useVariableAction(ctx, {
24556
+ const actionId = useVariableAction(ctx, {
24061
24557
  type: "listbox",
24062
24558
  label: ctx.varName,
24063
24559
  options,
@@ -24067,6 +24563,7 @@ defineMacro({
24067
24563
  });
24068
24564
  return /* @__PURE__ */ jsx("select", {
24069
24565
  id: ctx.id,
24566
+ "data-action": actionId || void 0,
24070
24567
  class: ctx.cls,
24071
24568
  value: display(ctx.value),
24072
24569
  onChange: (e) => ctx.setValue(e.target.value),
@@ -24093,7 +24590,7 @@ defineMacro({
24093
24590
  const nextIndex = (options.indexOf(String(current)) + 1) % options.length;
24094
24591
  ctx.setValue(options[nextIndex]);
24095
24592
  };
24096
- useVariableAction(ctx, {
24593
+ const actionId = useVariableAction(ctx, {
24097
24594
  type: "cycle",
24098
24595
  label: ctx.value == null ? options[0] || "" : String(ctx.value),
24099
24596
  options,
@@ -24105,6 +24602,7 @@ defineMacro({
24105
24602
  return /* @__PURE__ */ jsx("button", {
24106
24603
  type: "button",
24107
24604
  id: ctx.id,
24605
+ "data-action": actionId || void 0,
24108
24606
  class: ctx.cls,
24109
24607
  onClick: handleClick,
24110
24608
  children: ctx.value == null ? options[0] || "" : String(ctx.value)
@@ -24250,14 +24748,17 @@ function orStop(parse, where = "") {
24250
24748
  function knownParameters() {
24251
24749
  return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
24252
24750
  }
24751
+ /** The names of the registered macros that bind a variable (the inputs). */
24752
+ function storeVarMacroNames() {
24753
+ return getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
24754
+ }
24253
24755
  /**
24254
24756
  * The undeclared variables the passages refer to, with the macros known now:
24255
24757
  * the input macros that bind a variable (registered by author JS or
24256
24758
  * StoryInit) and the roles of their parameters decide what is a reference.
24257
24759
  */
24258
24760
  function variableErrors(storyData, schema) {
24259
- const storeVarMacros = getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
24260
- return validatePassages(storyData.passages, schema, storeVarMacros, knownParameters());
24761
+ return validatePassages(storyData.passages, schema, storeVarMacroNames(), knownParameters());
24261
24762
  }
24262
24763
  /**
24263
24764
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -24325,6 +24826,8 @@ function boot() {
24325
24826
  for (const [, passage] of storyData.passages) if (passage.tags.includes("widget")) orStop(() => registerWidgetDefinitions(parseMarkup(passage.content), passage.name), `Passage "${passage.name}": `);
24326
24827
  initializeStory(loadSession(storyData.ifid));
24327
24828
  const markup = [...variableErrors(storyData, schema), ...markupErrors(storyData, (p) => p.name !== "StoryInit")];
24829
+ const storyContext = storyData.passages.get("StoryContext");
24830
+ if (storyContext) markup.push(...storyContextErrors(storyContext.content, storeVarMacroNames()));
24328
24831
  if (markup.length > 0) stopWithErrors(markup);
24329
24832
  let prevNavigationId = useStoryStore.getState().navigationId;
24330
24833
  useStoryStore.subscribe((state) => {
@@ -24384,5 +24887,39 @@ function bootStory(options) {
24384
24887
  }
24385
24888
  });
24386
24889
  }
24890
+ /**
24891
+ * Record a playthrough for stateless decision models, which need the last few
24892
+ * steps sent with every call. A step that rejects records nothing.
24893
+ */
24894
+ function createTranscript(story, options = {}) {
24895
+ const limit = options.limit ?? 10;
24896
+ 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)}`);
24897
+ const withText = options.include?.text ?? true;
24898
+ const withContext = options.include?.context ?? false;
24899
+ const entries = [];
24900
+ return {
24901
+ entries,
24902
+ async step(id, value) {
24903
+ const before = story.observe();
24904
+ const action = before.actions.find((a) => a.id === id) ?? story.getActions().find((a) => a.id === id);
24905
+ const next = await story.step(id, value);
24906
+ const chose = {
24907
+ id,
24908
+ label: action?.label ?? id
24909
+ };
24910
+ if (value !== void 0) chose.value = value;
24911
+ const entry = {
24912
+ turn: before.turn,
24913
+ passage: before.passage,
24914
+ chose
24915
+ };
24916
+ if (withText) entry.text = before.text;
24917
+ if (withContext) entry.context = before.context;
24918
+ entries.push(entry);
24919
+ if (entries.length > limit) entries.splice(0, entries.length - limit);
24920
+ return next;
24921
+ }
24922
+ };
24923
+ }
24387
24924
  //#endregion
24388
- export { bootStory };
24925
+ export { bootStory, createTranscript };