motion-canvas-rs 0.2.3

A high-performance vector animation engine inspired by Motion Canvas, built on Vello and Typst.
Documentation
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
#![cfg(feature = "code")]
//! Code highlighting and animation module.
//!
//! Credits: The token-based animation logic and diffing approach is inspired by
//! [shiki-magic-move](https://github.com/shikijs/shiki-magic-move).

use crate::assets::code_tokenizer::{draw_token, parse_selection, CodeValue};
use crate::core::animation::{Node, Signal, Tweenable};
use glam::Vec2;
use std::time::Duration;
use vello::kurbo::Affine;
use vello::peniko::Color;
use vello::Scene;

/// A node that renders syntax-highlighted code with support for "magic move" transitions.
///
/// `CodeNode` uses `syntect` for syntax highlighting and implements a diffing algorithm
/// that allows code tokens to smoothly animate between different states (edits, line selections).
///
/// ### Example
/// ```rust
/// # use motion_canvas_rs::prelude::*;
/// let code = CodeNode::default()
///     .with_position(Vec2::new(640.0, 360.0))
///     .with_language("rs")
///     .with_code("fn main() {\n  println!(\"Hello\");\n}")
///     .with_theme("base16-ocean.dark")
///     .with_font_size(24.0);
/// ```
pub struct CodeNode {
    /// The absolute position of the code block.
    pub position: Signal<Vec2>,
    /// Rotation in radians.
    pub rotation: Signal<f32>,
    /// Scaling factor for the block.
    pub scale: Signal<Vec2>,
    /// The current state of the code (text, tokens, and transition progress).
    pub code: Signal<CodeValue>,
    /// Base font size in pixels.
    pub font_size: Signal<f32>,
    /// Overall opacity (0.0 to 1.0).
    pub opacity: Signal<f32>,
    /// Opacity factor for non-selected lines (0.0 to 1.0).
    pub dim_opacity: Signal<f32>,
    /// The syntax highlighting language (e.g., "rs", "js", "rust").
    pub language: String,
    /// The name of the highlighting theme.
    pub theme: String,
    /// The font family name for rendering.
    pub font_family: String,
    /// The relative transformation origin. (-1,-1) is top-left, (0,0) is center, (1,1) is bottom-right.
    pub anchor: Signal<Vec2>,
}

impl Default for CodeNode {
    fn default() -> Self {
        let font_size = crate::assets::code_tokenizer::DEFAULT_FONT_SIZE;
        let language = crate::assets::code_tokenizer::DEFAULT_LANGUAGE.to_string();
        let theme = crate::assets::code_tokenizer::DEFAULT_THEME.to_string();
        let font_family = crate::assets::code_tokenizer::DEFAULT_FONT_FAMILY.to_string();

        let val = CodeValue::new("".to_string(), font_size, &language, &theme, &font_family);

        Self {
            position: Signal::new(Vec2::ZERO),
            anchor: Signal::new(Vec2::new(-1.0, -1.0)),
            rotation: Signal::new(0.0),
            scale: Signal::new(Vec2::ONE),
            code: Signal::new(val),
            font_size: Signal::new(font_size),
            opacity: Signal::new(crate::assets::code_tokenizer::DEFAULT_OPACITY),
            dim_opacity: Signal::new(crate::assets::code_tokenizer::DEFAULT_DIM_OPACITY),
            language,
            theme,
            font_family,
        }
    }
}

impl Clone for CodeNode {
    fn clone(&self) -> Self {
        Self {
            position: self.position.clone(),
            rotation: self.rotation.clone(),
            scale: self.scale.clone(),
            code: self.code.clone(),
            font_size: self.font_size.clone(),
            opacity: self.opacity.clone(),
            dim_opacity: self.dim_opacity.clone(),
            language: self.language.clone(),
            theme: self.theme.clone(),
            font_family: self.font_family.clone(),
            anchor: self.anchor.clone(),
        }
    }
}

impl CodeNode {
    /// Creates a new code node at the given position with content and language.
    pub fn new(pos: Vec2, code: &str, lang: &str) -> Self {
        Self::default()
            .with_position(pos)
            .with_language(lang)
            .with_code(code)
    }

