@motionscript/code 0.0.0-stage → 0.1.0-alpha.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.
- package/CHANGELOG.md +5 -0
- package/LICENSE +201 -0
- package/README.md +76 -3
- package/dist/browser/chunks/chunk-HET2RCSD.js +2 -0
- package/dist/browser/chunks/chunk-HET2RCSD.js.map +7 -0
- package/dist/browser/chunks/chunk-SYZUZB3M.js +2 -0
- package/dist/browser/chunks/chunk-SYZUZB3M.js.map +7 -0
- package/dist/browser/chunks/dist-3F5TQHM6.js +2 -0
- package/dist/browser/chunks/dist-3F5TQHM6.js.map +7 -0
- package/dist/browser/chunks/dist-3SIR23P4.js +2 -0
- package/dist/browser/chunks/dist-3SIR23P4.js.map +7 -0
- package/dist/browser/chunks/dist-AQRNACF3.js +2 -0
- package/dist/browser/chunks/dist-AQRNACF3.js.map +7 -0
- package/dist/browser/chunks/dist-B46VH2YP.js +2 -0
- package/dist/browser/chunks/dist-B46VH2YP.js.map +7 -0
- package/dist/browser/chunks/dist-FH6BHJ6A.js +7 -0
- package/dist/browser/chunks/dist-FH6BHJ6A.js.map +7 -0
- package/dist/browser/chunks/dist-FQDUBZKU.js +2 -0
- package/dist/browser/chunks/dist-FQDUBZKU.js.map +7 -0
- package/dist/browser/chunks/dist-GPNEVCJI.js +2 -0
- package/dist/browser/chunks/dist-GPNEVCJI.js.map +7 -0
- package/dist/browser/chunks/dist-LRSXSDHT.js +2 -0
- package/dist/browser/chunks/dist-LRSXSDHT.js.map +7 -0
- package/dist/browser/chunks/dist-N4CNBNHL.js +2 -0
- package/dist/browser/chunks/dist-N4CNBNHL.js.map +7 -0
- package/dist/browser/chunks/dist-OXJDTPQ6.js +2 -0
- package/dist/browser/chunks/dist-OXJDTPQ6.js.map +7 -0
- package/dist/browser/chunks/dist-SH7H4MRK.js +2 -0
- package/dist/browser/chunks/dist-SH7H4MRK.js.map +7 -0
- package/dist/browser/chunks/dist-UG3NTKWL.js +2 -0
- package/dist/browser/chunks/dist-UG3NTKWL.js.map +7 -0
- package/dist/browser/chunks/dist-W5ZXIMV7.js +2 -0
- package/dist/browser/chunks/dist-W5ZXIMV7.js.map +7 -0
- package/dist/browser/index.js +8 -0
- package/dist/browser/index.js.map +7 -0
- package/dist/browser/manifest.json +11 -0
- package/dist/code-range.d.ts +69 -0
- package/dist/code-range.d.ts.map +1 -0
- package/dist/code-range.js +124 -0
- package/dist/code-range.js.map +1 -0
- package/dist/diff.d.ts +42 -0
- package/dist/diff.d.ts.map +1 -0
- package/dist/diff.js +179 -0
- package/dist/diff.js.map +1 -0
- package/dist/engine.d.ts +15 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +17 -0
- package/dist/engine.js.map +1 -0
- package/dist/highlight.d.ts +43 -0
- package/dist/highlight.d.ts.map +1 -0
- package/dist/highlight.js +243 -0
- package/dist/highlight.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/layout.d.ts +77 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/layout.js +74 -0
- package/dist/layout.js.map +1 -0
- package/dist/measure-cache.d.ts +38 -0
- package/dist/measure-cache.d.ts.map +1 -0
- package/dist/measure-cache.js +0 -0
- package/dist/measure-cache.js.map +1 -0
- package/dist/node.d.ts +293 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +733 -0
- package/dist/node.js.map +1 -0
- package/dist/nodes.d.ts +18 -0
- package/dist/nodes.d.ts.map +1 -0
- package/dist/nodes.js +18 -0
- package/dist/nodes.js.map +1 -0
- package/dist/render.d.ts +28 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/render.js +223 -0
- package/dist/render.js.map +1 -0
- package/dist/style.d.ts +88 -0
- package/dist/style.d.ts.map +1 -0
- package/dist/style.js +203 -0
- package/dist/style.js.map +1 -0
- package/dist/tokens.d.ts +24 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +50 -0
- package/dist/tokens.js.map +1 -0
- package/dist/transitions.d.ts +115 -0
- package/dist/transitions.d.ts.map +1 -0
- package/dist/transitions.js +85 -0
- package/dist/transitions.js.map +1 -0
- package/package.json +82 -3
- package/registry.json +6 -0
- package/src/code-range.ts +156 -0
- package/src/diff.ts +216 -0
- package/src/engine.ts +21 -0
- package/src/highlight.ts +291 -0
- package/src/index.ts +3 -0
- package/src/layout.ts +157 -0
- package/src/measure-cache.ts +0 -0
- package/src/node.ts +834 -0
- package/src/nodes.ts +18 -0
- package/src/render.ts +247 -0
- package/src/style.ts +251 -0
- package/src/tokens.ts +75 -0
- package/src/transitions.ts +184 -0
package/src/highlight.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { Parser, Tree } from "@lezer/common";
|
|
2
|
+
import { highlightTree } from "@lezer/highlight";
|
|
3
|
+
import {
|
|
4
|
+
BUILTIN_THEMES,
|
|
5
|
+
CodeHighlightStyle,
|
|
6
|
+
CodeTheme,
|
|
7
|
+
DefaultHighlightStyle,
|
|
8
|
+
compileStyle,
|
|
9
|
+
} from "./style";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Lezer-backed syntax highlighting for the Code component, replacing the former
|
|
13
|
+
* Shiki wiring. This mirrors Motion Canvas's `LezerHighlighter`:
|
|
14
|
+
*
|
|
15
|
+
* - {@link prepareHighlight} parses code once and builds a `from:to` → color map
|
|
16
|
+
* by walking {@link highlightTree}.
|
|
17
|
+
* - {@link tokenizeCode} splits code at parse-tree leaf boundaries.
|
|
18
|
+
* - {@link highlightAt} resolves the color (and run length) for a character index.
|
|
19
|
+
*
|
|
20
|
+
* Parsers load lazily and asynchronously (dynamic import) so the bundle doesn't
|
|
21
|
+
* pull in every grammar. The node's asset loader awaits {@link ensureHighlighter}
|
|
22
|
+
* before tokenizing; until a parser resolves, callers fall back to plain text and
|
|
23
|
+
* re-tokenize once {@link canHighlight} returns true.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** Dynamic-import factories for each supported language → a Lezer {@link Parser}. */
|
|
27
|
+
const LANGUAGE_LOADERS: Record<string, () => Promise<Parser>> = {
|
|
28
|
+
typescript: async () => (await import("@lezer/javascript")).parser.configure({ dialect: "ts" }),
|
|
29
|
+
tsx: async () => (await import("@lezer/javascript")).parser.configure({ dialect: "ts jsx" }),
|
|
30
|
+
javascript: async () => (await import("@lezer/javascript")).parser,
|
|
31
|
+
jsx: async () => (await import("@lezer/javascript")).parser.configure({ dialect: "jsx" }),
|
|
32
|
+
python: async () => (await import("@lezer/python")).parser,
|
|
33
|
+
json: async () => (await import("@lezer/json")).parser,
|
|
34
|
+
html: async () => (await import("@lezer/html")).parser,
|
|
35
|
+
css: async () => (await import("@lezer/css")).parser,
|
|
36
|
+
rust: async () => (await import("@lezer/rust")).parser,
|
|
37
|
+
go: async () => (await import("@lezer/go")).parser,
|
|
38
|
+
java: async () => (await import("@lezer/java")).parser,
|
|
39
|
+
cpp: async () => (await import("@lezer/cpp")).parser,
|
|
40
|
+
php: async () => (await import("@lezer/php")).parser,
|
|
41
|
+
markdown: async () => (await import("@lezer/markdown")).parser,
|
|
42
|
+
xml: async () => (await import("@lezer/xml")).parser,
|
|
43
|
+
yaml: async () => (await import("@lezer/yaml")).parser,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// Aliases so common language strings resolve to a loader above.
|
|
47
|
+
const LANGUAGE_ALIASES: Record<string, string> = {
|
|
48
|
+
ts: "typescript",
|
|
49
|
+
js: "javascript",
|
|
50
|
+
py: "python",
|
|
51
|
+
"c++": "cpp",
|
|
52
|
+
md: "markdown",
|
|
53
|
+
yml: "yaml",
|
|
54
|
+
shell: "javascript", // no shell grammar bundled; fall back rather than throw
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
function resolveLanguageKey(language: string): string {
|
|
58
|
+
const key = language.toLowerCase();
|
|
59
|
+
return LANGUAGE_ALIASES[key] ?? key;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Loaded parsers and in-flight loads, keyed by resolved language key, so
|
|
63
|
+
// concurrent Code nodes asking for the same language share one dynamic import.
|
|
64
|
+
const loadedParsers = new Map<string, Parser>();
|
|
65
|
+
const inFlightLangs = new Map<string, Promise<Parser | null>>();
|
|
66
|
+
|
|
67
|
+
export const DEFAULT_THEMES = [DefaultHighlightStyle.name];
|
|
68
|
+
export const DEFAULT_LANGS = ["typescript", "javascript", "json", "python"];
|
|
69
|
+
|
|
70
|
+
// Theme registry, seeded with the built-ins (Motion Canvas default + GitHub
|
|
71
|
+
// dark/light). The `theme` prop is a string name or a CodeHighlightStyle object;
|
|
72
|
+
// apps can register additional styles by name and reference them by that name.
|
|
73
|
+
const themesByName = new Map<string, CodeHighlightStyle>(Object.entries(BUILTIN_THEMES));
|
|
74
|
+
|
|
75
|
+
/** Register a custom {@link CodeHighlightStyle} so Code nodes can reference it by name. */
|
|
76
|
+
export function registerCodeTheme(style: CodeHighlightStyle): void {
|
|
77
|
+
themesByName.set(style.name, style);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Resolve a theme reference (a registered name, or a CodeHighlightStyle object)
|
|
82
|
+
* to a concrete style. Unknown names fall back to the Motion Canvas default so a
|
|
83
|
+
* stray theme string never throws.
|
|
84
|
+
*/
|
|
85
|
+
export function resolveTheme(theme: CodeTheme): CodeHighlightStyle {
|
|
86
|
+
if (typeof theme !== "string") return theme;
|
|
87
|
+
return themesByName.get(theme) ?? DefaultHighlightStyle;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Has `language` finished loading its parser? */
|
|
91
|
+
function isLanguageLoaded(language: string): boolean {
|
|
92
|
+
return loadedParsers.has(resolveLanguageKey(language));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Load the parsers for `langs` (themes are synchronous, so they're a no-op here
|
|
97
|
+
* but kept in the signature for API parity with the former Shiki implementation).
|
|
98
|
+
* Resolves once every requested language's parser is available. Unknown languages
|
|
99
|
+
* resolve without loading anything — {@link canHighlight} stays false for them and
|
|
100
|
+
* the node renders them as plain text.
|
|
101
|
+
*/
|
|
102
|
+
export function ensureHighlighter(
|
|
103
|
+
_themes: string[] = DEFAULT_THEMES,
|
|
104
|
+
langs: string[] = DEFAULT_LANGS,
|
|
105
|
+
): Promise<void> {
|
|
106
|
+
const jobs: Promise<unknown>[] = [];
|
|
107
|
+
|
|
108
|
+
for (const lang of langs) {
|
|
109
|
+
const key = resolveLanguageKey(lang);
|
|
110
|
+
if (loadedParsers.has(key)) continue;
|
|
111
|
+
|
|
112
|
+
const loader = LANGUAGE_LOADERS[key];
|
|
113
|
+
if (!loader) continue; // unsupported language; leave it unhighlighted
|
|
114
|
+
|
|
115
|
+
let job = inFlightLangs.get(key);
|
|
116
|
+
if (!job) {
|
|
117
|
+
job = loader()
|
|
118
|
+
.then(parser => {
|
|
119
|
+
loadedParsers.set(key, parser);
|
|
120
|
+
return parser;
|
|
121
|
+
})
|
|
122
|
+
.catch(() => null)
|
|
123
|
+
.finally(() => inFlightLangs.delete(key));
|
|
124
|
+
inFlightLangs.set(key, job);
|
|
125
|
+
}
|
|
126
|
+
jobs.push(job);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return jobs.length === 0 ? Promise.resolve() : Promise.all(jobs).then(() => undefined);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Load a syntax-highlight language into the shared highlighter. Exposed so a Code
|
|
134
|
+
* node's asset loader can run it on the timeline, and so apps can preload
|
|
135
|
+
* languages explicitly. Returns once the parser is ready (or immediately for an
|
|
136
|
+
* unsupported language). The `theme` arg is accepted for backwards compatibility.
|
|
137
|
+
*/
|
|
138
|
+
export async function loadCodeLanguage(language: string, _theme?: string): Promise<void> {
|
|
139
|
+
await ensureHighlighter(DEFAULT_THEMES, [language]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function initSyntaxHighlighter(
|
|
143
|
+
themes: string[] = DEFAULT_THEMES,
|
|
144
|
+
langs: string[] = DEFAULT_LANGS,
|
|
145
|
+
): Promise<void> {
|
|
146
|
+
await ensureHighlighter(themes, langs);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** True once `language` can be tokenized (its parser has loaded). */
|
|
150
|
+
export function canHighlight(language: string, _theme?: CodeTheme): boolean {
|
|
151
|
+
return isLanguageLoaded(language);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A parsed-and-prepared highlight cache for one snapshot of code. */
|
|
155
|
+
interface HighlightCache {
|
|
156
|
+
tree: Tree;
|
|
157
|
+
code: string;
|
|
158
|
+
// `${from}:${to}` node id → color, exactly as Motion Canvas keys it.
|
|
159
|
+
colorLookup: Map<string, string>;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function nodeId(from: number, to: number): string {
|
|
163
|
+
return `${from}:${to}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Parse `code` and build the per-node color map. Mirrors Motion Canvas's
|
|
168
|
+
* `LezerHighlighter.prepare`: for each highlighted range, walk the subtree and
|
|
169
|
+
* record the color against every contained node's `from:to` id, so a later
|
|
170
|
+
* {@link highlightAt} lookup by `resolveInner` index finds it.
|
|
171
|
+
*/
|
|
172
|
+
function prepareHighlight(code: string, language: string, style: CodeHighlightStyle): HighlightCache | null {
|
|
173
|
+
const parser = loadedParsers.get(resolveLanguageKey(language));
|
|
174
|
+
if (!parser) return null;
|
|
175
|
+
|
|
176
|
+
const tree = parser.parse(code);
|
|
177
|
+
const highlighter = compileStyle(style);
|
|
178
|
+
const colorLookup = new Map<string, string>();
|
|
179
|
+
|
|
180
|
+
highlightTree(tree, highlighter, (from, to, classes) => {
|
|
181
|
+
// tagHighlighter emits our color string as the "class".
|
|
182
|
+
const color = classes;
|
|
183
|
+
if (!color) return;
|
|
184
|
+
const cursor = tree.cursorAt(from, 1);
|
|
185
|
+
do {
|
|
186
|
+
colorLookup.set(nodeId(cursor.from, cursor.to), color);
|
|
187
|
+
} while (cursor.next() && cursor.to <= to);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
return { tree, code, colorLookup };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Resolve the color and run length for the token starting at `index`. Mirrors
|
|
195
|
+
* Motion Canvas's `LezerHighlighter.highlight`: resolve the innermost node, look
|
|
196
|
+
* up its color, and report how far the run extends (`skipAhead`).
|
|
197
|
+
*/
|
|
198
|
+
function highlightAt(index: number, cache: HighlightCache): { color: string | null; skipAhead: number } {
|
|
199
|
+
const node = cache.tree.resolveInner(index, 1);
|
|
200
|
+
const color = cache.colorLookup.get(nodeId(node.from, node.to));
|
|
201
|
+
if (color) {
|
|
202
|
+
return { color, skipAhead: node.to - index };
|
|
203
|
+
}
|
|
204
|
+
// No color: skip past a childless (leaf) node so we don't re-resolve every char.
|
|
205
|
+
const skipAhead = node.firstChild ? 0 : node.to - index;
|
|
206
|
+
return { color: null, skipAhead };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Split `code` into structural tokens at parse-tree leaf boundaries, including the
|
|
211
|
+
* gaps between leaves (whitespace/punctuation). Mirrors Motion Canvas's
|
|
212
|
+
* `LezerHighlighter.tokenize`; this segmentation is what the token-level
|
|
213
|
+
* append/insert/erase/replace animations diff against, so matching it keeps the
|
|
214
|
+
* animation behavior identical to Motion Canvas.
|
|
215
|
+
*/
|
|
216
|
+
function tokenizeCode(code: string, language: string): string[] {
|
|
217
|
+
const parser = loadedParsers.get(resolveLanguageKey(language));
|
|
218
|
+
if (!parser) return [code];
|
|
219
|
+
|
|
220
|
+
const tree = parser.parse(code);
|
|
221
|
+
const cursor = tree.cursor();
|
|
222
|
+
const tokens: string[] = [];
|
|
223
|
+
let current = 0;
|
|
224
|
+
|
|
225
|
+
do {
|
|
226
|
+
if (!cursor.node.firstChild) {
|
|
227
|
+
if (cursor.from > current) tokens.push(code.slice(current, cursor.from));
|
|
228
|
+
if (cursor.from < cursor.to) tokens.push(code.slice(cursor.from, cursor.to));
|
|
229
|
+
current = cursor.to;
|
|
230
|
+
}
|
|
231
|
+
} while (cursor.next());
|
|
232
|
+
|
|
233
|
+
if (current < code.length) tokens.push(code.slice(current));
|
|
234
|
+
return tokens;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Tokenize `code` into per-line, colored tokens — the contract the rest of the
|
|
239
|
+
* Code component consumes. Combines {@link tokenizeCode} (structural split) with
|
|
240
|
+
* {@link highlightAt} (per-run color), then breaks tokens at newlines so each
|
|
241
|
+
* output line is a row of single-line, single-color tokens.
|
|
242
|
+
*
|
|
243
|
+
* Callers must have checked {@link canHighlight} first; this returns a single
|
|
244
|
+
* uncolored line per source line if the parser isn't loaded.
|
|
245
|
+
*/
|
|
246
|
+
export function highlightToTokens(
|
|
247
|
+
code: string,
|
|
248
|
+
language: string,
|
|
249
|
+
theme: CodeTheme = DefaultHighlightStyle,
|
|
250
|
+
): { content: string; color?: string }[][] {
|
|
251
|
+
const style = resolveTheme(theme);
|
|
252
|
+
const cache = prepareHighlight(code, language, style);
|
|
253
|
+
|
|
254
|
+
const lines: { content: string; color?: string }[][] = [[]];
|
|
255
|
+
const pushLine = () => lines.push([]);
|
|
256
|
+
|
|
257
|
+
if (!cache) {
|
|
258
|
+
// Parser unavailable: one uncolored token per source line.
|
|
259
|
+
return code.split("\n").map(line => [{ content: line, color: style.defaultColor }]);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Walk the structural tokens, coloring each by its starting index and
|
|
263
|
+
// splitting on newlines so no token spans rows.
|
|
264
|
+
let index = 0;
|
|
265
|
+
for (const token of tokenizeCode(code, language)) {
|
|
266
|
+
let offset = 0;
|
|
267
|
+
while (offset < token.length) {
|
|
268
|
+
const { color, skipAhead } = highlightAt(index + offset, cache);
|
|
269
|
+
// Extend the run as far as the highlight says, but never past this
|
|
270
|
+
// structural token and never across a newline (lines are drawn rows).
|
|
271
|
+
let runEnd = offset + Math.max(skipAhead, 1);
|
|
272
|
+
if (runEnd > token.length) runEnd = token.length;
|
|
273
|
+
const newlineRel = token.indexOf("\n", offset);
|
|
274
|
+
if (newlineRel !== -1 && newlineRel < runEnd) runEnd = newlineRel;
|
|
275
|
+
|
|
276
|
+
const slice = token.slice(offset, runEnd);
|
|
277
|
+
if (slice.length > 0) {
|
|
278
|
+
lines[lines.length - 1].push({ content: slice, color: color ?? style.defaultColor });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (newlineRel === runEnd) {
|
|
282
|
+
pushLine();
|
|
283
|
+
runEnd += 1; // consume the newline itself
|
|
284
|
+
}
|
|
285
|
+
offset = runEnd;
|
|
286
|
+
}
|
|
287
|
+
index += token.length;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return lines;
|
|
291
|
+
}
|
package/src/index.ts
ADDED
package/src/layout.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type { InsetsResolved, MeasureContext2D, RenderContext2D } from "@motionscript/core";
|
|
2
|
+
import type { TokenAdvanceCache } from "./measure-cache";
|
|
3
|
+
import type { IdLine } from "./tokens";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Everything about a listing's geometry that is *not* its content — the type,
|
|
7
|
+
* the padding, whether there is a gutter. Split out from the node so a layout
|
|
8
|
+
* can be computed for a token structure the node is no longer holding: during a
|
|
9
|
+
* structural transition the frame is the interpolation of two of them, and the
|
|
10
|
+
* one that is going away is not reachable through `this` any more.
|
|
11
|
+
*/
|
|
12
|
+
export interface CodeMetrics {
|
|
13
|
+
fontSize: number;
|
|
14
|
+
fontFamily: string;
|
|
15
|
+
lineHeight: number;
|
|
16
|
+
letterSpacing: number;
|
|
17
|
+
padding: InsetsResolved;
|
|
18
|
+
showLineNumbers: boolean;
|
|
19
|
+
lineNumberGap: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Where one token sits: its LEFT edge, and the vertical CENTRE of its line's slot. */
|
|
23
|
+
export interface TokenBox {
|
|
24
|
+
x: number;
|
|
25
|
+
y: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A resolved listing geometry: every token placed, in the node's own space
|
|
30
|
+
* (origin at the block's centre, y-up).
|
|
31
|
+
*
|
|
32
|
+
* Positions are absolute rather than "a running sum plus a width scale", which
|
|
33
|
+
* is the whole point. A token's place in the *next* structure is knowable
|
|
34
|
+
* without drawing it, so a transition can move a token from where it was to
|
|
35
|
+
* where it will be instead of faking the motion by collapsing the advance of
|
|
36
|
+
* its neighbours — which is what made an insert look like a pile of glyphs at
|
|
37
|
+
* the left margin springing apart.
|
|
38
|
+
*/
|
|
39
|
+
export interface CodeLayout {
|
|
40
|
+
/** Token id → placement. */
|
|
41
|
+
tokens: Map<number, TokenBox>;
|
|
42
|
+
/** Vertical centre of each line's slot, by line index. */
|
|
43
|
+
lineY: number[];
|
|
44
|
+
/**
|
|
45
|
+
* Width of each line's ink, by line index — the sum of its tokens' advances,
|
|
46
|
+
* so a blank line is `0` and a short line is short.
|
|
47
|
+
*
|
|
48
|
+
* Returned rather than kept local because it is the only thing that knows a
|
|
49
|
+
* listing is **ragged**: `innerW` is the longest line, and everything that
|
|
50
|
+
* asks where the text actually is (hit testing, for one) would otherwise have
|
|
51
|
+
* to treat the block as a rectangle the width of its longest row.
|
|
52
|
+
*/
|
|
53
|
+
lineW: number[];
|
|
54
|
+
/** Line id → its index in this structure (i.e. its line *number* minus one). */
|
|
55
|
+
lineIndex: Map<number, number>;
|
|
56
|
+
gutter: number;
|
|
57
|
+
gutterGap: number;
|
|
58
|
+
/** Content size, no padding. */
|
|
59
|
+
innerW: number;
|
|
60
|
+
innerH: number;
|
|
61
|
+
/** Content size plus padding — what the block draws and measures as. */
|
|
62
|
+
blockW: number;
|
|
63
|
+
blockH: number;
|
|
64
|
+
/** Left edge of the code column (after padding and gutter). */
|
|
65
|
+
startX: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Signature of everything a layout depends on other than the token structure
|
|
70
|
+
* itself. A cached layout survives exactly as long as this is unchanged.
|
|
71
|
+
*/
|
|
72
|
+
export function metricsSignature(m: CodeMetrics): string {
|
|
73
|
+
const p = m.padding;
|
|
74
|
+
return [
|
|
75
|
+
m.fontSize, m.fontFamily, m.lineHeight, m.letterSpacing,
|
|
76
|
+
p.left, p.right, p.top, p.bottom,
|
|
77
|
+
m.showLineNumbers ? 1 : 0, m.lineNumberGap,
|
|
78
|
+
].join("|");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Horizontal gap between the line-number column and the code text. Sized in
|
|
83
|
+
* space-widths so it scales with the font, and measured with letterSpacing 0 —
|
|
84
|
+
* line numbers and the gap don't carry the code's letter-spacing.
|
|
85
|
+
*/
|
|
86
|
+
function gutterGapOf(scope: MeasureContext2D | RenderContext2D, m: CodeMetrics, cache: TokenAdvanceCache): number {
|
|
87
|
+
return cache.advance(scope, " ", m.fontSize, m.fontFamily, 0) * m.lineNumberGap;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Width of the line-number column for a structure of `lineCount` lines, gap included. */
|
|
91
|
+
function gutterOf(
|
|
92
|
+
scope: MeasureContext2D | RenderContext2D,
|
|
93
|
+
m: CodeMetrics,
|
|
94
|
+
cache: TokenAdvanceCache,
|
|
95
|
+
lineCount: number,
|
|
96
|
+
gap: number,
|
|
97
|
+
): number {
|
|
98
|
+
if (!m.showLineNumbers) return 0;
|
|
99
|
+
const sample = String(Math.max(1, lineCount));
|
|
100
|
+
return cache.advance(scope, sample, m.fontSize, m.fontFamily, 0) + gap;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Place every token of `lines`.
|
|
105
|
+
*
|
|
106
|
+
* Pure in (lines, metrics, font measurements), which is what lets a caller cache
|
|
107
|
+
* one per structure rather than recomputing it per frame — a transition's two
|
|
108
|
+
* endpoints are both fixed for its whole duration.
|
|
109
|
+
*/
|
|
110
|
+
export function layoutCode(
|
|
111
|
+
lines: IdLine[],
|
|
112
|
+
m: CodeMetrics,
|
|
113
|
+
cache: TokenAdvanceCache,
|
|
114
|
+
scope: MeasureContext2D | RenderContext2D,
|
|
115
|
+
): CodeLayout {
|
|
116
|
+
const lineH = m.fontSize * m.lineHeight;
|
|
117
|
+
const gutterGap = m.showLineNumbers ? gutterGapOf(scope, m, cache) : 0;
|
|
118
|
+
const gutter = gutterOf(scope, m, cache, lines.length, gutterGap);
|
|
119
|
+
|
|
120
|
+
const widths: number[] = new Array(lines.length);
|
|
121
|
+
let maxLineWidth = 0;
|
|
122
|
+
for (let i = 0; i < lines.length; i++) {
|
|
123
|
+
let w = 0;
|
|
124
|
+
for (const tok of lines[i].tokens) {
|
|
125
|
+
w += cache.advance(scope, tok.content, m.fontSize, m.fontFamily, m.letterSpacing);
|
|
126
|
+
}
|
|
127
|
+
widths[i] = w;
|
|
128
|
+
if (w > maxLineWidth) maxLineWidth = w;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const innerW = maxLineWidth + gutter;
|
|
132
|
+
const innerH = lines.length * lineH;
|
|
133
|
+
const blockW = innerW + m.padding.left + m.padding.right;
|
|
134
|
+
const blockH = innerH + m.padding.top + m.padding.bottom;
|
|
135
|
+
const startX = -blockW / 2 + m.padding.left + gutter;
|
|
136
|
+
// y-up author space: the first line sits at the TOP of the block, so the
|
|
137
|
+
// cursor starts at the top edge (+half height, minus top padding) and steps
|
|
138
|
+
// DOWNWARD by subtracting a line height per row.
|
|
139
|
+
const startY = blockH / 2 - m.padding.top;
|
|
140
|
+
|
|
141
|
+
const tokens = new Map<number, TokenBox>();
|
|
142
|
+
const lineY: number[] = new Array(lines.length);
|
|
143
|
+
const lineIndex = new Map<number, number>();
|
|
144
|
+
|
|
145
|
+
for (let i = 0; i < lines.length; i++) {
|
|
146
|
+
const centerY = startY - i * lineH - lineH / 2;
|
|
147
|
+
lineY[i] = centerY;
|
|
148
|
+
lineIndex.set(lines[i].id, i);
|
|
149
|
+
let x = startX;
|
|
150
|
+
for (const tok of lines[i].tokens) {
|
|
151
|
+
tokens.set(tok.id, { x, y: centerY });
|
|
152
|
+
x += cache.advance(scope, tok.content, m.fontSize, m.fontFamily, m.letterSpacing);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return { tokens, lineY, lineW: widths, lineIndex, gutter, gutterGap, innerW, innerH, blockW, blockH, startX };
|
|
157
|
+
}
|
|
Binary file
|