Skip to main content

rustmotion_components/
pill_nav.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use skia_safe::{Canvas, PaintStyle, RRect, Rect};
4
5use rustmotion_core::css::CssStyle;
6use rustmotion_core::engine::animator::AnimatedProperties;
7use rustmotion_core::engine::layout_pass::BoxLayout;
8use rustmotion_core::engine::renderer::{
9    draw_text_with_fallback, emoji_typeface, measure_text_with_fallback, paint_from_hex,
10    typeface_with_fallback,
11};
12use rustmotion_core::schema::TimelineStep;
13use rustmotion_core::traits::{PaintCtx, Painter, TimingConfig};
14
15fn default_pill_color() -> String {
16    "#3B82F6".to_string()
17}
18fn default_text_color() -> String {
19    "#FFFFFF".to_string()
20}
21fn default_inactive_text_color() -> String {
22    "#9CA3AF".to_string()
23}
24fn default_background_color() -> String {
25    "#1E293B".to_string()
26}
27fn default_height() -> f32 {
28    44.0
29}
30fn default_border_radius() -> f32 {
31    22.0
32}
33fn default_gap() -> f32 {
34    4.0
35}
36fn default_transition_duration() -> f64 {
37    0.3
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
41pub struct PillTransition {
42    pub to: u32,
43    pub at: f64,
44}
45
46#[derive(Debug, Serialize, Deserialize, JsonSchema)]
47pub struct PillNav {
48    pub items: Vec<String>,
49    #[serde(default)]
50    pub active_index: u32,
51    #[serde(default)]
52    pub transitions: Vec<PillTransition>,
53    #[serde(default = "default_pill_color")]
54    pub pill_color: String,
55    #[serde(default = "default_text_color")]
56    pub text_color: String,
57    #[serde(default = "default_inactive_text_color")]
58    pub inactive_text_color: String,
59    #[serde(default = "default_background_color")]
60    pub background_color: String,
61    #[serde(default = "default_height")]
62    pub height: f32,
63    #[serde(default = "default_border_radius")]
64    pub border_radius: f32,
65    #[serde(default = "default_gap")]
66    pub gap: f32,
67    #[serde(default = "default_transition_duration")]
68    pub transition_duration: f64,
69    #[serde(flatten)]
70    pub timing: TimingConfig,
71    #[serde(default)]
72    pub style: CssStyle,
73    #[serde(default)]
74    pub timeline: Vec<TimelineStep>,
75    #[serde(default)]
76    pub stagger: Option<f32>,
77}
78
79rustmotion_core::impl_traits!(PillNav {
80    Animatable => animation,
81    Timed => timing,
82    Styled => style,
83});
84
85impl PillNav {
86    /// Resolves `font-size` against a real per-frame viewport (`rem`/`vw`/
87    /// `vh` now resolve instead of silently dropping to 0px — lot B, wave
88    /// S). `em`/`%` on `font-size` itself remain approximate — see
89    /// `crate::intrinsic::font_size_ctx`'s doc comment.
90    fn resolved_font_size(&self, ctx: &PaintCtx) -> f32 {
91        self.style.font_size_px_ctx(
92            &crate::intrinsic::font_size_ctx(ctx.video_width as f32, ctx.video_height as f32, 0.0),
93            14.0,
94        )
95    }
96
97    fn make_font(&self, bold: bool, ctx: &PaintCtx) -> Option<skia_safe::Font> {
98        let font_style = if bold {
99            skia_safe::FontStyle::bold()
100        } else {
101            skia_safe::FontStyle::normal()
102        };
103        let family = self.style.font_family.as_deref().unwrap_or("Inter");
104        let typeface = typeface_with_fallback(family, font_style).ok()?;
105        Some(skia_safe::Font::from_typeface(
106            typeface,
107            self.resolved_font_size(ctx),
108        ))
109    }
110
111    fn compute_tab_layout(&self, ctx: &PaintCtx) -> Option<(f32, Vec<f32>, Vec<f32>)> {
112        let font = self.make_font(false, ctx)?;
113        let font_size = self.resolved_font_size(ctx);
114        let emoji_font = emoji_typeface().map(|tf| skia_safe::Font::from_typeface(tf, font_size));
115        let h_pad = font_size * 1.2;
116
117        let mut tab_widths: Vec<f32> = Vec::new();
118        for label in &self.items {
119            let text_w = measure_text_with_fallback(label, &font, &emoji_font, 0.0);
120            tab_widths.push(text_w + h_pad * 2.0);
121        }
122
123        let inner_pad = self.gap;
124        let mut tab_positions: Vec<f32> = Vec::new();
125        let mut x = inner_pad;
126        for (i, tw) in tab_widths.iter().enumerate() {
127            tab_positions.push(x);
128            x += tw;
129            if i < tab_widths.len() - 1 {
130                x += self.gap;
131            }
132        }
133
134        let total_w = x + inner_pad;
135        Some((total_w, tab_positions, tab_widths))
136    }
137
138    fn active_at_time(&self, time: f64) -> (u32, Option<(u32, f64)>) {
139        let mut current = self.active_index;
140        let mut _prev_index = self.active_index;
141        let mut transition_info: Option<(u32, f64)> = None;
142
143        let mut sorted_transitions = self.transitions.clone();
144        sorted_transitions.sort_by(|a, b| a.at.partial_cmp(&b.at).unwrap());
145
146        for tr in &sorted_transitions {
147            if time < tr.at {
148                break;
149            }
150            let end_time = tr.at + self.transition_duration;
151            if time < end_time {
152                // Mid-transition
153                let progress = (time - tr.at) / self.transition_duration;
154                _prev_index = current;
155                current = tr.to;
156                transition_info = Some((_prev_index, progress));
157                break;
158            }
159            _prev_index = current;
160            current = tr.to;
161        }
162
163        (current, transition_info)
164    }
165}
166
167impl PillNav {
168    fn paint(&self, canvas: &Canvas, layout_w: f32, layout_h: f32, time: f64, ctx: &PaintCtx) {
169        if self.items.is_empty() {
170            return;
171        }
172
173        let w = layout_w;
174        let h = layout_h;
175
176        // Outer container
177        let outer_rect = Rect::from_xywh(0.0, 0.0, w, h);
178        let outer_rrect = RRect::new_rect_xy(outer_rect, self.border_radius, self.border_radius);
179        let mut bg_paint = paint_from_hex(&self.background_color);
180        bg_paint.set_style(PaintStyle::Fill);
181        bg_paint.set_anti_alias(true);
182        canvas.draw_rrect(outer_rrect, &bg_paint);
183
184        let Some((_total_w, tab_positions, tab_widths)) = self.compute_tab_layout(ctx) else {
185            return;
186        };
187        let (active, transition_info) = self.active_at_time(time);
188
189        // Pill indicator
190        let pill_h = h - self.gap * 2.0;
191        let pill_y = self.gap;
192        let pill_radius = self.border_radius - self.gap;
193
194        let active_idx = active.min(self.items.len() as u32 - 1) as usize;
195        let (pill_x, pill_w) = if let Some((from_idx, progress)) = transition_info {
196            let from = from_idx.min(self.items.len() as u32 - 1) as usize;
197            let to = active_idx;
198            let t = progress as f32;
199            let from_x = tab_positions[from];
200            let to_x = tab_positions[to];
201            let from_w = tab_widths[from];
202            let to_w = tab_widths[to];
203            (from_x + (to_x - from_x) * t, from_w + (to_w - from_w) * t)
204        } else {
205            (tab_positions[active_idx], tab_widths[active_idx])
206        };
207
208        let pill_rect = Rect::from_xywh(pill_x, pill_y, pill_w, pill_h);
209        let pill_rrect = RRect::new_rect_xy(pill_rect, pill_radius, pill_radius);
210        let mut pill_paint = paint_from_hex(&self.pill_color);
211        pill_paint.set_style(PaintStyle::Fill);
212        pill_paint.set_anti_alias(true);
213        canvas.draw_rrect(pill_rrect, &pill_paint);
214
215        // Tab labels
216        let Some(font) = self.make_font(false, ctx) else {
217            return;
218        };
219        let font_size = self.resolved_font_size(ctx);
220        let emoji_font = emoji_typeface().map(|tf| skia_safe::Font::from_typeface(tf, font_size));
221        let (_, metrics) = font.metrics();
222        let text_y = (h + (-metrics.ascent)) / 2.0;
223
224        for (i, label) in self.items.iter().enumerate() {
225            let is_active = i == active_idx;
226            let color = if is_active {
227                &self.text_color
228            } else {
229                &self.inactive_text_color
230            };
231            let mut label_paint = paint_from_hex(color);
232            label_paint.set_anti_alias(true);
233
234            let text_w = measure_text_with_fallback(label, &font, &emoji_font, 0.0);
235            let text_x = tab_positions[i] + (tab_widths[i] - text_w) / 2.0;
236
237            draw_text_with_fallback(
238                canvas,
239                label,
240                &font,
241                &emoji_font,
242                0.0,
243                text_x,
244                text_y,
245                &label_paint,
246            );
247        }
248    }
249}
250
251impl Painter for PillNav {
252    fn paint_content(
253        &self,
254        canvas: &Canvas,
255        layout: &BoxLayout,
256        _props: &AnimatedProperties,
257        ctx: &PaintCtx,
258    ) {
259        self.paint(canvas, layout.width, layout.height, ctx.time, ctx);
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use rustmotion_core::css::CssStyle;
267    use rustmotion_core::css::Length;
268
269    fn test_ctx() -> PaintCtx {
270        PaintCtx {
271            time: 0.0,
272            scenario_time: 0.0,
273            scene_duration: 1.0,
274            frame_index: 0,
275            fps: 30,
276            video_width: 400,
277            video_height: 200,
278            stagger_offset: 0.0,
279        }
280    }
281
282    // ─── Lot B, wave S: relative `font-size` units ─────────────────────────
283
284    #[test]
285    fn rem_font_size_paints_visible_ink() {
286        // Reproduction: `font-size: "2rem"` used to resolve to 0px via the
287        // context-free `font_size_px_or`.
288        let nav = PillNav {
289            items: vec!["Home".to_string(), "About".to_string()],
290            active_index: 0,
291            transitions: Vec::new(),
292            pill_color: default_pill_color(),
293            text_color: default_text_color(),
294            inactive_text_color: default_inactive_text_color(),
295            background_color: default_background_color(),
296            height: default_height(),
297            border_radius: default_border_radius(),
298            gap: default_gap(),
299            transition_duration: default_transition_duration(),
300            timing: Default::default(),
301            style: CssStyle {
302                font_size: Some(Length::String("2rem".into())),
303                ..Default::default()
304            },
305            timeline: Vec::new(),
306            stagger: None,
307        };
308        const W: i32 = 400;
309        const H: i32 = 100;
310        let mut surface = skia_safe::surfaces::raster_n32_premul((W, H)).expect("raster surface");
311        {
312            let canvas = surface.canvas();
313            nav.paint(canvas, 300.0, 44.0, 0.0, &test_ctx());
314        }
315        let snapshot = surface.image_snapshot();
316        let info = skia_safe::ImageInfo::new(
317            (W, H),
318            skia_safe::ColorType::RGBA8888,
319            skia_safe::AlphaType::Premul,
320            None,
321        );
322        let mut buf = vec![0u8; (W * H * 4) as usize];
323        let ok = snapshot.read_pixels(
324            &info,
325            &mut buf,
326            (W * 4) as usize,
327            skia_safe::IPoint::new(0, 0),
328            skia_safe::image::CachingHint::Disallow,
329        );
330        assert!(ok, "pixel read should succeed");
331        let lit = buf.chunks_exact(4).filter(|p| p[3] > 0).count();
332        assert!(
333            lit > 20,
334            "pill_nav at font-size: 2rem must paint visible ink, got {lit} lit pixels"
335        );
336    }
337}