    /// Sets the absolute position of the code block.
    pub fn with_position(mut self, position: Vec2) -> Self {
        self.position = Signal::new(position);
        self
    }

    /// Sets the rotation in radians.
    pub fn with_rotation(mut self, angle: f32) -> Self {
        self.rotation = Signal::new(angle);
        self
    }

    /// Sets uniform scaling.
    pub fn with_scale(mut self, scale: f32) -> Self {
        self.scale = Signal::new(Vec2::splat(scale));
        self
    }

    /// Sets non-uniform scaling.
    pub fn with_scale_xy(mut self, scale: Vec2) -> Self {
        self.scale = Signal::new(scale);
        self
    }

    /// Sets overall opacity.
    pub fn with_opacity(mut self, opacity: f32) -> Self {
        self.opacity = Signal::new(opacity);
        self
    }

    /// Sets the code content and triggers re-tokenization.
    pub fn with_code(mut self, code: &str) -> Self {
        let val = CodeValue::new(
            code.to_string(),
            self.font_size.get(),
            &self.language,
            &self.theme,
            &self.font_family,
        );
        self.code = Signal::new(val);
        self
    }

    /// Sets the highlighting language.
    pub fn with_language(mut self, lang: &str) -> Self {
        self.language = lang.to_string();
        // Re-tokenize if code exists
        let current_text = self.code.get().text;
        let val = CodeValue::new(
            current_text,
            self.font_size.get(),
            &self.language,
            &self.theme,
            &self.font_family,
        );
        self.code = Signal::new(val);
        self
    }

    /// Sets the highlighting theme.
    pub fn with_theme(mut self, theme: &str) -> Self {
        self.theme = theme.to_string();
        let current_text = self.code.get().text;
        let val = CodeValue::new(
            current_text,
            self.font_size.get(),
            &self.language,
            &self.theme,
            &self.font_family,
        );
        self.code = Signal::new(val);
        self
    }

    /// Sets the font family.
    pub fn with_font(mut self, font: &str) -> Self {
        self.font_family = font.to_string();
        let current_text = self.code.get().text;
        let val = CodeValue::new(
            current_text,
            self.font_size.get(),
            &self.language,
            &self.theme,
            &self.font_family,
        );
        self.code = Signal::new(val);
        self
    }

    /// Sets the base font size.
    pub fn with_font_size(mut self, size: f32) -> Self {
        self.font_size = Signal::new(size);
        // Re-tokenize current code with new size to avoid "spazzing"
        let current_text = self.code.get().text;
        let mut val = CodeValue::new(
            current_text,
            size,
            &self.language,
            &self.theme,
            &self.font_family,
        );
        val.selection = self.code.get().selection;
        self.code = Signal::new(val);
        self
    }

    /// Sets the opacity for dimmed (non-selected) lines.
    pub fn with_dim_opacity(mut self, dim: f32) -> Self {
        self.dim_opacity = Signal::new(dim);
        self
    }

    /// Sets the relative transformation origin (anchor).
    /// (-1, -1) is top-left, (0, 0) is center, (1, 1) is bottom-right.
    pub fn with_anchor(mut self, anchor: Vec2) -> Self {
        self.anchor = Signal::new(anchor);
        self
    }

    /// Returns a tween that transition the current code to a new string.
    pub fn edit(
        &self,
        code: &str,
        duration: Duration,
    ) -> crate::core::animation::SignalTween<CodeValue> {
        let code = code.to_string();
        let font_size = self.font_size.get();
        let lang = self.language.clone();
        let theme = self.theme.clone();
        let font = self.font_family.clone();
        self.code.to_lazy(
            move |current| {
                let mut next_value = CodeValue::new(code.clone(), font_size, &lang, &theme, &font);
                next_value.selection = current.selection.clone();
                next_value
            },
            duration,
        )
    }

