rustmotion-components 0.6.1

Component library for rustmotion (51 components)
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Paint dispatcher for the new `paint_tree` pipeline. Bridges from the
//! taffy-laid-out `BoxNode` tree back to component-typed `Painter` impls.
//!
//! Naming kept as "legacy" for now to avoid churn in callers; this is the
//! sole dispatcher in use since all 51 components implement `Painter`.
//!
//! Containers (Card / Flex / Grid / Container / Positioned) are intentionally
//! skipped: paint_pass already paints their box decorations and recurses into
//! children — so calling the container's own `paint_content` would do nothing
//! anyway, and we save a no-op call.

use rustmotion_core::engine::animator::{resolve_props_for_effects, AnimatedProperties};
use rustmotion_core::engine::box_tree::NodeId;
use rustmotion_core::engine::layout_pass::BoxLayout;
use rustmotion_core::engine::paint_pass::{PaintDispatcher, PaintFrame};
use rustmotion_core::traits::PaintCtx;
use skia_safe::Canvas;

use crate::{ChildComponent, Component};

/// Maps NodeIds to `ChildComponent`s and dispatches paint to their
/// `Painter::paint_content` impls.
pub struct LegacyPaintDispatcher<'a> {
    /// `components[id as usize]` is the component for `id`. Slot 0 is the
    /// synthetic root and is always `None`.
    components: &'a [Option<&'a ChildComponent>],
    /// Per-node container-stagger delay (indexed like `components`); empty
    /// when the caller doesn't carry stagger information.
    stagger_delays: &'a [f64],
    /// Per-node accumulated affine time remap `(scale, shift)` from ancestor
    /// containers' `time_scale`/`time_offset` (indexed like `components`);
    /// `t_local = scale * t_global + shift`. Empty → identity everywhere.
    time_params: &'a [(f64, f64)],
}

impl<'a> LegacyPaintDispatcher<'a> {
    pub fn new(components: &'a [Option<&'a ChildComponent>]) -> Self {
        Self {
            components,
            stagger_delays: &[],
            time_params: &[],
        }
    }

    /// Build from a [`BuiltScene`], carrying its stagger delays so internal
    /// animations shift by the same amount as the CSS overrides, and its
    /// per-node time remaps so internal animations (counter, draw_in,
    /// typewriter…) advance at the same local time as the CSS overrides.
    pub fn for_scene(built: &'a crate::box_builder::BuiltScene<'a>) -> Self {
        Self {
            components: &built.components,
            stagger_delays: &built.stagger_delays,
            time_params: &built.time_params,
        }
    }

    fn lookup(&self, id: NodeId) -> Option<&'a ChildComponent> {
        let idx = id as usize;
        self.components.get(idx).copied().flatten()
    }
}

