@rohal12/spindle 0.59.31 → 0.59.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/headless.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  import { boot } from './index';
11
11
  import { useStoryStore } from './store';
12
12
  import type { StoryAPI } from './story-api';
13
+ import type { Observation } from './observe/observe';
13
14
 
14
15
  export interface BootStoryOptions {
15
16
  /**
@@ -84,4 +85,83 @@ export function bootStory(options: BootStoryOptions): Promise<StoryAPI> {
84
85
  });
85
86
  }
86
87
 
87
- export type { StoryAPI };
88
+ /** One recorded step: what the reader saw, and what they chose. */
89
+ export interface TranscriptEntry {
90
+ turn: number;
91
+ passage: string;
92
+ /** Left out when the transcript was created with `include.text: false`. */
93
+ text?: string;
94
+ /** Only with `include.context: true`. */
95
+ context?: string | null;
96
+ chose: { id: string; label: string; value?: unknown };
97
+ }
98
+
99
+ export interface TranscriptOptions {
100
+ /**
101
+ * How many of the latest entries to keep: a non-negative integer, or
102
+ * `Infinity` for all. Default 10. Anything else throws.
103
+ */
104
+ limit?: number;
105
+ /** Default `{ text: true, context: false }`. */
106
+ include?: { text?: boolean; context?: boolean };
107
+ }
108
+
109
+ export interface Transcript {
110
+ /**
111
+ * `Story.step()`, recording the observation it acted on and the choice.
112
+ * Await each step before the next: steps are not queued.
113
+ */
114
+ step(id: string, value?: unknown): Promise<Observation>;
115
+ readonly entries: readonly TranscriptEntry[];
116
+ }
117
+
118
+ /**
119
+ * Record a playthrough for stateless decision models, which need the last few
120
+ * steps sent with every call. A step that rejects records nothing.
121
+ */
122
+ export function createTranscript(
123
+ story: StoryAPI,
124
+ options: TranscriptOptions = {},
125
+ ): Transcript {
126
+ const limit = options.limit ?? 10;
127
+ if (
128
+ limit !== Infinity &&
129
+ !(typeof limit === 'number' && Number.isInteger(limit) && limit >= 0)
130
+ ) {
131
+ throw new Error(
132
+ `spindle: createTranscript(): "limit" must be a non-negative integer or Infinity, got ${typeof limit === 'string' ? JSON.stringify(limit) : String(limit)}`,
133
+ );
134
+ }
135
+ const withText = options.include?.text ?? true;
136
+ const withContext = options.include?.context ?? false;
137
+ const entries: TranscriptEntry[] = [];
138
+
139
+ return {
140
+ entries,
141
+ async step(id, value) {
142
+ const before = story.observe();
143
+ const action =
144
+ before.actions.find((a) => a.id === id) ??
145
+ story.getActions().find((a) => a.id === id);
146
+ const next = await story.step(id, value);
147
+
148
+ const chose: TranscriptEntry['chose'] = {
149
+ id,
150
+ label: action?.label ?? id,
151
+ };
152
+ if (value !== undefined) chose.value = value;
153
+ const entry: TranscriptEntry = {
154
+ turn: before.turn,
155
+ passage: before.passage,
156
+ chose,
157
+ };
158
+ if (withText) entry.text = before.text;
159
+ if (withContext) entry.context = before.context;
160
+ entries.push(entry);
161
+ if (entries.length > limit) entries.splice(0, entries.length - limit);
162
+ return next;
163
+ },
164
+ };
165
+ }
166
+
167
+ export type { Observation, StoryAPI };
@@ -1,4 +1,5 @@
1
- import { useLayoutEffect, useRef } from 'preact/hooks';
1
+ import { createContext } from 'preact';
2
+ import { useContext, useLayoutEffect, useRef } from 'preact/hooks';
2
3
  import {
3
4
  registerAction,
4
5
  generateActionId,
@@ -6,6 +7,7 @@ import {
6
7
  type ActionRegistration,
7
8
  type StoryAction,
8
9
  } from '../action-registry';
10
+ import { DialogCloseContext } from '../components/dialog-close-context';
9
11
 
10
12
  /** The action to register, and what its ID is generated from. */
11
13
  export interface UseActionOptions extends Omit<StoryAction, 'id'> {
@@ -13,13 +15,23 @@ export interface UseActionOptions extends Omit<StoryAction, 'id'> {
13
15
  authorId?: string;
14
16
  }
15
17
 
18
+ /**
19
+ * While true, controls rendered underneath do not register actions or reserve
20
+ * IDs. Used for display-only content mounted off-screen, so it never shows up
21
+ * in `getActions()` or shifts the IDs of the visible passage's controls.
22
+ */
23
+ export const ActionsDisabledContext = createContext(false);
24
+
16
25
  export function useAction(opts: UseActionOptions): string {
26
+ const disabled = useContext(ActionsDisabledContext);
27
+ // The dialog the control renders in, for observe() to scope by
28
+ const dialog = useContext(DialogCloseContext);
17
29
  const idRef = useRef<string>('');
18
30
  const performRef = useRef(opts.perform);
19
31
  performRef.current = opts.perform;
20
32
 
21
33
  // Generate ID only once on first call
22
- if (!idRef.current) {
34
+ if (!disabled && !idRef.current) {
23
35
  idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
24
36
  }
25
37
 
@@ -42,24 +54,32 @@ export function useAction(opts: UseActionOptions): string {
42
54
  // Registered for the component's lifetime. Unregistering removes only this
43
55
  // registration, never another control's holding the same ID (#233).
44
56
  const registration = useRef<ActionRegistration | null>(null);
57
+ // Set when the registration below is new in this commit: it is current
58
+ const fresh = useRef(false);
45
59
  useLayoutEffect(() => {
46
- const own = registerAction(buildAction());
60
+ if (disabled) return;
61
+ const own = registerAction(buildAction(), dialog);
47
62
  registration.current = own;
63
+ fresh.current = true;
48
64
  return () => own.unregister();
49
- }, [id]);
65
+ }, [id, disabled, dialog]);
50
66
 
51
67
  // When what the action exposes changes (e.g. an input's value), replace it
52
68
  // in place: one `actionsChanged` notification, and it keeps its position in
53
69
  // getActions(). Unregistering and registering again would notify twice and
54
- // move it to the end.
55
- const registered = useRef(false);
70
+ // move it to the end. Its dependencies include the registration's, so it
71
+ // runs in every commit that registers and clears `fresh` there.
56
72
  useLayoutEffect(() => {
57
- if (!registered.current) {
58
- registered.current = true; // the registration above is current
73
+ if (disabled) return;
74
+ if (fresh.current) {
75
+ fresh.current = false;
59
76
  return;
60
77
  }
61
78
  registration.current?.update(buildAction());
62
79
  }, [
80
+ id,
81
+ disabled,
82
+ dialog,
63
83
  opts.type,
64
84
  opts.label,
65
85
  opts.target,
@@ -69,5 +89,7 @@ export function useAction(opts: UseActionOptions): string {
69
89
  JSON.stringify(opts.options),
70
90
  ]);
71
91
 
72
- return id;
92
+ // A control that registers nothing has no ID (the flag may have turned
93
+ // true after it was generated)
94
+ return disabled ? '' : id;
73
95
  }
package/src/index.tsx CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  } from './story-api';
10
10
  import { resetIdCounters } from './action-registry';
11
11
  import { initializeStory } from './story-init';
12
+ import { storyContextErrors } from './story-context-passage';
12
13
  import { connectTriggersToStore } from './triggers';
13
14
  import { loadSession } from './saves/save-manager';
14
15
  import {
@@ -85,6 +86,13 @@ function knownParameters() {
85
86
  return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
86
87
  }
87
88
 
89
+ /** The names of the registered macros that bind a variable (the inputs). */
90
+ function storeVarMacroNames(): string[] {
91
+ return getMacroRegistry()
92
+ .filter((m) => m.storeVar)
93
+ .map((m) => m.name);
94
+ }
95
+
88
96
  /**
89
97
  * The undeclared variables the passages refer to, with the macros known now:
90
98
  * the input macros that bind a variable (registered by author JS or
@@ -94,13 +102,10 @@ function variableErrors(
94
102
  storyData: StoryData,
95
103
  schema: Parameters<typeof validatePassages>[1],
96
104
  ): string[] {
97
- const storeVarMacros = getMacroRegistry()
98
- .filter((m) => m.storeVar)
99
- .map((m) => m.name);
100
105
  return validatePassages(
101
106
  storyData.passages,
102
107
  schema,
103
- storeVarMacros,
108
+ storeVarMacroNames(),
104
109
  knownParameters(),
105
110
  );
106
111
  }
@@ -244,6 +249,13 @@ export function boot() {
244
249
  ...variableErrors(storyData, schema),
245
250
  ...markupErrors(storyData, (p) => p.name !== 'StoryInit'),
246
251
  ];
252
+ // StoryContext is display-only: not with the input macros known now either
253
+ const storyContext = storyData.passages.get('StoryContext');
254
+ if (storyContext) {
255
+ markup.push(
256
+ ...storyContextErrors(storyContext.content, storeVarMacroNames()),
257
+ );
258
+ }
247
259
  if (markup.length > 0) stopWithErrors(markup);
248
260
 
249
261
  // Reset action ID counters on every navigation (the passage remounts even
@@ -0,0 +1,147 @@
1
+ import { getAction } from '../action-registry';
2
+
3
+ /** Elements that start and end a line. */
4
+ const BLOCKS = new Set([
5
+ 'P',
6
+ 'DIV',
7
+ 'LI',
8
+ 'H1',
9
+ 'H2',
10
+ 'H3',
11
+ 'H4',
12
+ 'H5',
13
+ 'H6',
14
+ 'BLOCKQUOTE',
15
+ 'PRE',
16
+ 'TR',
17
+ 'SECTION',
18
+ 'ARTICLE',
19
+ 'HEADER',
20
+ 'FOOTER',
21
+ ]);
22
+
23
+ /** Elements whose content is never text the reader reads. */
24
+ const NOT_TEXT = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT']);
25
+
26
+ /**
27
+ * Whether the reader can't see the element. Headless DOMs compute no layout,
28
+ * so only what the markup says counts: the `hidden` attribute, an inline
29
+ * `display: none` and `aria-hidden="true"`.
30
+ */
31
+ function isHidden(el: Element): boolean {
32
+ return (
33
+ el.hasAttribute('hidden') ||
34
+ el.getAttribute('aria-hidden') === 'true' ||
35
+ /(^|;)\s*display\s*:\s*none\b/i.test(el.getAttribute('style') ?? '') ||
36
+ NOT_TEXT.has(el.tagName)
37
+ );
38
+ }
39
+
40
+ function formatValue(value: unknown): string {
41
+ return JSON.stringify(value) ?? String(value);
42
+ }
43
+
44
+ /** What a control with an action shows: its type, variable and value. */
45
+ function controlMarker(el: Element): string {
46
+ const own = el as Partial<HTMLInputElement>;
47
+ const action = getAction(el.getAttribute('data-action') ?? '');
48
+ const type = action?.type ?? el.getAttribute('type') ?? el.localName;
49
+ const isCheckbox = type === 'checkbox';
50
+ const value =
51
+ action?.value !== undefined
52
+ ? action.value
53
+ : isCheckbox
54
+ ? !!own.checked
55
+ : (own.value ?? '');
56
+ const shown = isCheckbox
57
+ ? value
58
+ ? 'checked'
59
+ : 'unchecked'
60
+ : formatValue(value);
61
+ const variable = action?.variable;
62
+ const name =
63
+ variable && !variable.startsWith('$') ? `$${variable}` : variable;
64
+ // A radio is one choice of its variable: its own value, and whether it is
65
+ // the one selected (the action's value is the variable's, shared by all)
66
+ if (type === 'radiobutton' && own.value !== undefined) {
67
+ const state = action?.value === own.value ? 'selected' : 'unselected';
68
+ return `[${type}${name ? ` ${name}` : ''} = ${formatValue(own.value)}: ${state}]`;
69
+ }
70
+ return `[${type}${name ? ` ${name}` : ''}: ${shown}]`;
71
+ }
72
+
73
+ /**
74
+ * The text a reader sees in the element, as lines: blocks and `<br>` break
75
+ * lines, hidden elements are left out, and a control with a `data-action`
76
+ * becomes a marker such as `[textbox $name: "Alice"]`. Elements inside `el`
77
+ * that match `skip` are left out with their content.
78
+ */
79
+ export function observableText(el: Element, skip?: string): string {
80
+ let out = '';
81
+ const endLine = () => {
82
+ if (out !== '' && !out.endsWith('\n')) out += '\n';
83
+ };
84
+
85
+ const walk = (node: Node, inPre: boolean) => {
86
+ if (node.nodeType === 3) {
87
+ const data = node.textContent ?? '';
88
+ if (inPre) out += data;
89
+ else {
90
+ // Source whitespace between blocks isn't a line of its own
91
+ const collapsed = data.replace(/\s+/g, ' ');
92
+ out +=
93
+ out === '' || out.endsWith('\n') ? collapsed.trimStart() : collapsed;
94
+ }
95
+ return;
96
+ }
97
+ if (node.nodeType !== 1) return;
98
+ const child = node as Element;
99
+ if (isHidden(child) || (skip && child !== el && child.matches(skip)))
100
+ return;
101
+ if (child.hasAttribute('data-action')) {
102
+ out += controlMarker(child);
103
+ return;
104
+ }
105
+ if (child.tagName === 'BR') {
106
+ out += '\n';
107
+ return;
108
+ }
109
+ const block = BLOCKS.has(child.tagName);
110
+ if (block) endLine();
111
+ for (const c of Array.from(child.childNodes)) {
112
+ walk(c, inPre || child.tagName === 'PRE');
113
+ }
114
+ if (block) endLine();
115
+ };
116
+
117
+ walk(el, false);
118
+ return (
119
+ out
120
+ .split('\n')
121
+ // Not trimStart: a <pre> line keeps its indentation, and no other line
122
+ // starts with whitespace
123
+ .map((line) => line.trimEnd())
124
+ .join('\n')
125
+ .replace(/\n{3,}/g, '\n\n')
126
+ .replace(/^\n+|\s+$/g, '')
127
+ );
128
+ }
129
+
130
+ /**
131
+ * The trimmed text of each error shown in the element, leaving out those
132
+ * the reader can't see (inside a hidden element, as observableText() does)
133
+ * and those inside an element within `el` that matches `skip`.
134
+ */
135
+ export function observableErrors(el: Element, skip?: string): string[] {
136
+ const left = (e: Element) => {
137
+ for (let at: Element | null = e; at; at = at.parentElement) {
138
+ if (isHidden(at)) return true;
139
+ if (at === el) return false;
140
+ if (skip && at.matches(skip)) return true;
141
+ }
142
+ return false;
143
+ };
144
+ return Array.from(el.querySelectorAll('.error'))
145
+ .filter((e) => !left(e))
146
+ .map((e) => (e.textContent ?? '').trim());
147
+ }
@@ -0,0 +1,160 @@
1
+ import {
2
+ actionMatches,
3
+ checkActionMatcher,
4
+ getActions,
5
+ getDialogActions,
6
+ type ActionMatcher,
7
+ type ActionType,
8
+ type StoryAction,
9
+ } from '../action-registry';
10
+ import { getRenderedNavigationId } from '../passage-render-state';
11
+ import { useStoryStore } from '../store';
12
+ import { getRuntimeErrors } from '../runtime-errors';
13
+ import { storyContextElement } from '../story-context-passage';
14
+ import { innermostOpenDialog, openDialogPanels } from '../triggers';
15
+ import { checkObject, type Fail } from '../utils/field-checks';
16
+ import { observableErrors, observableText } from './observable-text';
17
+
18
+ /** An action as an observation lists it: what it is, not how to run it. */
19
+ export type ObservedAction = Omit<StoryAction, 'perform'>;
20
+
21
+ /** Which actions an observation offers, besides the default ones. */
22
+ export interface ObservedActionRules {
23
+ /** Leave out the actions that match any of these. */
24
+ exclude?: ActionMatcher[];
25
+ /** Offer the default-excluded actions that match any of these. */
26
+ include?: ActionMatcher[];
27
+ }
28
+
29
+ /** What a reader of the story sees and can do, as plain data. */
30
+ export interface Observation {
31
+ /** The current passage's name. */
32
+ passage: string;
33
+ /** The reader-visible text of the passage area. */
34
+ text: string;
35
+ /** The rendered `StoryContext` text, or null if the story has none. */
36
+ context: string | null;
37
+ /** The open dialogs, innermost last. */
38
+ dialogs: { passage: string; text: string }[];
39
+ /** The offered actions (see `setObservedActions`). */
40
+ actions: ObservedAction[];
41
+ /** The macro and runtime errors on screen. */
42
+ errors: string[];
43
+ /** The navigation count: a link moves it forward, an input does not. */
44
+ turn: number;
45
+ }
46
+
47
+ /**
48
+ * Leaving the story's history, restarting, saving and loading, and the
49
+ * menubar's Saves and Settings dialogs (`dialog`) are not moves in the story.
50
+ */
51
+ const DEFAULT_EXCLUDED: ReadonlySet<ActionType> = new Set<ActionType>([
52
+ 'back',
53
+ 'forward',
54
+ 'restart',
55
+ 'save',
56
+ 'load',
57
+ 'dialog',
58
+ ]);
59
+
60
+ /**
61
+ * The actions an observation offers: without the default exclusions unless
62
+ * an `include` rule puts them back, and without what an `exclude` rule
63
+ * matches (exclude wins over include).
64
+ */
65
+ export function filterObservedActions(
66
+ actions: StoryAction[],
67
+ rules: ObservedActionRules,
68
+ ): ObservedAction[] {
69
+ const matchesAny = (action: StoryAction, matchers?: ActionMatcher[]) =>
70
+ matchers?.some((m) => actionMatches(action, m)) ?? false;
71
+ return actions
72
+ .filter(
73
+ (action) =>
74
+ !matchesAny(action, rules.exclude) &&
75
+ (!DEFAULT_EXCLUDED.has(action.type) ||
76
+ matchesAny(action, rules.include)),
77
+ )
78
+ .map(({ perform: _perform, ...rest }) => rest);
79
+ }
80
+
81
+ let observedRules: ObservedActionRules = {};
82
+
83
+ /** Test-only: forget the rules set with setObservedActions(). */
84
+ export function _resetObservedActions(): void {
85
+ observedRules = {};
86
+ }
87
+
88
+ /**
89
+ * Replace the rules for which actions observe() offers. Each matcher is
90
+ * checked as the automation YAML checks its matchers; a bad one throws,
91
+ * naming the rule.
92
+ */
93
+ export function setObservedActions(rules: ObservedActionRules): void {
94
+ const fail: Fail = (message) => {
95
+ throw new Error(`spindle: Story.setObservedActions(): ${message}`);
96
+ };
97
+ const r = checkObject(rules, 'the rules', ['exclude', 'include'], fail);
98
+ const next: ObservedActionRules = {};
99
+ for (const key of ['exclude', 'include'] as const) {
100
+ const list = r[key];
101
+ if (list === undefined) continue;
102
+ if (!Array.isArray(list))
103
+ fail(`"${key}" must be a list of action matchers`);
104
+ next[key] = list.map((m, i) =>
105
+ checkActionMatcher(m, `the rule ${key}[${i}]`, fail),
106
+ );
107
+ }
108
+ observedRules = next;
109
+ }
110
+
111
+ /** A dialog, from its backdrop down. */
112
+ const DIALOG = '.dialog-overlay';
113
+
114
+ /**
115
+ * The actions a reader can reach: while a dialog is open (it is modal) only
116
+ * those in the innermost one, its close button included.
117
+ */
118
+ function offeredActions(): StoryAction[] {
119
+ const dialog = innermostOpenDialog();
120
+ return dialog ? getDialogActions(dialog) : getActions();
121
+ }
122
+
123
+ /** What the story shows and offers now. */
124
+ export function observe(): Observation {
125
+ // Before the first passage is on screen there's nothing to observe, and a
126
+ // story that failed to boot must not mount StoryContext
127
+ if (getRenderedNavigationId() === null) {
128
+ throw new Error('spindle: Story.observe() needs a mounted story');
129
+ }
130
+ const { currentPassage, navigationId } = useStoryStore.getState();
131
+ const contextEl = storyContextElement();
132
+ const passageEl = document.querySelector('.passage');
133
+ // A dialog opened from a passage or another dialog renders inside it:
134
+ // each one is read on its own, so the others leave it out. In opening
135
+ // order, which the page's order needn't be
136
+ const bodies = openDialogPanels().map((el) => ({
137
+ passage: el.getAttribute('data-dialog-passage') ?? '',
138
+ body: el.querySelector(':scope > .dialog-body'),
139
+ }));
140
+ const dialogs = bodies.map(({ passage, body }) => ({
141
+ passage,
142
+ text: body ? observableText(body, DIALOG) : '',
143
+ }));
144
+ const errors = [passageEl, ...bodies.map((d) => d.body), contextEl].flatMap(
145
+ (el) => (el ? observableErrors(el, DIALOG) : []),
146
+ );
147
+ // The runtime errors shown (as banners) until dismissed, with what failed
148
+ for (const { context, message } of getRuntimeErrors()) {
149
+ errors.push(`${context.replace(/:$/, '')}: ${message}`);
150
+ }
151
+ return {
152
+ passage: currentPassage,
153
+ text: passageEl ? observableText(passageEl, DIALOG) : '',
154
+ context: contextEl ? observableText(contextEl) : null,
155
+ dialogs,
156
+ actions: filterObservedActions(offeredActions(), observedRules),
157
+ errors,
158
+ turn: navigationId,
159
+ };
160
+ }
package/src/store.ts CHANGED
@@ -104,6 +104,7 @@ const SPECIAL_PASSAGES = new Set([
104
104
  'PassageHeader',
105
105
  'PassageFooter',
106
106
  'PassageDone',
107
+ 'StoryContext',
107
108
  ]);
108
109
 
109
110
  // ---------------------------------------------------------------------------
package/src/story-api.ts CHANGED
@@ -42,6 +42,12 @@ import {
42
42
  type StoryAction,
43
43
  } from './action-registry';
44
44
  import { getRenderedNavigationId } from './passage-render-state';
45
+ import {
46
+ observe,
47
+ setObservedActions,
48
+ type Observation,
49
+ type ObservedActionRules,
50
+ } from './observe/observe';
45
51
  import {
46
52
  initPRNG,
47
53
  isPRNGEnabled,
@@ -170,6 +176,9 @@ export interface StoryAPI {
170
176
  callback: StoryEventCallback<E>,
171
177
  ): () => void;
172
178
  waitForActions(): Promise<StoryAction[]>;
179
+ observe(): Observation;
180
+ step(id: string, value?: unknown): Promise<Observation>;
181
+ setObservedActions(rules: ObservedActionRules): void;
173
182
  watch(
174
183
  condition: string,
175
184
  callbackOrOptions: (() => void) | WatchOptions,
@@ -282,7 +291,7 @@ function storeAction<K extends keyof StoryState>(name: K): StoryState[K] {
282
291
  }
283
292
 
284
293
  function createStoryAPI(): StoryAPI {
285
- return {
294
+ const api: StoryAPI = {
286
295
  get(name: string): unknown {
287
296
  const { isTransient, key } = parseName(name);
288
297
  // Mutation code running now ({do}, ctx.mutate, watcher run actions)
@@ -479,6 +488,16 @@ function createStoryAPI(): StoryAPI {
479
488
  return getActions();
480
489
  },
481
490
 
491
+ observe,
492
+
493
+ async step(id: string, value?: unknown): Promise<Observation> {
494
+ await api.performAction(id, value);
495
+ await api.waitForActions();
496
+ return observe();
497
+ },
498
+
499
+ setObservedActions,
500
+
482
501
  watch(
483
502
  condition: string,
484
503
  callbackOrOptions: (() => void) | WatchOptions,
@@ -602,6 +621,7 @@ function createStoryAPI(): StoryAPI {
602
621
  },
603
622
  },
604
623
  };
624
+ return api;
605
625
  }
606
626
 
607
627
  declare global {