@rohal12/spindle 0.59.33 → 0.60.1

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.
@@ -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): 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 = lenientClose(input, j + 2);
43
- if (close === -1) return -1;
44
- j = close + 1;
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(input: string, i: number): number {
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 end = memo.get(i);
64
- if (end === undefined) {
65
- end = scanLenient(input, i);
66
- memo.set(i, end);
86
+ let read = memo.get(i);
87
+ if (read === undefined) {
88
+ read = scanLenient(input, i);
89
+ memo.set(i, read);
67
90
  }
68
- return end;
91
+ return read;
69
92
  }
70
93
 
71
94
  let memoInput = '';
72
- const memo = new Map<number, number>();
95
+ const memo = new Map<number, Lenient>();
73
96
 
74
- function scanLenient(input: string, i: number): 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
- i = close === -1 ? i + 1 : close;
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();
@@ -139,7 +139,7 @@ export function analyzeMarkup(
139
139
  source: string,
140
140
  options: ParseMarkupOptions = {},
141
141
  ): MarkupAnalysis {
142
- const { tokens, errors, damage } = scan(source, options);
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 } = scan(source, options);
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 malformed, which an error inside it
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 scan(
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[] = [];
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),
@@ -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
+ };