@twick/2d 0.14.18 → 0.14.20

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.
Files changed (167) hide show
  1. package/LICENSE +21 -21
  2. package/editor/editor/tsconfig.build.tsbuildinfo +1 -1
  3. package/lib/components/Img.js +23 -23
  4. package/lib/components/Line.js +31 -31
  5. package/lib/components/Media.js +22 -22
  6. package/lib/components/Spline.js +25 -25
  7. package/lib/tsconfig.build.tsbuildinfo +1 -1
  8. package/package.json +4 -4
  9. package/src/editor/NodeInspectorConfig.tsx +76 -76
  10. package/src/editor/PreviewOverlayConfig.tsx +67 -67
  11. package/src/editor/Provider.tsx +93 -93
  12. package/src/editor/SceneGraphTabConfig.tsx +81 -81
  13. package/src/editor/icons/CircleIcon.tsx +7 -7
  14. package/src/editor/icons/CodeBlockIcon.tsx +8 -8
  15. package/src/editor/icons/CurveIcon.tsx +7 -7
  16. package/src/editor/icons/GridIcon.tsx +7 -7
  17. package/src/editor/icons/IconMap.ts +35 -35
  18. package/src/editor/icons/ImgIcon.tsx +8 -8
  19. package/src/editor/icons/LayoutIcon.tsx +9 -9
  20. package/src/editor/icons/LineIcon.tsx +7 -7
  21. package/src/editor/icons/NodeIcon.tsx +7 -7
  22. package/src/editor/icons/RayIcon.tsx +7 -7
  23. package/src/editor/icons/RectIcon.tsx +7 -7
  24. package/src/editor/icons/ShapeIcon.tsx +7 -7
  25. package/src/editor/icons/TxtIcon.tsx +8 -8
  26. package/src/editor/icons/VideoIcon.tsx +7 -7
  27. package/src/editor/icons/View2DIcon.tsx +10 -10
  28. package/src/editor/index.ts +17 -17
  29. package/src/editor/tree/DetachedRoot.tsx +23 -23
  30. package/src/editor/tree/NodeElement.tsx +74 -74
  31. package/src/editor/tree/TreeElement.tsx +72 -72
  32. package/src/editor/tree/TreeRoot.tsx +10 -10
  33. package/src/editor/tree/ViewRoot.tsx +20 -20
  34. package/src/editor/tree/index.module.scss +38 -38
  35. package/src/editor/tree/index.ts +3 -3
  36. package/src/editor/tsconfig.build.json +5 -5
  37. package/src/editor/tsconfig.json +12 -12
  38. package/src/editor/tsdoc.json +4 -4
  39. package/src/editor/vite-env.d.ts +1 -1
  40. package/src/lib/code/CodeCursor.ts +445 -445
  41. package/src/lib/code/CodeDiffer.ts +78 -78
  42. package/src/lib/code/CodeFragment.ts +97 -97
  43. package/src/lib/code/CodeHighlighter.ts +75 -75
  44. package/src/lib/code/CodeMetrics.ts +47 -47
  45. package/src/lib/code/CodeRange.test.ts +74 -74
  46. package/src/lib/code/CodeRange.ts +216 -216
  47. package/src/lib/code/CodeScope.ts +101 -101
  48. package/src/lib/code/CodeSelection.ts +24 -24
  49. package/src/lib/code/CodeSignal.ts +327 -327
  50. package/src/lib/code/CodeTokenizer.ts +54 -54
  51. package/src/lib/code/DefaultHighlightStyle.ts +98 -98
  52. package/src/lib/code/LezerHighlighter.ts +113 -113
  53. package/src/lib/code/diff.test.ts +311 -311
  54. package/src/lib/code/diff.ts +319 -319
  55. package/src/lib/code/extractRange.ts +126 -126
  56. package/src/lib/code/index.ts +13 -13
  57. package/src/lib/components/Audio.ts +168 -168
  58. package/src/lib/components/Bezier.ts +105 -105
  59. package/src/lib/components/Circle.ts +266 -266
  60. package/src/lib/components/Code.ts +526 -526
  61. package/src/lib/components/CodeBlock.ts +576 -576
  62. package/src/lib/components/CubicBezier.ts +112 -112
  63. package/src/lib/components/Curve.ts +455 -455
  64. package/src/lib/components/Grid.ts +135 -135
  65. package/src/lib/components/Icon.ts +96 -96
  66. package/src/lib/components/Img.ts +319 -319
  67. package/src/lib/components/Knot.ts +157 -157
  68. package/src/lib/components/Latex.ts +122 -122
  69. package/src/lib/components/Layout.ts +1092 -1092
  70. package/src/lib/components/Line.ts +429 -429
  71. package/src/lib/components/Media.ts +576 -576
  72. package/src/lib/components/Node.ts +1940 -1940
  73. package/src/lib/components/Path.ts +137 -137
  74. package/src/lib/components/Polygon.ts +171 -171
  75. package/src/lib/components/QuadBezier.ts +100 -100
  76. package/src/lib/components/Ray.ts +125 -125
  77. package/src/lib/components/Rect.ts +187 -187
  78. package/src/lib/components/Rive.ts +156 -156
  79. package/src/lib/components/SVG.ts +797 -797
  80. package/src/lib/components/Shape.ts +143 -143
  81. package/src/lib/components/Spline.ts +344 -344
  82. package/src/lib/components/Txt.test.tsx +81 -81
  83. package/src/lib/components/Txt.ts +203 -203
  84. package/src/lib/components/TxtLeaf.ts +205 -205
  85. package/src/lib/components/Video.ts +461 -461
  86. package/src/lib/components/View2D.ts +98 -98
  87. package/src/lib/components/__tests__/children.test.tsx +142 -142
  88. package/src/lib/components/__tests__/clone.test.tsx +126 -126
  89. package/src/lib/components/__tests__/generatorTest.ts +28 -28
  90. package/src/lib/components/__tests__/mockScene2D.ts +45 -45
  91. package/src/lib/components/__tests__/query.test.tsx +122 -122
  92. package/src/lib/components/__tests__/state.test.tsx +60 -60
  93. package/src/lib/components/index.ts +28 -28
  94. package/src/lib/components/types.ts +35 -35
  95. package/src/lib/curves/ArcSegment.ts +159 -159
  96. package/src/lib/curves/CircleSegment.ts +77 -77
  97. package/src/lib/curves/CubicBezierSegment.ts +78 -78
  98. package/src/lib/curves/CurveDrawingInfo.ts +11 -11
  99. package/src/lib/curves/CurvePoint.ts +15 -15
  100. package/src/lib/curves/CurveProfile.ts +7 -7
  101. package/src/lib/curves/KnotInfo.ts +10 -10
  102. package/src/lib/curves/LineSegment.ts +62 -62
  103. package/src/lib/curves/Polynomial.ts +355 -355
  104. package/src/lib/curves/Polynomial2D.ts +62 -62
  105. package/src/lib/curves/PolynomialSegment.ts +124 -124
  106. package/src/lib/curves/QuadBezierSegment.ts +64 -64
  107. package/src/lib/curves/Segment.ts +17 -17
  108. package/src/lib/curves/UniformPolynomialCurveSampler.ts +94 -94
  109. package/src/lib/curves/createCurveProfileLerp.ts +471 -471
  110. package/src/lib/curves/getBezierSplineProfile.ts +223 -223
  111. package/src/lib/curves/getCircleProfile.ts +86 -86
  112. package/src/lib/curves/getPathProfile.ts +178 -178
  113. package/src/lib/curves/getPointAtDistance.ts +21 -21
  114. package/src/lib/curves/getPolylineProfile.test.ts +21 -21
  115. package/src/lib/curves/getPolylineProfile.ts +89 -89
  116. package/src/lib/curves/getRectProfile.ts +139 -139
  117. package/src/lib/curves/index.ts +16 -16
  118. package/src/lib/decorators/canvasStyleSignal.ts +16 -16
  119. package/src/lib/decorators/colorSignal.ts +9 -9
  120. package/src/lib/decorators/compound.ts +72 -72
  121. package/src/lib/decorators/computed.ts +18 -18
  122. package/src/lib/decorators/defaultStyle.ts +18 -18
  123. package/src/lib/decorators/filtersSignal.ts +136 -136
  124. package/src/lib/decorators/index.ts +10 -10
  125. package/src/lib/decorators/initializers.ts +32 -32
  126. package/src/lib/decorators/nodeName.ts +13 -13
  127. package/src/lib/decorators/signal.test.ts +90 -90
  128. package/src/lib/decorators/signal.ts +345 -345
  129. package/src/lib/decorators/spacingSignal.ts +15 -15
  130. package/src/lib/decorators/vector2Signal.ts +30 -30
  131. package/src/lib/globals.d.ts +2 -2
  132. package/src/lib/index.ts +8 -8
  133. package/src/lib/jsx-dev-runtime.ts +2 -2
  134. package/src/lib/jsx-runtime.ts +46 -46
  135. package/src/lib/parse-svg-path.d.ts +14 -14
  136. package/src/lib/partials/Filter.ts +180 -180
  137. package/src/lib/partials/Gradient.ts +102 -102
  138. package/src/lib/partials/Pattern.ts +34 -34
  139. package/src/lib/partials/ShaderConfig.ts +117 -117
  140. package/src/lib/partials/index.ts +4 -4
  141. package/src/lib/partials/types.ts +58 -58
  142. package/src/lib/scenes/Scene2D.ts +242 -242
  143. package/src/lib/scenes/index.ts +3 -3
  144. package/src/lib/scenes/makeScene2D.ts +16 -16
  145. package/src/lib/scenes/useScene2D.ts +6 -6
  146. package/src/lib/tsconfig.build.json +5 -5
  147. package/src/lib/tsconfig.json +10 -10
  148. package/src/lib/tsdoc.json +4 -4
  149. package/src/lib/utils/CanvasUtils.ts +306 -306
  150. package/src/lib/utils/diff.test.ts +453 -453
  151. package/src/lib/utils/diff.ts +148 -148
  152. package/src/lib/utils/index.ts +2 -2
  153. package/src/lib/utils/is.ts +11 -11
  154. package/src/lib/utils/makeSignalExtensions.ts +30 -30
  155. package/src/lib/utils/video/declarations.d.ts +1 -1
  156. package/src/lib/utils/video/ffmpeg-client.ts +50 -50
  157. package/src/lib/utils/video/mp4-parser-manager.ts +72 -72
  158. package/src/lib/utils/video/parser/index.ts +1 -1
  159. package/src/lib/utils/video/parser/parser.ts +257 -257
  160. package/src/lib/utils/video/parser/sampler.ts +72 -72
  161. package/src/lib/utils/video/parser/segment.ts +302 -302
  162. package/src/lib/utils/video/parser/sink.ts +29 -29
  163. package/src/lib/utils/video/parser/utils.ts +31 -31
  164. package/src/tsconfig.base.json +19 -19
  165. package/src/tsconfig.build.json +8 -8
  166. package/src/tsconfig.json +5 -5
  167. package/tsconfig.project.json +7 -7