    /// Returns a tween that appends text to the current code.
    pub fn append(
        &self,
        text: &str,
        duration: Duration,
    ) -> crate::core::animation::SignalTween<CodeValue> {
        let text = text.to_string();
        let font_size = self.font_size.get();
        let lang = self.language.clone();
        let theme = self.theme.clone();
        let font = self.font_family.clone();
        self.code.to_lazy(
            move |current| {
                let next_text = format!("{}{}", current.text, text);
                let mut next_val = CodeValue::new(next_text, font_size, &lang, &theme, &font);
                next_val.selection = current.selection.clone();
                next_val
            },
            duration,
        )
    }

    /// Returns a tween that prepends text to the current code.
    pub fn prepend(
        &self,
        text: &str,
        duration: Duration,
    ) -> crate::core::animation::SignalTween<CodeValue> {
        let text = text.to_string();
        let font_size = self.font_size.get();
        let lang = self.language.clone();
        let theme = self.theme.clone();
        let font = self.font_family.clone();
        self.code.to_lazy(
            move |current| {
                let next_text = format!("{}{}", text, current.text);
                let mut next_val = CodeValue::new(next_text, font_size, &lang, &theme, &font);
                next_val.selection = current.selection.clone();
                next_val
            },
            duration,
        )
    }

    /// Returns a tween that changes the selected lines (dimming others).
    pub fn select_lines(
        &self,
        lines: Vec<usize>,
        duration: Duration,
    ) -> crate::core::animation::SignalTween<CodeValue> {
        self.code.to_lazy(
            move |current| {
                let mut next_value = current.clone();
                next_value.transition = None; // Reset transition for the target
                next_value.selection = lines.clone();
                next_value
            },
            duration,
        )
    }

    /// Select lines using a printer-style selection string (e.g., "1-3, 5").
    /// Uses 1-based indexing for user convenience.
    pub fn select_string(
        &self,
        selection: &str,
        duration: Duration,
    ) -> crate::core::animation::SignalTween<CodeValue> {
        let lines = parse_selection(selection);
        self.select_lines(lines, duration)
    }
}

