@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.
- package/README.md +20 -18
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +635 -98
- package/dist/pkg/story-variables.js +830 -54
- package/dist/pkg/tooling.js +1 -0
- package/package.json +4 -2
- 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/format/format-passage.ts +626 -0
- package/src/format/placeholders.ts +316 -0
- package/src/format/prettier.ts +62 -0
- package/src/format/segment.ts +126 -0
- package/src/headless.ts +81 -1
- package/src/hooks/use-action.ts +31 -9
- package/src/index.tsx +16 -4
- package/src/js-lexer.ts +36 -6
- package/src/markup/code-end.ts +97 -41
- package/src/markup/parse.ts +6 -6
- 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/tooling.ts +23 -1
- package/src/triggers.ts +32 -8
- package/src/twine-editor/builtin-macros.ts +11 -0
- package/src/twine-editor/commands.ts +173 -0
- package/src/twine-editor/highlight.ts +471 -0
- package/src/twine-editor/icons.ts +35 -0
- package/src/twine-editor/index.ts +19 -0
- package/src/twine-editor/mode.ts +137 -0
- package/src/twine-editor/references.ts +34 -0
- package/src/twine-editor/snippets.ts +74 -0
- package/src/twine-editor/toolbar.ts +85 -0
- package/src/types-drift-check.ts +12 -0
- package/src/utils/field-checks.ts +46 -0
- package/types/headless.d.ts +43 -2
- package/types/index.d.ts +71 -0
- package/types/tooling.d.ts +68 -0
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
|
package/src/js-lexer.ts
CHANGED
|
@@ -793,6 +793,15 @@ export interface FindCodeEndOptions {
|
|
|
793
793
|
goal?: JsGoal;
|
|
794
794
|
/** End the code at a `{` in code, at any depth, for which this holds. */
|
|
795
795
|
stop?: (index: number) => boolean;
|
|
796
|
+
/**
|
|
797
|
+
* Called when a line appended to `src` (text after a line break) could
|
|
798
|
+
* change the result: there is no end because the code runs to the end of
|
|
799
|
+
* `src` (an open bracket, comment, string or template literal), or the
|
|
800
|
+
* end was found by reading a template literal that runs to the end as
|
|
801
|
+
* closed early (see above). Not called when the code before the end
|
|
802
|
+
* can't be JavaScript.
|
|
803
|
+
*/
|
|
804
|
+
onRunOut?: () => void;
|
|
796
805
|
}
|
|
797
806
|
|
|
798
807
|
/** The rest of a word, after a number (`2s`). */
|
|
@@ -828,9 +837,9 @@ const WORDS_BEFORE_STRING = new Set(['of', 'get', 'set', 'static', 'async']);
|
|
|
828
837
|
export function findCodeEnd(
|
|
829
838
|
src: string,
|
|
830
839
|
start: number,
|
|
831
|
-
{ goal = 'expression', stop }: FindCodeEndOptions = {},
|
|
840
|
+
{ goal = 'expression', stop, onRunOut }: FindCodeEndOptions = {},
|
|
832
841
|
): number {
|
|
833
|
-
const end = scanCodeEnd(src, start, goal, stop);
|
|
842
|
+
const end = scanCodeEnd(src, start, goal, stop, onRunOut);
|
|
834
843
|
return end < 0 && !stop ? parsedCodeEnd(src, start, goal) : end;
|
|
835
844
|
}
|
|
836
845
|
|
|
@@ -866,7 +875,13 @@ function scanCodeEnd(
|
|
|
866
875
|
start: number,
|
|
867
876
|
goal: JsGoal,
|
|
868
877
|
stop: ((index: number) => boolean) | undefined,
|
|
878
|
+
onRunOut: (() => void) | undefined,
|
|
869
879
|
): number {
|
|
880
|
+
/** No end: the code runs to the end of `src`. */
|
|
881
|
+
const ranOut = () => {
|
|
882
|
+
onRunOut?.();
|
|
883
|
+
return -1;
|
|
884
|
+
};
|
|
870
885
|
const stack: string[] = [];
|
|
871
886
|
let prevEnd = -1;
|
|
872
887
|
let prevWord = false;
|
|
@@ -885,15 +900,30 @@ function scanCodeEnd(
|
|
|
885
900
|
// on after its first character, as after an operator
|
|
886
901
|
resumeAt = Math.max(tok.pos, from) + 1;
|
|
887
902
|
afterOperand = false;
|
|
888
|
-
if (resumeAt >= src.length) return
|
|
903
|
+
if (resumeAt >= src.length) return ranOut();
|
|
889
904
|
break;
|
|
890
905
|
}
|
|
891
906
|
const k = stack.lastIndexOf('${');
|
|
892
907
|
const unclosed = /^Unterminated template/.test(message);
|
|
893
908
|
// One such slip per block: more is no code an author meant. (A raw
|
|
894
909
|
// body that is no code ends at its first closer.)
|
|
895
|
-
if (!unclosed || k < 0 || templateSlip || stop)
|
|
896
|
-
|
|
910
|
+
if (!unclosed || k < 0 || templateSlip || stop) {
|
|
911
|
+
// An unterminated literal runs to the end, and a line after it
|
|
912
|
+
// could close it; not so a regex literal, which ends at the line
|
|
913
|
+
// break, or a quote after a word (`don't`), which is no string
|
|
914
|
+
const toEnd =
|
|
915
|
+
/^Unterminated/.test(message) &&
|
|
916
|
+
!/^Unterminated regular/.test(message) &&
|
|
917
|
+
!(
|
|
918
|
+
/^Unterminated string/.test(message) &&
|
|
919
|
+
prevWord &&
|
|
920
|
+
tok.pos === prevEnd
|
|
921
|
+
);
|
|
922
|
+
return toEnd ? ranOut() : -1;
|
|
923
|
+
}
|
|
924
|
+
// The template's text starts just past the backtick that opened it.
|
|
925
|
+
// It ran to the end: a backtick appended would close it instead.
|
|
926
|
+
onRunOut?.();
|
|
897
927
|
templateSlip = true;
|
|
898
928
|
stack.length = k;
|
|
899
929
|
resumeAt = tok.pos;
|
|
@@ -902,7 +932,7 @@ function scanCodeEnd(
|
|
|
902
932
|
}
|
|
903
933
|
if (tok.restarted && stack.includes('${')) return -1;
|
|
904
934
|
const t = tok.type;
|
|
905
|
-
if (t === tt.eof) return
|
|
935
|
+
if (t === tt.eof) return ranOut();
|
|
906
936
|
if (t === tt.string && prevWord && tok.start === prevEnd) return -1;
|
|
907
937
|
prevWord =
|
|
908
938
|
(t === tt.name && !WORDS_BEFORE_STRING.has(tok.value as string)) ||
|
package/src/markup/code-end.ts
CHANGED
|
@@ -25,61 +25,85 @@ export interface CodeEnd {
|
|
|
25
25
|
*/
|
|
26
26
|
const NON_STRING_QUOTE_PREFIX = /[\p{L}\p{N}_\\]/u;
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* An index the lenient reading found, or -1, and whether the reading ran
|
|
30
|
+
* to the end of the input on the way: a template literal without its
|
|
31
|
+
* closing backtick there, which a line appended to the input could close.
|
|
32
|
+
*/
|
|
33
|
+
interface Lenient {
|
|
34
|
+
end: number;
|
|
35
|
+
ranOut: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
28
38
|
/**
|
|
29
39
|
* Skip the literal opening at `i`: a '…' or "…" string, which must close on
|
|
30
40
|
* its line, or a `…` template, whose `${…}` parts are read as braces.
|
|
31
41
|
* Returns the index just past its closing quote or backtick, or -1.
|
|
32
42
|
*/
|
|
33
|
-
function skipLiteral(input: string, i: number):
|
|
43
|
+
function skipLiteral(input: string, i: number): Lenient {
|
|
34
44
|
const quote = input[i];
|
|
35
45
|
const template = quote === '`';
|
|
46
|
+
let ranOut = false;
|
|
36
47
|
for (let j = i + 1; j < input.length;) {
|
|
37
48
|
const c = input[j];
|
|
38
49
|
if (c === '\\') j += 2;
|
|
39
|
-
else if (c === quote) return j + 1;
|
|
40
|
-
else if (!template && c === '\n') return -1;
|
|
50
|
+
else if (c === quote) return { end: j + 1, ranOut };
|
|
51
|
+
else if (!template && c === '\n') return { end: -1, ranOut };
|
|
41
52
|
else if (template && c === '$' && input[j + 1] === '{') {
|
|
42
|
-
const close =
|
|
43
|
-
|
|
44
|
-
|
|
53
|
+
const close = lenientRead(input, j + 2);
|
|
54
|
+
ranOut ||= close.ranOut;
|
|
55
|
+
if (close.end === -1) return { end: -1, ranOut };
|
|
56
|
+
j = close.end + 1;
|
|
45
57
|
} else j++;
|
|
46
58
|
}
|
|
47
|
-
return -1;
|
|
59
|
+
return { end: -1, ranOut: ranOut || template };
|
|
48
60
|
}
|
|
49
61
|
|
|
50
62
|
/**
|
|
51
63
|
* The closing `}` of braces read leniently from `i` (just past a `{`): braces
|
|
52
64
|
* count except inside string and template literals, and a quote that can't
|
|
53
65
|
* start a string (an apostrophe, or one not closed on its line) is text, as
|
|
54
|
-
* is a backtick without a closing one.
|
|
66
|
+
* is a backtick without a closing one. `onRunOut` is called when a line
|
|
67
|
+
* appended to `input` could change the result (see `Lenient`).
|
|
55
68
|
*/
|
|
56
|
-
export function lenientClose(
|
|
69
|
+
export function lenientClose(
|
|
70
|
+
input: string,
|
|
71
|
+
i: number,
|
|
72
|
+
onRunOut?: () => void,
|
|
73
|
+
): number {
|
|
74
|
+
const { end, ranOut } = lenientRead(input, i);
|
|
75
|
+
if (ranOut) onRunOut?.();
|
|
76
|
+
return end;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function lenientRead(input: string, i: number): Lenient {
|
|
57
80
|
// Results per start, for the last input: unclosed nested template
|
|
58
81
|
// literals (`` {$a`${$a`${… ``) would otherwise take exponential time.
|
|
59
82
|
if (memoInput !== input) {
|
|
60
83
|
memoInput = input;
|
|
61
84
|
memo.clear();
|
|
62
85
|
}
|
|
63
|
-
let
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
memo.set(i,
|
|
86
|
+
let read = memo.get(i);
|
|
87
|
+
if (read === undefined) {
|
|
88
|
+
read = scanLenient(input, i);
|
|
89
|
+
memo.set(i, read);
|
|
67
90
|
}
|
|
68
|
-
return
|
|
91
|
+
return read;
|
|
69
92
|
}
|
|
70
93
|
|
|
71
94
|
let memoInput = '';
|
|
72
|
-
const memo = new Map<number,
|
|
95
|
+
const memo = new Map<number, Lenient>();
|
|
73
96
|
|
|
74
|
-
function scanLenient(input: string, i: number):
|
|
97
|
+
function scanLenient(input: string, i: number): Lenient {
|
|
75
98
|
let depth = 0;
|
|
99
|
+
let ranOut = false;
|
|
76
100
|
while (i < input.length) {
|
|
77
101
|
const c = input[i]!;
|
|
78
102
|
if (c === '{') {
|
|
79
103
|
depth++;
|
|
80
104
|
i++;
|
|
81
105
|
} else if (c === '}') {
|
|
82
|
-
if (depth === 0) return i;
|
|
106
|
+
if (depth === 0) return { end: i, ranOut };
|
|
83
107
|
depth--;
|
|
84
108
|
i++;
|
|
85
109
|
} else if (
|
|
@@ -88,34 +112,66 @@ function scanLenient(input: string, i: number): number {
|
|
|
88
112
|
!(i > 0 && NON_STRING_QUOTE_PREFIX.test(input[i - 1]!)))
|
|
89
113
|
) {
|
|
90
114
|
const close = skipLiteral(input, i);
|
|
91
|
-
|
|
115
|
+
ranOut ||= close.ranOut;
|
|
116
|
+
i = close.end === -1 ? i + 1 : close.end;
|
|
92
117
|
} else {
|
|
93
118
|
i++;
|
|
94
119
|
}
|
|
95
120
|
}
|
|
96
|
-
return -1;
|
|
121
|
+
return { end: -1, ranOut: true };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Told where code starts whose end a line appended to `input` could move:
|
|
126
|
+
* the JavaScript reader or the lenient one ran to the end of `input`.
|
|
127
|
+
*/
|
|
128
|
+
export type OnOpenCodeEnd = (input: string, codeStart: number) => void;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The JavaScript reader Spindle uses: js-lexer, then a lenient scan. With
|
|
132
|
+
* `onOpenEnd`, it also reports code whose end depends on what follows the
|
|
133
|
+
* input (see `OnOpenCodeEnd`); the ends it finds are the same.
|
|
134
|
+
*/
|
|
135
|
+
export function jsCodeEnd(onOpenEnd?: OnOpenCodeEnd): CodeEnd {
|
|
136
|
+
return {
|
|
137
|
+
closeBrace(input, codeStart, lenientStart) {
|
|
138
|
+
let ranOut = false;
|
|
139
|
+
const onRunOut = () => (ranOut = true);
|
|
140
|
+
const strict = findCodeEnd(input, codeStart, { onRunOut });
|
|
141
|
+
const end =
|
|
142
|
+
strict !== -1 ? strict : lenientClose(input, lenientStart, onRunOut);
|
|
143
|
+
if (ranOut) onOpenEnd?.(input, codeStart);
|
|
144
|
+
return end;
|
|
145
|
+
},
|
|
146
|
+
rawBodyEnd(input, bodyStart, name) {
|
|
147
|
+
const closer = `\\{/${name}\\s*\\}`;
|
|
148
|
+
const first = new RegExp(closer, 'gi');
|
|
149
|
+
first.lastIndex = bodyStart;
|
|
150
|
+
const firstAt = first.exec(input)?.index ?? -1;
|
|
151
|
+
if (firstAt === -1) return -1;
|
|
152
|
+
const at = new RegExp(closer, 'iy');
|
|
153
|
+
let ranOut = false;
|
|
154
|
+
const end = findCodeEnd(input, bodyStart, {
|
|
155
|
+
goal: 'statements',
|
|
156
|
+
stop: (k) => {
|
|
157
|
+
at.lastIndex = k;
|
|
158
|
+
return at.test(input);
|
|
159
|
+
},
|
|
160
|
+
onRunOut: () => (ranOut = true),
|
|
161
|
+
});
|
|
162
|
+
if (end !== -1) return end;
|
|
163
|
+
// A closer cut off at the end (`{/do`) may end the code once a line
|
|
164
|
+
// with its `}` follows
|
|
165
|
+
if (
|
|
166
|
+
onOpenEnd &&
|
|
167
|
+
(ranOut || new RegExp(`\\{/${name}\\s*$`, 'i').test(input))
|
|
168
|
+
) {
|
|
169
|
+
onOpenEnd(input, bodyStart);
|
|
170
|
+
}
|
|
171
|
+
return firstAt;
|
|
172
|
+
},
|
|
173
|
+
};
|
|
97
174
|
}
|
|
98
175
|
|
|
99
176
|
/** The JavaScript reader Spindle uses today: js-lexer, then a lenient scan. */
|
|
100
|
-
export const defaultCodeEnd: CodeEnd =
|
|
101
|
-
closeBrace(input, codeStart, lenientStart) {
|
|
102
|
-
const end = findCodeEnd(input, codeStart);
|
|
103
|
-
return end !== -1 ? end : lenientClose(input, lenientStart);
|
|
104
|
-
},
|
|
105
|
-
rawBodyEnd(input, bodyStart, name) {
|
|
106
|
-
const closer = `\\{/${name}\\s*\\}`;
|
|
107
|
-
const first = new RegExp(closer, 'gi');
|
|
108
|
-
first.lastIndex = bodyStart;
|
|
109
|
-
const firstAt = first.exec(input)?.index ?? -1;
|
|
110
|
-
if (firstAt === -1) return -1;
|
|
111
|
-
const at = new RegExp(closer, 'iy');
|
|
112
|
-
const end = findCodeEnd(input, bodyStart, {
|
|
113
|
-
goal: 'statements',
|
|
114
|
-
stop: (k) => {
|
|
115
|
-
at.lastIndex = k;
|
|
116
|
-
return at.test(input);
|
|
117
|
-
},
|
|
118
|
-
});
|
|
119
|
-
return end === -1 ? firstAt : end;
|
|
120
|
-
},
|
|
121
|
-
};
|
|
177
|
+
export const defaultCodeEnd: CodeEnd = jsCodeEnd();
|
package/src/markup/parse.ts
CHANGED
|
@@ -139,7 +139,7 @@ export function analyzeMarkup(
|
|
|
139
139
|
source: string,
|
|
140
140
|
options: ParseMarkupOptions = {},
|
|
141
141
|
): MarkupAnalysis {
|
|
142
|
-
const { tokens, errors, damage } =
|
|
142
|
+
const { tokens, errors, damage } = scanMarkupTolerant(source, options);
|
|
143
143
|
const hooks = { ...defaultHooks, ...options.hooks };
|
|
144
144
|
const paired = pairMarkup(tokens, {
|
|
145
145
|
isBlock: hooks.isBlock,
|
|
@@ -242,18 +242,18 @@ export function tokenizeMarkupTolerant(
|
|
|
242
242
|
source: string,
|
|
243
243
|
options: ParseMarkupOptions = {},
|
|
244
244
|
): TolerantTokens {
|
|
245
|
-
const { tokens, errors } =
|
|
245
|
+
const { tokens, errors } = scanMarkupTolerant(source, options);
|
|
246
246
|
return { tokens, errors };
|
|
247
247
|
}
|
|
248
248
|
|
|
249
249
|
/**
|
|
250
250
|
* The tokens of tolerant tokenizing, the errors, and where the damage of
|
|
251
|
-
* each error starts: the tag that is
|
|
252
|
-
* (an attribute value) is after.
|
|
251
|
+
* each error starts (`damage[i]` for `errors[i]`): the tag that is
|
|
252
|
+
* malformed, which an error inside it (an attribute value) is after.
|
|
253
253
|
*/
|
|
254
|
-
function
|
|
254
|
+
export function scanMarkupTolerant(
|
|
255
255
|
source: string,
|
|
256
|
-
options: ParseMarkupOptions,
|
|
256
|
+
options: ParseMarkupOptions = {},
|
|
257
257
|
): TolerantTokens & { damage: number[] } {
|
|
258
258
|
const tokens: Token[] = [];
|
|
259
259
|
const errors: MarkupError[] = [];
|
|
@@ -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
|
+
}
|