@@ -1,576 +1,576 @@
1
- import type {
2
- SerializedVector2,
3
- Signal,
4
- SignalValue,
5
- SimpleSignal,
6
- ThreadGenerator,
7
- TimingFunction,
8
- } from '@twick/core';
9
- import {
10
- Vector2,
11
- clampRemap,
12
- createComputedAsync,
13
- createSignal,
14
- easeInOutSine,
15
- join,
16
- map,
17
- threadable,
18
- tween,
19
- useLogger,
20
- waitFor,
21
- } from '@twick/core';
22
- import type {Code, CodeStyle, CodeTree, MorphToken, Token} from 'code-fns';
23
- import {diff, parse, ready} from 'code-fns';
24
- import {computed, initial, nodeName, parser, signal} from '../decorators';
25
- import type {DesiredLength} from '../partials';
26
- import type {ShapeProps} from './Shape';
27
- import {Shape} from './Shape';
28
-
29
- type CodePoint = [number, number];
30
- type CodeRange = [CodePoint, CodePoint];
31
-
32
- export interface CodeProps extends ShapeProps {
33
- language?: string;
34
- children?: Code;
35
- code?: SignalValue<Code>;
36
- selection?: CodeRange[];
37
- theme?: CodeStyle;
38
- }
39
-
40
- export interface CodeModification {
41
- from: Code;
42
- to: Code;
43
- }
44
-
45
- /**
46
- * @deprecated Use {@link Code} instead.
47
- */
48
- @nodeName('CodeBlock')
49
- export class CodeBlock extends Shape {
50
- private static initialized = createComputedAsync(
51
- () => ready().then(() => true),
52
- false,
53
- );
54
-
55
- @initial('tsx')
56
- @signal()
57
- public declare readonly language: SimpleSignal<string, this>;
58
-
59
- @initial('')
60
- @parser(function (this: CodeBlock, value: Code): CodeTree {
61
- return typeof value === 'string'
62
- ? {
63
- language: this.language(),
64
- spans: [value],
65
- nodes: [],
66
- }
67
- : value;
68
- })
69
- @signal()
70
- public declare readonly code: Signal<Code, CodeTree, this>;
71
-
72
- @initial(undefined)
73
- @signal()
74
- public declare readonly theme: Signal<CodeStyle | null, CodeStyle, this>;
75
-
76
- @initial(lines(0, Infinity))
77
- @signal()
78
- public declare readonly selection: SimpleSignal<CodeRange[], this>;
79
-
80
- protected *tweenSelection(
81
- value: CodeRange[],
82
- duration: number,
83
- timingFunction: TimingFunction,
84
- ): ThreadGenerator {
85
- this.oldSelection = this.selection();
86
- this.selection(value);
87
- this.selectionProgress(0);
88
- yield* this.selectionProgress(1, duration, timingFunction);
89
- this.selectionProgress(null);
90
- this.oldSelection = null;
91
- }
92
-
93
- @initial(0.32)
94
- @signal()
95
- public declare readonly unselectedOpacity: SimpleSignal<number, this>;
96
-
97
- private codeProgress = createSignal<number | null>(null);
98
- private selectionProgress = createSignal<number | null>(null);
99
- private oldSelection: CodeRange[] | null = null;
100
- private diffed: MorphToken[] | null = null;
101
- private currentLineCount = 0;
102
- private newLineCount = 0;
103
-
104
- protected getLineCountOfTokenArray(tokens: Token[]): number {
105
- let count = 0;
106
-
107
- for (const token of tokens) {
108
- for (let i = 0; i < token.code.length; i++) {
109
- if (token.code[i] === '\n') {
110
- count++;
111
- }
112
- }
113
- }
114
-
115
- if (tokens.length > 0) {
116
- count++;
117
- }
118
-
119
- return count;
120
- }
121
-
122
- @computed()
123
- public lineCount(): number {
124
- const progress = this.codeProgress();
125
- if (progress !== null) {
126
- return Math.round(
127
- map(this.currentLineCount, this.newLineCount, progress),
128
- );
129
- }
130
-
131
- return this.getLineCountOfTokenArray(this.parsed());
132
- }
133
-
134
- @computed()
135
- protected parsed() {
136
- if (!CodeBlock.initialized()) {
137
- return [];
138
- }
139
-
140
- return parse(this.code(), {codeStyle: this.theme()});
141
- }
142
-
143
- public constructor({children, ...rest}: CodeProps) {
144
- super({
145
- fontFamily: 'monospace',
146
- ...rest,
147
- });
148
- if (children) {
149
- this.code(children);
150
- }
151
- }
152
-
153
- @computed()
154
- protected characterSize() {
155
- this.requestFontUpdate();
156
- const context = this.cacheCanvas();
157
- context.save();
158
- this.applyStyle(context);
159
- context.font = this.styles.font;
160
- const width = context.measureText('X').width;
161
- context.restore();
162
-
163
- return new Vector2(width, parseFloat(this.styles.lineHeight));
164
- }
165
-
166
- protected override desiredSize(): SerializedVector2<DesiredLength> {
167
- const custom = super.desiredSize();
168
- const tokensSize = this.getTokensSize(this.parsed());
169
- return {
170
- x: custom.x ?? tokensSize.x,
171
- y: custom.y ?? tokensSize.y,
172
- };
173
- }
174
-
175
- protected getTokensSize(tokens: Token[]) {
176
- const size = this.characterSize();
177
- let maxWidth = 0;
178
- let height = size.height;
179
- let width = 0;
180
-
181
- for (const token of tokens) {
182
- for (let i = 0; i < token.code.length; i++) {
183
- if (token.code[i] === '\n') {
184
- if (width > maxWidth) {
185
- maxWidth = width;
186
- }
187
- width = 0;
188
- height += size.height;
189
- } else {
190
- width += size.width;
191
- }
192
- }
193
- }
194
-
195
- if (width > maxWidth) {
196
- maxWidth = width;
197
- }
198
-
199
- return {x: maxWidth, y: height};
200
- }
201
-
202
- protected override collectAsyncResources(): void {
203
- super.collectAsyncResources();
204
- CodeBlock.initialized();
205
- }
206
-
207
- public set(strings: string[], ...rest: any[]) {
208
- this.code({
209
- language: this.language(),
210
- spans: strings,
211
- nodes: rest,
212
- });
213
- }
214
-
215
- /**
216
- * Smoothly edit the code.
217
- *
218
- * @remarks
219
- * This method returns a tag function that should be used together with a
220
- * template literal to define what to edit. Expressions can be used to either
221
- * {@link insert}, {@link remove}, or {@link edit} the code.
222
- *
223
- * @example
224
- * ```ts
225
- * yield* codeBlock().edit()`
226
- * const ${edit('a', 'b')} = [${insert('1, 2, 3')}];${remove(`
227
- * // this comment will be removed`)}
228
- * `;
229
- * ```
230
- *
231
- * @param duration - The duration of the transition.
232
- * @param changeSelection - When set to `true`, the selection will be modified
233
- * to highlight the newly inserted code. Setting it
234
- * to `false` leaves the selection untouched.
235
- * Providing a custom {@link CodeRange} will select
236
- * it instead.
237
- */
238
- public edit(duration = 0.6, changeSelection: CodeRange[] | boolean = true) {
239
- function* generator(
240
- this: CodeBlock,
241
- strings: TemplateStringsArray,
242
- ...rest: (CodeModification | Code)[]
243
- ): ThreadGenerator {
244
- const from = {
245
- language: this.language(),
246
- spans: [...strings],
247
- nodes: rest.map(modification =>
248
- isCodeModification(modification) ? modification.from : modification,
249
- ),
250
- };
251
- const to = {
252
- language: this.language(),
253
- spans: [...strings],
254
- nodes: rest.map(modification =>
255
- isCodeModification(modification) ? modification.to : modification,
256
- ),
257
- };
258
- this.code(from);
259
-
260
- if (changeSelection) {
261
- const task = yield this.code(to, duration);
262
- yield* waitFor(duration * 0.2);
263
- yield* this.selection([], duration * 0.3);
264
-
265
- const newSelection: CodeRange[] =
266
- changeSelection === true
267
- ? diff(from, to)
268
- .filter(token => token.morph === 'create')
269
- .map(token => [
270
- [token.to![1], token.to![0]],
271
- [token.to![1], token.to![0] + token.code.length],
272
- ])
273
- : changeSelection;
274
-
275
- yield* this.selection(newSelection, duration * 0.3);
276
- yield* join(task);
277
- } else {
278
- yield* this.code(to, duration);
279
- }
280
- }
281
-
282
- return generator.bind(this);
283
- }
284
-
285
- @threadable()
286
- public *tweenCode(
287
- code: CodeTree,
288
- time: number,
289
- timingFunction: TimingFunction,
290
- ) {
291
- if (typeof code === 'function') throw new Error();
292
- if (!CodeBlock.initialized()) return;
293
-
294
- const currentParsedCode = parse(this.code(), {codeStyle: this.theme()});
295
- const newParsedCode = parse(code, {codeStyle: this.theme()});
296
- this.currentLineCount = this.getLineCountOfTokenArray(currentParsedCode);
297
- this.newLineCount = this.getLineCountOfTokenArray(newParsedCode);
298
-
299
- const autoWidth = this.width.isInitial();
300
- const autoHeight = this.height.isInitial();
301
- const fromSize = this.size();
302
- const toSize = this.getTokensSize(newParsedCode);
303
-
304
- const beginning = 0.2;
305
- const ending = 0.8;
306
-
307
- this.codeProgress(0);
308
- this.diffed = diff(this.code(), code, {codeStyle: this.theme()});
309
- yield* tween(
310
- time,
311
- value => {
312
- const progress = timingFunction(value);
313
- const remapped = clampRemap(beginning, ending, 0, 1, progress);
314
- this.codeProgress(progress);
315
- if (autoWidth) {
316
- this.width(easeInOutSine(remapped, fromSize.x, toSize.x));
317
- }
318
- if (autoHeight) {
319
- this.height(easeInOutSine(remapped, fromSize.y, toSize.y));
320
- }
321
- },
322
- () => {
323
- this.codeProgress(null);
324
- this.diffed = null;
325
- if (autoWidth) {
326
- this.width.reset();
327
- }
328
- if (autoHeight) {
329
- this.height.reset();
330
- }
331
- this.code(code);
332
- },
333
- );
334
- }
335
-
336
- protected override async draw(context: CanvasRenderingContext2D) {
337
- if (!CodeBlock.initialized()) return;
338
-
339
- this.requestFontUpdate();
340
- this.applyStyle(context);
341
- context.font = this.styles.font;
342
- context.textBaseline = 'top';
343
- const lh = parseFloat(this.styles.lineHeight);
344
- const w = context.measureText('X').width;
345
- const size = this.computedSize();
346
- const progress = this.codeProgress();
347
- const unselectedOpacity = this.unselectedOpacity();
348
- const globalAlpha = context.globalAlpha;
349
-
350
- const getSelectionAlpha = (x: number, y: number) =>
351
- map(unselectedOpacity, 1, this.selectionStrength(x, y));
352
-
353
- const drawToken = (
354
- code: string,
355
- position: SerializedVector2,
356
- alpha = 1,
357
- ) => {
358
- for (let i = 0; i < code.length; i++) {
359
- const char = code.charAt(i);
360
- if (char === '\n') {
361
- position.y++;
362
- position.x = 0;
363
- continue;
364
- }
365
- context.globalAlpha =
366
- globalAlpha * alpha * getSelectionAlpha(position.x, position.y);
367
- context.fillText(char, position.x * w, position.y * lh);
368
- position.x++;
369
- }
370
- };
371
-
372
- context.translate(size.x / -2, size.y / -2);
373
- if (progress == null) {
374
- const parsed = this.parsed();
375
- const position = {x: 0, y: 0};
376
- for (const token of parsed) {
377
- context.save();
378
- context.fillStyle = token.color ?? '#c9d1d9';
379
- drawToken(token.code, position);
380
- context.restore();
381
- }
382
- } else {
383
- const diffed = this.diffed!;
384
- const beginning = 0.2;
385
- const ending = 0.8;
386
- const overlap = 0.15;
387
- for (const token of diffed) {
388
- context.save();
389
- context.fillStyle = token.color ?? '#c9d1d9';
390
-
391
- if (token.morph === 'delete') {
392
- drawToken(
393
- token.code,
394
- {x: token.from![0], y: token.from![1]},
395
- clampRemap(0, beginning + overlap, 1, 0, progress),
396
- );
397
- } else if (token.morph === 'create') {
398
- drawToken(
399
- token.code,
400
- {x: token.to![0], y: token.to![1]},
401
- clampRemap(ending - overlap, 1, 0, 1, progress),
402
- );
403
- } else if (token.morph === 'retain') {
404
- const remapped = clampRemap(beginning, ending, 0, 1, progress);
405
- const x = easeInOutSine(remapped, token.from![0], token.to![0]);
406
- const y = easeInOutSine(remapped, token.from![1], token.to![1]);
407
- const point: CodePoint = remapped > 0.5 ? token.to! : token.from!;
408
-
409
- let offsetX = 0;
410
- let offsetY = 0;
411
- for (let i = 0; i < token.code.length; i++) {
412
- const char = token.code.charAt(i);
413
- if (char === '\n') {
414
- offsetY++;
415
- offsetX = 0;
416
- continue;
417
- }
418
-
419
- context.globalAlpha =
420
- globalAlpha *
421
- getSelectionAlpha(point[0] + offsetX, point[1] + offsetY);
422
-
423
- context.fillText(char, (x + offsetX) * w, (y + offsetY) * lh);
424
- offsetX++;
425
- }
426
- } else {
427
- useLogger().warn({
428
- message: 'Invalid token',
429
- object: token,
430
- });
431
- }
432
- context.restore();
433
- }
434
- }
435
- }
436
-
437
- protected selectionStrength(x: number, y: number): number {
438
- const selection = this.selection();
439
- const selectionProgress = this.selectionProgress();
440
-
441
- const isSelected = CodeBlock.selectionStrength(selection, x, y);
442
- if (selectionProgress === null || this.oldSelection === null) {
443
- return isSelected ? 1 : 0;
444
- }
445
-
446
- const wasSelected = CodeBlock.selectionStrength(this.oldSelection, x, y);
447
- if (isSelected === wasSelected) {
448
- return isSelected;
449
- }
450
-
451
- return map(wasSelected, isSelected, selectionProgress);
452
- }
453
-
454
- protected static selectionStrength(
455
- selection: CodeRange[],
456
- x: number,
457
- y: number,
458
- ): number {
459
- return selection.length > 0 &&
460
- !!selection.find(([[startLine, startColumn], [endLine, endColumn]]) => {
461
- return (
462
- ((y === startLine && x >= startColumn) || y > startLine) &&
463
- ((y === endLine && x < endColumn) || y < endLine)
464
- );
465
- })
466
- ? 1
467
- : 0;
468
- }
469
- }
470
-
471
- function isCodeModification(value: any): value is CodeModification {
472
- return (
473
- value &&
474
- typeof value === 'object' &&
475
- value.from !== undefined &&
476
- value.to !== undefined
477
- );
478
- }
479
-
480
- /**
481
- * Create a code modification that inserts a piece of code.
482
- *
483
- * @remarks
484
- * Should be used in conjunction with {@link CodeBlock.edit}.
485
- *
486
- * @param content - The code to insert.
487
- */
488
- export function insert(content: Code): CodeModification {
489
- return {
490
- from: '',
491
- to: content,
492
- };
493
- }
494
-
495
- /**
496
- * Create a code modification that removes a piece of code.
497
- *
498
- * @remarks
499
- * Should be used in conjunction with {@link CodeBlock.edit}.
500
- *
501
- * @param content - The code to remove.
502
- */
503
- export function remove(content: Code): CodeModification {
504
- return {
505
- from: content,
506
- to: '',
507
- };
508
- }
509
-
510
- /**
511
- * Create a code modification that changes one piece of code into another.
512
- *
513
- * @remarks
514
- * Should be used in conjunction with {@link CodeBlock.edit}.
515
- *
516
- * @param from - The code to change from.
517
- * @param to - The code to change to.
518
- */
519
- export function edit(from: Code, to: Code): CodeModification {
520
- return {from, to};
521
- }
522
-
523
- /**
524
- * Create a selection range that highlights the given lines.
525
- *
526
- * @param from - The line from which the selection starts.
527
- * @param to - The line at which the selection ends. If omitted, the selection
528
- * will cover only one line.
529
- */
530
- export function lines(from: number, to?: number): CodeRange[] {
531
- return [
532
- [
533
- [from, 0],
534
- [to ?? from, Infinity],
535
- ],
536
- ];
537
- }
538
-
539
- /**
540
- * Create a selection range that highlights the given word.
541
- *
542
- * @param line - The line at which the word appears.
543
- * @param from - The column at which the word starts.
544
- * @param length - The length of the word. If omitted, the selection will cover
545
- * the rest of the line.
546
- */
547
- export function word(line: number, from: number, length?: number): CodeRange[] {
548
- return [
549
- [
550
- [line, from],
551
- [line, from + (length ?? Infinity)],
552
- ],
553
- ];
554
- }
555
-
556
- /**
557
- * Create a custom selection range.
558
- *
559
- * @param startLine - The line at which the selection starts.
560
- * @param startColumn - The column at which the selection starts.
561
- * @param endLine - The line at which the selection ends.
562
- * @param endColumn - The column at which the selection ends.
563
- */
564
- export function range(
565
- startLine: number,
566
- startColumn: number,
567
- endLine: number,
568
- endColumn: number,
569
- ): CodeRange[] {
570
- return [
571
- [
572
- [startLine, startColumn],
573
- [endLine, endColumn],
574
- ],
575
- ];
576
- }
1
+ import type {
2
+ SerializedVector2,
3
+ Signal,
4
+ SignalValue,
5
+ SimpleSignal,
6
+ ThreadGenerator,
7
+ TimingFunction,
8
+ } from '@twick/core';
9
+ import {
10
+ Vector2,
11
+ clampRemap,
12
+ createComputedAsync,
13
+ createSignal,
14
+ easeInOutSine,
15
+ join,
16
+ map,
17
+ threadable,
18
+ tween,
19
+ useLogger,
20
+ waitFor,
21
+ } from '@twick/core';
22
+ import type {Code, CodeStyle, CodeTree, MorphToken, Token} from 'code-fns';
23
+ import {diff, parse, ready} from 'code-fns';
24
+ import {computed, initial, nodeName, parser, signal} from '../decorators';
25
+ import type {DesiredLength} from '../partials';
26
+ import type {ShapeProps} from './Shape';
27
+ import {Shape} from './Shape';
28
+
29
+ type CodePoint = [number, number];
30
+ type CodeRange = [CodePoint, CodePoint];
31
+
32
+ export interface CodeProps extends ShapeProps {
33
+ language?: string;
34
+ children?: Code;
35
+ code?: SignalValue<Code>;
36
+ selection?: CodeRange[];
37
+ theme?: CodeStyle;
38
+ }
39
+
40
+ export interface CodeModification {
41
+ from: Code;
42
+ to: Code;
43
+ }
44
+
45
+ /**
46
+ * @deprecated Use {@link Code} instead.
47
+ */
48
+ @nodeName('CodeBlock')
49
+ export class CodeBlock extends Shape {
50
+ private static initialized = createComputedAsync(
51
+ () => ready().then(() => true),
52
+ false,
53
+ );
54
+
55
+ @initial('tsx')
56
+ @signal()
57
+ public declare readonly language: SimpleSignal<string, this>;
58
+
59
+ @initial('')
60
+ @parser(function (this: CodeBlock, value: Code): CodeTree {
61
+ return typeof value === 'string'
62
+ ? {
63
+ language: this.language(),
64
+ spans: [value],
65
+ nodes: [],
66
+ }
67
+ : value;
68
+ })
69
+ @signal()
70
+ public declare readonly code: Signal<Code, CodeTree, this>;
71
+
72
+ @initial(undefined)
73
+ @signal()
74
+ public declare readonly theme: Signal<CodeStyle | null, CodeStyle, this>;
75
+
76
+ @initial(lines(0, Infinity))
77
+ @signal()
78
+ public declare readonly selection: SimpleSignal<CodeRange[], this>;
79
+
80
+ protected *tweenSelection(
81
+ value: CodeRange[],
82
+ duration: number,
83
+ timingFunction: TimingFunction,
84
+ ): ThreadGenerator {
85
+ this.oldSelection = this.selection();
86
+ this.selection(value);
87
+ this.selectionProgress(0);
88
+ yield* this.selectionProgress(1, duration, timingFunction);
89
+ this.selectionProgress(null);
90
+ this.oldSelection = null;
91
+ }
92
+
93
+ @initial(0.32)
94
+ @signal()
95
+ public declare readonly unselectedOpacity: SimpleSignal<number, this>;
96
+
97
+ private codeProgress = createSignal<number | null>(null);
98
+ private selectionProgress = createSignal<number | null>(null);
99
+ private oldSelection: CodeRange[] | null = null;
100
+ private diffed: MorphToken[] | null = null;
101
+ private currentLineCount = 0;
102
+ private newLineCount = 0;
103
+
104
+ protected getLineCountOfTokenArray(tokens: Token[]): number {
105
+ let count = 0;
106
+
107
+ for (const token of tokens) {
108
+ for (let i = 0; i < token.code.length; i++) {
109
+ if (token.code[i] === '\n') {
110
+ count++;
111
+ }
112
+ }
113
+ }
114
+
115
+ if (tokens.length > 0) {
116
+ count++;
117
+ }
118
+
119
+ return count;
120
+ }
121
+
122
+ @computed()
123
+ public lineCount(): number {
124
+ const progress = this.codeProgress();
125
+ if (progress !== null) {
126
+ return Math.round(
127
+ map(this.currentLineCount, this.newLineCount, progress),
128
+ );
129
+ }
130
+
131
+ return this.getLineCountOfTokenArray(this.parsed());
132
+ }
133
+
134
+ @computed()
135
+ protected parsed() {
136
+ if (!CodeBlock.initialized()) {
137
+ return [];
138
+ }
139
+
140
+ return parse(this.code(), {codeStyle: this.theme()});
141
+ }
142
+
143
+ public constructor({children, ...rest}: CodeProps) {
144
+ super({
145
+ fontFamily: 'monospace',
146
+ ...rest,
147
+ });
148
+ if (children) {
149
+ this.code(children);
150
+ }
151
+ }
152
+
153
+ @computed()
154
+ protected characterSize() {
155
+ this.requestFontUpdate();
156
+ const context = this.cacheCanvas();
157
+ context.save();
158
+ this.applyStyle(context);
159
+ context.font = this.styles.font;
160
+ const width = context.measureText('X').width;
161
+ context.restore();
162
+
163
+ return new Vector2(width, parseFloat(this.styles.lineHeight));
164
+ }
165
+
166
+ protected override desiredSize(): SerializedVector2<DesiredLength> {
167
+ const custom = super.desiredSize();
168
+ const tokensSize = this.getTokensSize(this.parsed());
169
+ return {
170
+ x: custom.x ?? tokensSize.x,
171
+ y: custom.y ?? tokensSize.y,
172
+ };
173
+ }
174
+
175
+ protected getTokensSize(tokens: Token[]) {
176
+ const size = this.characterSize();
177
+ let maxWidth = 0;
178
+ let height = size.height;
179
+ let width = 0;
180
+
181
+ for (const token of tokens) {
182
+ for (let i = 0; i < token.code.length; i++) {
183
+ if (token.code[i] === '\n') {
184
+ if (width > maxWidth) {
185
+ maxWidth = width;
186
+ }
187
+ width = 0;
188
+ height += size.height;
189
+ } else {
190
+ width += size.width;
191
+ }
192
+ }
193
+ }
194
+
195
+ if (width > maxWidth) {
196
+ maxWidth = width;
197
+ }
198
+
199
+ return {x: maxWidth, y: height};
200
+ }
201
+
202
+ protected override collectAsyncResources(): void {
203
+ super.collectAsyncResources();
204
+ CodeBlock.initialized();
205
+ }
206
+
207
+ public set(strings: string[], ...rest: any[]) {
208
+ this.code({
209
+ language: this.language(),
210
+ spans: strings,
211
+ nodes: rest,
212
+ });
213
+ }
214
+
215
+ /**
216
+ * Smoothly edit the code.
217
+ *
218
+ * @remarks
219
+ * This method returns a tag function that should be used together with a
220
+ * template literal to define what to edit. Expressions can be used to either
221
+ * {@link insert}, {@link remove}, or {@link edit} the code.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * yield* codeBlock().edit()`
226
+ * const ${edit('a', 'b')} = [${insert('1, 2, 3')}];${remove(`
227
+ * // this comment will be removed`)}
228
+ * `;
229
+ * ```
230
+ *
231
+ * @param duration - The duration of the transition.
232
+ * @param changeSelection - When set to `true`, the selection will be modified
233
+ * to highlight the newly inserted code. Setting it
234
+ * to `false` leaves the selection untouched.
235
+ * Providing a custom {@link CodeRange} will select
236
+ * it instead.
237
+ */
238
+ public edit(duration = 0.6, changeSelection: CodeRange[] | boolean = true) {
239
+ function* generator(
240
+ this: CodeBlock,
241
+ strings: TemplateStringsArray,
242
+ ...rest: (CodeModification | Code)[]
243
+ ): ThreadGenerator {
244
+ const from = {
245
+ language: this.language(),
246
+ spans: [...strings],
247
+ nodes: rest.map(modification =>
248
+ isCodeModification(modification) ? modification.from : modification,
249
+ ),
250
+ };
251
+ const to = {
252
+ language: this.language(),
253
+ spans: [...strings],
254
+ nodes: rest.map(modification =>
255
+ isCodeModification(modification) ? modification.to : modification,
256
+ ),
257
+ };
258
+ this.code(from);
259
+
260
+ if (changeSelection) {
261
+ const task = yield this.code(to, duration);
262
+ yield* waitFor(duration * 0.2);
263
+ yield* this.selection([], duration * 0.3);
264
+
265
+ const newSelection: CodeRange[] =
266
+ changeSelection === true
267
+ ? diff(from, to)
268
+ .filter(token => token.morph === 'create')
269
+ .map(token => [
270
+ [token.to![1], token.to![0]],
271
+ [token.to![1], token.to![0] + token.code.length],
272
+ ])
273
+ : changeSelection;
274
+
275
+ yield* this.selection(newSelection, duration * 0.3);
276
+ yield* join(task);
277
+ } else {
278
+ yield* this.code(to, duration);
279
+ }
280
+ }
281
+
282
+ return generator.bind(this);
283
+ }
284
+
285
+ @threadable()
286
+ public *tweenCode(
287
+ code: CodeTree,
288
+ time: number,
289
+ timingFunction: TimingFunction,
290
+ ) {
291
+ if (typeof code === 'function') throw new Error();
292
+ if (!CodeBlock.initialized()) return;
293
+
294
+ const currentParsedCode = parse(this.code(), {codeStyle: this.theme()});
295
+ const newParsedCode = parse(code, {codeStyle: this.theme()});
296
+ this.currentLineCount = this.getLineCountOfTokenArray(currentParsedCode);
297
+ this.newLineCount = this.getLineCountOfTokenArray(newParsedCode);
298
+
299
+ const autoWidth = this.width.isInitial();
300
+ const autoHeight = this.height.isInitial();
301
+ const fromSize = this.size();
302
+ const toSize = this.getTokensSize(newParsedCode);
303
+
304
+ const beginning = 0.2;
305
+ const ending = 0.8;
306
+
307
+ this.codeProgress(0);
308
+ this.diffed = diff(this.code(), code, {codeStyle: this.theme()});
309
+ yield* tween(
310
+ time,
311
+ value => {
312
+ const progress = timingFunction(value);
313
+ const remapped = clampRemap(beginning, ending, 0, 1, progress);
314
+ this.codeProgress(progress);
315
+ if (autoWidth) {
316
+ this.width(easeInOutSine(remapped, fromSize.x, toSize.x));
317
+ }
318
+ if (autoHeight) {
319
+ this.height(easeInOutSine(remapped, fromSize.y, toSize.y));
320
+ }
321
+ },
322
+ () => {
323
+ this.codeProgress(null);
324
+ this.diffed = null;
325
+ if (autoWidth) {
326
+ this.width.reset();
327
+ }
328
+ if (autoHeight) {
329
+ this.height.reset();
330
+ }
331
+ this.code(code);
332
+ },
333
+ );
334
+ }
335
+
336
+ protected override async draw(context: CanvasRenderingContext2D) {
337
+ if (!CodeBlock.initialized()) return;
338
+
339
+ this.requestFontUpdate();
340
+ this.applyStyle(context);
341
+ context.font = this.styles.font;
342
+ context.textBaseline = 'top';
343
+ const lh = parseFloat(this.styles.lineHeight);
344
+ const w = context.measureText('X').width;
345
+ const size = this.computedSize();
346
+ const progress = this.codeProgress();
347
+ const unselectedOpacity = this.unselectedOpacity();
348
+ const globalAlpha = context.globalAlpha;
349
+
350
+ const getSelectionAlpha = (x: number, y: number) =>
351
+ map(unselectedOpacity, 1, this.selectionStrength(x, y));
352
+
353
+ const drawToken = (
354
+ code: string,
355
+ position: SerializedVector2,
356
+ alpha = 1,
357
+ ) => {
358
+ for (let i = 0; i < code.length; i++) {
359
+ const char = code.charAt(i);
360
+ if (char === '\n') {
361
+ position.y++;
362
+ position.x = 0;
363
+ continue;
364
+ }
365
+ context.globalAlpha =
366
+ globalAlpha * alpha * getSelectionAlpha(position.x, position.y);
367
+ context.fillText(char, position.x * w, position.y * lh);
368
+ position.x++;
369
+ }
370
+ };
371
+
372
+ context.translate(size.x / -2, size.y / -2);
373
+ if (progress == null) {
374
+ const parsed = this.parsed();
375
+ const position = {x: 0, y: 0};
376
+ for (const token of parsed) {
377
+ context.save();
378
+ context.fillStyle = token.color ?? '#c9d1d9';
379
+ drawToken(token.code, position);
380
+ context.restore();
381
+ }
382
+ } else {
383
+ const diffed = this.diffed!;
384
+ const beginning = 0.2;
385
+ const ending = 0.8;
386
+ const overlap = 0.15;
387
+ for (const token of diffed) {
388
+ context.save();
389
+ context.fillStyle = token.color ?? '#c9d1d9';
390
+
391
+ if (token.morph === 'delete') {
392
+ drawToken(
393
+ token.code,
394
+ {x: token.from![0], y: token.from![1]},
395
+ clampRemap(0, beginning + overlap, 1, 0, progress),
396
+ );
397
+ } else if (token.morph === 'create') {
398
+ drawToken(
399
+ token.code,
400
+ {x: token.to![0], y: token.to![1]},
401
+ clampRemap(ending - overlap, 1, 0, 1, progress),
402
+ );
403
+ } else if (token.morph === 'retain') {
404
+ const remapped = clampRemap(beginning, ending, 0, 1, progress);
405
+ const x = easeInOutSine(remapped, token.from![0], token.to![0]);
406
+ const y = easeInOutSine(remapped, token.from![1], token.to![1]);
407
+ const point: CodePoint = remapped > 0.5 ? token.to! : token.from!;
408
+
409
+ let offsetX = 0;
410
+ let offsetY = 0;
411
+ for (let i = 0; i < token.code.length; i++) {
412
+ const char = token.code.charAt(i);
413
+ if (char === '\n') {
414
+ offsetY++;
415
+ offsetX = 0;
416
+ continue;
417
+ }
418
+
419
+ context.globalAlpha =
420
+ globalAlpha *
421
+ getSelectionAlpha(point[0] + offsetX, point[1] + offsetY);
422
+
423
+ context.fillText(char, (x + offsetX) * w, (y + offsetY) * lh);
424
+ offsetX++;
425
+ }
426
+ } else {
427
+ useLogger().warn({
428
+ message: 'Invalid token',
429
+ object: token,
430
+ });
431
+ }
432
+ context.restore();
433
+ }
434
+ }
435
+ }
436
+
437
+ protected selectionStrength(x: number, y: number): number {
438
+ const selection = this.selection();
439
+ const selectionProgress = this.selectionProgress();
440
+
441
+ const isSelected = CodeBlock.selectionStrength(selection, x, y);
442
+ if (selectionProgress === null || this.oldSelection === null) {
443
+ return isSelected ? 1 : 0;
444
+ }
445
+
446
+ const wasSelected = CodeBlock.selectionStrength(this.oldSelection, x, y);
447
+ if (isSelected === wasSelected) {
448
+ return isSelected;
449
+ }
450
+
451
+ return map(wasSelected, isSelected, selectionProgress);
452
+ }
453
+
454
+ protected static selectionStrength(
455
+ selection: CodeRange[],
456
+ x: number,
457
+ y: number,
458
+ ): number {
459
+ return selection.length > 0 &&
460
+ !!selection.find(([[startLine, startColumn], [endLine, endColumn]]) => {
461
+ return (
462
+ ((y === startLine && x >= startColumn) || y > startLine) &&
463
+ ((y === endLine && x < endColumn) || y < endLine)
464
+ );
465
+ })
466
+ ? 1
467
+ : 0;
468
+ }
469
+ }
470
+
471
+ function isCodeModification(value: any): value is CodeModification {
472
+ return (
473
+ value &&
474
+ typeof value === 'object' &&
475
+ value.from !== undefined &&
476
+ value.to !== undefined
477
+ );
478
+ }
479
+
480
+ /**
481
+ * Create a code modification that inserts a piece of code.
482
+ *
483
+ * @remarks
484
+ * Should be used in conjunction with {@link CodeBlock.edit}.
485
+ *
486
+ * @param content - The code to insert.
487
+ */
488
+ export function insert(content: Code): CodeModification {
489
+ return {
490
+ from: '',
491
+ to: content,
492
+ };
493
+ }
494
+
495
+ /**
496
+ * Create a code modification that removes a piece of code.
497
+ *
498
+ * @remarks
499
+ * Should be used in conjunction with {@link CodeBlock.edit}.
500
+ *
501
+ * @param content - The code to remove.
502
+ */
503
+ export function remove(content: Code): CodeModification {
504
+ return {
505
+ from: content,
506
+ to: '',
507
+ };
508
+ }
509
+
510
+ /**
511
+ * Create a code modification that changes one piece of code into another.
512
+ *
513
+ * @remarks
514
+ * Should be used in conjunction with {@link CodeBlock.edit}.
515
+ *
516
+ * @param from - The code to change from.
517
+ * @param to - The code to change to.
518
+ */
519
+ export function edit(from: Code, to: Code): CodeModification {
520
+ return {from, to};
521
+ }
522
+
523
+ /**
524
+ * Create a selection range that highlights the given lines.
525
+ *
526
+ * @param from - The line from which the selection starts.
527
+ * @param to - The line at which the selection ends. If omitted, the selection
528
+ * will cover only one line.
529
+ */
530
+ export function lines(from: number, to?: number): CodeRange[] {
531
+ return [
532
+ [
533
+ [from, 0],
534
+ [to ?? from, Infinity],
535
+ ],
536
+ ];
537
+ }
538
+
539
+ /**
540
+ * Create a selection range that highlights the given word.
541
+ *
542
+ * @param line - The line at which the word appears.
543
+ * @param from - The column at which the word starts.
544
+ * @param length - The length of the word. If omitted, the selection will cover
545
+ * the rest of the line.
546
+ */
547
+ export function word(line: number, from: number, length?: number): CodeRange[] {
548
+ return [
549
+ [
550
+ [line, from],
551
+ [line, from + (length ?? Infinity)],
552
+ ],
553
+ ];
554
+ }
555
+
556
+ /**
557
+ * Create a custom selection range.
558
+ *
559
+ * @param startLine - The line at which the selection starts.
560
+ * @param startColumn - The column at which the selection starts.
561
+ * @param endLine - The line at which the selection ends.
562
+ * @param endColumn - The column at which the selection ends.
563
+ */
564
+ export function range(
565
+ startLine: number,
566
+ startColumn: number,
567
+ endLine: number,
568
+ endColumn: number,
569
+ ): CodeRange[] {
570
+ return [
571
+ [
572
+ [startLine, startColumn],
573
+ [endLine, endColumn],
574
+ ],
575
+ ];
576
+ }