Skip to main content

rustmotion_components/
treemap.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
15const DEFAULT_PALETTE: &[&str] = &[
16    "#3B82F6", "#EF4444", "#22C55E", "#F59E0B", "#8B5CF6", "#EC4899", "#06B6D4", "#F97316",
17];
18
19fn default_gap() -> f32 {
20    3.0
21}
22
23fn default_border_radius() -> f32 {
24    6.0
25}
26
27fn default_show_labels() -> bool {
28    true
29}
30
31fn default_animated() -> bool {
32    true
33}
34
35fn default_animation_duration() -> f64 {
36    1.0
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
40pub struct TreemapItem {
41    #[serde(default)]
42    pub label: Option<String>,
43    pub value: f64,
44    #[serde(default)]
45    pub color: Option<String>,
46}
47
48#[derive(Debug, Serialize, Deserialize, JsonSchema)]
49pub struct Treemap {
50    /// Data items to display in the treemap.
51    pub data: Vec<TreemapItem>,
52    /// Gap between rectangles in pixels.
53    #[serde(default = "default_gap")]
54    pub gap: f32,
55    /// Corner radius of rectangles.
56    #[serde(default = "default_border_radius")]
57    pub border_radius: f32,
58    /// Whether to show labels inside rectangles.
59    #[serde(default = "default_show_labels")]
60    pub show_labels: bool,
61    /// Whether to show values inside rectangles.
62    #[serde(default)]
63    pub show_values: bool,
64    /// Whether the treemap animates in.
65    #[serde(default = "default_animated")]
66    pub animated: bool,
67    /// Duration of the scale animation in seconds.
68    #[serde(default = "default_animation_duration")]
69    pub animation_duration: f64,
70    #[serde(flatten)]
71    pub timing: TimingConfig,
72    #[serde(default)]
73    pub style: CssStyle,
74    #[serde(default)]
75    pub timeline: Vec<TimelineStep>,
76    #[serde(default)]
77    pub stagger: Option<f32>,
78}
79
80rustmotion_core::impl_traits!(Treemap {
81    Animatable => animation,
82    Timed => timing,
83    Styled => style,
84});
85
86fn layout_treemap(items: &[(f64, usize)], rect: Rect, vertical: bool) -> Vec<(usize, Rect)> {
87    let total: f64 = items.iter().map(|i| i.0).sum();
88    if total <= 0.0 || items.is_empty() {
89        return vec![];
90    }
91    let mut results = vec![];
92    let mut offset = if vertical { rect.top } else { rect.left };
93    for &(value, idx) in items {
94        let fraction = (value / total) as f32;
95        let r = if vertical {
96            let h = rect.height() * fraction;
97            let r = Rect::from_xywh(rect.left, offset, rect.width(), h);
98            offset += h;
99            r
100        } else {
101            let w = rect.width() * fraction;
102            let r = Rect::from_xywh(offset, rect.top, w, rect.height());
103            offset += w;
104            r
105        };
106        results.push((idx, r));
107    }
108    results
109}
110
111impl Treemap {
112    fn progress_at(&self, time: f64) -> f32 {
113        if !self.animated {
114            return 1.0;
115        }
116        let start = self.timing.start_at.unwrap_or(0.0);
117        let elapsed = (time - start).max(0.0);
118        let p = (elapsed / self.animation_duration).clamp(0.0, 1.0) as f32;
119        1.0 - (1.0 - p).powi(3)
120    }
121
122    fn paint(&self, canvas: &Canvas, layout_w: f32, layout_h: f32, time: f64) {
123        let w = layout_w;
124        let h = layout_h;
125
126        if self.data.is_empty() {
127            return;
128        }
129
130        let progress = self.progress_at(time);
131
132        let mut sorted: Vec<(f64, usize)> = self
133            .data
134            .iter()
135            .enumerate()
136            .map(|(i, item)| (item.value, i))
137            .collect();
138        sorted.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
139
140        let full_rect = Rect::from_xywh(0.0, 0.0, w, h);
141        let rects = layout_treemap(&sorted, full_rect, false);
142
143        let font_style = skia_safe::FontStyle::normal();
144        let Ok(typeface) = typeface_with_fallback("Inter", font_style) else {
145            return;
146        };
147
148        for (idx, rect) in &rects {
149            let item = &self.data[*idx];
150
151            let inset = self.gap / 2.0;
152            let inset_rect = Rect::from_xywh(
153                rect.left + inset,
154                rect.top + inset,
155                (rect.width() - self.gap).max(0.0),
156                (rect.height() - self.gap).max(0.0),
157            );
158
159            if inset_rect.width() <= 0.0 || inset_rect.height() <= 0.0 {
160                continue;
161            }
162
163            let cx = inset_rect.left + inset_rect.width() / 2.0;
164            let cy = inset_rect.top + inset_rect.height() / 2.0;
165            let scaled_w = inset_rect.width() * progress;
166            let scaled_h = inset_rect.height() * progress;
167            let scaled_rect =
168                Rect::from_xywh(cx - scaled_w / 2.0, cy - scaled_h / 2.0, scaled_w, scaled_h);
169
170            let color_str = item
171                .color
172                .as_deref()
173                .unwrap_or(DEFAULT_PALETTE[*idx % DEFAULT_PALETTE.len()]);
174            let mut paint = paint_from_hex(color_str);
175            paint.set_style(PaintStyle::Fill);
176            paint.set_anti_alias(true);
177
178            let rrect = RRect::new_rect_xy(scaled_rect, self.border_radius, self.border_radius);
179            canvas.draw_rrect(rrect, &paint);
180
181            if self.show_labels || self.show_values {
182                let mut text_parts: Vec<String> = vec![];
183                if self.show_labels {
184                    if let Some(label) = &item.label {
185                        text_parts.push(label.clone());
186                    }
187                }
188                if self.show_values {
189                    text_parts.push(format!("{}", item.value));
190                }
191
192                if text_parts.is_empty() {
193                    continue;
194                }
195
196                let font_size = (scaled_rect.width() * 0.12).clamp(10.0, 24.0);
197                let line_height = font_size * 1.2;
198                if scaled_rect.width() < 30.0
199                    || scaled_rect.height() < 20.0 * text_parts.len() as f32
200                {
201                    continue;
202                }
203
204                let font = skia_safe::Font::from_typeface(&typeface, font_size);
205                let emoji_font =
206                    emoji_typeface().map(|tf| skia_safe::Font::from_typeface(tf, font_size));
207
208                let mut text_paint = paint_from_hex("#FFFFFF");
209                text_paint.set_anti_alias(true);
210
211                let (_, metrics) = font.metrics();
212                let ascent = -metrics.ascent;
213                let descent = metrics.descent;
214                let block_h = line_height * text_parts.len() as f32;
215                let block_top = scaled_rect.top + scaled_rect.height() / 2.0 - block_h / 2.0;
216
217                for (li, part) in text_parts.iter().enumerate() {
218                    let part_w = measure_text_with_fallback(part, &font, &emoji_font, 0.0);
219                    let part_x = scaled_rect.left + (scaled_rect.width() - part_w) / 2.0;
220                    let line_center_y = block_top + (li as f32 + 0.5) * line_height;
221                    let part_y = line_center_y + (ascent - descent) / 2.0;
222
223                    draw_text_with_fallback(
224                        canvas,
225                        part,
226                        &font,
227                        &emoji_font,
228                        0.0,
229                        part_x,
230                        part_y,
231                        &text_paint,
232                    );
233                }
234            }
235        }
236    }
237}
238
239impl Painter for Treemap {
240    fn paint_content(
241        &self,
242        canvas: &Canvas,
243        layout: &BoxLayout,
244        _props: &AnimatedProperties,
245        ctx: &PaintCtx,
246    ) {
247        self.paint(canvas, layout.width, layout.height, ctx.time);
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use rustmotion_core::traits::TimingConfig;
255
256    fn base_treemap(data: Vec<TreemapItem>) -> Treemap {
257        Treemap {
258            data,
259            gap: default_gap(),
260            border_radius: default_border_radius(),
261            show_labels: default_show_labels(),
262            show_values: false,
263            animated: true,
264            animation_duration: 1.0,
265            timing: TimingConfig::default(),
266            style: CssStyle::default(),
267            timeline: Vec::new(),
268            stagger: None,
269        }
270    }
271
272    fn read_rgba(surface: &mut skia_safe::Surface, w: i32, h: i32) -> Vec<u8> {
273        let snapshot = surface.image_snapshot();
274        let info = skia_safe::ImageInfo::new(
275            (w, h),
276            skia_safe::ColorType::RGBA8888,
277            skia_safe::AlphaType::Premul,
278            None,
279        );
280        let mut buf = vec![0u8; (w * h * 4) as usize];
281        snapshot.read_pixels(
282            &info,
283            &mut buf,
284            (w * 4) as usize,
285            skia_safe::IPoint::new(0, 0),
286            skia_safe::image::CachingHint::Disallow,
287        );
288        buf
289    }
290
291    fn is_text_ink(buf: &[u8], w: i32, x: i32, y: i32) -> bool {
292        let idx = ((y * w + x) * 4) as usize;
293        let (r, g, b, a) = (buf[idx], buf[idx + 1], buf[idx + 2], buf[idx + 3]);
294        a > 40 && r > 200 && g > 200 && b > 200
295    }
296
297    fn row_bands(buf: &[u8], w: i32, h: i32) -> Vec<(i32, i32)> {
298        let mut bands: Vec<(i32, i32)> = vec![];
299        for y in 0..h {
300            let has_ink = (0..w).any(|x| is_text_ink(buf, w, x, y));
301            if has_ink {
302                match bands.last_mut() {
303                    Some((_, end)) if y <= *end + 1 => *end = y,
304                    _ => bands.push((y, y)),
305                }
306            }
307        }
308        bands
309    }
310
311    fn row_ink_x_range(buf: &[u8], w: i32, y0: i32, y1: i32) -> (i32, i32) {
312        let (mut minx, mut maxx) = (i32::MAX, i32::MIN);
313        for y in y0..=y1 {
314            for x in 0..w {
315                if is_text_ink(buf, w, x, y) {
316                    minx = minx.min(x);
317                    maxx = maxx.max(x);
318                }
319            }
320        }
321        (minx, maxx)
322    }
323
324    #[test]
325    fn label_and_value_render_on_two_separate_centered_lines() {
326        const W: i32 = 300;
327        const H: i32 = 200;
328        let mut treemap = base_treemap(vec![TreemapItem {
329            label: Some("Alpha".to_string()),
330            value: 50.0,
331            color: None,
332        }]);
333        treemap.show_labels = true;
334        treemap.show_values = true;
335        treemap.animated = false;
336
337        let mut surface = skia_safe::surfaces::raster_n32_premul((W, H)).expect("raster surface");
338        {
339            let canvas = surface.canvas();
340            treemap.paint(canvas, W as f32, H as f32, 0.0);
341        }
342        let buf = read_rgba(&mut surface, W, H);
343        let bands = row_bands(&buf, W, H);
344        assert_eq!(
345            bands.len(),
346            2,
347            "label and value must render as two stacked lines, got bands={bands:?}"
348        );
349        for (y0, y1) in bands {
350            let (minx, maxx) = row_ink_x_range(&buf, W, y0, y1);
351            let center = (minx + maxx) as f32 / 2.0;
352            assert!(
353                (center - W as f32 / 2.0).abs() < 12.0,
354                "line y=[{y0}..{y1}] is not centered on the box: ink x center = {center}"
355            );
356        }
357    }
358
359    #[test]
360    fn a_single_label_still_renders_as_one_centered_line() {
361        const W: i32 = 300;
362        const H: i32 = 200;
363        let mut treemap = base_treemap(vec![TreemapItem {
364            label: Some("Alpha".to_string()),
365            value: 50.0,
366            color: None,
367        }]);
368        treemap.show_labels = true;
369        treemap.show_values = false;
370        treemap.animated = false;
371
372        let mut surface = skia_safe::surfaces::raster_n32_premul((W, H)).expect("raster surface");
373        {
374            let canvas = surface.canvas();
375            treemap.paint(canvas, W as f32, H as f32, 0.0);
376        }
377        let buf = read_rgba(&mut surface, W, H);
378        let bands = row_bands(&buf, W, H);
379        assert_eq!(
380            bands.len(),
381            1,
382            "a single label is one line, got bands={bands:?}"
383        );
384    }
385
386    #[test]
387    fn progress_ramp_starts_at_start_at_not_at_scene_time_zero() {
388        let mut treemap = base_treemap(vec![TreemapItem {
389            label: None,
390            value: 1.0,
391            color: None,
392        }]);
393        treemap.animation_duration = 1.5;
394        treemap.timing = TimingConfig {
395            start_at: Some(2.0),
396            end_at: None,
397        };
398        assert_eq!(treemap.progress_at(2.0), 0.0);
399        assert!(treemap.progress_at(2.75) < 1.0);
400        assert_eq!(treemap.progress_at(3.5), 1.0);
401    }
402}