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    subpixel_font, 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 = subpixel_font(&typeface, font_size);
205                let emoji_font = emoji_typeface().map(|tf| subpixel_font(tf, font_size));
206
207                let mut text_paint = paint_from_hex("#FFFFFF");
208                text_paint.set_anti_alias(true);
209
210                let (_, metrics) = font.metrics();
211                let ascent = -metrics.ascent;
212                let descent = metrics.descent;
213                let block_h = line_height * text_parts.len() as f32;
214                let block_top = scaled_rect.top + scaled_rect.height() / 2.0 - block_h / 2.0;
215
216                for (li, part) in text_parts.iter().enumerate() {
217                    let part_w = measure_text_with_fallback(part, &font, &emoji_font, 0.0);
218                    let part_x = scaled_rect.left + (scaled_rect.width() - part_w) / 2.0;
219                    let line_center_y = block_top + (li as f32 + 0.5) * line_height;
220                    let part_y = line_center_y + (ascent - descent) / 2.0;
221
222                    draw_text_with_fallback(
223                        canvas,
224                        part,
225                        &font,
226                        &emoji_font,
227                        0.0,
228                        part_x,
229                        part_y,
230                        &text_paint,
231                    );
232                }
233            }
234        }
235    }
236}
237
238impl Painter for Treemap {
239    fn paint_content(
240        &self,
241        canvas: &Canvas,
242        layout: &BoxLayout,
243        _props: &AnimatedProperties,
244        ctx: &PaintCtx,
245    ) {
246        self.paint(canvas, layout.width, layout.height, ctx.time);
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use rustmotion_core::traits::TimingConfig;
254
255    fn base_treemap(data: Vec<TreemapItem>) -> Treemap {
256        Treemap {
257            data,
258            gap: default_gap(),
259            border_radius: default_border_radius(),
260            show_labels: default_show_labels(),
261            show_values: false,
262            animated: true,
263            animation_duration: 1.0,
264            timing: TimingConfig::default(),
265            style: CssStyle::default(),
266            timeline: Vec::new(),
267            stagger: None,
268        }
269    }
270
271    fn read_rgba(surface: &mut skia_safe::Surface, w: i32, h: i32) -> Vec<u8> {
272        let snapshot = surface.image_snapshot();
273        let info = skia_safe::ImageInfo::new(
274            (w, h),
275            skia_safe::ColorType::RGBA8888,
276            skia_safe::AlphaType::Premul,
277            None,
278        );
279        let mut buf = vec![0u8; (w * h * 4) as usize];
280        snapshot.read_pixels(
281            &info,
282            &mut buf,
283            (w * 4) as usize,
284            skia_safe::IPoint::new(0, 0),
285            skia_safe::image::CachingHint::Disallow,
286        );
287        buf
288    }
289
290    fn is_text_ink(buf: &[u8], w: i32, x: i32, y: i32) -> bool {
291        let idx = ((y * w + x) * 4) as usize;
292        let (r, g, b, a) = (buf[idx], buf[idx + 1], buf[idx + 2], buf[idx + 3]);
293        a > 40 && r > 200 && g > 200 && b > 200
294    }
295
296    fn row_bands(buf: &[u8], w: i32, h: i32) -> Vec<(i32, i32)> {
297        let mut bands: Vec<(i32, i32)> = vec![];
298        for y in 0..h {
299            let has_ink = (0..w).any(|x| is_text_ink(buf, w, x, y));
300            if has_ink {
301                match bands.last_mut() {
302                    Some((_, end)) if y <= *end + 1 => *end = y,
303                    _ => bands.push((y, y)),
304                }
305            }
306        }
307        bands
308    }
309
310    fn row_ink_x_range(buf: &[u8], w: i32, y0: i32, y1: i32) -> (i32, i32) {
311        let (mut minx, mut maxx) = (i32::MAX, i32::MIN);
312        for y in y0..=y1 {
313            for x in 0..w {
314                if is_text_ink(buf, w, x, y) {
315                    minx = minx.min(x);
316                    maxx = maxx.max(x);
317                }
318            }
319        }
320        (minx, maxx)
321    }
322
323    #[test]
324    fn label_and_value_render_on_two_separate_centered_lines() {
325        const W: i32 = 300;
326        const H: i32 = 200;
327        let mut treemap = base_treemap(vec![TreemapItem {
328            label: Some("Alpha".to_string()),
329            value: 50.0,
330            color: None,
331        }]);
332        treemap.show_labels = true;
333        treemap.show_values = true;
334        treemap.animated = false;
335
336        let mut surface = skia_safe::surfaces::raster_n32_premul((W, H)).expect("raster surface");
337        {
338            let canvas = surface.canvas();
339            treemap.paint(canvas, W as f32, H as f32, 0.0);
340        }
341        let buf = read_rgba(&mut surface, W, H);
342        let bands = row_bands(&buf, W, H);
343        assert_eq!(
344            bands.len(),
345            2,
346            "label and value must render as two stacked lines, got bands={bands:?}"
347        );
348        for (y0, y1) in bands {
349            let (minx, maxx) = row_ink_x_range(&buf, W, y0, y1);
350            let center = (minx + maxx) as f32 / 2.0;
351            assert!(
352                (center - W as f32 / 2.0).abs() < 12.0,
353                "line y=[{y0}..{y1}] is not centered on the box: ink x center = {center}"
354            );
355        }
356    }
357
358    #[test]
359    fn a_single_label_still_renders_as_one_centered_line() {
360        const W: i32 = 300;
361        const H: i32 = 200;
362        let mut treemap = base_treemap(vec![TreemapItem {
363            label: Some("Alpha".to_string()),
364            value: 50.0,
365            color: None,
366        }]);
367        treemap.show_labels = true;
368        treemap.show_values = false;
369        treemap.animated = false;
370
371        let mut surface = skia_safe::surfaces::raster_n32_premul((W, H)).expect("raster surface");
372        {
373            let canvas = surface.canvas();
374            treemap.paint(canvas, W as f32, H as f32, 0.0);
375        }
376        let buf = read_rgba(&mut surface, W, H);
377        let bands = row_bands(&buf, W, H);
378        assert_eq!(
379            bands.len(),
380            1,
381            "a single label is one line, got bands={bands:?}"
382        );
383    }
384
385    #[test]
386    fn progress_ramp_starts_at_start_at_not_at_scene_time_zero() {
387        let mut treemap = base_treemap(vec![TreemapItem {
388            label: None,
389            value: 1.0,
390            color: None,
391        }]);
392        treemap.animation_duration = 1.5;
393        treemap.timing = TimingConfig {
394            start_at: Some(2.0),
395            end_at: None,
396        };
397        assert_eq!(treemap.progress_at(2.0), 0.0);
398        assert!(treemap.progress_at(2.75) < 1.0);
399        assert_eq!(treemap.progress_at(3.5), 1.0);
400    }
401}