@rohal12/spindle 0.59.32 → 0.59.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -18
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +536 -49
- package/package.json +1 -1
- package/src/action-registry.ts +84 -2
- 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 +8 -3
- 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/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 +71 -0
package/src/hooks/use-action.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
58
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
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
|
-
|
|
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 {
|
|
@@ -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
|
+
}
|