impl<'a> PaintDispatcher for LegacyPaintDispatcher<'a> {
    fn dispatch(
        &self,
        canvas: &Canvas,
        payload: &(dyn std::any::Any + Send + Sync),
        _css: &rustmotion_core::css::CssStyle,
        layout: &BoxLayout,
        frame: &PaintFrame,
    ) {
        let Some(node_id) = payload.downcast_ref::<NodeId>() else {
            return;
        };
        let Some(child) = self.lookup(*node_id) else {
            return;
        };

        // Containers paint nothing of their own here — children are handled
        // recursively by paint_tree, and decorations were already painted.
        if is_container(&child.component) {
            return;
        }

        // Resolve animations for this leaf. Outer transforms (translate /
        // scale / rotate / opacity / blur) are applied by `paint_pass` via
        // the CSS overrides injected at box-tree build time, so we don't
        // wrap the canvas here. `props` is still needed for internal-only
        // fields like `draw_progress`, `stroke_width`, `visible_chars*`,
        // and `char_animation`. Timeline steps and container-stagger delays
        // are folded in so those internal animations shift exactly like the
        // CSS overrides do.
        let stagger_delay = self
            .stagger_delays
            .get(*node_id as usize)
            .copied()
            .unwrap_or(0.0);
        // Ancestor `time_scale`/`time_offset` remap the time seen by this
        // node's whole animation surface: internal effect resolution below
        // AND `PaintCtx.time` (a counter or a typewriter inside a slowed
        // container must advance at local time). `scene_duration` stays
        // GLOBAL — it describes the physical scene window, not the remapped
        // timeline, so duration-relative effects keep their real-time span.
        let (t_scale, t_shift) = self
            .time_params
            .get(*node_id as usize)
            .copied()
            .unwrap_or((1.0, 0.0));
        let local_time = frame.time * t_scale + t_shift;
        let props = match crate::box_builder::effective_effects(&child.component, stagger_delay) {
            Some(effects) => resolve_props_for_effects(&effects, local_time, frame.scene_duration),
            None => AnimatedProperties::default(),
        };
        if props.opacity <= 0.0 {
            return;
        }

        let Some(painter) = child.component.as_painter() else {
            return;
        };

        // The `Painter` contract (traits/painter.rs, rules/paint-context.md)
        // promises the canvas is already translated to the CONTENT-box
        // origin, with `layout` describing the content box — padding
        // reserved by taffy is consumed here, not left for the painter to
        // rediscover. `Codeblock` is a deliberate, documented exception: it
        // reads `style.padding` itself (`codeblock/render.rs` computes
        // `code_x = x + pad_left + gutter_width` from the layout origin it
        // receives) and paints its own background/border directly from the
        // BORDER-box origin. Honoring the general contract for it too would
        // double-apply padding — content shifted twice, background rect
        // shrunk incorrectly — so it keeps receiving the untranslated
        // border-box origin and dimensions, exactly as before this fix.
        let is_self_padding = matches!(child.component, Component::Codeblock(_));

        canvas.save();
        let local = if is_self_padding {
            canvas.translate((layout.x, layout.y));
            BoxLayout {
                x: 0.0,
                y: 0.0,
                width: layout.width,
                height: layout.height,
                ..Default::default()
            }
        } else {
            let (cx, cy, cw, ch) = layout.content_box();
            canvas.translate((cx, cy));
            BoxLayout {
                x: 0.0,
                y: 0.0,
                width: cw,
                height: ch,
                ..Default::default()
            }
        };

        let paint_ctx = PaintCtx {
            time: local_time,
            scenario_time: frame.scenario_time,
            scene_duration: frame.scene_duration,
            frame_index: frame.frame_index,
            fps: frame.fps,
            video_width: frame.video_width,
            video_height: frame.video_height,
            stagger_offset: stagger_delay,
        };
        painter.paint_content(canvas, &local, &props, &paint_ctx);

        canvas.restore();
    }
}

