@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/README.md +19 -18
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +717 -203
- package/package.json +1 -1
- package/src/action-registry.ts +87 -3
- package/src/automation/load-yaml.ts +10 -55
- package/src/automation/runner.ts +2 -14
- package/src/automation/types.ts +2 -8
- package/src/components/PassageDialog.tsx +47 -11
- package/src/components/dialog-close-context.ts +10 -0
- package/src/components/macros/Checkbox.tsx +2 -1
- package/src/components/macros/Cycle.tsx +2 -1
- package/src/components/macros/Dialog.tsx +14 -3
- package/src/components/macros/Listbox.tsx +2 -1
- package/src/components/macros/Radiobutton.tsx +3 -1
- package/src/components/macros/detached-body.tsx +19 -8
- package/src/components/macros/input-macro.ts +2 -1
- package/src/define-macro.ts +42 -16
- package/src/display-only.ts +30 -0
- package/src/headless.ts +81 -1
- package/src/hooks/use-action.ts +31 -9
- package/src/index.tsx +16 -4
- package/src/observe/observable-text.ts +147 -0
- package/src/observe/observe.ts +160 -0
- package/src/store.ts +1 -0
- package/src/story-api.ts +21 -1
- package/src/story-context-passage.ts +132 -0
- package/src/triggers.ts +32 -8
- package/src/utils/field-checks.ts +46 -0
- package/types/headless.d.ts +43 -2
- package/types/index.d.ts +74 -1
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { h, render, type ComponentChild } from 'preact';
|
|
2
|
+
import { useErrorBoundary } from 'preact/hooks';
|
|
3
|
+
import { useStoryStore } from './store';
|
|
4
|
+
import { MarkupError, parseMarkup, tokenizeMarkup } from './markup/parse';
|
|
5
|
+
import type { ASTNode } from './markup/ast';
|
|
6
|
+
import { renderNodes } from './markup/render';
|
|
7
|
+
import { errorMessage } from './utils/error-message';
|
|
8
|
+
import { ActionsDisabledContext } from './hooks/use-action';
|
|
9
|
+
import { ACTING_MACROS, DisplayOnlyContext } from './display-only';
|
|
10
|
+
import { NameSet } from './utils/macro-names';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The macros a display-only passage may not use besides the input macros:
|
|
14
|
+
* they change the story, act when they mount, or are controls.
|
|
15
|
+
*/
|
|
16
|
+
const REJECTED_MACROS: readonly string[] = [
|
|
17
|
+
...ACTING_MACROS,
|
|
18
|
+
'link',
|
|
19
|
+
'button',
|
|
20
|
+
'dialog',
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Why `StoryContext` (the passage an agent reads for stats and
|
|
25
|
+
* instructions) may not use what it uses: it is display-only, so no macro
|
|
26
|
+
* that changes the story or acts on mount, no input and no `[[link]]`.
|
|
27
|
+
* `inputMacros` are the names of the macros that bind a variable. Each
|
|
28
|
+
* name is reported once. Malformed markup is left to the markup validation.
|
|
29
|
+
*/
|
|
30
|
+
export function storyContextErrors(
|
|
31
|
+
content: string,
|
|
32
|
+
inputMacros: Iterable<string>,
|
|
33
|
+
): string[] {
|
|
34
|
+
// Macro names are case-insensitive: {Set} is {set}
|
|
35
|
+
const rejected = new NameSet([...REJECTED_MACROS, ...inputMacros]);
|
|
36
|
+
let tokens;
|
|
37
|
+
try {
|
|
38
|
+
tokens = tokenizeMarkup(content);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
if (err instanceof MarkupError) return [];
|
|
41
|
+
throw err;
|
|
42
|
+
}
|
|
43
|
+
const found = new Set<string>();
|
|
44
|
+
for (const token of tokens) {
|
|
45
|
+
if (token.type === 'link') found.add('[[links]]');
|
|
46
|
+
else if (
|
|
47
|
+
token.type === 'macro' &&
|
|
48
|
+
!token.isClose &&
|
|
49
|
+
rejected.has(token.name)
|
|
50
|
+
) {
|
|
51
|
+
found.add(`{${token.name.toLowerCase()}}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return [...found].map(
|
|
55
|
+
(what) =>
|
|
56
|
+
`StoryContext: ${what} is not allowed; StoryContext is display-only`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The element the mounted StoryContext tree renders into. */
|
|
61
|
+
let container: HTMLElement | null = null;
|
|
62
|
+
/** The hidden element the container was put in. */
|
|
63
|
+
let wrapper: HTMLElement | null = null;
|
|
64
|
+
|
|
65
|
+
/** What shows in place of a StoryContext that can't be rendered. */
|
|
66
|
+
function contextError(err: unknown) {
|
|
67
|
+
return h('span', { class: 'error' }, `StoryContext: ${errorMessage(err)}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The passage's tree, or the error that stops it from rendering. */
|
|
71
|
+
function StoryContextView({ ast }: { ast: ASTNode[] }) {
|
|
72
|
+
const [error] = useErrorBoundary();
|
|
73
|
+
return error ? contextError(error) : renderNodes(ast);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The element holding the rendered `StoryContext` passage, or null when the
|
|
78
|
+
* story has none. It is mounted on the first call, hidden from the page and
|
|
79
|
+
* with its controls registering no actions, and stays mounted: it follows the
|
|
80
|
+
* story's variables, also across a restart. The element itself is not hidden
|
|
81
|
+
* (its parent is), so observableText() reads it. A passage that can't be
|
|
82
|
+
* parsed or rendered shows its error as text in the element; this never
|
|
83
|
+
* throws.
|
|
84
|
+
*/
|
|
85
|
+
export function storyContextElement(): Element | null {
|
|
86
|
+
if (container?.isConnected) return container;
|
|
87
|
+
// The page lost it: the old tree must not keep following the store
|
|
88
|
+
if (container) {
|
|
89
|
+
render(null, container);
|
|
90
|
+
wrapper?.remove();
|
|
91
|
+
container = wrapper = null;
|
|
92
|
+
}
|
|
93
|
+
const passage = useStoryStore
|
|
94
|
+
.getState()
|
|
95
|
+
.storyData?.passages.get('StoryContext');
|
|
96
|
+
if (!passage) return null;
|
|
97
|
+
|
|
98
|
+
const hidden = document.createElement('div');
|
|
99
|
+
hidden.style.display = 'none';
|
|
100
|
+
const el = document.createElement('div');
|
|
101
|
+
hidden.appendChild(el);
|
|
102
|
+
document.body.appendChild(hidden);
|
|
103
|
+
container = el;
|
|
104
|
+
wrapper = hidden;
|
|
105
|
+
|
|
106
|
+
let view: ComponentChild;
|
|
107
|
+
try {
|
|
108
|
+
view = h(StoryContextView, { ast: parseMarkup(passage.content) });
|
|
109
|
+
} catch (err) {
|
|
110
|
+
view = contextError(err);
|
|
111
|
+
}
|
|
112
|
+
// Display-only: its controls register no actions, and nothing in it, also
|
|
113
|
+
// what an {include} or a widget brings in, changes the story
|
|
114
|
+
const mount = () =>
|
|
115
|
+
render(
|
|
116
|
+
h(
|
|
117
|
+
ActionsDisabledContext.Provider,
|
|
118
|
+
{ value: true },
|
|
119
|
+
h(DisplayOnlyContext.Provider, { value: true }, view),
|
|
120
|
+
),
|
|
121
|
+
el,
|
|
122
|
+
);
|
|
123
|
+
try {
|
|
124
|
+
mount();
|
|
125
|
+
// An error caught below the boundary re-renders it a tick later: render
|
|
126
|
+
// again so that the element shows the error when this returns
|
|
127
|
+
mount();
|
|
128
|
+
} catch (err) {
|
|
129
|
+
render(contextError(err), el);
|
|
130
|
+
}
|
|
131
|
+
return el;
|
|
132
|
+
}
|
package/src/triggers.ts
CHANGED
|
@@ -404,32 +404,56 @@ export function registerDialogHost(callbacks: DialogHostCallbacks): () => void {
|
|
|
404
404
|
};
|
|
405
405
|
}
|
|
406
406
|
|
|
407
|
+
/** A dialog on display: the function that closes it, and its panel. */
|
|
408
|
+
interface OpenDialog {
|
|
409
|
+
close: () => void;
|
|
410
|
+
panel: Element | null;
|
|
411
|
+
}
|
|
412
|
+
|
|
407
413
|
/**
|
|
408
414
|
* The dialogs on display, bottom first, whoever opened them: the trigger
|
|
409
415
|
* host, `{dialog}` or a menubar button (each PassageDialog registers itself
|
|
410
|
-
* while mounted)
|
|
416
|
+
* while mounted).
|
|
411
417
|
*/
|
|
412
|
-
const openDialogs:
|
|
418
|
+
const openDialogs: OpenDialog[] = [];
|
|
413
419
|
|
|
414
|
-
/**
|
|
415
|
-
|
|
416
|
-
|
|
420
|
+
/**
|
|
421
|
+
* Register a displayed dialog, as the function that closes it (its
|
|
422
|
+
* DialogCloseContext value) and its panel element; returns the function
|
|
423
|
+
* that unregisters it.
|
|
424
|
+
*/
|
|
425
|
+
export function registerOpenDialog(
|
|
426
|
+
close: () => void,
|
|
427
|
+
panel: Element | null = null,
|
|
428
|
+
): () => void {
|
|
429
|
+
const entry: OpenDialog = { close, panel };
|
|
430
|
+
openDialogs.push(entry);
|
|
417
431
|
return () => {
|
|
418
|
-
const i = openDialogs.lastIndexOf(
|
|
432
|
+
const i = openDialogs.lastIndexOf(entry);
|
|
419
433
|
if (i >= 0) openDialogs.splice(i, 1);
|
|
420
434
|
};
|
|
421
435
|
}
|
|
422
436
|
|
|
437
|
+
/** The close function of the topmost dialog, or undefined when none is open. */
|
|
438
|
+
export function innermostOpenDialog(): (() => void) | undefined {
|
|
439
|
+
return openDialogs[openDialogs.length - 1]?.close;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** The panels of the dialogs on display, in opening order (innermost last). */
|
|
443
|
+
export function openDialogPanels(): Element[] {
|
|
444
|
+
return openDialogs.flatMap((d) => (d.panel ? [d.panel] : []));
|
|
445
|
+
}
|
|
446
|
+
|
|
423
447
|
/** Close the topmost dialog. */
|
|
424
448
|
export function closeCurrentDialog(): void {
|
|
425
|
-
const top =
|
|
449
|
+
const top = innermostOpenDialog();
|
|
426
450
|
if (top) top();
|
|
427
451
|
else dialogHostCallbacks?.close();
|
|
428
452
|
}
|
|
429
453
|
|
|
430
454
|
export function closeAllOpenDialogs(): void {
|
|
431
455
|
clearDialogQueue();
|
|
432
|
-
for (const close of [...openDialogs].reverse()) close();
|
|
456
|
+
for (const { close } of [...openDialogs].reverse()) close();
|
|
433
457
|
dialogHostCallbacks?.closeAll();
|
|
434
458
|
}
|
|
435
459
|
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks for the shape of plain data an author or a script hands in (the
|
|
3
|
+
* automation YAML, Story.setObservedActions() rules). Each takes a `fail`
|
|
4
|
+
* that throws with the caller's prefix, so the message names where the
|
|
5
|
+
* bad value came from.
|
|
6
|
+
*/
|
|
7
|
+
export type Fail = (message: string) => never;
|
|
8
|
+
|
|
9
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
10
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** `value` as an object whose keys are all in `allowed`. */
|
|
14
|
+
export function checkObject(
|
|
15
|
+
value: unknown,
|
|
16
|
+
what: string,
|
|
17
|
+
allowed: readonly string[],
|
|
18
|
+
fail: Fail,
|
|
19
|
+
): Record<string, unknown> {
|
|
20
|
+
if (!isRecord(value)) fail(`${what} must be an object`);
|
|
21
|
+
for (const key of Object.keys(value)) {
|
|
22
|
+
if (!allowed.includes(key)) {
|
|
23
|
+
fail(`${what} has an unknown field "${key}" (${allowed.join(', ')})`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type FieldCheck = (value: unknown) => boolean;
|
|
30
|
+
|
|
31
|
+
export const isString: FieldCheck = (v) => typeof v === 'string';
|
|
32
|
+
export const isBoolean: FieldCheck = (v) => typeof v === 'boolean';
|
|
33
|
+
|
|
34
|
+
/** Each field of `obj` named in `checks` passes its check. */
|
|
35
|
+
export function checkFields(
|
|
36
|
+
obj: Record<string, unknown>,
|
|
37
|
+
what: string,
|
|
38
|
+
checks: Record<string, [FieldCheck, string]>,
|
|
39
|
+
fail: Fail,
|
|
40
|
+
): void {
|
|
41
|
+
for (const [key, [valid, expected]] of Object.entries(checks)) {
|
|
42
|
+
if (key in obj && !valid(obj[key])) {
|
|
43
|
+
fail(`"${key}" of ${what} must be ${expected}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
package/types/headless.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { StoryAPI } from './index';
|
|
1
|
+
import type { Observation, StoryAPI } from './index';
|
|
2
2
|
|
|
3
3
|
/** Options for {@link bootStory}. */
|
|
4
4
|
export interface BootStoryOptions {
|
|
@@ -24,4 +24,45 @@ export interface BootStoryOptions {
|
|
|
24
24
|
*/
|
|
25
25
|
export function bootStory(options: BootStoryOptions): Promise<StoryAPI>;
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
/** One recorded step: what the reader saw, and what they chose. */
|
|
28
|
+
export interface TranscriptEntry {
|
|
29
|
+
turn: number;
|
|
30
|
+
passage: string;
|
|
31
|
+
/** Left out when the transcript was created with `include.text: false`. */
|
|
32
|
+
text?: string;
|
|
33
|
+
/** Only with `include.context: true`. */
|
|
34
|
+
context?: string | null;
|
|
35
|
+
chose: { id: string; label: string; value?: unknown };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Options for {@link createTranscript}. */
|
|
39
|
+
export interface TranscriptOptions {
|
|
40
|
+
/**
|
|
41
|
+
* How many of the latest entries to keep: a non-negative integer, or
|
|
42
|
+
* `Infinity` for all. Default 10. Anything else throws.
|
|
43
|
+
*/
|
|
44
|
+
limit?: number;
|
|
45
|
+
/** Default `{ text: true, context: false }`. */
|
|
46
|
+
include?: { text?: boolean; context?: boolean };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A recorder returned by {@link createTranscript}. */
|
|
50
|
+
export interface Transcript {
|
|
51
|
+
/**
|
|
52
|
+
* `Story.step()`, recording the observation it acted on and the choice.
|
|
53
|
+
* Await each step before the next: steps are not queued.
|
|
54
|
+
*/
|
|
55
|
+
step(id: string, value?: unknown): Promise<Observation>;
|
|
56
|
+
readonly entries: readonly TranscriptEntry[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Record a playthrough for stateless decision models, which need the last few
|
|
61
|
+
* steps sent with every call. A step that rejects records nothing.
|
|
62
|
+
*/
|
|
63
|
+
export function createTranscript(
|
|
64
|
+
story: StoryAPI,
|
|
65
|
+
options?: TranscriptOptions,
|
|
66
|
+
): Transcript;
|
|
67
|
+
|
|
68
|
+
export type { Observation, StoryAPI };
|
package/types/index.d.ts
CHANGED
|
@@ -200,7 +200,9 @@ export type ActionType =
|
|
|
200
200
|
| 'restart'
|
|
201
201
|
| 'save'
|
|
202
202
|
| 'load'
|
|
203
|
-
| 'dialog'
|
|
203
|
+
| 'dialog'
|
|
204
|
+
| 'open-dialog'
|
|
205
|
+
| 'close-dialog';
|
|
204
206
|
|
|
205
207
|
/**
|
|
206
208
|
* A registered interactive action (link, button, input, etc.).
|
|
@@ -218,6 +220,56 @@ export interface StoryAction {
|
|
|
218
220
|
perform: (value?: unknown) => void | Promise<void>;
|
|
219
221
|
}
|
|
220
222
|
|
|
223
|
+
/**
|
|
224
|
+
* Selects actions by their fields; unset fields match anything. Used by
|
|
225
|
+
* `Story.setObservedActions()` and the automation YAML's `assert.actions`.
|
|
226
|
+
* @see {@link ../../src/action-registry.ts} for the implementation.
|
|
227
|
+
*/
|
|
228
|
+
export interface ActionMatcher {
|
|
229
|
+
id?: string;
|
|
230
|
+
type?: string;
|
|
231
|
+
target?: string;
|
|
232
|
+
variable?: string;
|
|
233
|
+
label?: string;
|
|
234
|
+
/** `true` matches only disabled actions, `false` only enabled ones. */
|
|
235
|
+
disabled?: boolean;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** An action as `Story.observe()` lists it: without `perform`. */
|
|
239
|
+
export type ObservedAction = Omit<StoryAction, 'perform'>;
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Which actions `Story.observe()` offers. `exclude` removes what it
|
|
243
|
+
* matches; `include` puts back what the default exclusions removed (`back`,
|
|
244
|
+
* `forward`, `restart`, `save`, `load`, `dialog`). `exclude` wins.
|
|
245
|
+
*/
|
|
246
|
+
export interface ObservedActionRules {
|
|
247
|
+
exclude?: ActionMatcher[];
|
|
248
|
+
include?: ActionMatcher[];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* What a reader of the story sees and can do, as plain data
|
|
253
|
+
* (`Story.observe()`).
|
|
254
|
+
* @see {@link ../../src/observe/observe.ts} for the implementation.
|
|
255
|
+
*/
|
|
256
|
+
export interface Observation {
|
|
257
|
+
/** The current passage's name. */
|
|
258
|
+
passage: string;
|
|
259
|
+
/** The reader-visible text of the passage area (not StoryInterface chrome). */
|
|
260
|
+
text: string;
|
|
261
|
+
/** The rendered `StoryContext` passage, or null if the story has none. */
|
|
262
|
+
context: string | null;
|
|
263
|
+
/** The open dialogs, innermost last. */
|
|
264
|
+
dialogs: { passage: string; text: string }[];
|
|
265
|
+
/** The offered actions (see `setObservedActions()`). */
|
|
266
|
+
actions: ObservedAction[];
|
|
267
|
+
/** The macro and runtime errors on screen. */
|
|
268
|
+
errors: string[];
|
|
269
|
+
/** The navigation count: a link moves it forward, an input does not. */
|
|
270
|
+
turn: number;
|
|
271
|
+
}
|
|
272
|
+
|
|
221
273
|
/**
|
|
222
274
|
* Storage usage information returned by `Story.storage.getInfo()`.
|
|
223
275
|
* @see {@link ../../src/saves/types.ts} for the implementation.
|
|
@@ -844,6 +896,27 @@ export interface StoryAPI {
|
|
|
844
896
|
*/
|
|
845
897
|
waitForActions(): Promise<StoryAction[]>;
|
|
846
898
|
|
|
899
|
+
/**
|
|
900
|
+
* What the story shows and offers now: the passage text, the
|
|
901
|
+
* `StoryContext` passage, open dialogs, the offered actions and the errors
|
|
902
|
+
* on screen. The first call mounts `StoryContext`. Throws before the first
|
|
903
|
+
* passage is on screen.
|
|
904
|
+
*/
|
|
905
|
+
observe(): Observation;
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Perform an action (any ID, offered or not), wait for its effects as
|
|
909
|
+
* `waitForActions()` does, and return the observation. Rejects as
|
|
910
|
+
* `performAction()` throws. Doesn't wait for `{timed}` content.
|
|
911
|
+
*/
|
|
912
|
+
step(id: string, value?: unknown): Promise<Observation>;
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* Replace the rules for which actions `observe()` offers. Throws, naming
|
|
916
|
+
* the rule, when a rule isn't a valid matcher.
|
|
917
|
+
*/
|
|
918
|
+
setObservedActions(rules: ObservedActionRules): void;
|
|
919
|
+
|
|
847
920
|
/** Register a trigger that fires when a condition expression becomes truthy. Returns an unsubscribe function. */
|
|
848
921
|
watch(
|
|
849
922
|
condition: string,
|