@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
@@ -0,0 +1,74 @@
1
+ export interface Snippet {
2
+ /** The command name suffix: the command is `snippet:<id>`. */
3
+ id: string;
4
+ /** The menu item's label. */
5
+ label: string;
6
+ menu: 'links' | 'logic' | 'variables' | 'inputs' | 'ui';
7
+ /**
8
+ * Inserted before the selection. Its one `|` marks the cursor slot, where
9
+ * the cursor goes when nothing is selected; it is not inserted.
10
+ */
11
+ before: string;
12
+ /** Inserted after the selection ('' for a snippet that does not wrap). */
13
+ after: string;
14
+ }
15
+
16
+ type Row = readonly [id: string, label: string, before: string, after?: string];
17
+
18
+ /** The snippets of one menu from rows of `[id, label, before, after]`. */
19
+ function group(menu: Snippet['menu'], rows: readonly Row[]): Snippet[] {
20
+ return rows.map(([id, label, before, after = '']) => ({
21
+ id,
22
+ label,
23
+ menu,
24
+ before,
25
+ after,
26
+ }));
27
+ }
28
+
29
+ /**
30
+ * The templates follow `docs/macros.md`. A block macro wraps the selection as
31
+ * its body; the slot is where the author types next.
32
+ */
33
+ export const snippets: readonly Snippet[] = [
34
+ ...group('links', [
35
+ ['bracket-link', 'Link [[…]]', '[[|', ']]'],
36
+ ['link', 'Link macro…', '{link "|" "Passage"}', '{/link}'],
37
+ ['goto', 'Go to…', '{goto "|"}'],
38
+ ['include', 'Include…', '{include "|"}'],
39
+ ['back', 'Back', '{back}|'],
40
+ ]),
41
+ ...group('logic', [
42
+ ['if', 'If…', '{if |}', '{/if}'],
43
+ ['if-else', 'If / else…', '{if |}', '{else}{/if}'],
44
+ ['for', 'For each…', '{for @item of |}', '{/for}'],
45
+ ['switch', 'Switch…', '{switch |}{case 1}', '{default}{/switch}'],
46
+ ['do', 'Do (code)', '{do}|', '{/do}'],
47
+ ['watch', 'Watch…', `{watch '|' dialog "Passage" once}`],
48
+ ]),
49
+ ...group('variables', [
50
+ ['set', 'Set…', '{set |}'],
51
+ ['unset', 'Unset…', '{unset |}'],
52
+ ['print', 'Print…', '{print |}'],
53
+ ['display', 'Display {$x}', '{$|}'],
54
+ ['computed', 'Computed…', '{computed |}'],
55
+ ]),
56
+ ...group('inputs', [
57
+ ['textbox', 'Text box…', '{textbox |}'],
58
+ ['numberbox', 'Number box…', '{numberbox |}'],
59
+ ['textarea', 'Text area…', '{textarea |}'],
60
+ ['checkbox', 'Checkbox…', '{checkbox | "Label"}'],
61
+ ['radiobutton', 'Radio button…', '{radiobutton | "value" "Label"}'],
62
+ ['listbox', 'List box…', '{listbox |}{option "Option"}', '{/listbox}'],
63
+ ['cycle', 'Cycle…', '{cycle |}{option "Option"}', '{/cycle}'],
64
+ ['button', 'Button…', '{button "|"}', '{/button}'],
65
+ ]),
66
+ ...group('ui', [
67
+ ['dialog', 'Dialog…', '{dialog "|"}', '{/dialog}'],
68
+ ['repeat', 'Repeat…', '{repeat |}', '{/repeat}'],
69
+ ['timed', 'Timed…', '{timed |}', '{/timed}'],
70
+ ['meter', 'Meter…', '{meter | 100}'],
71
+ ['nobr', 'No line breaks', '{nobr}|', '{/nobr}'],
72
+ ['widget', 'Widget…', '{widget "|"}', '{/widget}'],
73
+ ]),
74
+ ];
@@ -0,0 +1,85 @@
1
+ import type CodeMirror from 'codemirror';
2
+ import { icon, type IconName } from './icons';
3
+ import { snippets, type Snippet } from './snippets';
4
+
5
+ /** The items Twine 2.4+ accepts from `codeMirror.toolbar`. */
6
+ export type ToolbarItem =
7
+ | {
8
+ type: 'button';
9
+ command: string;
10
+ label: string;
11
+ /** Required at the top level, not allowed inside a menu. */
12
+ icon?: string;
13
+ disabled?: boolean;
14
+ iconOnly?: boolean;
15
+ }
16
+ | {
17
+ type: 'menu';
18
+ icon: string;
19
+ label: string;
20
+ items: ToolbarMenuItem[];
21
+ disabled?: boolean;
22
+ }
23
+ | { type: 'separator' };
24
+
25
+ export type ToolbarMenuItem = Extract<
26
+ ToolbarItem,
27
+ { type: 'button' | 'separator' }
28
+ >;
29
+
30
+ export interface ToolbarEnvironment {
31
+ appTheme: 'dark' | 'light';
32
+ foregroundColor: string;
33
+ locale: string;
34
+ }
35
+
36
+ const menus: readonly { id: Snippet['menu']; label: string }[] = [
37
+ { id: 'links', label: 'Links' },
38
+ { id: 'logic', label: 'Logic' },
39
+ { id: 'variables', label: 'Variables' },
40
+ { id: 'inputs', label: 'Inputs' },
41
+ { id: 'ui', label: 'UI' },
42
+ ];
43
+
44
+ /**
45
+ * The toolbar above the passage editor: one menu of snippets per group, then
46
+ * Check and Format. The items are the same for every editor, theme and
47
+ * locale; only Check and Format are disabled while the passage is empty. The
48
+ * commands they run are in `codeMirror.commands`.
49
+ */
50
+ export function toolbar(
51
+ editor: CodeMirror.Editor,
52
+ environment: ToolbarEnvironment,
53
+ ): ToolbarItem[] {
54
+ const color = environment.foregroundColor;
55
+ const empty = editor.getValue() === '';
56
+ const named = (name: IconName) => icon(name, color);
57
+ return [
58
+ ...menus.map(({ id, label }): ToolbarItem => ({
59
+ type: 'menu',
60
+ icon: named(id),
61
+ label,
62
+ items: snippets
63
+ .filter((snippet) => snippet.menu === id)
64
+ .map((snippet) => ({
65
+ type: 'button',
66
+ command: `snippet:${snippet.id}`,
67
+ label: snippet.label,
68
+ })),
69
+ })),
70
+ {
71
+ type: 'button',
72
+ command: 'check',
73
+ label: 'Check',
74
+ icon: named('check'),
75
+ disabled: empty,
76
+ },
77
+ {
78
+ type: 'button',
79
+ command: 'format',
80
+ label: 'Format',
81
+ icon: named('format'),
82
+ disabled: empty,
83
+ },
84
+ ];
85
+ }
@@ -126,6 +126,15 @@ const _toolingTypes: [
126
126
  SourceTooling.ValidateMarkupOptions,
127
127
  PublishedTooling.ValidateMarkupOptions
128
128
  >,
129
+ Same<SourceTooling.PrettierLike, PublishedTooling.PrettierLike>,
130
+ Same<
131
+ SourceTooling.PassageFormatOptions,
132
+ PublishedTooling.PassageFormatOptions
133
+ >,
134
+ Same<
135
+ typeof SourceTooling.formatPassage,
136
+ typeof PublishedTooling.formatPassage
137
+ >,
129
138
  ] = [
130
139
  true,
131
140
  true,
@@ -144,6 +153,9 @@ const _toolingTypes: [
144
153
  true,
145
154
  true,
146
155
  true,
156
+ true,
157
+ true,
158
+ true,
147
159
  ];
148
160
 
149
161
  // A typical custom macro written against the published types must type-check,
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Checks for the shape of plain data an author or a script hands in (the
3
+ * automation YAML, Story.setObservedActions() rules). Each takes a `fail`
4
+ * that throws with the caller's prefix, so the message names where the
5
+ * bad value came from.
6
+ */
7
+ export type Fail = (message: string) => never;
8
+
9
+ export function isRecord(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+
13
+ /** `value` as an object whose keys are all in `allowed`. */
14
+ export function checkObject(
15
+ value: unknown,
16
+ what: string,
17
+ allowed: readonly string[],
18
+ fail: Fail,
19
+ ): Record<string, unknown> {
20
+ if (!isRecord(value)) fail(`${what} must be an object`);
21
+ for (const key of Object.keys(value)) {
22
+ if (!allowed.includes(key)) {
23
+ fail(`${what} has an unknown field "${key}" (${allowed.join(', ')})`);
24
+ }
25
+ }
26
+ return value;
27
+ }
28
+
29
+ export type FieldCheck = (value: unknown) => boolean;
30
+
31
+ export const isString: FieldCheck = (v) => typeof v === 'string';
32
+ export const isBoolean: FieldCheck = (v) => typeof v === 'boolean';
33
+
34
+ /** Each field of `obj` named in `checks` passes its check. */
35
+ export function checkFields(
36
+ obj: Record<string, unknown>,
37
+ what: string,
38
+ checks: Record<string, [FieldCheck, string]>,
39
+ fail: Fail,
40
+ ): void {
41
+ for (const [key, [valid, expected]] of Object.entries(checks)) {
42
+ if (key in obj && !valid(obj[key])) {
43
+ fail(`"${key}" of ${what} must be ${expected}`);
44
+ }
45
+ }
46
+ }
@@ -1,4 +1,4 @@
1
- import type { StoryAPI } from './index';
1
+ import type { Observation, StoryAPI } from './index';
2
2
 
3
3
  /** Options for {@link bootStory}. */
4
4
  export interface BootStoryOptions {
@@ -24,4 +24,45 @@ export interface BootStoryOptions {
24
24
  */
25
25
  export function bootStory(options: BootStoryOptions): Promise<StoryAPI>;
26
26
 
27
- export type { StoryAPI };
27
+ /** One recorded step: what the reader saw, and what they chose. */
28
+ export interface TranscriptEntry {
29
+ turn: number;
30
+ passage: string;
31
+ /** Left out when the transcript was created with `include.text: false`. */
32
+ text?: string;
33
+ /** Only with `include.context: true`. */
34
+ context?: string | null;
35
+ chose: { id: string; label: string; value?: unknown };
36
+ }
37
+
38
+ /** Options for {@link createTranscript}. */
39
+ export interface TranscriptOptions {
40
+ /**
41
+ * How many of the latest entries to keep: a non-negative integer, or
42
+ * `Infinity` for all. Default 10. Anything else throws.
43
+ */
44
+ limit?: number;
45
+ /** Default `{ text: true, context: false }`. */
46
+ include?: { text?: boolean; context?: boolean };
47
+ }
48
+
49
+ /** A recorder returned by {@link createTranscript}. */
50
+ export interface Transcript {
51
+ /**
52
+ * `Story.step()`, recording the observation it acted on and the choice.
53
+ * Await each step before the next: steps are not queued.
54
+ */
55
+ step(id: string, value?: unknown): Promise<Observation>;
56
+ readonly entries: readonly TranscriptEntry[];
57
+ }
58
+
59
+ /**
60
+ * Record a playthrough for stateless decision models, which need the last few
61
+ * steps sent with every call. A step that rejects records nothing.
62
+ */
63
+ export function createTranscript(
64
+ story: StoryAPI,
65
+ options?: TranscriptOptions,
66
+ ): Transcript;
67
+
68
+ export type { Observation, StoryAPI };
package/types/index.d.ts CHANGED
@@ -220,6 +220,56 @@ export interface StoryAction {
220
220
  perform: (value?: unknown) => void | Promise<void>;
221
221
  }
222
222
 
223
+ /**
224
+ * Selects actions by their fields; unset fields match anything. Used by
225
+ * `Story.setObservedActions()` and the automation YAML's `assert.actions`.
226
+ * @see {@link ../../src/action-registry.ts} for the implementation.
227
+ */
228
+ export interface ActionMatcher {
229
+ id?: string;
230
+ type?: string;
231
+ target?: string;
232
+ variable?: string;
233
+ label?: string;
234
+ /** `true` matches only disabled actions, `false` only enabled ones. */
235
+ disabled?: boolean;
236
+ }
237
+
238
+ /** An action as `Story.observe()` lists it: without `perform`. */
239
+ export type ObservedAction = Omit<StoryAction, 'perform'>;
240
+
241
+ /**
242
+ * Which actions `Story.observe()` offers. `exclude` removes what it
243
+ * matches; `include` puts back what the default exclusions removed (`back`,
244
+ * `forward`, `restart`, `save`, `load`, `dialog`). `exclude` wins.
245
+ */
246
+ export interface ObservedActionRules {
247
+ exclude?: ActionMatcher[];
248
+ include?: ActionMatcher[];
249
+ }
250
+
251
+ /**
252
+ * What a reader of the story sees and can do, as plain data
253
+ * (`Story.observe()`).
254
+ * @see {@link ../../src/observe/observe.ts} for the implementation.
255
+ */
256
+ export interface Observation {
257
+ /** The current passage's name. */
258
+ passage: string;
259
+ /** The reader-visible text of the passage area (not StoryInterface chrome). */
260
+ text: string;
261
+ /** The rendered `StoryContext` passage, or null if the story has none. */
262
+ context: string | null;
263
+ /** The open dialogs, innermost last. */
264
+ dialogs: { passage: string; text: string }[];
265
+ /** The offered actions (see `setObservedActions()`). */
266
+ actions: ObservedAction[];
267
+ /** The macro and runtime errors on screen. */
268
+ errors: string[];
269
+ /** The navigation count: a link moves it forward, an input does not. */
270
+ turn: number;
271
+ }
272
+
223
273
  /**
224
274
  * Storage usage information returned by `Story.storage.getInfo()`.
225
275
  * @see {@link ../../src/saves/types.ts} for the implementation.
@@ -846,6 +896,27 @@ export interface StoryAPI {
846
896
  */
847
897
  waitForActions(): Promise<StoryAction[]>;
848
898
 
899
+ /**
900
+ * What the story shows and offers now: the passage text, the
901
+ * `StoryContext` passage, open dialogs, the offered actions and the errors
902
+ * on screen. The first call mounts `StoryContext`. Throws before the first
903
+ * passage is on screen.
904
+ */
905
+ observe(): Observation;
906
+
907
+ /**
908
+ * Perform an action (any ID, offered or not), wait for its effects as
909
+ * `waitForActions()` does, and return the observation. Rejects as
910
+ * `performAction()` throws. Doesn't wait for `{timed}` content.
911
+ */
912
+ step(id: string, value?: unknown): Promise<Observation>;
913
+
914
+ /**
915
+ * Replace the rules for which actions `observe()` offers. Throws, naming
916
+ * the rule, when a rule isn't a valid matcher.
917
+ */
918
+ setObservedActions(rules: ObservedActionRules): void;
919
+
849
920
  /** Register a trigger that fires when a condition expression becomes truthy. Returns an unsubscribe function. */
850
921
  watch(
851
922
  condition: string,
@@ -1116,3 +1116,71 @@ export interface DiscoveredMacro extends ToolingMacro {
1116
1116
  * throws.
1117
1117
  */
1118
1118
  export declare function discoverMacros(source: string): DiscoveredMacro[];
1119
+
1120
+ // ---------------------------------------------------------------------------
1121
+ // Formatting
1122
+ // ---------------------------------------------------------------------------
1123
+
1124
+ /**
1125
+ * The part of Prettier's API `formatPassage` calls: `prettier`, or
1126
+ * `prettier/standalone` with the plugins for the languages in the passage.
1127
+ */
1128
+ export interface PrettierLike {
1129
+ format(code: string, options: object): Promise<string>;
1130
+ }
1131
+
1132
+ /** What `formatPassage` formats and how. */
1133
+ export interface PassageFormatOptions {
1134
+ /**
1135
+ * What the passage holds (default: 'normal', story markup). The text of a
1136
+ * 'script' or 'stylesheet' passage is formatted whole, as JavaScript or CSS.
1137
+ */
1138
+ kind?: 'normal' | 'script' | 'stylesheet';
1139
+ /**
1140
+ * Prettier, for the `<script>` and HTML blocks of the markup and for script
1141
+ * and stylesheet passages. Without it, or where it throws on a piece of
1142
+ * code, that code stays as written.
1143
+ */
1144
+ prettier?: PrettierLike;
1145
+ /**
1146
+ * The options Prettier is given (default: `{ tabWidth: 2 }`). They replace
1147
+ * the default; the formatter sets `parser` (and HTML whitespace handling)
1148
+ * itself. Standalone Prettier needs its `plugins` in every call: wrap
1149
+ * `prettier` to add them rather than passing them here.
1150
+ */
1151
+ prettierOptions?: object;
1152
+ /**
1153
+ * Whether the named macro takes a body (default: the built-in block macros
1154
+ * and the names the passage closes with `{/name}`). Replaces that default
1155
+ * whole; use `blockMacros` to add to it.
1156
+ */
1157
+ isBlock?: (name: string) => boolean;
1158
+ /**
1159
+ * Names of block macros to add to the default `isBlock` (ignored when
1160
+ * `isBlock` is given), such as the ones the story or an editor knows.
1161
+ */
1162
+ blockMacros?: Iterable<string>;
1163
+ /**
1164
+ * Whether the named sub-macro snaps back to its parent's indentation
1165
+ * (default: else, elseif, next, case, default).
1166
+ */
1167
+ isDedentingSubMacro?: (name: string) => boolean;
1168
+ /** Wrap prose lines longer than this many characters. */
1169
+ maxLineLength?: number;
1170
+ }
1171
+
1172
+ /**
1173
+ * Format the text of a passage: indent the bodies of block macros by two
1174
+ * spaces per level, snap `{else}`, `{case}` and the like back to their
1175
+ * macro, strip trailing whitespace (keeping Markdown hard breaks, lists and
1176
+ * code fences), and format `<script>` and HTML blocks with Prettier. What the
1177
+ * runtime executes is never touched: a macro, a link or a `{do}` body keeps
1178
+ * its text, line breaks included, and a multiline JavaScript literal keeps its
1179
+ * value. What the passage displays does not change. The result ends with one
1180
+ * newline and keeps the line endings of the text (the more common of CRLF and
1181
+ * LF) and its byte order mark. It is idempotent.
1182
+ */
1183
+ export declare function formatPassage(
1184
+ body: string,
1185
+ options?: PassageFormatOptions,
1186
+ ): Promise<string>;