@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
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { lexJs, lexTemplate } from '../js-lexer';
|
|
2
|
+
import { tokenizeMarkupTolerant } from '../markup/parse';
|
|
3
|
+
import type { Token } from '../markup/tokens';
|
|
4
|
+
|
|
5
|
+
export interface TokenMatch {
|
|
6
|
+
start: number;
|
|
7
|
+
end: number;
|
|
8
|
+
token: string;
|
|
9
|
+
/** Set for a token in the value of an HTML attribute (else absent). */
|
|
10
|
+
inAttribute?: true;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A `{do}…{/do}` block: its body is JavaScript, run as written. */
|
|
14
|
+
export interface DoBlock {
|
|
15
|
+
/** Start of `{do}` and end of `{/do}`. */
|
|
16
|
+
start: number;
|
|
17
|
+
end: number;
|
|
18
|
+
/** The JavaScript between the two tags. */
|
|
19
|
+
bodyStart: number;
|
|
20
|
+
bodyEnd: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** What the formatter must leave to the runtime in a piece of markup. */
|
|
24
|
+
export interface MarkupScan {
|
|
25
|
+
/** Macros, variables, expressions and links (also those in attribute values), in source order. */
|
|
26
|
+
tokens: TokenMatch[];
|
|
27
|
+
/** The HTML tags (opening, closing and self-closing). */
|
|
28
|
+
tags: { start: number; end: number }[];
|
|
29
|
+
/** The `{do}…{/do}` blocks. */
|
|
30
|
+
doBlocks: DoBlock[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Read `text` with Spindle's own tokenizer (`tokenizeMarkupTolerant`), so the
|
|
35
|
+
* formatter protects exactly what the runtime executes. A token inside an
|
|
36
|
+
* HTML attribute value is reported too, with the attribute-safe placeholder
|
|
37
|
+
* it needs, because it must not be reformatted either.
|
|
38
|
+
*/
|
|
39
|
+
export function scanSpindleMarkup(text: string): MarkupScan {
|
|
40
|
+
const tokens: TokenMatch[] = [];
|
|
41
|
+
const tags: { start: number; end: number }[] = [];
|
|
42
|
+
const doBlocks: DoBlock[] = [];
|
|
43
|
+
let open: Token | undefined;
|
|
44
|
+
|
|
45
|
+
const push = (t: { start: number; end: number }, inAttribute?: true) => {
|
|
46
|
+
const match: TokenMatch = {
|
|
47
|
+
start: t.start,
|
|
48
|
+
end: t.end,
|
|
49
|
+
token: text.slice(t.start, t.end),
|
|
50
|
+
};
|
|
51
|
+
if (inAttribute) match.inAttribute = true;
|
|
52
|
+
tokens.push(match);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
for (const t of tokenizeMarkupTolerant(text).tokens) {
|
|
56
|
+
if (t.type === 'html') {
|
|
57
|
+
tags.push({ start: t.start, end: t.end });
|
|
58
|
+
for (const attribute of t.attributeSpans) {
|
|
59
|
+
if (
|
|
60
|
+
attribute.valueStart === undefined ||
|
|
61
|
+
attribute.valueEnd === undefined
|
|
62
|
+
)
|
|
63
|
+
continue;
|
|
64
|
+
const value = text.slice(attribute.valueStart, attribute.valueEnd);
|
|
65
|
+
if (!value.includes('{')) continue;
|
|
66
|
+
for (const inner of tokenizeMarkupTolerant(value, { text: true })
|
|
67
|
+
.tokens) {
|
|
68
|
+
if (
|
|
69
|
+
inner.type === 'macro' ||
|
|
70
|
+
inner.type === 'variable' ||
|
|
71
|
+
inner.type === 'expression'
|
|
72
|
+
) {
|
|
73
|
+
push(
|
|
74
|
+
{
|
|
75
|
+
start: attribute.valueStart + inner.start,
|
|
76
|
+
end: attribute.valueStart + inner.end,
|
|
77
|
+
},
|
|
78
|
+
true,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
} else if (t.type !== 'text') {
|
|
84
|
+
// The body of {do} is one text token, so nothing in it is a token
|
|
85
|
+
if (t.type === 'macro' && t.name === 'do') {
|
|
86
|
+
if (!t.isClose) open = t;
|
|
87
|
+
else if (open) {
|
|
88
|
+
doBlocks.push({
|
|
89
|
+
start: open.start,
|
|
90
|
+
end: t.end,
|
|
91
|
+
bodyStart: open.end,
|
|
92
|
+
bodyEnd: t.start,
|
|
93
|
+
});
|
|
94
|
+
open = undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
push(t);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { tokens, tags, doBlocks };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The ranges of the string and template literals of the JavaScript `code`
|
|
105
|
+
* that span lines (outermost only): their line breaks are part of the value.
|
|
106
|
+
*/
|
|
107
|
+
export function multilineJsLiterals(code: string): [number, number][] {
|
|
108
|
+
const spans: [number, number][] = [];
|
|
109
|
+
let skipUntil = 0;
|
|
110
|
+
lexJs(
|
|
111
|
+
code,
|
|
112
|
+
{
|
|
113
|
+
literal(text, index, nesting) {
|
|
114
|
+
if (nesting > 0 || index < skipUntil) return;
|
|
115
|
+
const quote = text[0];
|
|
116
|
+
if (quote === '`') {
|
|
117
|
+
// The backtick that opens a template literal: its parts follow
|
|
118
|
+
skipUntil = lexTemplate(code, index);
|
|
119
|
+
if (code.slice(index, skipUntil).includes('\n'))
|
|
120
|
+
spans.push([index, skipUntil]);
|
|
121
|
+
} else if ((quote === '"' || quote === "'") && text.includes('\n')) {
|
|
122
|
+
spans.push([index, index + text.length]);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
'statements',
|
|
127
|
+
);
|
|
128
|
+
return spans;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Whether an HTML tag (opening, closing or self-closing) overlaps the range. */
|
|
132
|
+
function lineHasTag(
|
|
133
|
+
tags: { start: number; end: number }[],
|
|
134
|
+
start: number,
|
|
135
|
+
end: number,
|
|
136
|
+
): boolean {
|
|
137
|
+
return tags.some((tag) => tag.start < end && tag.end > start);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface PlaceholderResult {
|
|
141
|
+
text: string;
|
|
142
|
+
tokens: string[];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Replace `<svg>…</svg>` blocks with HTML comment placeholders so Prettier
|
|
147
|
+
* does not reformat them (CommonMark does not recognise multi-line SVG tags
|
|
148
|
+
* as HTML blocks, so reformatted attributes break rendering).
|
|
149
|
+
*/
|
|
150
|
+
export function replaceSvgBlocks(html: string): PlaceholderResult {
|
|
151
|
+
const tokens: string[] = [];
|
|
152
|
+
const result = html.replace(/<svg[\s>][\s\S]*?<\/svg>/gi, (match) => {
|
|
153
|
+
const idx = tokens.length;
|
|
154
|
+
tokens.push(match);
|
|
155
|
+
return `<!--SVG:${idx}-->`;
|
|
156
|
+
});
|
|
157
|
+
return { text: result, tokens };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The placeholders of the token at an index. */
|
|
161
|
+
type PlaceholdersOf = (index: number) => string[];
|
|
162
|
+
|
|
163
|
+
export const SVG_PLACEHOLDERS: PlaceholdersOf = (i) => [`<!--SVG:${i}-->`];
|
|
164
|
+
export const SPINDLE_PLACEHOLDERS: PlaceholdersOf = (i) => [
|
|
165
|
+
`<!--SP:${i}-->`,
|
|
166
|
+
`__SP${i}__`,
|
|
167
|
+
];
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Whether `text` (what a formatter made of the placeholdered text) holds
|
|
171
|
+
* the placeholder of every one of `tokens` exactly once. If not, the
|
|
172
|
+
* formatter lost, changed or copied one, and restoring the tokens would
|
|
173
|
+
* lose or duplicate story text.
|
|
174
|
+
*/
|
|
175
|
+
export function placeholdersIntact(
|
|
176
|
+
text: string,
|
|
177
|
+
tokens: readonly string[],
|
|
178
|
+
placeholdersOf: PlaceholdersOf,
|
|
179
|
+
): boolean {
|
|
180
|
+
return tokens.every(
|
|
181
|
+
(_, index) =>
|
|
182
|
+
placeholdersOf(index).reduce(
|
|
183
|
+
(count, placeholder) => count + text.split(placeholder).length - 1,
|
|
184
|
+
0,
|
|
185
|
+
) === 1,
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Whether `before` and `after` hold the same Spindle tokens, in the same order. */
|
|
190
|
+
export function sameSpindleTokens(before: string, after: string): boolean {
|
|
191
|
+
const tokensOf = (text: string) =>
|
|
192
|
+
scanSpindleMarkup(text).tokens.map((m) => m.token);
|
|
193
|
+
const expected = tokensOf(before);
|
|
194
|
+
const found = tokensOf(after);
|
|
195
|
+
return (
|
|
196
|
+
expected.length === found.length && expected.every((t, i) => t === found[i])
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Put each of `tokens` back in place of its placeholders (those that
|
|
202
|
+
* `placeholdersOf` gives for its index): the first of each.
|
|
203
|
+
*/
|
|
204
|
+
function restorePlaceholders(
|
|
205
|
+
text: string,
|
|
206
|
+
tokens: string[],
|
|
207
|
+
placeholdersOf: PlaceholdersOf,
|
|
208
|
+
): string {
|
|
209
|
+
let result = text;
|
|
210
|
+
tokens.forEach((token, index) => {
|
|
211
|
+
for (const placeholder of placeholdersOf(index)) {
|
|
212
|
+
// Callback form: a replacement string would expand `$&`, `$'`, etc.
|
|
213
|
+
result = result.replace(placeholder, () => token);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Restore SVG blocks from placeholders.
|
|
221
|
+
*/
|
|
222
|
+
export function restoreSvgBlocks(text: string, tokens: string[]): string {
|
|
223
|
+
return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Replace Spindle tokens with placeholders.
|
|
228
|
+
* Uses <!--SP:N--> in HTML content and __SPN__ in attribute values.
|
|
229
|
+
*
|
|
230
|
+
* Lines that contain Spindle tokens but no HTML tags are replaced as a
|
|
231
|
+
* single whole-line placeholder so Prettier cannot split them. A token that
|
|
232
|
+
* spans lines (a template literal with a line break) keeps its line break:
|
|
233
|
+
* the lines it spans are one line here. A `{do}…{/do}` block is one token:
|
|
234
|
+
* its body is JavaScript executed as written, which an HTML formatter must
|
|
235
|
+
* not re-indent or re-flow.
|
|
236
|
+
*/
|
|
237
|
+
export function replaceSpindleTokens(html: string): PlaceholderResult {
|
|
238
|
+
const { tokens: found, tags, doBlocks } = scanSpindleMarkup(html);
|
|
239
|
+
// The units to protect, in source order: a do block whole, else each token
|
|
240
|
+
const units: TokenMatch[] = [];
|
|
241
|
+
const pushDoBlock = (block: DoBlock) =>
|
|
242
|
+
units.push({
|
|
243
|
+
start: block.start,
|
|
244
|
+
end: block.end,
|
|
245
|
+
token: html.slice(block.start, block.end),
|
|
246
|
+
});
|
|
247
|
+
let doIndex = 0;
|
|
248
|
+
for (const m of found) {
|
|
249
|
+
for (let block = doBlocks[doIndex]; block && block.end <= m.start;) {
|
|
250
|
+
pushDoBlock(block);
|
|
251
|
+
block = doBlocks[++doIndex];
|
|
252
|
+
}
|
|
253
|
+
const open = doBlocks[doIndex];
|
|
254
|
+
if (open && m.start >= open.start) continue;
|
|
255
|
+
units.push(m);
|
|
256
|
+
}
|
|
257
|
+
for (; doIndex < doBlocks.length; doIndex++) pushDoBlock(doBlocks[doIndex]!);
|
|
258
|
+
units.sort((a, b) => a.start - b.start);
|
|
259
|
+
|
|
260
|
+
const tokens: string[] = [];
|
|
261
|
+
const resultLines: string[] = [];
|
|
262
|
+
let unit = 0;
|
|
263
|
+
let lineStart = 0;
|
|
264
|
+
while (lineStart <= html.length) {
|
|
265
|
+
// A line ends at a line break outside every unit
|
|
266
|
+
let lineEnd = lineStart;
|
|
267
|
+
const lineUnits: TokenMatch[] = [];
|
|
268
|
+
for (;;) {
|
|
269
|
+
while (unit < units.length && units[unit]!.end <= lineEnd) unit++;
|
|
270
|
+
const next = units[unit];
|
|
271
|
+
const inside = next && next.start <= lineEnd ? next : undefined;
|
|
272
|
+
if (inside) {
|
|
273
|
+
lineUnits.push(inside);
|
|
274
|
+
lineEnd = inside.end;
|
|
275
|
+
unit++;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (lineEnd >= html.length || html[lineEnd] === '\n') break;
|
|
279
|
+
lineEnd++;
|
|
280
|
+
}
|
|
281
|
+
const line = html.slice(lineStart, lineEnd);
|
|
282
|
+
const indent = line.match(/^(\s*)/)?.[1] ?? '';
|
|
283
|
+
|
|
284
|
+
if (lineUnits.length === 0) {
|
|
285
|
+
resultLines.push(line);
|
|
286
|
+
} else if (!lineHasTag(tags, lineStart, lineEnd)) {
|
|
287
|
+
// Spindle tokens but no HTML: one placeholder for the whole line
|
|
288
|
+
const idx = tokens.length;
|
|
289
|
+
tokens.push(line.trim());
|
|
290
|
+
resultLines.push(`${indent}<!--SP:${idx}-->`);
|
|
291
|
+
} else {
|
|
292
|
+
// Both HTML and Spindle: one placeholder per token, in source order
|
|
293
|
+
let replaced = '';
|
|
294
|
+
let last = lineStart;
|
|
295
|
+
for (const u of lineUnits) {
|
|
296
|
+
const idx = tokens.length;
|
|
297
|
+
tokens.push(u.token);
|
|
298
|
+
replaced +=
|
|
299
|
+
html.slice(last, u.start) +
|
|
300
|
+
(u.inAttribute ? `__SP${idx}__` : `<!--SP:${idx}-->`);
|
|
301
|
+
last = u.end;
|
|
302
|
+
}
|
|
303
|
+
resultLines.push(replaced + html.slice(last, lineEnd));
|
|
304
|
+
}
|
|
305
|
+
lineStart = lineEnd + 1;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return { text: resultLines.join('\n'), tokens };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Restore original Spindle tokens from placeholders.
|
|
313
|
+
*/
|
|
314
|
+
export function restoreSpindleTokens(text: string, tokens: string[]): string {
|
|
315
|
+
return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
|
|
316
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Prettier calls of the formatter. Prettier is not imported here: the
|
|
3
|
+
* caller injects it, so this module (and the tooling bundle that has it) holds
|
|
4
|
+
* no copy of Prettier. Without it, or when it throws on a piece of code, there
|
|
5
|
+
* is no formatted text (`undefined`): the caller keeps the code as written.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** The part of Prettier's API the formatter calls (`prettier` and `prettier/standalone` have it). */
|
|
9
|
+
export interface PrettierLike {
|
|
10
|
+
format(code: string, options: object): Promise<string>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The options the formatter gives Prettier unless the caller passes its own. */
|
|
14
|
+
export const DEFAULT_PRETTIER_OPTIONS = { tabWidth: 2 };
|
|
15
|
+
|
|
16
|
+
async function run(
|
|
17
|
+
code: string,
|
|
18
|
+
prettier: PrettierLike | undefined,
|
|
19
|
+
options: object | undefined,
|
|
20
|
+
overrides: object,
|
|
21
|
+
): Promise<string | undefined> {
|
|
22
|
+
if (!prettier) return undefined;
|
|
23
|
+
try {
|
|
24
|
+
return await prettier.format(code, {
|
|
25
|
+
...(options ?? DEFAULT_PRETTIER_OPTIONS),
|
|
26
|
+
...overrides,
|
|
27
|
+
});
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function formatJS(
|
|
34
|
+
code: string,
|
|
35
|
+
prettier?: PrettierLike,
|
|
36
|
+
options?: object,
|
|
37
|
+
): Promise<string | undefined> {
|
|
38
|
+
return run(code, prettier, options, { parser: 'babel' });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function formatCSS(
|
|
42
|
+
code: string,
|
|
43
|
+
prettier?: PrettierLike,
|
|
44
|
+
options?: object,
|
|
45
|
+
): Promise<string | undefined> {
|
|
46
|
+
return run(code, prettier, options, { parser: 'css' });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function formatHTML(
|
|
50
|
+
code: string,
|
|
51
|
+
prettier?: PrettierLike,
|
|
52
|
+
options?: object,
|
|
53
|
+
): Promise<string | undefined> {
|
|
54
|
+
// 'css': Prettier adds and removes whitespace only where the default CSS
|
|
55
|
+
// display of the elements says it does not render, so Format never
|
|
56
|
+
// changes the text a passage shows ('ignore' turned `<b>a</b>,` into
|
|
57
|
+
// `<b>a</b> ,`)
|
|
58
|
+
return run(code, prettier, options, {
|
|
59
|
+
parser: 'html',
|
|
60
|
+
htmlWhitespaceSensitivity: 'css',
|
|
61
|
+
});
|
|
62
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/** A run of a passage body that is formatted as one kind of content. */
|
|
2
|
+
export interface Region {
|
|
3
|
+
type: 'spindle' | 'html' | 'script' | 'svg';
|
|
4
|
+
lines: string[];
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const VOID_ELEMENTS = new Set([
|
|
8
|
+
'area',
|
|
9
|
+
'base',
|
|
10
|
+
'br',
|
|
11
|
+
'col',
|
|
12
|
+
'embed',
|
|
13
|
+
'hr',
|
|
14
|
+
'img',
|
|
15
|
+
'input',
|
|
16
|
+
'link',
|
|
17
|
+
'meta',
|
|
18
|
+
'param',
|
|
19
|
+
'source',
|
|
20
|
+
'track',
|
|
21
|
+
'wbr',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Segment a passage body into regions: spindle (markdown/macros), html blocks, script blocks.
|
|
26
|
+
*/
|
|
27
|
+
export function segmentRegions(body: string): Region[] {
|
|
28
|
+
const lines = body.split('\n');
|
|
29
|
+
// Remove trailing empty line from split
|
|
30
|
+
if (lines.length > 0 && lines[lines.length - 1] === '') {
|
|
31
|
+
lines.pop();
|
|
32
|
+
}
|
|
33
|
+
if (lines.length === 0) return [];
|
|
34
|
+
|
|
35
|
+
const regions: Region[] = [];
|
|
36
|
+
let i = 0;
|
|
37
|
+
|
|
38
|
+
while (i < lines.length) {
|
|
39
|
+
const line = lines[i]!;
|
|
40
|
+
const trimmed = line.trim();
|
|
41
|
+
|
|
42
|
+
// Detect <script> blocks. A same-line element `<script>…</script>` is
|
|
43
|
+
// a region of this line only.
|
|
44
|
+
if (/^<script(\s|>)/i.test(trimmed)) {
|
|
45
|
+
const block = blockLines(lines, i, /<\/script\s*>/i);
|
|
46
|
+
regions.push({ type: 'script', lines: block });
|
|
47
|
+
i += block.length;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Detect <svg> blocks — treat as opaque to prevent Prettier from
|
|
52
|
+
// breaking multi-line attributes (CommonMark does not list svg as a
|
|
53
|
+
// type-6 HTML block tag, so reformatted multi-line tags break rendering).
|
|
54
|
+
if (/^<svg(\s|>)/i.test(trimmed)) {
|
|
55
|
+
const block = blockLines(lines, i, /<\/svg\s*>/i);
|
|
56
|
+
regions.push({ type: 'svg', lines: block });
|
|
57
|
+
i += block.length;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Detect multi-line HTML blocks
|
|
62
|
+
if (/^<([a-zA-Z][\w-]*)/.test(trimmed)) {
|
|
63
|
+
const tagMatch = trimmed.match(/^<([a-zA-Z][\w-]*)/);
|
|
64
|
+
const tagName = tagMatch![1]!.toLowerCase();
|
|
65
|
+
|
|
66
|
+
// Skip void elements on their own line — not a multi-line block
|
|
67
|
+
if (VOID_ELEMENTS.has(tagName) && !lines[i + 1]?.trim().startsWith('<')) {
|
|
68
|
+
pushSpindleLine(regions, line);
|
|
69
|
+
i++;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Check if this is truly multi-line: does the tag close on the same line?
|
|
74
|
+
const selfClosing = new RegExp(`</${tagName}\\s*>`, 'i');
|
|
75
|
+
if (selfClosing.test(trimmed)) {
|
|
76
|
+
pushSpindleLine(regions, line);
|
|
77
|
+
i++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Multi-line HTML block
|
|
82
|
+
const htmlLines: string[] = [line];
|
|
83
|
+
let depth = 1;
|
|
84
|
+
i++;
|
|
85
|
+
while (i < lines.length && depth > 0) {
|
|
86
|
+
htmlLines.push(lines[i]!);
|
|
87
|
+
const opens = (
|
|
88
|
+
lines[i]!.match(new RegExp(`<${tagName}(?:[\\s>]|$)`, 'gi')) ?? []
|
|
89
|
+
).length;
|
|
90
|
+
const closes = (
|
|
91
|
+
lines[i]!.match(new RegExp(`</${tagName}\\s*>`, 'gi')) ?? []
|
|
92
|
+
).length;
|
|
93
|
+
depth += opens - closes;
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
regions.push({ type: 'html', lines: htmlLines });
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Default: spindle/markdown line
|
|
101
|
+
pushSpindleLine(regions, line);
|
|
102
|
+
i++;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return regions;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The lines of the block that opens on line `start`: up to the first line
|
|
110
|
+
* (the opening one included) that matches `close`, or to the end.
|
|
111
|
+
*/
|
|
112
|
+
function blockLines(lines: string[], start: number, close: RegExp): string[] {
|
|
113
|
+
let end = start;
|
|
114
|
+
while (end < lines.length - 1 && !close.test(lines[end]!)) end++;
|
|
115
|
+
return lines.slice(start, end + 1);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Append a line to the last spindle region, or create a new one. */
|
|
119
|
+
function pushSpindleLine(regions: Region[], line: string): void {
|
|
120
|
+
const last = regions[regions.length - 1];
|
|
121
|
+
if (last?.type === 'spindle') {
|
|
122
|
+
last.lines.push(line);
|
|
123
|
+
} else {
|
|
124
|
+
regions.push({ type: 'spindle', lines: [line] });
|
|
125
|
+
}
|
|
126
|
+
}
|
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
|
-
|
|
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 };
|
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
|
}
|