@rohal12/spindle 0.64.10 → 0.64.12

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.
@@ -12,9 +12,11 @@ export {
12
12
  collectStoryPassageReferences,
13
13
  passagePieces,
14
14
  completionContext,
15
+ completionTarget,
15
16
  pieceOffset,
16
17
  pairMarkup,
17
18
  macroCalls,
19
+ macroCallAt,
18
20
  isBlockMacro,
19
21
  isSpecialPassage,
20
22
  parseStoryVariables,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.10",
3
+ "version": "0.64.12",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -108,14 +108,14 @@
108
108
  "@vitest/coverage-v8": "^5.0.3",
109
109
  "codemirror": "^5.65.21",
110
110
  "fake-indexeddb": "^6.2.5",
111
- "fallow": "3.34.1",
111
+ "fallow": "3.36.0",
112
112
  "fast-check": "^4.10.2",
113
113
  "happy-dom": "^21.0.4",
114
114
  "husky": "^9.1.7",
115
115
  "js-yaml": "^5.4.3",
116
- "jscpd": "5.4.1",
116
+ "jscpd": "5.4.2",
117
117
  "lint-staged": "^17.6.0",
118
- "peggy": "5.1.0",
118
+ "peggy": "5.1.1",
119
119
  "playwright": "^1.64.0",
120
120
  "prettier": "^3.9.9",
121
121
  "typescript": "^7.0.2",
@@ -1,5 +1,6 @@
1
1
  /** Cursor context from the runtime grammar and argument metadata, without executing code. */
2
2
  import { completionTokens } from './markup/parse';
3
+ import type { Token } from './markup/tokens';
3
4
  import { isRawMacro } from './markup/ast';
4
5
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
5
6
  import {
@@ -14,6 +15,8 @@ import { macroArgumentSpans } from './components/macros/macro-args';
14
15
  import { readQuoted, splitArgSpans } from './components/macros/arg-utils';
15
16
  import {
16
17
  lexJs,
18
+ completionIdentifier,
19
+ type CompletionIdentifier,
17
20
  scanStringLiteral,
18
21
  stringLiteralValue,
19
22
  type JsGoal,
@@ -37,6 +40,13 @@ export type CompletionContext =
37
40
  containers?: readonly CompletionContainer[];
38
41
  });
39
42
 
43
+ /** Full code and identifier boundaries for an edit at the cursor. */
44
+ export type CompletionTarget =
45
+ | { kind: 'literal' }
46
+ | (Extract<CompletionContext, { kind: 'code' }> & {
47
+ identifier?: CompletionIdentifier;
48
+ });
49
+
40
50
  const LITERAL = { kind: 'literal' } as const;
41
51
 
42
52
  /**
@@ -49,7 +59,46 @@ export function completionContext(
49
59
  cursor: number,
50
60
  macros: Iterable<ToolingMacro> = [],
51
61
  ): CompletionContext {
52
- if (!Number.isInteger(cursor) || cursor < 0 || cursor > source.length) {
62
+ return readCompletion(
63
+ source.slice(0, cursor),
64
+ cursor,
65
+ macros,
66
+ false,
67
+ source.length,
68
+ );
69
+ }
70
+
71
+ /** Includes the identifier suffix and its mappings through enclosing markup. */
72
+ export function completionTarget(
73
+ source: string,
74
+ cursor: number,
75
+ macros: Iterable<ToolingMacro> = [],
76
+ ): CompletionTarget {
77
+ return readCompletion(source, cursor, macros, true);
78
+ }
79
+
80
+ /** Visit the markup scopes enclosing a cursor, from outermost to innermost. */
81
+ export function completionScopes(
82
+ source: string,
83
+ cursor: number,
84
+ macros: Iterable<ToolingMacro>,
85
+ visit: (tokens: readonly Token[], map: (offset: number) => number) => boolean,
86
+ ): void {
87
+ readCompletion(source, cursor, macros, true, source.length, visit);
88
+ }
89
+
90
+ function readCompletion(
91
+ source: string,
92
+ cursor: number,
93
+ macros: Iterable<ToolingMacro>,
94
+ full: boolean,
95
+ sourceLength = source.length,
96
+ visit?: (
97
+ tokens: readonly Token[],
98
+ map: (offset: number) => number,
99
+ ) => boolean,
100
+ ): CompletionTarget {
101
+ if (!Number.isInteger(cursor) || cursor < 0 || cursor > sourceLength) {
53
102
  throw new RangeError('cursor must be a UTF-16 offset within source');
54
103
  }
55
104
  const parametersOf = parameterLookup(macros);
@@ -64,10 +113,13 @@ export function completionContext(
64
113
  // A following identifier probes the lexer's state at EOF. It cannot
65
114
  // close a string, regex, comment or template, and needs no guessed
66
115
  // delimiters. A dot before it still counts as executable property code.
67
- const probe = code.length + 1;
116
+ let position = 0;
117
+ while (position < code.length && map(position) < cursor) position++;
118
+ const prefix = code.slice(0, position);
119
+ const probe = prefix.length + 1;
68
120
  let executable = false;
69
121
  lexJs(
70
- code + ' __spindle_cursor__',
122
+ prefix + ' __spindle_cursor__',
71
123
  {
72
124
  code(_ch, at) {
73
125
  if (at >= probe) executable = true;
@@ -79,6 +131,9 @@ export function completionContext(
79
131
  goal,
80
132
  );
81
133
  if (!executable) return LITERAL;
134
+ const identifier = full
135
+ ? completionIdentifier(code, position, goal)
136
+ : undefined;
82
137
  const offset = map(0);
83
138
  const offsets = Array.from({ length: code.length + 1 }, (_, i) => map(i));
84
139
  return {
@@ -86,7 +141,8 @@ export function completionContext(
86
141
  code,
87
142
  goal,
88
143
  offset,
89
- cursor: code.length,
144
+ cursor: position,
145
+ ...(identifier && { identifier }),
90
146
  ...(containers.length ? { containers } : {}),
91
147
  ...(offsets.some((at, i) => at !== offset + i)
92
148
  ? { sourceOffsets: offsets }
@@ -107,7 +163,10 @@ export function completionContext(
107
163
  let at = 0;
108
164
  for (const part of splitSigilTemplate(src, true)) {
109
165
  if ('expr' in part) {
110
- if (at + 1 + part.expr.length === src.length) {
166
+ if (
167
+ map(at + 1) <= cursor &&
168
+ cursor <= map(at + 1 + part.expr.length)
169
+ ) {
111
170
  return codeContext(
112
171
  part.expr,
113
172
  'expression',
@@ -127,8 +186,14 @@ export function completionContext(
127
186
  isRawMacro(name, parametersOf.widget?.(name) !== undefined),
128
187
  },
129
188
  });
130
- const token = tokens[tokens.length - 1];
131
- if (!token || token.end !== src.length) return LITERAL;
189
+ if (visit && !visit(tokens, map)) return LITERAL;
190
+ const contains = (start: number, end: number) =>
191
+ map(start) <= cursor && cursor <= map(end);
192
+ const index = tokens.findIndex(
193
+ (token) => map(token.start) < cursor && cursor <= map(token.end),
194
+ );
195
+ const token = tokens[index];
196
+ if (!token) return LITERAL;
132
197
  const codeAt = (code: string, at: number, goal: JsGoal = 'expression') =>
133
198
  codeContext(code, goal, (i) => map(at + i), containers);
134
199
  const nested = (
@@ -147,15 +212,24 @@ export function completionContext(
147
212
  container ? [...containers, container] : containers,
148
213
  );
149
214
 
150
- if (token.type === 'variable' && token.nameEnd === src.length) {
151
- return codeAt(src.slice(token.nameStart - 1), token.nameStart - 1);
215
+ if (
216
+ token.type === 'variable' &&
217
+ contains(token.nameStart - 1, token.nameEnd)
218
+ ) {
219
+ return codeAt(
220
+ src.slice(token.nameStart - 1, token.nameEnd),
221
+ token.nameStart - 1,
222
+ );
152
223
  }
153
- if (token.type === 'expression' && token.expressionEnd === src.length) {
224
+ if (
225
+ token.type === 'expression' &&
226
+ contains(token.expressionStart, token.expressionEnd)
227
+ ) {
154
228
  return codeAt(token.expression, token.expressionStart);
155
229
  }
156
230
  if (token.type === 'html') {
157
231
  for (const { name, value, at } of attributeValues(src, token)) {
158
- if (at + value.length === src.length) {
232
+ if (contains(at, at + value.length)) {
159
233
  const span = token.attributeSpans.find(
160
234
  (span) => span.valueStart === at,
161
235
  );
@@ -167,12 +241,15 @@ export function completionContext(
167
241
  });
168
242
  }
169
243
  }
170
- } else if (token.type === 'link' && token.displayEnd === src.length) {
244
+ } else if (
245
+ token.type === 'link' &&
246
+ contains(token.displayStart, token.displayEnd)
247
+ ) {
171
248
  return nested(token.display, token.displayStart, undefined, false, {
172
249
  kind: 'link-label',
173
250
  });
174
251
  } else if (token.type === 'text' && !token.comment) {
175
- const opener = tokens[tokens.length - 2];
252
+ const opener = tokens[index - 1];
176
253
  if (
177
254
  opener?.type === 'macro' &&
178
255
  !opener.isClose &&
@@ -183,7 +260,7 @@ export function completionContext(
183
260
  } else if (
184
261
  token.type === 'macro' &&
185
262
  !token.isClose &&
186
- token.argsEnd === src.length
263
+ contains(token.argsStart, token.argsEnd)
187
264
  ) {
188
265
  const name = token.name.toLowerCase();
189
266
  const args = token.rawArgs;
@@ -206,10 +283,13 @@ export function completionContext(
206
283
  return holds === 'markup' ? nested(raw, at) : LITERAL;
207
284
  }
208
285
  const scan = scanStringLiteral(raw, 0);
209
- if (scan.closed) return LITERAL;
286
+ const bodyEnd = scan.closed ? scan.end - 1 : scan.end;
287
+ if (!contains(at + 1, at + bodyEnd)) return LITERAL;
210
288
  const value =
211
289
  escapes === 'javascript'
212
- ? stringLiteralValue(raw + raw[0])
290
+ ? stringLiteralValue(
291
+ raw.slice(0, scan.end) + (scan.closed ? '' : raw[0]),
292
+ )
213
293
  : quoted.value;
214
294
  if (value == null) return LITERAL;
215
295
  const container: CompletionContainer = {
@@ -217,7 +297,12 @@ export function completionContext(
217
297
  quote: raw[0] as '"' | "'",
218
298
  escapes,
219
299
  };
220
- const offsets = escapeOffsets(raw.slice(1), at + 1, value, escapes);
300
+ const offsets = escapeOffsets(
301
+ raw.slice(1, bodyEnd),
302
+ at + 1,
303
+ value,
304
+ escapes,
305
+ );
221
306
  if (holds === 'expression' || holds === 'statements') {
222
307
  return codeContext(
223
308
  value,
@@ -232,10 +317,13 @@ export function completionContext(
232
317
  };
233
318
  if (widget) {
234
319
  const spans = splitArgSpans(args);
235
- const span = spans[spans.length - 1];
320
+ const which = spans.findIndex(([start, end]) =>
321
+ contains(token.argsStart + start, token.argsStart + end),
322
+ );
323
+ const span = spans[which];
236
324
  if (!span) return LITERAL;
237
- const raw = args.slice(span[0]);
238
- const holds = widget[spans.length - 1]?.holds;
325
+ const raw = args.slice(...span);
326
+ const holds = widget[which]?.holds;
239
327
  return /^["']/.test(raw) && holds
240
328
  ? stringContext(raw, token.argsStart + span[0], holds, 'javascript')
241
329
  : codeAt(raw, token.argsStart + span[0]);
@@ -245,7 +333,7 @@ export function completionContext(
245
333
  const spans = macroArgumentSpans(args, params).filter(
246
334
  (span) =>
247
335
  span.parameter.type !== 'options' &&
248
- span.end === args.trimEnd().length,
336
+ contains(token.argsStart + span.start, token.argsStart + span.end),
249
337
  );
250
338
  const span = spans[spans.length - 1];
251
339
  if (!span) return LITERAL;
@@ -256,7 +344,7 @@ export function completionContext(
256
344
  at += param.name.length;
257
345
  while (/\s/.test(args.charAt(at))) at++;
258
346
  }
259
- const raw = args.slice(at);
347
+ const raw = args.slice(at, span.end);
260
348
  const offset = token.argsStart + at;
261
349
  if (param.type === 'expression' || param.type === 'passage')
262
350
  return codeAt(raw, offset);
@@ -266,5 +354,5 @@ export function completionContext(
266
354
  }
267
355
  return LITERAL;
268
356
  };
269
- return read(source.slice(0, cursor), (i) => i);
357
+ return read(source, (i) => i);
270
358
  }
@@ -1,26 +1,13 @@
1
+ import { tokenizeMarkupTolerant } from '../markup/parse';
2
+ import type { HtmlToken } from '../markup/tokens';
3
+ import { sourceLines } from './source-lines';
4
+
1
5
  /** A run of a passage body that is formatted as one kind of content. */
2
6
  export interface Region {
3
7
  type: 'spindle' | 'html' | 'script' | 'svg';
4
8
  lines: string[];
5
9
  }
6
10
 
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
11
  /**
25
12
  * Segment a passage body into regions: spindle (markdown/macros), html blocks, script blocks.
26
13
  */
@@ -32,6 +19,26 @@ export function segmentRegions(body: string): Region[] {
32
19
  }
33
20
  if (lines.length === 0) return [];
34
21
 
22
+ // Count only real tags: comments, attributes and macro strings can all
23
+ // contain tag-shaped text. Index once, including the opening region line.
24
+ const tags: HtmlToken[][] = lines.map(() => []);
25
+ const tagEndLines = lines.map((_, line) => line);
26
+ const lineAt = sourceLines(body);
27
+ for (const token of tokenizeMarkupTolerant(body).tokens) {
28
+ if (token.type !== 'html') continue;
29
+ const line = lineAt(token.start);
30
+ tags[line]!.push(token);
31
+ tagEndLines[line] = Math.max(tagEndLines[line]!, lineAt(token.end - 1));
32
+ }
33
+ const depthOnLine = (line: number, name: string) =>
34
+ tags[line]!.reduce(
35
+ (depth, token) =>
36
+ token.tag.toLowerCase() === name && !token.isSelfClose
37
+ ? depth + (token.isClose ? -1 : 1)
38
+ : depth,
39
+ 0,
40
+ );
41
+
35
42
  const regions: Region[] = [];
36
43
  let i = 0;
37
44
 
@@ -63,16 +70,13 @@ export function segmentRegions(body: string): Region[] {
63
70
  const tagMatch = trimmed.match(/^<([a-zA-Z][\w-]*)/);
64
71
  const tagName = tagMatch![1]!.toLowerCase();
65
72
 
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)) {
73
+ // All same-name openers must close, even when an inner one closes on
74
+ // the opening line. Self-closing tags do not increase the depth.
75
+ let depth = depthOnLine(i, tagName);
76
+ // A closed or void tag can still span lines. Never send its attribute
77
+ // continuation through prose indentation or split a closing tag.
78
+ let endLine = tagEndLines[i]!;
79
+ if (depth <= 0 && endLine === i) {
76
80
  pushSpindleLine(regions, line);
77
81
  i++;
78
82
  continue;
@@ -80,17 +84,11 @@ export function segmentRegions(body: string): Region[] {
80
84
 
81
85
  // Multi-line HTML block
82
86
  const htmlLines: string[] = [line];
83
- let depth = 1;
84
87
  i++;
85
- while (i < lines.length && depth > 0) {
88
+ while (i < lines.length && (depth > 0 || i <= endLine)) {
86
89
  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;
90
+ endLine = Math.max(endLine, tagEndLines[i]!);
91
+ depth += depthOnLine(i, tagName);
94
92
  i++;
95
93
  }
96
94
  regions.push({ type: 'html', lines: htmlLines });