@rohal12/spindle 0.62.2 → 0.62.4
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.
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +464 -272
- package/dist/pkg/play-worker.js +95 -7
- package/dist/pkg/play.js +3 -3
- package/dist/pkg/story-variables.js +590 -386
- package/dist/pkg/tooling.js +1 -0
- package/package.json +1 -1
- package/src/code-check.ts +1 -1
- package/src/completion-context.ts +226 -0
- package/src/components/Passage.tsx +28 -3
- package/src/define-macro.ts +6 -1
- package/src/hooks/use-render-options.ts +4 -0
- package/src/macro-discovery.ts +27 -15
- package/src/markup/code-attributes.ts +10 -3
- package/src/markup/parse.ts +19 -4
- package/src/markup/render.tsx +6 -4
- package/src/markup/spindle.d.peggy.ts +2 -0
- package/src/markup/spindle.peggy +22 -13
- package/src/passage-render-state.ts +7 -0
- package/src/play/session.ts +3 -3
- package/src/play/window-events.ts +63 -0
- package/src/play/worker.ts +62 -9
- package/src/saves/format.ts +4 -0
- package/src/saves/types.ts +6 -6
- package/src/static-literal.ts +24 -22
- package/src/store.ts +42 -16
- package/src/tooling.ts +4 -0
- package/src/triggers.ts +107 -0
- package/src/twine-editor/references.ts +9 -11
- package/src/widgets/ast-scanner.ts +40 -44
- package/src/widgets/widget-def.ts +74 -45
- package/types/play.d.ts +6 -5
- package/types/tooling.d.ts +17 -0
package/dist/pkg/tooling.js
CHANGED
package/package.json
CHANGED
package/src/code-check.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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 &&
|
|
175
|
+
{doneContent && (
|
|
176
|
+
<EntryRenderBoundary>
|
|
177
|
+
<div hidden>{doneContent}</div>
|
|
178
|
+
</EntryRenderBoundary>
|
|
179
|
+
)}
|
|
155
180
|
</div>
|
|
156
181
|
</ViewScopeContext.Provider>
|
|
157
182
|
</InterfaceContext.Provider>
|
package/src/define-macro.ts
CHANGED
|
@@ -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
|
|
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) {
|
|
@@ -17,6 +17,7 @@ export function useRenderOptions(): {
|
|
|
17
17
|
inline: boolean;
|
|
18
18
|
raw: boolean;
|
|
19
19
|
structural: boolean;
|
|
20
|
+
preserveEdges: boolean;
|
|
20
21
|
locals: Record<string, unknown>;
|
|
21
22
|
} {
|
|
22
23
|
return {
|
|
@@ -24,6 +25,9 @@ export function useRenderOptions(): {
|
|
|
24
25
|
inline: useContext(InlineContext),
|
|
25
26
|
raw: useContext(RawTextContext),
|
|
26
27
|
structural: useContext(StructuralContext),
|
|
28
|
+
// These are content fragments (macro/widget bodies and forwarded
|
|
29
|
+
// children), whose edge whitespace separates surrounding prose.
|
|
30
|
+
preserveEdges: true,
|
|
27
31
|
locals: useContext(LocalsValuesContext),
|
|
28
32
|
};
|
|
29
33
|
}
|
package/src/macro-discovery.ts
CHANGED
|
@@ -53,6 +53,7 @@ const CONFIG_KEYS: ReadonlySet<string> = new Set([
|
|
|
53
53
|
class ConfigReader extends Reader {
|
|
54
54
|
/** Whether the text could not be skipped through (it ends the reading). */
|
|
55
55
|
failed = false;
|
|
56
|
+
private depth = 0;
|
|
56
57
|
|
|
57
58
|
/** The static value of a member or element, whatever follows is skipped. */
|
|
58
59
|
private member(): Datum | undefined {
|
|
@@ -124,22 +125,33 @@ class ConfigReader extends Reader {
|
|
|
124
125
|
* after what it read. False if the text ends first, or cannot be read.
|
|
125
126
|
*/
|
|
126
127
|
private elements(close: string, read: () => void): boolean {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
128
|
+
// Deeper values are unknown, but skipping them must leave the reader
|
|
129
|
+
// at the next member so unrelated config fields and calls still work.
|
|
130
|
+
if (this.depth >= 64) {
|
|
131
|
+
if (!this.skipBalanced()) this.fail();
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
this.depth++;
|
|
135
|
+
try {
|
|
136
|
+
this.i++;
|
|
137
|
+
for (;;) {
|
|
138
|
+
this.space();
|
|
139
|
+
const c = this.src.charAt(this.i);
|
|
140
|
+
if (c === close) {
|
|
141
|
+
this.i++;
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
if (c === ',') {
|
|
145
|
+
this.i++;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (this.failed || this.i >= this.src.length) return false;
|
|
149
|
+
const before = this.i;
|
|
150
|
+
read();
|
|
151
|
+
if (this.i === before) this.fail();
|
|
138
152
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
read();
|
|
142
|
-
if (this.i === before) this.fail();
|
|
153
|
+
} finally {
|
|
154
|
+
this.depth--;
|
|
143
155
|
}
|
|
144
156
|
}
|
|
145
157
|
|
|
@@ -26,7 +26,10 @@ export type SigilPart =
|
|
|
26
26
|
* sigil is not followed by a word character (`{$(…)}`) is code, kept
|
|
27
27
|
* verbatim: not resolved, and not decoded like text.
|
|
28
28
|
*/
|
|
29
|
-
export function splitSigilTemplate(
|
|
29
|
+
export function splitSigilTemplate(
|
|
30
|
+
template: string,
|
|
31
|
+
incomplete = false,
|
|
32
|
+
): SigilPart[] {
|
|
30
33
|
const parts: SigilPart[] = [];
|
|
31
34
|
let text = '';
|
|
32
35
|
let i = 0;
|
|
@@ -39,9 +42,10 @@ export function splitSigilTemplate(template: string): SigilPart[] {
|
|
|
39
42
|
}
|
|
40
43
|
text += template.slice(i, brace);
|
|
41
44
|
i = brace + 1;
|
|
42
|
-
|
|
45
|
+
let end = isSigil(template[i])
|
|
43
46
|
? defaultCodeEnd.closeBrace(template, i, i)
|
|
44
47
|
: -1;
|
|
48
|
+
if (end === -1 && incomplete && isSigil(template[i])) end = template.length;
|
|
45
49
|
if (end === -1) {
|
|
46
50
|
text += '{';
|
|
47
51
|
continue;
|
|
@@ -50,7 +54,10 @@ export function splitSigilTemplate(template: string): SigilPart[] {
|
|
|
50
54
|
text = '';
|
|
51
55
|
const block = template.slice(i, end);
|
|
52
56
|
parts.push(
|
|
53
|
-
/^.\w/.test(block)
|
|
57
|
+
/^.\w/.test(block) ||
|
|
58
|
+
(incomplete && block.length === 1 && end === template.length)
|
|
59
|
+
? { expr: block }
|
|
60
|
+
: { verbatim: `{${block}}` },
|
|
54
61
|
);
|
|
55
62
|
i = end + 1;
|
|
56
63
|
}
|
package/src/markup/parse.ts
CHANGED
|
@@ -91,12 +91,18 @@ function run(
|
|
|
91
91
|
source: string,
|
|
92
92
|
startRule: 'Tokens' | 'SelectorsPrefix',
|
|
93
93
|
options: ParseMarkupOptions,
|
|
94
|
+
completion = false,
|
|
94
95
|
): unknown {
|
|
95
96
|
const hooks = options.hooks
|
|
96
97
|
? { ...defaultHooks, ...options.hooks }
|
|
97
98
|
: defaultHooks;
|
|
98
99
|
try {
|
|
99
|
-
return pegParse(source, {
|
|
100
|
+
return pegParse(source, {
|
|
101
|
+
startRule,
|
|
102
|
+
text: options.text === true,
|
|
103
|
+
hooks,
|
|
104
|
+
completion,
|
|
105
|
+
});
|
|
100
106
|
} catch (err) {
|
|
101
107
|
const { location, code } = err as {
|
|
102
108
|
location?: { start: { offset: number }; end: { offset: number } };
|
|
@@ -260,6 +266,7 @@ export function tokenizeMarkupTolerant(
|
|
|
260
266
|
export function scanMarkupTolerant(
|
|
261
267
|
source: string,
|
|
262
268
|
options: ParseMarkupOptions = {},
|
|
269
|
+
completion = false,
|
|
263
270
|
): TolerantTokens & { damage: number[] } {
|
|
264
271
|
const tokens: Token[] = [];
|
|
265
272
|
const errors: MarkupError[] = [];
|
|
@@ -280,9 +287,9 @@ export function scanMarkupTolerant(
|
|
|
280
287
|
: closeBrace(input, codeStart, lenientStart),
|
|
281
288
|
};
|
|
282
289
|
try {
|
|
283
|
-
return
|
|
284
|
-
|
|
285
|
-
);
|
|
290
|
+
return (
|
|
291
|
+
run(text, 'Tokens', { ...options, hooks }, completion) as Token[]
|
|
292
|
+
).map((token) => shiftOffsets(token, base));
|
|
286
293
|
} catch (error) {
|
|
287
294
|
if (!(error instanceof MarkupError)) throw error;
|
|
288
295
|
return error;
|
|
@@ -334,6 +341,14 @@ export function scanMarkupTolerant(
|
|
|
334
341
|
return { tokens, errors, damage };
|
|
335
342
|
}
|
|
336
343
|
|
|
344
|
+
/** Runtime grammar with unfinished EOF tokens, for cursor contexts only. */
|
|
345
|
+
export function completionTokens(
|
|
346
|
+
source: string,
|
|
347
|
+
options: ParseMarkupOptions = {},
|
|
348
|
+
): Token[] {
|
|
349
|
+
return scanMarkupTolerant(source, options, true).tokens;
|
|
350
|
+
}
|
|
351
|
+
|
|
337
352
|
/** The offset fields of a token (and of an attribute): `start`, `nameEnd`… */
|
|
338
353
|
const OFFSET_FIELD = /^(start|end|[A-Za-z]*(Start|End))$/;
|
|
339
354
|
|
package/src/markup/render.tsx
CHANGED
|
@@ -1075,6 +1075,8 @@ export function renderNodes(
|
|
|
1075
1075
|
raw?: boolean;
|
|
1076
1076
|
/** Content of a structural element (see StructuralContext). */
|
|
1077
1077
|
structural?: boolean;
|
|
1078
|
+
/** A content fragment: keep whitespace separating it from its neighbours. */
|
|
1079
|
+
preserveEdges?: boolean;
|
|
1078
1080
|
},
|
|
1079
1081
|
): preact.ComponentChildren {
|
|
1080
1082
|
if (nodes.length === 0) return null;
|
|
@@ -1131,9 +1133,9 @@ export function renderNodes(
|
|
|
1131
1133
|
// Inline content (inside <span> etc.) never gets <p> wrappers (#220).
|
|
1132
1134
|
const unwrapParagraphs = !!(options?.nobr || options?.inline);
|
|
1133
1135
|
|
|
1134
|
-
// Markdown strips whitespace at paragraph edges.
|
|
1135
|
-
//
|
|
1136
|
-
// `<span>*HP*: </span>{$hp}`)
|
|
1136
|
+
// Markdown strips whitespace at paragraph edges. In content fragments and
|
|
1137
|
+
// without <p> wrappers it separates content from its neighbours (as in
|
|
1138
|
+
// `A.{if true} B.{/if}` or `<span>*HP*: </span>{$hp}`).
|
|
1137
1139
|
const lead = combined.slice(0, skipChars(combined, 0, 1, EDGE_WS));
|
|
1138
1140
|
const trail =
|
|
1139
1141
|
lead.length === combined.length
|
|
@@ -1141,7 +1143,7 @@ export function renderNodes(
|
|
|
1141
1143
|
: combined.slice(skipChars(combined, combined.length, -1, EDGE_WS));
|
|
1142
1144
|
const core = combined.slice(lead.length, combined.length - trail.length);
|
|
1143
1145
|
const edges = (content: preact.ComponentChildren) =>
|
|
1144
|
-
unwrapParagraphs && (lead || trail) ? (
|
|
1146
|
+
(unwrapParagraphs || options?.preserveEdges) && (lead || trail) ? (
|
|
1145
1147
|
<>
|
|
1146
1148
|
{lead}
|
|
1147
1149
|
{content}
|
|
@@ -14,6 +14,8 @@ export declare class SyntaxError extends globalThis.SyntaxError {
|
|
|
14
14
|
|
|
15
15
|
export interface ParseOptions {
|
|
16
16
|
startRule: 'Tokens' | 'SelectorsPrefix';
|
|
17
|
+
/** Internal cursor-context mode accepts unfinished EOF tokens. */
|
|
18
|
+
completion?: boolean;
|
|
17
19
|
/** Text mode (attribute values, labels). */
|
|
18
20
|
text: boolean;
|
|
19
21
|
/** What the grammar leaves to code (see parse.ts MarkupHooks). */
|
package/src/markup/spindle.peggy
CHANGED
|
@@ -130,6 +130,8 @@ function joinText(items) {
|
|
|
130
130
|
|
|
131
131
|
{
|
|
132
132
|
const textMode = options.text === true;
|
|
133
|
+
// Only cursor-context parsing accepts EOF in place of an unfinished closer.
|
|
134
|
+
const completionMode = options.completion === true;
|
|
133
135
|
const hooks = options.hooks;
|
|
134
136
|
/** End of the stretch a `.|n|` repetition consumes (see skipTo). */
|
|
135
137
|
let skipEnd = -1;
|
|
@@ -229,6 +231,7 @@ RawTokens
|
|
|
229
231
|
const loc = { start: { offset: start }, end: { offset: start + body.length } };
|
|
230
232
|
return [body ? lexeme('text', loc, { value: body }) : null, end];
|
|
231
233
|
}
|
|
234
|
+
/ &{ return completionMode; } body:$.* { return lexeme('text', location(), { value: body }); }
|
|
232
235
|
|
|
233
236
|
// ----------------------------------------------------------------- lexemes
|
|
234
237
|
|
|
@@ -243,7 +246,7 @@ TextRun
|
|
|
243
246
|
* rendering drops it. (An unclosed `<!--` is ordinary text.)
|
|
244
247
|
*/
|
|
245
248
|
Comment
|
|
246
|
-
= value:$("<!--" (">" / "->" / (!"-->" .)* "-->")) {
|
|
249
|
+
= value:$("<!--" (">" / "->" / (!"-->" .)* ("-->" / OpenEnd))) {
|
|
247
250
|
const node = lexeme('text', location(), { value });
|
|
248
251
|
node.comment = true;
|
|
249
252
|
return node;
|
|
@@ -280,7 +283,7 @@ Literal
|
|
|
280
283
|
/ "[" { return lexeme('text', location(), { value: '[' }); }
|
|
281
284
|
|
|
282
285
|
LinkLexeme
|
|
283
|
-
= &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:$LinkText "]]" {
|
|
286
|
+
= &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:$LinkText ("]]" / OpenEnd) {
|
|
284
287
|
const link = lexeme('link', location(), parseLink(inner, at, (separator) => linkSeparatorIndex(inner, at, separator)));
|
|
285
288
|
link.selectorSpan = selectorSpan(s, ss, at);
|
|
286
289
|
return withSelectors(link, s);
|
|
@@ -313,12 +316,12 @@ SelectorChar
|
|
|
313
316
|
|
|
314
317
|
/** A variable `{$a.b}` or expression `{$a + 1}`, `{(…)}`, `{!…}`. */
|
|
315
318
|
Value
|
|
316
|
-
= "{" ss:Here s:Selectors sigil:[$_@%] nameStart:Here name:$[a-zA-Z0-9_.]*
|
|
319
|
+
= "{" ss:Here s:Selectors sigil:[$_@%] nameStart:Here name:$[a-zA-Z0-9_.]* BraceEnd {
|
|
317
320
|
const variable = lexeme('variable', location(), { name, nameStart, nameEnd: nameStart + name.length, scope: SIGIL_SCOPES[sigil] });
|
|
318
321
|
variable.selectorSpan = selectorSpan(s, ss, nameStart - 1);
|
|
319
322
|
return withSelectors(variable, s);
|
|
320
323
|
}
|
|
321
|
-
/ "{" ss:Here s:Selectors after:Here &[$_@%(!] expression:CodeToBrace
|
|
324
|
+
/ "{" ss:Here s:Selectors after:Here &[$_@%(!] expression:CodeToBrace BraceEnd {
|
|
322
325
|
const node = lexeme('expression', location(), { expression, expressionStart: after, expressionEnd: after + expression.length });
|
|
323
326
|
node.selectorSpan = selectorSpan(s, ss, after);
|
|
324
327
|
return withSelectors(node, s);
|
|
@@ -327,12 +330,18 @@ Value
|
|
|
327
330
|
|
|
328
331
|
/** JavaScript up to the } that ends it: where is up to options.hooks. */
|
|
329
332
|
CodeToBrace
|
|
330
|
-
= start:Here &{
|
|
333
|
+
= start:Here &{ const end = hooks.closeBrace(input, start, start); return skipTo(end < 0 && completionMode ? input.length : end); } code:$(.|{ return skipEnd - offset(); }|) { return code; }
|
|
334
|
+
|
|
335
|
+
OpenEnd
|
|
336
|
+
= &{ return completionMode; } !.
|
|
337
|
+
|
|
338
|
+
BraceEnd
|
|
339
|
+
= "}" / OpenEnd
|
|
331
340
|
|
|
332
341
|
/** A macro tag: `{name args}`, `{/name}`, with selectors on an opener. */
|
|
333
342
|
MacroTag
|
|
334
343
|
= "{" ss:Here s:Selectors start:Here close:"/"? name:MacroName nameEnd:Here
|
|
335
|
-
tail:( &{
|
|
344
|
+
tail:( &{ const end = hooks.closeBrace(input, nameEnd, start); return skipTo(end < 0 && completionMode ? input.length : end); } args:$(.|{ return skipEnd - offset(); }|) BraceEnd { return args; } )? {
|
|
336
345
|
const loc = location();
|
|
337
346
|
const lower = name.toLowerCase();
|
|
338
347
|
const tag = lexeme('macro', loc, { name, lower, rawArgs: '', isClose: !!close });
|
|
@@ -340,7 +349,7 @@ MacroTag
|
|
|
340
349
|
tag.nameEnd = nameEnd;
|
|
341
350
|
tag.selectorSpan = selectorSpan(s, ss, start);
|
|
342
351
|
if (tail === null) fail('Unclosed ' + LB + (close ? '/' : '') + name + '…: no ' + RB + ' ends the macro', loc, 'unclosed-macro');
|
|
343
|
-
tag.rawArgs = tail.trim();
|
|
352
|
+
tag.rawArgs = completionMode ? tail.trimStart() : tail.trim();
|
|
344
353
|
tag.argsStart = tag.rawArgs ? nameEnd + tail.length - tail.trimStart().length : nameEnd;
|
|
345
354
|
tag.argsEnd = tag.argsStart + tag.rawArgs.length;
|
|
346
355
|
if (close) {
|
|
@@ -376,7 +385,7 @@ UriAutolink
|
|
|
376
385
|
{ return lexeme('text', location(), { value }); }
|
|
377
386
|
|
|
378
387
|
HtmlOpen
|
|
379
|
-
= "<" tagStart:Here tag:TagName list:Attribute* _ slash:"/"? ">" {
|
|
388
|
+
= "<" tagStart:Here tag:TagName list:Attribute* _ slash:"/"? (">" / OpenEnd) {
|
|
380
389
|
const lower = tag.toLowerCase();
|
|
381
390
|
return lexeme('html', location(), { tag, lower, tagNameStart: tagStart, tagNameEnd: tagStart + tag.length, attributes: attrs(list), attributeSpans: list, isClose: false, isSelfClose: !!slash || VOID_TAGS.has(lower) });
|
|
382
391
|
}
|
|
@@ -414,8 +423,8 @@ Attribute
|
|
|
414
423
|
|
|
415
424
|
/** An attribute value: its text, where that is written and its quote, if any. */
|
|
416
425
|
AttrValue
|
|
417
|
-
= '"' start:Here value:$(ValuePart / [^"])* end:Here '"' { return { value, start, end, quote: '"' }; }
|
|
418
|
-
/ "'" start:Here value:$(ValuePart / [^'])* end:Here "'" { return { value, start, end, quote: "'" }; }
|
|
426
|
+
= '"' start:Here value:$(ValuePart / [^"])* end:Here ('"' / OpenEnd) { return { value, start, end, quote: '"' }; }
|
|
427
|
+
/ "'" start:Here value:$(ValuePart / [^'])* end:Here ("'" / OpenEnd) { return { value, start, end, quote: "'" }; }
|
|
419
428
|
/ q:["'] { fail('Unclosed attribute value: the ' + q + ' here has no closing ' + q, location(), 'unclosed-attribute'); }
|
|
420
429
|
/ start:Here value:$[^ \t\n\r\x0B\x0C\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF>]* end:Here { return { value, start, end }; }
|
|
421
430
|
|
|
@@ -423,9 +432,9 @@ AttrValue
|
|
|
423
432
|
ValuePart
|
|
424
433
|
= &{ return !attrCode; } bs:$"\\"+ (&{ return bs.length % 2 === 1; } [{}])?
|
|
425
434
|
/ &{ return !attrCode; } "{" Selectors start:Here "/"? MacroName nameEnd:Here
|
|
426
|
-
&{
|
|
427
|
-
/ &{ return !attrCode; } "{" Selectors !("/"? [a-zA-Z]) CodeToBrace
|
|
428
|
-
/ &{ return attrCode; } "{" &[$_@%] CodeToBrace
|
|
435
|
+
&{ const end = hooks.closeBrace(input, nameEnd, start); return skipTo(end < 0 && completionMode ? input.length : end); } $(.|{ return skipEnd - offset(); }|) BraceEnd
|
|
436
|
+
/ &{ return !attrCode; } "{" Selectors !("/"? [a-zA-Z]) CodeToBrace BraceEnd
|
|
437
|
+
/ &{ return attrCode; } "{" &[$_@%] CodeToBrace BraceEnd
|
|
429
438
|
|
|
430
439
|
_
|
|
431
440
|
= _c*
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
import { createContext } from 'preact';
|
|
2
|
+
|
|
3
|
+
/** Initial render of a deferred passage subtree, until its first commit. */
|
|
4
|
+
export const EntryRenderContext = createContext<{ pending: boolean } | null>(
|
|
5
|
+
null,
|
|
6
|
+
);
|
|
7
|
+
|
|
1
8
|
/**
|
|
2
9
|
* Navigation id (the store's `navigationId`) of the passage most recently
|
|
3
10
|
* mounted by <Passage> (null until the first render, e.g. when the story
|