@rohal12/spindle 0.62.1 → 0.62.3

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.
@@ -11,6 +11,7 @@ export {
11
11
  validateStoryMarkup,
12
12
  collectStoryPassageReferences,
13
13
  passagePieces,
14
+ completionContext,
14
15
  pieceOffset,
15
16
  pairMarkup,
16
17
  isBlockMacro,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.1",
3
+ "version": "0.62.3",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -28,12 +28,7 @@
28
28
  */
29
29
  import type { HtmlToken, Token } from './markup/tokens';
30
30
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
31
- import {
32
- analyzeMarkup,
33
- lineColumn,
34
- MarkupError,
35
- mapOffsets,
36
- } from './markup/parse';
31
+ import { analyzeMarkup, MarkupError, mapOffsets } from './markup/parse';
37
32
  import {
38
33
  CodeSyntaxError,
39
34
  parseCode,
@@ -53,6 +48,8 @@ import { subMacroParameters } from './components/macros/option-utils';
53
48
  import { splitArgSpans } from './components/macros/arg-utils';
54
49
  import { NameMap } from './utils/macro-names';
55
50
  import { hasOwn } from './utils/namespace';
51
+ import { isRawMacro } from './markup/ast';
52
+ import { sourcePositions } from './markup/line-column';
56
53
 
57
54
  /** While a pass runs: the code it parsed so far, by goal and source. */
58
55
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -471,7 +468,19 @@ export function* passagePiecesOf(
471
468
  parametersOf: ParametersOf,
472
469
  options: PieceOptions = {},
473
470
  ): Generator<Piece> {
474
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, undefined);
471
+ let position: ReturnType<typeof sourcePositions> | undefined;
472
+ const locate = (offset: number) =>
473
+ (position ??= sourcePositions(src))(offset);
474
+ yield* expand(
475
+ src,
476
+ src,
477
+ tokens,
478
+ parametersOf,
479
+ options,
480
+ (i) => i,
481
+ undefined,
482
+ locate,
483
+ );
475
484
  }
476
485
 
477
486
  /**
@@ -487,6 +496,7 @@ function* expand(
487
496
  options: PieceOptions,
488
497
  toRoot: (offset: number) => number,
489
498
  where: string | undefined,
499
+ locate: ReturnType<typeof sourcePositions>,
490
500
  ): Generator<Piece> {
491
501
  for (const flat of codeAndText(src, tokens, parametersOf)) {
492
502
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
@@ -498,13 +508,17 @@ function* expand(
498
508
  const toText = (i: number) => toRoot(pieceOffset(flat, i));
499
509
  const inner = analyzeMarkup(flat.text, {
500
510
  text: true,
501
- hooks: options.isBlock && { isBlock: options.isBlock },
511
+ hooks: {
512
+ ...(options.isBlock && { isBlock: options.isBlock }),
513
+ isRaw: (name) =>
514
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
515
+ },
502
516
  });
503
517
  yield {
504
518
  ...(piece as TextPiece),
505
519
  tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
506
520
  errors: inner.errors.map((e) => {
507
- const { line, column } = lineColumn(root, toText(e.offset));
521
+ const { line, column } = locate(toText(e.offset));
508
522
  return new MarkupError(
509
523
  e.reason,
510
524
  toText(e.offset),
@@ -524,6 +538,7 @@ function* expand(
524
538
  options,
525
539
  toText,
526
540
  flat.where,
541
+ locate,
527
542
  );
528
543
  }
529
544
  }
@@ -590,7 +605,7 @@ function escapeAt(
590
605
  * is where the escape begins. None when the text is where its length says, or
591
606
  * is not that string.
592
607
  */
593
- function escapeOffsets(
608
+ export function escapeOffsets(
594
609
  raw: string,
595
610
  at: number,
596
611
  value: string,
@@ -0,0 +1,226 @@
1
+ /** Cursor context from the runtime grammar and argument metadata, without executing code. */
2
+ import { completionTokens } from './markup/parse';
3
+ import { isRawMacro } from './markup/ast';
4
+ import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
5
+ import {
6
+ attributeValues,
7
+ escapeOffsets,
8
+ parameterLookup,
9
+ type PieceBase,
10
+ } from './code-check';
11
+ import { macroArgumentSpans } from './components/macros/macro-args';
12
+ import { readQuoted, splitArgSpans } from './components/macros/arg-utils';
13
+ import {
14
+ lexJs,
15
+ scanStringLiteral,
16
+ stringLiteralValue,
17
+ type JsGoal,
18
+ } from './js-lexer';
19
+ import type { ToolingMacro } from './tooling';
20
+
21
+ export type CompletionContext =
22
+ | { kind: 'literal' }
23
+ | (PieceBase & { kind: 'code'; code: string; goal: JsGoal; cursor: number });
24
+
25
+ const LITERAL = { kind: 'literal' } as const;
26
+
27
+ /**
28
+ * Whether a cursor is in executable markup, including unfinished EOF tags.
29
+ * Only the source before cursor is inspected. Code includes its literals;
30
+ * kind is literal when the cursor itself is inside one, a comment, or prose.
31
+ */
32
+ export function completionContext(
33
+ source: string,
34
+ cursor: number,
35
+ macros: Iterable<ToolingMacro> = [],
36
+ ): CompletionContext {
37
+ if (!Number.isInteger(cursor) || cursor < 0 || cursor > source.length) {
38
+ throw new RangeError('cursor must be a UTF-16 offset within source');
39
+ }
40
+ const parametersOf = parameterLookup(macros);
41
+ type Mapping = (offset: number) => number;
42
+
43
+ const codeContext = (
44
+ code: string,
45
+ goal: JsGoal,
46
+ map: Mapping,
47
+ ): CompletionContext => {
48
+ // A following identifier probes the lexer's state at EOF. It cannot
49
+ // close a string, regex, comment or template, and needs no guessed
50
+ // delimiters. A dot before it still counts as executable property code.
51
+ const probe = code.length + 1;
52
+ let executable = false;
53
+ lexJs(
54
+ code + ' __spindle_cursor__',
55
+ {
56
+ code(_ch, at) {
57
+ if (at >= probe) executable = true;
58
+ },
59
+ variable(_sigil, _name, at) {
60
+ if (at >= probe) executable = true;
61
+ },
62
+ },
63
+ goal,
64
+ );
65
+ if (!executable) return LITERAL;
66
+ const offset = map(0);
67
+ const offsets = Array.from({ length: code.length + 1 }, (_, i) => map(i));
68
+ return {
69
+ kind: 'code',
70
+ code,
71
+ goal,
72
+ offset,
73
+ cursor: code.length,
74
+ ...(offsets.some((at, i) => at !== offset + i)
75
+ ? { sourceOffsets: offsets }
76
+ : {}),
77
+ };
78
+ };
79
+
80
+ const read = (
81
+ src: string,
82
+ map: Mapping,
83
+ text = false,
84
+ depth = 0,
85
+ sigilsOnly = false,
86
+ ): CompletionContext => {
87
+ if (depth >= 64) return LITERAL;
88
+ if (sigilsOnly) {
89
+ let at = 0;
90
+ for (const part of splitSigilTemplate(src, true)) {
91
+ if ('expr' in part) {
92
+ if (at + 1 + part.expr.length === src.length) {
93
+ return codeContext(part.expr, 'expression', (i) => map(at + 1 + i));
94
+ }
95
+ at += part.expr.length + 2;
96
+ } else at += ('text' in part ? part.text : part.verbatim).length;
97
+ }
98
+ return LITERAL;
99
+ }
100
+ const tokens = completionTokens(src, {
101
+ text,
102
+ hooks: {
103
+ isRaw: (name) =>
104
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
105
+ },
106
+ });
107
+ const token = tokens[tokens.length - 1];
108
+ if (!token || token.end !== src.length) return LITERAL;
109
+ const codeAt = (code: string, at: number, goal: JsGoal = 'expression') =>
110
+ codeContext(code, goal, (i) => map(at + i));
111
+ const nested = (
112
+ value: string,
113
+ at: number,
114
+ offsets?: readonly number[],
115
+ onlySigils = false,
116
+ ) =>
117
+ read(
118
+ value,
119
+ (i) => map(offsets?.[i] ?? at + i),
120
+ true,
121
+ depth + 1,
122
+ onlySigils,
123
+ );
124
+
125
+ if (token.type === 'variable' && token.nameEnd === src.length) {
126
+ return codeAt(src.slice(token.nameStart - 1), token.nameStart - 1);
127
+ }
128
+ if (token.type === 'expression' && token.expressionEnd === src.length) {
129
+ return codeAt(token.expression, token.expressionStart);
130
+ }
131
+ if (token.type === 'html') {
132
+ for (const { name, value, at } of attributeValues(src, token)) {
133
+ if (at + value.length === src.length) {
134
+ return nested(value, at, undefined, isCodeAttribute(name));
135
+ }
136
+ }
137
+ } else if (token.type === 'link' && token.displayEnd === src.length) {
138
+ return nested(token.display, token.displayStart);
139
+ } else if (token.type === 'text' && !token.comment) {
140
+ const opener = tokens[tokens.length - 2];
141
+ if (
142
+ opener?.type === 'macro' &&
143
+ !opener.isClose &&
144
+ isRawMacro(
145
+ opener.name,
146
+ parametersOf.widget?.(opener.name) !== undefined,
147
+ )
148
+ ) {
149
+ return codeAt(token.value, token.start, 'statements');
150
+ }
151
+ } else if (
152
+ token.type === 'macro' &&
153
+ !token.isClose &&
154
+ token.argsEnd === src.length
155
+ ) {
156
+ const name = token.name.toLowerCase();
157
+ const args = token.rawArgs;
158
+ const widget = parametersOf.widget?.(name);
159
+ if (!widget && ['if', 'elseif', 'case'].includes(name)) {
160
+ return codeAt(args, token.argsStart);
161
+ }
162
+ const stringContext = (
163
+ raw: string,
164
+ at: number,
165
+ holds: string | undefined,
166
+ escapes: 'quotes' | 'javascript' = 'quotes',
167
+ ): CompletionContext => {
168
+ const quoted = readQuoted(raw, 0, true);
169
+ if (!quoted) {
170
+ if (holds === 'expression' || holds === 'statements')
171
+ return codeAt(raw, at, holds);
172
+ return holds === 'markup' ? nested(raw, at) : LITERAL;
173
+ }
174
+ const scan = scanStringLiteral(raw, 0);
175
+ if (scan.closed) return LITERAL;
176
+ const value =
177
+ escapes === 'javascript'
178
+ ? stringLiteralValue(raw + raw[0])
179
+ : quoted.value;
180
+ if (value == null) return LITERAL;
181
+ const offsets = escapeOffsets(raw.slice(1), at + 1, value, escapes);
182
+ if (holds === 'expression' || holds === 'statements') {
183
+ return codeContext(value, holds, (i) =>
184
+ map(offsets?.[i] ?? at + 1 + i),
185
+ );
186
+ }
187
+ return holds === 'markup' ? nested(value, at + 1, offsets) : LITERAL;
188
+ };
189
+ if (widget) {
190
+ const spans = splitArgSpans(args);
191
+ const span = spans[spans.length - 1];
192
+ if (!span) return LITERAL;
193
+ const raw = args.slice(span[0]);
194
+ const holds = widget[spans.length - 1]?.holds;
195
+ return /^["']/.test(raw) && holds
196
+ ? stringContext(raw, token.argsStart + span[0], holds, 'javascript')
197
+ : codeAt(raw, token.argsStart + span[0]);
198
+ }
199
+ const params = parametersOf(name);
200
+ if (!params) return LITERAL;
201
+ const spans = macroArgumentSpans(args, params).filter(
202
+ (span) =>
203
+ span.parameter.type !== 'options' &&
204
+ span.end === args.trimEnd().length,
205
+ );
206
+ const span = spans[spans.length - 1];
207
+ if (!span) return LITERAL;
208
+ const param = span.parameter;
209
+ let at = span.start;
210
+ if (span.parameterPath.length > 1) {
211
+ // Option spans include their keyword; the value begins after it.
212
+ at += param.name.length;
213
+ while (/\s/.test(args.charAt(at))) at++;
214
+ }
215
+ const raw = args.slice(at);
216
+ const offset = token.argsStart + at;
217
+ if (param.type === 'expression' || param.type === 'passage')
218
+ return codeAt(raw, offset);
219
+ if (param.type === 'statements') return codeAt(raw, offset, 'statements');
220
+ if (param.type === 'string' || param.type === 'text')
221
+ return stringContext(raw, offset, param.holds);
222
+ }
223
+ return LITERAL;
224
+ };
225
+ return read(source.slice(0, cursor), (i) => i);
226
+ }
@@ -18,7 +18,12 @@ import { useStoryFields } from '../hooks/use-story-fields';
18
18
  import type { Passage as PassageData } from '../parser';
19
19
  import { sourceLocationOf } from '../utils/source-location';
20
20
  import { emitFromRender } from '../event-emitter';
21
- import { markPassageRendered } from '../passage-render-state';
21
+ import { duringEntryRender } from '../triggers';
22
+ import type { ComponentChildren } from 'preact';
23
+ import {
24
+ EntryRenderContext,
25
+ markPassageRendered,
26
+ } from '../passage-render-state';
22
27
  import { errorMessage } from '../utils/error-message';
23
28
 
24
29
  /**
@@ -75,6 +80,19 @@ const CODE_PASSAGES = new Set([
75
80
  'PassageDone',
76
81
  ]);
77
82
 
83
+ /** PassageDone mounts after the main passage committed, but replays on load. */
84
+ function EntryRenderBoundary({ children }: { children: ComponentChildren }) {
85
+ const phase = useRef({ pending: true });
86
+ useLayoutEffect(() => {
87
+ phase.current.pending = false;
88
+ }, []);
89
+ return (
90
+ <EntryRenderContext.Provider value={phase.current}>
91
+ {children}
92
+ </EntryRenderContext.Provider>
93
+ );
94
+ }
95
+
78
96
  export function Passage({
79
97
  passage,
80
98
  dataTransition,
@@ -131,7 +149,10 @@ export function Passage({
131
149
  useLayoutEffect(() => {
132
150
  if (navigationId !== undefined) markPassageRendered(navigationId);
133
151
  if (elRef.current) {
134
- emitFromRender('passagerender', passage.name, elRef.current);
152
+ const element = elRef.current;
153
+ const emit = () => emitFromRender('passagerender', passage.name, element);
154
+ if (navigationId !== undefined) duringEntryRender(emit);
155
+ else emit();
135
156
  }
136
157
  }, [passage.name, navigationId]);
137
158
 
@@ -151,7 +172,11 @@ export function Passage({
151
172
  {headerContent && <div class="passage-header">{headerContent}</div>}
152
173
  {content}
153
174
  {footerContent && <div class="passage-footer">{footerContent}</div>}
154
- {doneContent && <div hidden>{doneContent}</div>}
175
+ {doneContent && (
176
+ <EntryRenderBoundary>
177
+ <div hidden>{doneContent}</div>
178
+ </EntryRenderBoundary>
179
+ )}
155
180
  </div>
156
181
  </ViewScopeContext.Provider>
157
182
  </InterfaceContext.Provider>
@@ -1,3 +1,5 @@
1
+ import { duringMacroRender, duringEntryRender } from './triggers';
2
+ import { EntryRenderContext } from './passage-render-state';
1
3
  import { h } from 'preact';
2
4
  import type { VNode, ComponentChildren } from 'preact';
3
5
  import {
@@ -156,6 +158,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
156
158
  const acts = actingMacros.has(config.name);
157
159
 
158
160
  function Wrapper(props: MacroProps) {
161
+ const entryRender = useContext(EntryRenderContext);
159
162
  // In a display-only passage nothing may change the story (a mount's
160
163
  // context never changes, so the hooks below run alike on every render)
161
164
  const displayOnly = useContext(DisplayOnlyContext);
@@ -318,7 +321,9 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
318
321
  }
319
322
 
320
323
  try {
321
- return config.render(props, ctx);
324
+ return entryRender?.pending
325
+ ? duringEntryRender(() => config.render(props, ctx))
326
+ : duringMacroRender(() => config.render(props, ctx));
322
327
  } catch (error) {
323
328
  // An argument read while rendering, e.g. a sub-macro's ({option})
324
329
  if (error instanceof MacroArgumentError) {
@@ -1,17 +1,7 @@
1
+ import { sourcePositions } from '../markup/line-column';
2
+
1
3
  /** Index a source once; locate zero-based lines without rescanning its prefixes. */
2
4
  export function sourceLines(source: string): (offset: number) => number {
3
- const starts = [0];
4
- for (let i = 0; i < source.length; i++) {
5
- if (source[i] === '\n') starts.push(i + 1);
6
- }
7
- return (offset) => {
8
- let low = 0;
9
- let high = starts.length;
10
- while (low < high) {
11
- const middle = (low + high) >>> 1;
12
- if (starts[middle]! <= offset) low = middle + 1;
13
- else high = middle;
14
- }
15
- return Math.max(0, low - 1);
16
- };
5
+ const position = sourcePositions(source);
6
+ return (offset) => position(offset).line - 1;
17
7
  }