@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.
Files changed (51) hide show
  1. package/README.md +20 -18
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +635 -98
  4. package/dist/pkg/story-variables.js +830 -54
  5. package/dist/pkg/tooling.js +1 -0
  6. package/package.json +4 -2
  7. package/src/action-registry.ts +84 -2
  8. package/src/automation/load-yaml.ts +10 -55
  9. package/src/automation/runner.ts +2 -14
  10. package/src/automation/types.ts +2 -8
  11. package/src/components/PassageDialog.tsx +8 -3
  12. package/src/components/dialog-close-context.ts +10 -0
  13. package/src/components/macros/Checkbox.tsx +2 -1
  14. package/src/components/macros/Cycle.tsx +2 -1
  15. package/src/components/macros/Listbox.tsx +2 -1
  16. package/src/components/macros/Radiobutton.tsx +3 -1
  17. package/src/components/macros/detached-body.tsx +19 -8
  18. package/src/components/macros/input-macro.ts +2 -1
  19. package/src/define-macro.ts +42 -16
  20. package/src/display-only.ts +30 -0
  21. package/src/format/format-passage.ts +626 -0
  22. package/src/format/placeholders.ts +316 -0
  23. package/src/format/prettier.ts +62 -0
  24. package/src/format/segment.ts +126 -0
  25. package/src/headless.ts +81 -1
  26. package/src/hooks/use-action.ts +31 -9
  27. package/src/index.tsx +16 -4
  28. package/src/js-lexer.ts +36 -6
  29. package/src/markup/code-end.ts +97 -41
  30. package/src/markup/parse.ts +6 -6
  31. package/src/observe/observable-text.ts +147 -0
  32. package/src/observe/observe.ts +160 -0
  33. package/src/store.ts +1 -0
  34. package/src/story-api.ts +21 -1
  35. package/src/story-context-passage.ts +132 -0
  36. package/src/tooling.ts +23 -1
  37. package/src/triggers.ts +32 -8
  38. package/src/twine-editor/builtin-macros.ts +11 -0
  39. package/src/twine-editor/commands.ts +173 -0
  40. package/src/twine-editor/highlight.ts +471 -0
  41. package/src/twine-editor/icons.ts +35 -0
  42. package/src/twine-editor/index.ts +19 -0
  43. package/src/twine-editor/mode.ts +137 -0
  44. package/src/twine-editor/references.ts +34 -0
  45. package/src/twine-editor/snippets.ts +74 -0
  46. package/src/twine-editor/toolbar.ts +85 -0
  47. package/src/types-drift-check.ts +12 -0
  48. package/src/utils/field-checks.ts +46 -0
  49. package/types/headless.d.ts +43 -2
  50. package/types/index.d.ts +71 -0
  51. package/types/tooling.d.ts +68 -0
package/src/story-api.ts CHANGED
@@ -42,6 +42,12 @@ import {
42
42
  type StoryAction,
43
43
  } from './action-registry';
44
44
  import { getRenderedNavigationId } from './passage-render-state';