impl Node for CodeNode {
    fn render(&self, scene: &mut Scene, parent_transform: Affine, parent_opacity: f32) {
        let code_val = self.code.get();
        let opacity = self.opacity.get();

        let pos = self.position.get();
        let rot = self.rotation.get();
        let sc = self.scale.get();
        let anchor = self.anchor.get();

        // Calculate bounding box for centering and anchor
        let mut min_x = f64::MAX;
        let mut min_y = f64::MAX;
        let mut max_x = f64::MIN;
        let mut max_y = f64::MIN;

        for token in &code_val.tokens {
            // Find bounds of each token. We can estimate based on token.pos and font size
            // or just use token.pos for simplicity if accurate bounds aren't available.
            // code_tokenizer gives us token.pos.
            min_x = min_x.min(token.pos.x as f64);
            min_y = min_y.min(token.pos.y as f64);
            max_x = max_x.max((token.pos.x + token.size) as f64); // Assume square-ish? No, width varies.
            max_y = max_y.max((token.pos.y + token.size) as f64);
        }

        let size_vec = if min_x == f64::MAX {
            Vec2::ZERO
        } else {
            Vec2::new((max_x - min_x) as f32, (max_y - min_y) as f32)
        };
        let center_offset = if min_x == f64::MAX {
            Vec2::ZERO
        } else {
            Vec2::new((min_x + max_x) as f32 * 0.5, (min_y + max_y) as f32 * 0.5)
        };

        let anchor_offset = anchor * size_vec * 0.5;

        let local_transform = Affine::translate((pos.x as f64, pos.y as f64))
            * Affine::rotate(rot as f64)
            * Affine::scale_non_uniform(sc.x as f64, sc.y as f64)
            * Affine::translate((-anchor_offset.x as f64, -anchor_offset.y as f64))
            * Affine::translate((-center_offset.x as f64, -center_offset.y as f64));

        let root_transform = parent_transform * local_transform;
        let combined_opacity = parent_opacity * opacity;

        let dim_factor = self.dim_opacity.get();

        let trans = match &code_val.transition {
            Some(t) => t,
            None => {
                // Static render
                let has_selection = !code_val.selection.is_empty();
                for token in &code_val.tokens {
                    let is_selected =
                        !has_selection || code_val.selection.contains(&token.line_index);
                    let dim = if is_selected { 1.0 } else { dim_factor };
                    draw_token(
                        scene,
                        root_transform
                            * Affine::translate((token.pos.x as f64, token.pos.y as f64)),
                        token,
                        token.color,
                        combined_opacity * dim,
                    );
                }
                return;
            }
        };

        let p = trans.progress;
        let mut matched_from = vec![false; trans.from_tokens.len()];
        let mut matched_to = vec![false; trans.to_tokens.len()];

        // 1. Draw moving matches
        for &(from_idx, to_idx) in &trans.matches {
            let from = &trans.from_tokens[from_idx];
            let to = &trans.to_tokens[to_idx];

            let current_pos = from.pos.lerp(to.pos, p);
            let current_color = Color::interpolate(&from.color, &to.color, p);

            let scale = if from.size != to.size {
                (from.size + (to.size - from.size) * p) / to.size
            } else {
                1.0
            };

            let from_is_dimmed = !trans.from_selection.is_empty()
                && !trans.from_selection.contains(&from.line_index);
            let to_is_dimmed =
                !trans.to_selection.is_empty() && !trans.to_selection.contains(&to.line_index);

            let from_dim = if from_is_dimmed { dim_factor } else { 1.0 };
            let to_dim = if to_is_dimmed { dim_factor } else { 1.0 };
            let current_dim = from_dim + (to_dim - from_dim) * p;

            draw_token(
                scene,
                root_transform
                    * Affine::translate((current_pos.x as f64, current_pos.y as f64))
                    * Affine::scale(scale as f64),
                to,
                current_color,
                combined_opacity * current_dim,
            );

            matched_from[from_idx] = true;
            matched_to[to_idx] = true;
        }

        // Draw unmatched from-tokens (vanishing)
        for (i, matched) in matched_from.iter().enumerate() {
            if !*matched {
                let from = &trans.from_tokens[i];
                let is_dimmed = !trans.from_selection.is_empty()
                    && !trans.from_selection.contains(&from.line_index);
                let dim = if is_dimmed { dim_factor } else { 1.0 };
                draw_token(
                    scene,
                    root_transform * Affine::translate((from.pos.x as f64, from.pos.y as f64)),
                    from,
                    from.color,
                    combined_opacity * dim * (1.0 - p),
                );
            }
        }

        // Draw unmatched to-tokens (appearing)
        for (i, matched) in matched_to.iter().enumerate() {
            if !*matched {
                let to = &trans.to_tokens[i];
                let is_dimmed =
                    !trans.to_selection.is_empty() && !trans.to_selection.contains(&to.line_index);
                let dim = if is_dimmed { dim_factor } else { 1.0 };
                draw_token(
                    scene,
                    root_transform * Affine::translate((to.pos.x as f64, to.pos.y as f64)),
                    to,
                    to.color,
                    combined_opacity * dim * p,
                );
            }
        }
    }

    fn update(&mut self, _dt: Duration) {}

    fn state_hash(&self) -> u64 {
        use crate::assets::hash::Hasher;
        let mut h = Hasher::new();

        h.update_u64(self.position.state_hash());
        h.update_u64(self.rotation.state_hash());
        h.update_u64(self.scale.state_hash());
        h.update_u64(self.font_size.state_hash());
        h.update_u64(self.code.state_hash());
        h.update_u64(self.opacity.state_hash());
        h.update_u64(self.dim_opacity.state_hash());
        h.update_u64(self.anchor.state_hash());

        h.update_bytes(self.language.as_bytes());
        h.update_bytes(self.theme.as_bytes());
        h.update_bytes(self.font_family.as_bytes());

        h.finish()
    }

    fn clone_node(&self) -> Box<dyn Node> {
        Box::new(self.clone())
    }

    fn reset(&mut self) {
        self.position.reset();
        self.rotation.reset();
        self.scale.reset();
        self.code.reset();
        self.font_size.reset();
        self.opacity.reset();
        self.dim_opacity.reset();
        self.anchor.reset();
    }
}