/
Code.ts
525 lines (482 loc) · 12.3 KB
/
Code.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import {
BBox,
createSignal,
experimentalLog,
map,
SerializedVector2,
Signal,
SignalValue,
SimpleSignal,
ThreadGenerator,
TimingFunction,
unwrap,
useLogger,
useScene,
Vector2,
} from '@motion-canvas/core';
import {
CodeCursor,
CodeFragmentDrawingInfo,
CodeHighlighter,
CodePoint,
CodeRange,
CodeSelection,
CodeSignal,
codeSignal,
CodeSignalContext,
findAllCodeRanges,
isPointInCodeSelection,
lines,
parseCodeSelection,
PossibleCodeScope,
PossibleCodeSelection,
resolveScope,
} from '../code';
import {computed, initial, nodeName, parser, signal} from '../decorators';
import {DesiredLength} from '../partials';
import {Shape, ShapeProps} from './Shape';
/**
* @experimental
*/
export interface DrawTokenHook {
(
ctx: CanvasRenderingContext2D,
text: string,
position: Vector2,
color: string,
selection: number,
): void;
}
/**
* Describes custom drawing logic used by the Code node.
*
* @experimental
*/
export interface DrawHooks {
/**
* Custom drawing logic for individual code tokens.
*
* @example
* ```ts
* token(ctx, text, position, color, selection) {
* const blur = map(3, 0, selection);
* const alpha = map(0.5, 1, selection);
* ctx.globalAlpha *= alpha;
* ctx.filter = `blur(${blur}px)`;
* ctx.fillStyle = color;
* ctx.fillText(text, position.x, position.y);
* }
* ```
*/
token: DrawTokenHook;
}
export interface CodeProps extends ShapeProps {
/**
* {@inheritDoc Code.highlighter}
*/
highlighter?: SignalValue<CodeHighlighter | null>;
/**
* {@inheritDoc Code.code}
*/
code?: SignalValue<PossibleCodeScope>;
/**
* {@inheritDoc Code.selection}
*/
selection?: SignalValue<PossibleCodeSelection>;
/**
* {@inheritDoc Code.drawHooks}
*/
drawHooks?: SignalValue<DrawHooks>;
}
/**
* A node for displaying and animating code.
*
* @preview
* ```tsx editor
* import {Code, makeScene2D} from '@motion-canvas/2d';
* import {createRef} from '@motion-canvas/core';
*
* export default makeScene2D(function* (view) {
* const code = createRef<Code>();
*
* view.add(
* <Code
* ref={code}
* offset={-1}
* position={view.size().scale(-0.5).add(60)}
* fontFamily={'JetBrains Mono, monospace'}
* fontSize={36}
* code={`\
* function hello() {
* console.log('Hello');
* }`}
* />,
* );
*
* yield* code()
* .code(
* `\
* function hello() {
* console.warn('Hello World');
* }`,
* 1,
* )
* .wait(0.5)
* .back(1)
* .wait(0.5);
* });
* ```
*/
@nodeName('CodeBlock')
export class Code extends Shape {
/**
* Create a standalone code signal.
*
* @param initial - The initial code.
* @param highlighter - Custom highlighter to use.
*/
public static createSignal(
initial: SignalValue<PossibleCodeScope>,
highlighter?: SignalValue<CodeHighlighter>,
): CodeSignal<void> {
return new CodeSignalContext<void>(
initial,
undefined,
highlighter,
).toSignal();
}
public static defaultHighlighter: CodeHighlighter | null = null;
/**
* The code highlighter to use for this code node.
*
* @remarks
* Defaults to a shared {@link code.LezerHighlighter}.
*/
@initial(() => Code.defaultHighlighter)
@signal()
public declare readonly highlighter: SimpleSignal<
CodeHighlighter | null,
this
>;
/**
* The code to display.
*/
@codeSignal()
public declare readonly code: CodeSignal<this>;
/**
* Custom drawing logic for the code.
*
* @remarks
* Check out {@link DrawHooks} for available render hooks.
*
* @experimental
*
* @example
* Make the unselected code blurry and transparent:
* ```tsx
* <Code
* drawHooks={{
* token(ctx, text, position, color, selection) {
* const blur = map(3, 0, selection);
* const alpha = map(0.5, 1, selection);
* ctx.globalAlpha *= alpha;
* ctx.filter = `blur(${blur}px)`;
* ctx.fillStyle = color;
* ctx.fillText(text, position.x, position.y);
* },
* }}
* // ...
* />
* ```
*/
@initial<DrawHooks>({
token(ctx, text, position, color, selection) {
ctx.fillStyle = color;
ctx.globalAlpha *= map(0.2, 1, selection);
ctx.fillText(text, position.x, position.y);
},
})
@signal()
public declare readonly drawHooks: SimpleSignal<DrawHooks, this>;
protected setDrawHooks(value: DrawHooks) {
if (
!useScene().experimentalFeatures &&
value !== this.drawHooks.context.getInitial()
) {
useLogger().log({
...experimentalLog(`Code uses experimental draw hooks.`),
inspect: this.key,
});
} else {
this.drawHooks.context.setter(value);
}
}
/**
* The currently selected code range.
*
* @remarks
* Either a single {@link code.CodeRange} or an array of them
* describing which parts of the code should be visually emphasized.
*
* You can use {@link code.word} and
* {@link code.lines} to quickly create ranges.
*
* @example
* The following will select the word "console" in the code.
* Both lines and columns are 0-based. So it will select a 7-character-long
* (`7`) word in the second line (`1`) starting at the third character (`2`).
* ```tsx
* <Code
* selection={word(1, 2, 7)}
* code={`\
* function hello() => {
* console.log('Hello');
* }`}
* // ...
* />
* ```
*/
@initial(lines(0, Infinity))
@parser(parseCodeSelection)
@signal()
public declare readonly selection: Signal<
PossibleCodeSelection,
CodeSelection,
this
>;
public oldSelection: CodeSelection | null = null;
public selectionProgress = createSignal<number | null>(null);
protected *tweenSelection(
value: CodeRange[],
duration: number,
timingFunction: TimingFunction,
): ThreadGenerator {
this.oldSelection = this.selection();
this.selection(value);
this.selectionProgress(0);
yield* this.selectionProgress(1, duration, timingFunction);
this.selectionProgress(null);
this.oldSelection = null;
}
/**
* Get the currently displayed code as a string.
*/
@computed()
public parsed(): string {
return resolveScope(this.code(), scope => unwrap(scope.progress) > 0.5);
}
@computed()
public highlighterCache() {
const highlighter = this.highlighter();
if (!highlighter || !highlighter.initialize()) return null;
const code = this.code();
const before = resolveScope(code, false);
const after = resolveScope(code, true);
return {
before: highlighter.prepare(before),
after: highlighter.prepare(after),
};
}
private cursorCache: CodeCursor | undefined;
private get cursor() {
this.cursorCache ??= new CodeCursor(this);
return this.cursorCache;
}
public constructor(props: CodeProps) {
super({
fontFamily: 'monospace',
...props,
});
}
/**
* Create a child code signal.
*
* @param initial - The initial code.
*/
public createSignal(
initial: SignalValue<PossibleCodeScope>,
): CodeSignal<this> {
return new CodeSignalContext<this>(
initial,
this,
this.highlighter,
).toSignal();
}
/**
* Find all code ranges that match the given pattern.
*
* @param pattern - Either a string or a regular expression to match.
*/
public findAllRanges(pattern: string | RegExp): CodeRange[] {
return findAllCodeRanges(this.parsed(), pattern);
}
/**
* Find the first code range that matches the given pattern.
*
* @param pattern - Either a string or a regular expression to match.
*/
public findFirstRange(pattern: string | RegExp): CodeRange {
return (
findAllCodeRanges(this.parsed(), pattern, 1)[0] ?? [
[0, 0],
[0, 0],
]
);
}
/**
* Find the last code range that matches the given pattern.
*
* @param pattern - Either a string or a regular expression to match.
*/
public findLastRange(pattern: string | RegExp): CodeRange {
return (
findAllCodeRanges(this.parsed(), pattern).at(-1) ?? [
[0, 0],
[0, 0],
]
);
}
/**
* Return the bounding box of the given point (character) in the code.
*
* @remarks
* The returned bound box is in local space of the `Code` node.
*
* @param point - The point to get the bounding box for.
*/
public getPointBBox(point: CodePoint): BBox {
const [line, column] = point;
const drawingInfo = this.drawingInfo();
let match: CodeFragmentDrawingInfo | undefined;
for (const info of drawingInfo.fragments) {
if (info.cursor.y < line) {
match = info;
continue;
}
if (info.cursor.y === line && info.cursor.x < column) {
match = info;
continue;
}
break;
}
if (!match) return new BBox();
const size = this.computedSize();
return new BBox(
match.position
.sub(size.scale(0.5))
.addX(match.characterSize.x * (column - match.cursor.x)),
match.characterSize,
);
}
/**
* Return bounding boxes of all characters in the selection.
*
* @remarks
* The returned bounding boxes are in local space of the `Code` node.
* Each line of code has a separate bounding box.
*
* @param selection - The selection to get the bounding boxes for.
*/
public getSelectionBBox(selection: PossibleCodeSelection): BBox[] {
const size = this.computedSize();
const range = parseCodeSelection(selection);
const drawingInfo = this.drawingInfo();
const bboxes: BBox[] = [];
let current: BBox | null = null;
let line = 0;
let column = 0;
for (const info of drawingInfo.fragments) {
if (info.cursor.y !== line) {
line = info.cursor.y;
if (current) {
bboxes.push(current);
current = null;
}
}
column = info.cursor.x;
for (let i = 0; i < info.text.length; i++) {
if (isPointInCodeSelection([line, column], range)) {
const bbox = new BBox(
info.position
.sub(size.scale(0.5))
.addX(info.characterSize.x * (column - info.cursor.x)),
info.characterSize,
);
if (!current) {
current = bbox;
} else {
current = current.union(bbox);
}
} else if (current) {
bboxes.push(current);
current = null;
}
column++;
}
}
if (current) {
bboxes.push(current);
}
return bboxes;
}
@computed()
protected drawingInfo() {
this.requestFontUpdate();
const context = this.cacheCanvas();
const code = this.code();
context.save();
this.applyStyle(context);
this.applyText(context);
this.cursor.setupDraw(context);
this.cursor.drawScope(code);
const info = this.cursor.getDrawingInfo();
context.restore();
return info;
}
protected override desiredSize(): SerializedVector2<DesiredLength> {
this.requestFontUpdate();
const context = this.cacheCanvas();
const code = this.code();
context.save();
this.applyStyle(context);
this.applyText(context);
this.cursor.setupMeasure(context);
this.cursor.measureSize(code);
const size = this.cursor.getSize();
context.restore();
return size;
}
protected override draw(context: CanvasRenderingContext2D): void {
this.requestFontUpdate();
this.applyStyle(context);
this.applyText(context);
const size = this.computedSize();
const drawingInfo = this.drawingInfo();
context.save();
context.translate(
-size.width / 2,
-size.height / 2 + drawingInfo.verticalOffset,
);
const drawHooks = this.drawHooks();
for (const info of drawingInfo.fragments) {
context.save();
context.globalAlpha *= info.alpha;
drawHooks.token(context, info.text, info.position, info.fill, info.time);
context.restore();
}
context.restore();
this.drawChildren(context);
}
protected override applyText(context: CanvasRenderingContext2D) {
super.applyText(context);
context.font = this.styles.font;
context.textBaseline = 'top';
if ('letterSpacing' in context) {
context.letterSpacing = this.styles.letterSpacing;
}
}
protected override collectAsyncResources(): void {
super.collectAsyncResources();
this.highlighter()?.initialize();
}
}