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
use rustmotion_core::css::CssStyle;
use rustmotion_core::error::Result;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use skia_safe::{Canvas, ColorType, ImageInfo, Paint, PaintStyle, RRect, Rect};

use rustmotion_core::engine::animator::AnimatedProperties;
use rustmotion_core::engine::layout_pass::BoxLayout;
use rustmotion_core::engine::renderer::{
    asset_cache, draw_text_with_fallback, emoji_typeface, fetch_icon_svg, paint_from_hex,
    typeface_with_fallback,
};
use rustmotion_core::schema::TimelineStep;
use rustmotion_core::traits::{PaintCtx, Painter, TimingConfig};

fn default_width() -> f32 {
    360.0
}
fn default_slide_in_at() -> f64 {
    0.5
}
fn default_slide_duration() -> f64 {
    0.15
}
fn default_stack_gap() -> f32 {
    12.0
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum NotificationVariant {
    #[default]
    Info,
    Success,
    Warning,
    Error,
}

impl NotificationVariant {
    fn default_color(&self) -> &str {
        match self {
            NotificationVariant::Info => "#3B82F6",
            NotificationVariant::Success => "#22C55E",
            NotificationVariant::Warning => "#F59E0B",
            NotificationVariant::Error => "#EF4444",
        }
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct Notification {
    pub title: String,
    #[serde(default)]
    pub message: Option<String>,
    #[serde(default)]
    pub icon: Option<String>,
    #[serde(default)]
    pub variant: NotificationVariant,
    #[serde(default = "default_width")]
    pub width: f32,
    #[serde(default = "default_slide_in_at")]
    pub slide_in_at: f64,
    #[serde(default)]
    pub slide_out_at: Option<f64>,
    #[serde(default = "default_slide_duration")]
    pub slide_duration: f64,
    #[serde(default)]
    pub accent_color: Option<String>,
    /// Timestamps at which this notification gets pushed down one slot
    /// (i.e. when another notification appears above it).
    #[serde(default)]
    pub push_at: Vec<f64>,
    /// Gap between stacked notifications in pixels (default 12).
    #[serde(default = "default_stack_gap")]
    pub stack_gap: f32,
    /// Delay fade-in until after other notifications finish their push animation.
    /// Set to true when this notification triggers a push_at on others.
    #[serde(default)]
    pub wait_for_push: bool,
    #[serde(flatten)]
    pub timing: TimingConfig,
    #[serde(default)]
    pub style: CssStyle,
    #[serde(default)]
    pub timeline: Vec<TimelineStep>,
    #[serde(default)]
    pub stagger: Option<f32>,
}

rustmotion_core::impl_traits!(Notification {
    Animatable => animation,
    Timed => timing,
    Styled => style,
});

impl Notification {
    fn resolved_accent_color(&self) -> &str {
        self.accent_color
            .as_deref()
            .unwrap_or_else(|| self.variant.default_color())
    }

    /// Resolves `font-size` against a real per-frame viewport (`rem`/`vw`/
    /// `vh` now resolve instead of silently dropping to 0px — lot B, wave
    /// S). `em`/`%` on `font-size` itself remain approximate — see
    /// `crate::intrinsic::font_size_ctx`'s doc comment.
    fn title_font_size(&self, ctx: &PaintCtx) -> f32 {
        self.style.font_size_px_ctx(
            &crate::intrinsic::font_size_ctx(ctx.video_width as f32, ctx.video_height as f32, 0.0),
            16.0,
        )
    }

    fn message_font_size(&self, ctx: &PaintCtx) -> f32 {
        self.title_font_size(ctx) * 0.85
    }

    fn make_font(&self, bold: bool, size: f32) -> Option<skia_safe::Font> {
        let font_style = if bold {
            skia_safe::FontStyle::bold()
        } else {
            skia_safe::FontStyle::normal()
        };
        let family = self.style.font_family.as_deref().unwrap_or("Inter");
        let typeface = typeface_with_fallback(family, font_style).ok()?;
        Some(skia_safe::Font::from_typeface(typeface, size))
    }

    fn compute_opacity(&self, time: f64) -> f32 {
        // Effective start: if wait_for_push, delay by slide_duration so push animations finish first
        let effective_start = if self.wait_for_push {
            self.slide_in_at + self.slide_duration
        } else {
            self.slide_in_at
        };

        // Before fade in
        if time < effective_start {
            return 0.0;
        }

        // During fade in
        let fade_in_end = effective_start + self.slide_duration;
        if time < fade_in_end {
            let t = ((time - effective_start) / self.slide_duration) as f32;
            return (t * t * (3.0 - 2.0 * t)).clamp(0.0, 1.0); // smoothstep
        }

        // Check fade out
        if let Some(slide_out_at) = self.slide_out_at {
            if time >= slide_out_at {
                let fade_out_end = slide_out_at + self.slide_duration;
                if time >= fade_out_end {
                    return 0.0;
                }
                let t = ((time - slide_out_at) / self.slide_duration) as f32;
                return (1.0 - t * t * (3.0 - 2.0 * t)).clamp(0.0, 1.0);
            }
        }

        // Fully visible
        1.0
    }

    fn render_icon_svg(
        &self,
        canvas: &Canvas,
        icon_id: &str,
        color: &str,
        x: f32,
        y: f32,
        size: f32,
    ) -> Result<()> {
        let icon_w = size.round() as u32;
        let icon_h = size.round() as u32;
        let cache_key = format!("icon:{}:{}:{}x{}", icon_id, color, icon_w, icon_h);

        let cache = asset_cache();
        let img = if let Some(cached) = cache.get(&cache_key) {
            cached.clone()
        } else if let Ok(svg_data) = fetch_icon_svg(icon_id, color, icon_w, icon_h) {
            let opt = usvg::Options::default();
            if let Ok(tree) = usvg::Tree::from_data(&svg_data, &opt) {
                let svg_size = tree.size();
                if let Some(mut pixmap) = tiny_skia::Pixmap::new(icon_w, icon_h) {
                    let sx = icon_w as f32 / svg_size.width();
                    let sy = icon_h as f32 / svg_size.height();
                    resvg::render(
                        &tree,
                        tiny_skia::Transform::from_scale(sx, sy),
                        &mut pixmap.as_mut(),
                    );
                    let img_data = skia_safe::Data::new_copy(pixmap.data());
                    let info = ImageInfo::new(
                        (icon_w as i32, icon_h as i32),
                        ColorType::RGBA8888,
                        skia_safe::AlphaType::Premul,
                        None,
                    );
                    if let Some(decoded) =
                        skia_safe::images::raster_from_data(&info, img_data, icon_w as usize * 4)
                    {
                        cache.insert(cache_key, decoded.clone());
                        decoded
                    } else {
                        return Ok(());
                    }
                } else {
                    return Ok(());
                }
            } else {
                return Ok(());
            }
        } else {
            return Ok(());
        };

        let dst = Rect::from_xywh(x, y, size, size);
        canvas.draw_image_rect(img, None, dst, &Paint::default());
        Ok(())
    }
}

impl Notification {
    fn paint(
        &self,
        canvas: &Canvas,
        layout_w: f32,
        layout_h: f32,
        time: f64,
        ctx: &PaintCtx,
    ) -> Result<()> {
        let w = layout_w;
        let h = layout_h;
        let opacity = self.compute_opacity(time);

        if opacity <= 0.0 {
            return Ok(());
        }

        // Resolve the title font before any canvas.save() so an early return
        // on font failure keeps save/restore balanced.
        let Some(title_font) = self.make_font(true, self.title_font_size(ctx)) else {
            return Ok(());
        };

        // Stack offset: count how many push_at timestamps have passed,
        // each one shifts this notification down by one slot with animation.
        let slot_size = h + self.stack_gap;
        let mut stack_y = 0.0_f32;
        let transition_dur = self.slide_duration;
        for &push_time in &self.push_at {
            if time >= push_time {
                let t = ((time - push_time) / transition_dur).clamp(0.0, 1.0) as f32;
                let eased = t * t * (3.0 - 2.0 * t); // smoothstep
                stack_y += slot_size * eased;
            }
        }

        canvas.save();
        if stack_y > 0.0 {
            canvas.translate((0.0, stack_y));
        }
        if opacity < 1.0 {
            let mut layer_paint = Paint::default();
            layer_paint.set_alpha_f(opacity);
            canvas.save_layer(&skia_safe::canvas::SaveLayerRec::default().paint(&layer_paint));
        }

        let bg_color = self.style.background_color_str().unwrap_or("#1E293B");
        let radius = self.style.border_radius_px_or(12.0);
        let accent_color = self.resolved_accent_color();
        let accent_width = 4.0;

        // Background rounded rect
        let bg_rect = Rect::from_xywh(0.0, 0.0, w, h);
        let bg_rrect = RRect::new_rect_xy(bg_rect, radius, radius);
        let mut bg_paint = paint_from_hex(bg_color);
        bg_paint.set_style(PaintStyle::Fill);
        bg_paint.set_anti_alias(true);
        canvas.draw_rrect(bg_rrect, &bg_paint);

        // Left accent stripe
        let accent_rect = Rect::from_xywh(0.0, 0.0, accent_width, h);
        let accent_rrect = RRect::new_rect_radii(
            accent_rect,
            &[
                (radius, radius).into(),
                (0.0, 0.0).into(),
                (0.0, 0.0).into(),
                (radius, radius).into(),
            ],
        );
        let mut accent_paint = paint_from_hex(accent_color);
        accent_paint.set_style(PaintStyle::Fill);
        accent_paint.set_anti_alias(true);
        canvas.draw_rrect(accent_rrect, &accent_paint);

        // Content area
        let h_pad = 16.0;
        let v_pad = 16.0;
        let icon_size = self.title_font_size(ctx) * 1.5;
        let mut content_x = accent_width + h_pad;

        // Icon
        if let Some(icon_id) = &self.icon {
            let icon_y = (h - icon_size) / 2.0;
            self.render_icon_svg(canvas, icon_id, accent_color, content_x, icon_y, icon_size)?;
            content_x += icon_size + 12.0;
        }

        // Title
        let title_fs = self.title_font_size(ctx);
        let emoji_font_title =
            emoji_typeface().map(|tf| skia_safe::Font::from_typeface(tf, title_fs));
        let title_color = self.style.color_str_or("#FFFFFF");
        let mut title_paint = paint_from_hex(title_color);
        title_paint.set_anti_alias(true);

        let (_, title_metrics) = title_font.metrics();
        let title_y = v_pad + (-title_metrics.ascent);

        draw_text_with_fallback(
            canvas,
            &self.title,
            &title_font,
            &emoji_font_title,
            0.0,
            content_x,
            title_y,
            &title_paint,
        );

        // Message
        if let Some(message) = &self.message {
            let msg_fs = self.message_font_size(ctx);
            if let Some(msg_font) = self.make_font(false, msg_fs) {
                let emoji_font_msg =
                    emoji_typeface().map(|tf| skia_safe::Font::from_typeface(tf, msg_fs));
                let mut msg_paint = paint_from_hex("#9CA3AF");
                msg_paint.set_anti_alias(true);

                let (_, msg_metrics) = msg_font.metrics();
                let msg_y = title_y + 4.0 + title_fs * 0.3 + (-msg_metrics.ascent);

                draw_text_with_fallback(
                    canvas,
                    message,
                    &msg_font,
                    &emoji_font_msg,
                    0.0,
                    content_x,
                    msg_y,
                    &msg_paint,
                );
            }
        }

        if opacity < 1.0 {
            canvas.restore();
        }
        canvas.restore();
        Ok(())
    }
}

impl Painter for Notification {
    fn paint_content(
        &self,
        canvas: &Canvas,
        layout: &BoxLayout,
        _props: &AnimatedProperties,
        ctx: &PaintCtx,
    ) {
        let _ = self.paint(canvas, layout.width, layout.height, ctx.time, ctx);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustmotion_core::css::CssStyle;
    use rustmotion_core::css::Length;

    fn test_ctx() -> PaintCtx {
        PaintCtx {
            time: 1.0,
            scenario_time: 1.0,
            scene_duration: 2.0,
            frame_index: 30,
            fps: 30,
            video_width: 400,
            video_height: 200,
            stagger_offset: 0.0,
        }
    }

    // ─── Lot B, wave S: relative `font-size` units ─────────────────────────

    #[test]
    fn rem_font_size_paints_visible_ink() {
        // Reproduction: `font-size: "2rem"` used to resolve to 0px via the
        // context-free `font_size_px_or`.
        let notification = Notification {
            title: "Hello".to_string(),
            message: None,
            icon: None,
            variant: NotificationVariant::Info,
            width: default_width(),
            slide_in_at: 0.0,
            slide_out_at: None,
            slide_duration: default_slide_duration(),
            accent_color: None,
            push_at: Vec::new(),
            stack_gap: default_stack_gap(),
            wait_for_push: false,
            timing: Default::default(),
            style: CssStyle {
                font_size: Some(Length::String("2rem".into())),
                ..Default::default()
            },
            timeline: Vec::new(),
            stagger: None,
        };
        const W: i32 = 400;
        const H: i32 = 200;
        let mut surface = skia_safe::surfaces::raster_n32_premul((W, H)).expect("raster surface");
        {
            let canvas = surface.canvas();
            notification
                .paint(canvas, 360.0, 100.0, 1.0, &test_ctx())
                .expect("paint succeeds");
        }
        let snapshot = surface.image_snapshot();
        let info = skia_safe::ImageInfo::new(
            (W, H),
            skia_safe::ColorType::RGBA8888,
            skia_safe::AlphaType::Premul,
            None,
        );
        let mut buf = vec![0u8; (W * H * 4) as usize];
        let ok = snapshot.read_pixels(
            &info,
            &mut buf,
            (W * 4) as usize,
            skia_safe::IPoint::new(0, 0),
            skia_safe::image::CachingHint::Disallow,
        );
        assert!(ok, "pixel read should succeed");
        // Title text is white (#FFFFFF default) on a dark #1E293B card —
        // probe for near-white ink specifically.
        let text_ink = buf
            .chunks_exact(4)
            .filter(|p| p[3] > 0 && p[0] > 200 && p[1] > 200 && p[2] > 200)
            .count();
        assert!(
            text_ink > 10,
            "notification at font-size: 2rem must paint visible text, got {text_ink} pixels"
        );
    }
}