fn is_container(c: &Component) -> bool {
    matches!(
        c,
        Component::Card(_)
            | Component::Flex(_)
            | Component::Grid(_)
            | Component::Container(_)
            | Component::Positioned(_)
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::box_builder::build_scene;
    use crate::shape::Shape;
    use crate::PositionMode;
    use rustmotion_core::css::style::{CssStyle, Size as CSize};
    use rustmotion_core::css::taffy_bridge::ConversionContext;
    use rustmotion_core::css::units::LengthPercentage as CLP;
    use rustmotion_core::engine::box_tree::BoxKind;
    use rustmotion_core::engine::layout_pass::run_layout;
    use rustmotion_core::schema::ShapeType;
    use std::sync::Arc;

    fn shape_child(w: f32, h: f32, x: f32, y: f32) -> ChildComponent {
        ChildComponent {
            component: Component::Shape(Shape {
                shape: ShapeType::Rect,
                text: None,
                timing: Default::default(),
                style: CssStyle {
                    width: Some(CSize::Length(CLP::Px(w))),
                    height: Some(CSize::Length(CLP::Px(h))),
                    ..Default::default()
                },
                timeline: Vec::new(),
                stagger: None,
                fill: Some(rustmotion_core::schema::Fill::Solid("#ff0000".into())),
                stroke: None,
            }),
            position: Some(PositionMode::Absolute { x, y }),
            x: None,
            y: None,
            z_index: None,
            bleed: false,
        }
    }

    #[test]
    fn leaf_painter_content_is_inset_by_padding() {
        // A 100x80 red shape at (0,0) with `padding: 20`. The Painter
        // contract (traits/painter.rs, rules/paint-context.md) promises the
        // canvas is already translated to the CONTENT-box origin — so the
        // shape's own fill (which just paints (0,0)..(layout.width,
        // layout.height)) should only cover the 60x40 content box (20,20)
        // to (80,60), leaving the 20px padding ring showing the (empty/
        // background) canvas underneath. Bug: the dispatcher translated to
        // the BORDER-box origin and handed the painter the full border-box
        // dimensions, so the fill ignored padding entirely and covered the
        // whole (0,0)-(100,80) box.
        use rustmotion_core::css::style::Edges;

        let mut scene = vec![shape_child(100.0, 80.0, 0.0, 0.0)];
        if let Component::Shape(s) = &mut scene[0].component {
            s.style.padding = Some(Edges::Uniform(CLP::Px(20.0)));
        }
        let built = build_scene(&scene, (200.0, 200.0));
        let layout = run_layout(&built.root, (200.0, 200.0), &ConversionContext::default());

        let mut surface =
            skia_safe::surfaces::raster_n32_premul((200, 200)).expect("raster surface");
        let canvas = surface.canvas();
        let dispatcher = LegacyPaintDispatcher::new(&built.components);
        let frame = PaintFrame {
            time: 0.0,
            scenario_time: 0.0,
            frame_index: 0,
            fps: 30,
            video_width: 200,
            video_height: 200,
            scene_duration: 1.0,
            camera: None,
        };
        rustmotion_core::engine::paint_pass::paint_tree(
            canvas,
            &built.root,
            &layout,
            &frame,
            &dispatcher,
        );

        let snapshot = surface.image_snapshot();
        let info = skia_safe::ImageInfo::new(
            (1, 1),
            skia_safe::ColorType::RGBA8888,
            skia_safe::AlphaType::Premul,
            None,
        );
        let read = |x: i32, y: i32| -> [u8; 4] {
            let mut buf = [0u8; 4];
            assert!(snapshot.read_pixels(
                &info,
                &mut buf,
                4,
                skia_safe::IPoint::new(x, y),
                skia_safe::image::CachingHint::Disallow,
            ));
            buf
        };

        // Inside the padding ring (5,5): must NOT be red after the fix.
        let padding_zone = read(5, 5);
        assert!(
            !(padding_zone[0] > 200 && padding_zone[1] < 50 && padding_zone[2] < 50),
            "padding ring must not be painted by the leaf's own fill, got {:?}",
            padding_zone
        );
        // Deep inside the content box (50,40): must be red either way.
        let content_zone = read(50, 40);
        assert!(
            content_zone[0] > 200 && content_zone[1] < 50 && content_zone[2] < 50,
            "content box must still be painted red, got {:?}",
            content_zone
        );
    }

    #[test]
    fn dispatch_runs_paint_content_on_leaf() {
        let scene = vec![shape_child(50.0, 30.0, 10.0, 20.0)];
        let built = build_scene(&scene, (200.0, 200.0));
        let layout = run_layout(&built.root, (200.0, 200.0), &ConversionContext::default());

        // Sanity: the only component slot at idx 1 points to the shape.
        assert!(built.components[0].is_none());
        assert!(built.components[1].is_some());

        // Build a Skia raster surface and run a paint pass against the
        // dispatcher — this just exercises the dispatcher hook end-to-end.
        let mut surface =
            skia_safe::surfaces::raster_n32_premul((200, 200)).expect("raster surface");
        let canvas = surface.canvas();
        let dispatcher = LegacyPaintDispatcher::new(&built.components);
        let frame = PaintFrame {
            time: 0.0,
            scenario_time: 0.0,
            frame_index: 0,
            fps: 30,
            video_width: 200,
            video_height: 200,
            scene_duration: 1.0,
            camera: None,
        };
        rustmotion_core::engine::paint_pass::paint_tree(
            canvas,
            &built.root,
            &layout,
            &frame,
            &dispatcher,
        );

        // Read back the pixel at the centre of the shape (10+25, 20+15)=(35,35)
        // and assert it's red-ish — confirms paint_content painted.
        let snapshot = surface.image_snapshot();
        let mut buf = [0u8; 4];
        let info = skia_safe::ImageInfo::new(
            (1, 1),
            skia_safe::ColorType::RGBA8888,
            skia_safe::AlphaType::Premul,
            None,
        );
        let read_ok = snapshot.read_pixels(
            &info,
            &mut buf,
            4,
            skia_safe::IPoint::new(35, 35),
            skia_safe::image::CachingHint::Disallow,
        );
        assert!(read_ok, "pixel read should succeed");
        // Red channel should dominate (#ff0000).
        assert!(buf[0] > 200, "expected red, got rgba {:?}", buf);
        assert!(buf[1] < 50, "green should be low, got rgba {:?}", buf);
        assert!(buf[2] < 50, "blue should be low, got rgba {:?}", buf);
    }

    #[test]
    fn card_background_painted_with_red_shape_inside() {
        // Card 100×80 at (40,30), green background, contains a red 30×20 shape
        // absolutely positioned at (10,10) inside the card.
        use crate::card::Card;

        use rustmotion_core::css::style::{Background, Color};

        let red_shape = ChildComponent {
            component: Component::Shape(Shape {
                shape: ShapeType::Rect,
                text: None,
                timing: Default::default(),
                style: CssStyle {
                    width: Some(CSize::Length(CLP::Px(30.0))),
                    height: Some(CSize::Length(CLP::Px(20.0))),
                    ..Default::default()
                },
                timeline: Vec::new(),
                stagger: None,
                fill: Some(rustmotion_core::schema::Fill::Solid("#ff0000".into())),
                stroke: None,
            }),
            position: Some(PositionMode::Absolute { x: 10.0, y: 10.0 }),
            x: None,
            y: None,
            z_index: None,
            bleed: false,
        };

        let card = ChildComponent {
            component: Component::Card(Card {
                children: vec![red_shape],
                timing: Default::default(),
                style: CssStyle {
                    width: Some(CSize::Length(CLP::Px(100.0))),
                    height: Some(CSize::Length(CLP::Px(80.0))),
                    background: Some(Background::Color(Color::String("#00ff00".into()))),
                    ..Default::default()
                },
                timeline: Vec::new(),
                stagger: None,
                time_scale: None,
                time_offset: None,
            }),
            position: Some(PositionMode::Absolute { x: 40.0, y: 30.0 }),
            x: None,
            y: None,
            z_index: None,
            bleed: false,
        };

        let scene = vec![card];
        let built = build_scene(&scene, (200.0, 200.0));
        let layout = run_layout(&built.root, (200.0, 200.0), &ConversionContext::default());

        let mut surface =
            skia_safe::surfaces::raster_n32_premul((200, 200)).expect("raster surface");
        let canvas = surface.canvas();
        let dispatcher = LegacyPaintDispatcher::new(&built.components);
        let frame = PaintFrame {
            time: 0.0,
            scenario_time: 0.0,
            frame_index: 0,
            fps: 30,
            video_width: 200,
            video_height: 200,
            scene_duration: 1.0,
            camera: None,
        };
        rustmotion_core::engine::paint_pass::paint_tree(
            canvas,
            &built.root,
            &layout,
            &frame,
            &dispatcher,
        );

        let snapshot = surface.image_snapshot();
        let info = skia_safe::ImageInfo::new(
            (1, 1),
            skia_safe::ColorType::RGBA8888,
            skia_safe::AlphaType::Premul,
            None,
        );
        let read = |x: i32, y: i32| -> [u8; 4] {
            let mut buf = [0u8; 4];
            assert!(snapshot.read_pixels(
                &info,
                &mut buf,
                4,
                skia_safe::IPoint::new(x, y),
                skia_safe::image::CachingHint::Disallow,
            ));
            buf
        };

        // Card background area: bottom-right corner of the card (well away
        // from the red shape at (10,10)+(30,20)). Card spans x∈[40,140],
        // y∈[30,110]. Pick (130, 100) — green.
        let bg = read(130, 100);
        assert!(bg[1] > 200, "expected green card bg, got {:?}", bg);
        assert!(bg[0] < 50, "red should be low at bg, got {:?}", bg);

        // Red shape area: shape spans (50,40)→(80,60). Pick centre (65, 50).
        let fg = read(65, 50);
        assert!(fg[0] > 200, "expected red shape, got {:?}", fg);
        assert!(fg[1] < 50, "green should be low at shape, got {:?}", fg);
    }

    #[test]
    fn fade_in_preset_drives_alpha_through_dispatcher() {
        // A red shape with a `FadeIn` preset over 0.5s, sampled at two points:
        //   t=0.05s — early in the curve, opacity should be near zero
        //   t=0.5s  — at the end of the curve, opacity should be ~1
        // The dispatcher must wire animator output into the canvas alpha,
        // otherwise both samples render fully opaque and the test fails.
        use crate::shape::Shape;
        use rustmotion_core::schema::{AnimationEffect, AnimationTiming, ShapeType};

        let make_scene = || {
            let shape = ChildComponent {
                component: Component::Shape(Shape {
                    shape: ShapeType::Rect,
                    text: None,
                    timing: Default::default(),
                    style: CssStyle {
                        width: Some(CSize::Length(CLP::Px(100.0))),
                        height: Some(CSize::Length(CLP::Px(100.0))),
                        animation: vec![AnimationEffect::FadeIn(AnimationTiming {
                            duration: 0.5,
                            ..Default::default()
                        })],
                        ..Default::default()
                    },
                    timeline: Vec::new(),
                    stagger: None,
                    fill: Some(rustmotion_core::schema::Fill::Solid("#ff0000".into())),
                    stroke: None,
                }),
                position: Some(PositionMode::Absolute { x: 0.0, y: 0.0 }),
                x: None,
                y: None,
                z_index: None,
                bleed: false,
            };
            vec![shape]
        };

        let sample_red_at = |time: f64| -> u8 {
            let scene = make_scene();
            // Build the box tree with an animation context so the FadeIn
            // preset is resolved into CSS overrides (transform/opacity) on
            // each box. paint_pass then applies those during painting.
            let built = crate::box_builder::build_scene_with_anim(
                &scene,
                (200.0, 200.0),
                crate::box_builder::BuildAnimationCtx {
                    time,
                    scenario_time: time,
                    scene_duration: 1.0,
                    fps: 30,
                },
            );
            let layout = run_layout(&built.root, (200.0, 200.0), &ConversionContext::default());
            let mut surface =
                skia_safe::surfaces::raster_n32_premul((200, 200)).expect("raster surface");
            let canvas = surface.canvas();
            canvas.clear(skia_safe::Color::BLACK);
            let dispatcher = LegacyPaintDispatcher::new(&built.components);
            let frame = PaintFrame {
                time,
                scenario_time: time,
                frame_index: 0,
                fps: 30,
                video_width: 200,
                video_height: 200,
                scene_duration: 1.0,
                camera: None,
            };
            rustmotion_core::engine::paint_pass::paint_tree(
                canvas,
                &built.root,
                &layout,
                &frame,
                &dispatcher,
            );
            let snap = surface.image_snapshot();
            let info = skia_safe::ImageInfo::new(
                (1, 1),
                skia_safe::ColorType::RGBA8888,
                skia_safe::AlphaType::Premul,
                None,
            );
            let mut buf = [0u8; 4];
            assert!(snap.read_pixels(
                &info,
                &mut buf,
                4,
                skia_safe::IPoint::new(50, 50),
                skia_safe::image::CachingHint::Disallow,
            ));
            buf[0]
        };

        let early = sample_red_at(0.05);
        let late = sample_red_at(0.5);
        assert!(
            late > early + 50,
            "FadeIn should produce a clearly higher red at t=0.5 than at t=0.05 \
             (early={}, late={})",
            early,
            late,
        );
        assert!(
            late > 200,
            "at t=duration the shape should be ~fully opaque red, got {}",
            late
        );
        assert!(
            early < 150,
            "at t=0.05 the shape should be mostly transparent, got {}",
            early
        );
    }

    #[test]
    fn dispatch_skips_unknown_payloads() {
        let dispatcher = LegacyPaintDispatcher::new(&[]);
        let mut surface = skia_safe::surfaces::raster_n32_premul((10, 10)).unwrap();
        let canvas = surface.canvas();
        let css = rustmotion_core::css::CssStyle::default();
        let layout = BoxLayout {
            x: 0.0,
            y: 0.0,
            width: 10.0,
            height: 10.0,
            ..Default::default()
        };
        let frame = PaintFrame {
            time: 0.0,
            scenario_time: 0.0,
            frame_index: 0,
            fps: 30,
            video_width: 10,
            video_height: 10,
            scene_duration: 1.0,
            camera: None,
        };
        // Wrong payload type — must not panic.
        let bogus: Arc<dyn std::any::Any + Send + Sync> = Arc::new(42i64);
        // Reach into the dispatcher trait method.
        // (BoxKind::Component is just a marker here; we drive dispatch directly.)
        dispatcher.dispatch(canvas, bogus.as_ref(), &css, &layout, &frame);
        let _ = BoxKind::Container; // touch import
    }
}