45
+ import {
46
+ observe,
47
+ setObservedActions,
48
+ type Observation,
49
+ type ObservedActionRules,
50
+ } from './observe/observe';
45
51
  import {
46
52
  initPRNG,
47
53
  isPRNGEnabled,
@@ -170,6 +176,9 @@ export interface StoryAPI {
170
176
  callback: StoryEventCallback<E>,
171
177
  ): () => void;
172
178
  waitForActions(): Promise<StoryAction[]>;
179
+ observe(): Observation;
180
+ step(id: string, value?: unknown): Promise<Observation>;
181
+ setObservedActions(rules: ObservedActionRules): void;
173
182
  watch(
174
183
  condition: string,
175
184
  callbackOrOptions: (() => void) | WatchOptions,
@@ -282,7 +291,7 @@ function storeAction<K extends keyof StoryState>(name: K): StoryState[K] {
282
291
  }
283
292
 
284
293
  function createStoryAPI(): StoryAPI {
285
- return {
294
+ const api: StoryAPI = {
286
295
  get(name: string): unknown {
287
296
  const { isTransient, key } = parseName(name);
288
297
  // Mutation code running now ({do}, ctx.mutate, watcher run actions)
@@ -479,6 +488,16 @@ function createStoryAPI(): StoryAPI {
479
488
  return getActions();
480
489
  },
481
490
 
491
+ observe,
492
+
493
+ async step(id: string, value?: unknown): Promise<Observation> {
494
+ await api.performAction(id, value);
495
+ await api.waitForActions();
496
+ return observe();
497
+ },
498
+
499
+ setObservedActions,
500
+
482
501
  watch(
483
502
  condition: string,
484
503
  callbackOrOptions: (() => void) | WatchOptions,
@@ -602,6 +621,7 @@ function createStoryAPI(): StoryAPI {
602
621
  },
603
622
  },
604
623
  };
624
+ return api;
605
625
  }
606
626
 
607
627
  declare global {
@@ -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/tooling.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  type VariableReference,
33
33
  } from './story-variables';
34
34
  import type { ParameterDef } from './registry';
35
+ import type { Token } from './markup/tokens';
35
36
  import type { WidgetDef } from './widgets/widget-def';
36
37
 
37
38
  export { parseDeclarations, parseStoryVariables } from './story-variables';
@@ -86,6 +87,11 @@ export type {
86
87
  VariableScope,
87
88
  VariableToken,
88
89
  } from './markup/tokens';
90
+ export { formatPassage } from './format/format-passage';
91
+ export type {
92
+ PassageFormatOptions,
93
+ PrettierLike,
94
+ } from './format/format-passage';
89
95
  export { pairMarkup } from './markup/pair';
90
96
  export { pieceOffset };
91
97
  export type {
@@ -239,9 +245,25 @@ function blockLookup(macros: readonly ToolingMacro[]) {
239
245
  export function passagePieces(
240
246
  source: string,
241
247
  macros: Iterable<ToolingMacro> = [],
248
+ ): Piece[] {
249
+ return passagePiecesOfTokens(
250
+ source,
251
+ macros,
252
+ tokenizeMarkupTolerant(source).tokens,
253
+ );
254
+ }
255
+
256
+ /**
257
+ * `passagePieces` for a caller that has the tokens of
258
+ * `tokenizeMarkupTolerant(source)` already (the editor's highlighter). Not
259
+ * part of the published tooling API.
260
+ */
261
+ export function passagePiecesOfTokens(
262
+ source: string,
263
+ macros: Iterable<ToolingMacro>,
264
+ tokens: readonly Token[],
242
265
  ): Piece[] {
243
266
  const all = [...macros];
244
- const { tokens } = tokenizeMarkupTolerant(source);
245
267
  return [
246
268
  ...passagePiecesOf(source, tokens, parameterLookup(all), {
247
269
  isBlock: blockLookup(all),
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), as the function that closes each.
416
+ * while mounted).
411
417
  */
412
- const openDialogs: Array<() => void> = [];
418
+ const openDialogs: OpenDialog[] = [];
413
419
 
414
- /** Register a displayed dialog; returns the function that unregisters it. */
415
- export function registerOpenDialog(close: () => void): () => void {
416
- openDialogs.push(close);
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(close);
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 = openDialogs[openDialogs.length - 1];
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,11 @@
1
+ import '../macros/register-builtins';
2
+ import { getMacroRegistry, type MacroMetadata } from '../registry';
3
+
4
+ /**
5
+ * The built-in macros, computed as `scripts/dump-macro-registry.ts` does:
6
+ * what `getMacroRegistry()` returns once register-builtins has run. The
7
+ * hydrate build replaces this module with the generated
8
+ * `dist/pkg/macro-registry.js`, so the bundle carries no Preact. Every
9
+ * file under `src/twine-editor/` gets the built-in macros from here only.
10
+ */
11
+ export const builtinMacros: readonly MacroMetadata[] = getMacroRegistry();
@@ -0,0 +1,173 @@
1
+ import type CodeMirror from 'codemirror';
2
+ import * as prettierStandalone from 'prettier/standalone';
3
+ import * as babel from 'prettier/plugins/babel';
4
+ import * as estree from 'prettier/plugins/estree';
5
+ import * as postcss from 'prettier/plugins/postcss';
6
+ import * as html from 'prettier/plugins/html';
7
+ import {
8
+ formatPassage,
9
+ validateStoryMarkup,
10
+ type PrettierLike,
11
+ type ToolingMacro,
12
+ } from '../tooling';
13
+ import { closedMacroNames } from '../format/format-passage';
14
+ import { builtinMacros } from './builtin-macros';
15
+ import { snippets } from './snippets';
16
+
17
+ type Editor = CodeMirror.Editor;
18
+ type Command = (editor: Editor) => void | Promise<void>;
19
+
20
+ /** The marker of the cursor slot in a snippet's `before`. */
21
+ const SLOT = '|';
22
+
23
+ /** The most problems Check lists by message. */
24
+ const LISTED_PROBLEMS = 5;
25
+
26
+ /**
27
+ * Standalone Prettier, which takes its parsers from the plugins it is given:
28
+ * every call carries them, whatever options the formatter passes.
29
+ */
30
+ const prettier: PrettierLike = {
31
+ format: (code, options) =>
32
+ prettierStandalone.format(code, {
33
+ ...options,
34
+ plugins: [babel, estree, postcss, html],
35
+ }),
36
+ };
37
+
38
+ /**
39
+ * Insert the snippet around every selection, as one undo step. The cursor
40
+ * goes to the slot of each insert; a selection is wrapped, not replaced.
41
+ */
42
+ function insertSnippet(editor: Editor, before: string, after: string): void {
43
+ const slot = before.indexOf(SLOT);
44
+ const opening = before.replace(SLOT, '');
45
+ editor.operation(() => {
46
+ editor.replaceSelections(
47
+ editor.getSelections().map((selected) => opening + selected + after),
48
+ 'around',
49
+ );
50
+ editor.setSelections(
51
+ editor.listSelections().map((range) => {
52
+ const start = editor.indexFromPos(range.from());
53
+ const cursor = editor.posFromIndex(start + slot);
54
+ return { anchor: cursor, head: cursor };
55
+ }),
56
+ );
57
+ });
58
+ }
59
+
60
+ const snippetCommands = Object.fromEntries(
61
+ snippets.map(({ id, before, after }): [string, Command] => [
62
+ `snippet:${id}`,
63
+ (editor) => insertSnippet(editor, before, after),
64
+ ]),
65
+ );
66
+
67
+ /** The marks of the last Check, which the editor's next change clears. */
68
+ const checkMarks = new WeakMap<Editor, CodeMirror.TextMarker[]>();
69
+ const watchedForChanges = new WeakSet<Editor>();
70
+
71
+ function clearCheckMarks(editor: Editor): void {
72
+ for (const mark of checkMarks.get(editor) ?? []) mark.clear();
73
+ checkMarks.delete(editor);
74
+ }
75
+
76
+ /** Mark the span `start`..`end` (offsets) as a problem; an empty span covers a character. */
77
+ function markProblem(
78
+ editor: Editor,
79
+ start: number,
80
+ end: number,
81
+ title: string,
82
+ ): CodeMirror.TextMarker {
83
+ let from = editor.posFromIndex(start);
84
+ let to = editor.posFromIndex(Math.max(end, start + 1));
85
+ // At the very end of the text there is no character after: mark the one before
86
+ if (from.line === to.line && from.ch === to.ch) {
87
+ from = editor.posFromIndex(Math.max(start - 1, 0));
88
+ }
89
+ return editor.markText(from, to, {
90
+ css: 'text-decoration: underline wavy red',
91
+ title,
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Macros and widgets defined elsewhere in the story are unknown here, and a
97
+ * typo cannot be told from them: Check reports neither. A `{/name}` closer
98
+ * says the unknown macro has a body, so it is read as a block macro rather
99
+ * than reported as a stray closer.
100
+ */
101
+ function closedUserMacros(content: string): ToolingMacro[] {
102
+ const known = new Set(builtinMacros.map((m) => m.name.toLowerCase()));
103
+ return [...closedMacroNames(content)]
104
+ .filter((name) => !known.has(name))
105
+ .map((name) => ({ name, block: true, subMacros: [] }));
106
+ }
107
+
108
+ function check(editor: Editor): void {
109
+ clearCheckMarks(editor);
110
+ if (!watchedForChanges.has(editor)) {
111
+ watchedForChanges.add(editor);
112
+ editor.on('change', () => clearCheckMarks(editor));
113
+ }
114
+ const content = editor.getValue();
115
+ const diagnostics = validateStoryMarkup(
116
+ [{ name: 'passage', content }],
117
+ [...builtinMacros, ...closedUserMacros(content)],
118
+ { checkPassageNames: false, tolerant: true },
119
+ ).filter((d) => d.code !== 'unknown-macro');
120
+ if (diagnostics.length === 0) {
121
+ window.alert('No problems found');
122
+ return;
123
+ }
124
+ checkMarks.set(
125
+ editor,
126
+ diagnostics.map((d) => markProblem(editor, d.start, d.end, d.message)),
127
+ );
128
+ const listed = diagnostics
129
+ .slice(0, LISTED_PROBLEMS)
130
+ .map((d) => `Line ${d.line}: ${d.message}`);
131
+ const more = diagnostics.length - listed.length;
132
+ const count = `${diagnostics.length} ${diagnostics.length === 1 ? 'problem' : 'problems'} found`;
133
+ window.alert(
134
+ [`${count}:`, ...listed, ...(more > 0 ? [`…and ${more} more`] : [])].join(
135
+ '\n',
136
+ ),
137
+ );
138
+ }
139
+
140
+ async function format(editor: Editor): Promise<void> {
141
+ try {
142
+ const text = editor.getValue();
143
+ const formatted = await formatPassage(text, {
144
+ prettier,
145
+ blockMacros: builtinMacros.filter((m) => m.block).map((m) => m.name),
146
+ });
147
+ // The author kept typing while Prettier ran: their text wins
148
+ if (editor.getValue() !== text || formatted === text) return;
149
+ const cursor = editor.getCursor();
150
+ editor.operation(() => {
151
+ const last = editor.lastLine();
152
+ editor.replaceRange(
153
+ formatted,
154
+ { line: 0, ch: 0 },
155
+ { line: last, ch: editor.getLine(last).length },
156
+ );
157
+ const line = Math.min(cursor.line, editor.lastLine());
158
+ editor.setCursor({
159
+ line,
160
+ ch: Math.min(cursor.ch, editor.getLine(line).length),
161
+ });
162
+ });
163
+ } catch (error) {
164
+ window.alert(error instanceof Error ? error.message : String(error));
165
+ }
166
+ }
167
+
168
+ /** The commands the toolbar runs: `snippet:<id>` for each snippet, `check` and `format`. */
169
+ export const commands: Record<string, Command> = {
170
+ ...snippetCommands,
171
+ check,
172
+ format,
173
+ };