Skip to main content

fc_ui/capabilities/data/
treemap.rs

1//! Squarified treemap chart for hierarchical data visualization.
2
3use crate::capabilities::data::palette::default_color;
4use crate::capabilities::foundation::theme::use_theme;
5use gpui::{prelude::FluentBuilder as _, *};
6
7fn pixels_to_f32(p: Pixels) -> f32 {
8    p / px(1.0)
9}
10
11#[derive(Clone)]
12pub struct TreeMapNode {
13    pub label: SharedString,
14    pub value: f64,
15    pub color: Option<Hsla>,
16    pub children: Vec<TreeMapNode>,
17}
18
19impl TreeMapNode {
20    pub fn new(label: impl Into<SharedString>, value: f64) -> Self {
21        Self {
22            label: label.into(),
23            value: value.max(0.0),
24            children: Vec::new(),
25            color: None,
26        }
27    }
28
29    pub fn color(mut self, color: Hsla) -> Self {
30        self.color = Some(color);
31        self
32    }
33
34    pub fn children(mut self, children: Vec<TreeMapNode>) -> Self {
35        self.children = children;
36        self
37    }
38
39    fn total_value(&self) -> f64 {
40        if self.children.is_empty() {
41            self.value
42        } else {
43            self.children.iter().map(|c| c.total_value()).sum()
44        }
45    }
46}
47
48#[derive(Clone)]
49struct FlatRect {
50    x: f32,
51    y: f32,
52    w: f32,
53    h: f32,
54    color: Hsla,
55    label: SharedString,
56}
57
58fn squarify_layout(
59    nodes: &[TreeMapNode],
60    x: f32,
61    y: f32,
62    w: f32,
63    h: f32,
64    color_scale: &[Hsla],
65    depth_index: &mut usize,
66    padding: f32,
67    min_cell: f32,
68    out: &mut Vec<FlatRect>,
69) {
70    if nodes.is_empty() || w <= 0.0 || h <= 0.0 {
71        return;
72    }
73
74    let total: f64 = nodes.iter().map(|n| n.total_value()).sum();
75    if total <= 0.0 {
76        return;
77    }
78
79    let area = (w as f64) * (h as f64);
80    let mut sorted: Vec<&TreeMapNode> = nodes.iter().collect();
81    sorted.sort_by(|a, b| {
82        b.total_value()
83            .partial_cmp(&a.total_value())
84            .unwrap_or(std::cmp::Ordering::Equal)
85    });
86
87    let mut rects: Vec<(f32, f32, f32, f32, usize)> = Vec::new();
88    layout_strip(&sorted, x, y, w, h, total, area, &mut rects);
89
90    for (rx, ry, rw, rh, idx) in rects {
91        let node = sorted[idx];
92        let color = node.color.unwrap_or_else(|| {
93            if !color_scale.is_empty() {
94                color_scale[*depth_index % color_scale.len()]
95            } else {
96                default_color(*depth_index)
97            }
98        });
99        *depth_index += 1;
100
101        if rw < min_cell || rh < min_cell {
102            continue;
103        }
104
105        if !node.children.is_empty() {
106            let inner_x = rx + padding;
107            let inner_y = ry + padding;
108            let inner_w = (rw - 2.0 * padding).max(0.0);
109            let inner_h = (rh - 2.0 * padding).max(0.0);
110            squarify_layout(
111                &node.children,
112                inner_x,
113                inner_y,
114                inner_w,
115                inner_h,
116                color_scale,
117                depth_index,
118                padding,
119                min_cell,
120                out,
121            );
122        } else {
123            out.push(FlatRect {
124                x: rx,
125                y: ry,
126                w: rw,
127                h: rh,
128                color,
129                label: node.label.clone(),
130            });
131        }
132    }
133}
134
135fn layout_strip(
136    nodes: &[&TreeMapNode],
137    x: f32,
138    y: f32,
139    w: f32,
140    h: f32,
141    total: f64,
142    area: f64,
143    out: &mut Vec<(f32, f32, f32, f32, usize)>,
144) {
145    if nodes.is_empty() {
146        return;
147    }
148
149    if nodes.len() == 1 {
150        out.push((x, y, w, h, 0));
151        return;
152    }
153
154    let horizontal = w >= h;
155    let mut row: Vec<usize> = Vec::new();
156    let mut row_sum = 0.0f64;
157    let mut best_worst = f64::MAX;
158    let mut split_at = nodes.len();
159
160    let short_side = if horizontal { h as f64 } else { w as f64 };
161
162    for i in 0..nodes.len() {
163        let val = nodes[i].total_value();
164        let test_sum = row_sum + val;
165        let test_count = row.len() + 1;
166
167        let strip_area = test_sum / total * area;
168        let strip_side = if short_side > 0.0 {
169            strip_area / short_side
170        } else {
171            0.0
172        };
173
174        let mut worst = 0.0f64;
175        for &ri in row.iter().chain(std::iter::once(&i)) {
176            let cell_area = nodes[ri].total_value() / total * area;
177            let cell_side = if strip_side > 0.0 {
178                cell_area / strip_side
179            } else {
180                0.0
181            };
182            let ratio = if cell_side > 0.0 && strip_side > 0.0 {
183                (strip_side / cell_side).max(cell_side / strip_side)
184            } else {
185                f64::MAX
186            };
187            worst = worst.max(ratio);
188        }
189
190        if test_count >= 2 && worst > best_worst {
191            split_at = i;
192            break;
193        }
194
195        best_worst = worst;
196        row_sum = test_sum;
197        row.push(i);
198    }
199
200    let row_fraction = row_sum / total;
201
202    if horizontal {
203        let row_w = (w as f64 * row_fraction) as f32;
204        let mut cy = y;
205        for &ri in &row {
206            let frac = nodes[ri].total_value() / row_sum;
207            let cell_h = (h as f64 * frac) as f32;
208            out.push((x, cy, row_w, cell_h, ri));
209            cy += cell_h;
210        }
211
212        if split_at < nodes.len() {
213            let remaining: Vec<&TreeMapNode> = nodes[split_at..].to_vec();
214            let mut sub_out = Vec::new();
215            layout_strip(
216                &remaining,
217                x + row_w,
218                y,
219                w - row_w,
220                h,
221                total - row_sum,
222                area * (1.0 - row_fraction),
223                &mut sub_out,
224            );
225            for (sx, sy, sw, sh, si) in sub_out {
226                out.push((sx, sy, sw, sh, si + split_at));
227            }
228        }
229    } else {
230        let row_h = (h as f64 * row_fraction) as f32;
231        let mut cx = x;
232        for &ri in &row {
233            let frac = nodes[ri].total_value() / row_sum;
234            let cell_w = (w as f64 * frac) as f32;
235            out.push((cx, y, cell_w, row_h, ri));
236            cx += cell_w;
237        }
238
239        if split_at < nodes.len() {
240            let remaining: Vec<&TreeMapNode> = nodes[split_at..].to_vec();
241            let mut sub_out = Vec::new();
242            layout_strip(
243                &remaining,
244                x,
245                y + row_h,
246                w,
247                h - row_h,
248                total - row_sum,
249                area * (1.0 - row_fraction),
250                &mut sub_out,
251            );
252            for (sx, sy, sw, sh, si) in sub_out {
253                out.push((sx, sy, sw, sh, si + split_at));
254            }
255        }
256    }
257}
258
259#[derive(IntoElement)]
260pub struct TreeMap {
261    data: Vec<TreeMapNode>,
262    color_scale: Vec<Hsla>,
263    show_labels: bool,
264    padding: Pixels,
265    min_cell_size: Pixels,
266    style: StyleRefinement,
267}
268
269impl TreeMap {
270    pub fn new() -> Self {
271        Self {
272            data: Vec::new(),
273            color_scale: Vec::new(),
274            show_labels: true,
275            padding: px(2.0),
276            min_cell_size: px(20.0),
277            style: StyleRefinement::default(),
278        }
279    }
280
281    pub fn data(mut self, data: Vec<TreeMapNode>) -> Self {
282        self.data = data;
283        self
284    }
285
286    pub fn color_scale(mut self, colors: Vec<Hsla>) -> Self {
287        self.color_scale = colors;
288        self
289    }
290
291    pub fn show_labels(mut self, show: bool) -> Self {
292        self.show_labels = show;
293        self
294    }
295
296    pub fn padding(mut self, padding: Pixels) -> Self {
297        self.padding = padding;
298        self
299    }
300
301    pub fn min_cell_size(mut self, size: Pixels) -> Self {
302        self.min_cell_size = size;
303        self
304    }
305}
306
307impl Default for TreeMap {
308    fn default() -> Self {
309        Self::new()
310    }
311}
312
313impl Styled for TreeMap {
314    fn style(&mut self) -> &mut StyleRefinement {
315        &mut self.style
316    }
317}
318
319impl RenderOnce for TreeMap {
320    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
321        let theme = use_theme(cx);
322        let user_style = self.style;
323        let data = self.data;
324        let color_scale = self.color_scale;
325        let show_labels = self.show_labels;
326        let pad = pixels_to_f32(self.padding);
327        let min_cell = pixels_to_f32(self.min_cell_size);
328        let border_color = theme.tokens.background;
329
330        div()
331            .w_full()
332            .h(px(300.0))
333            .overflow_hidden()
334            .bg(theme.tokens.background)
335            .rounded(px(6.0))
336            .map(|this| {
337                let mut el = this;
338                el.style().refine(&user_style);
339                el
340            })
341            .child(
342                canvas(
343                    move |_bounds, _window, _cx| {},
344                    move |bounds, _, window, cx| {
345                        let bx = pixels_to_f32(bounds.origin.x);
346                        let by = pixels_to_f32(bounds.origin.y);
347                        let bw = pixels_to_f32(bounds.size.width);
348                        let bh = pixels_to_f32(bounds.size.height);
349
350                        let mut rects = Vec::new();
351                        let mut depth_index = 0usize;
352                        squarify_layout(
353                            &data,
354                            bx + pad,
355                            by + pad,
356                            bw - 2.0 * pad,
357                            bh - 2.0 * pad,
358                            &color_scale,
359                            &mut depth_index,
360                            pad,
361                            min_cell,
362                            &mut rects,
363                        );
364
365                        for rect in &rects {
366                            window.paint_quad(PaintQuad {
367                                bounds: Bounds {
368                                    origin: point(px(rect.x), px(rect.y)),
369                                    size: gpui::size(px(rect.w), px(rect.h)),
370                                },
371                                corner_radii: Corners::all(px(3.0)),
372                                background: rect.color.into(),
373                                border_widths: Edges::all(px(1.0)),
374                                border_color,
375                                border_style: BorderStyle::default(),
376                                continuous_corners: false,
377                                transform: Default::default(),
378                                blend_mode: Default::default(),
379                            });
380                        }
381
382                        if show_labels {
383                            for rect in &rects {
384                                if rect.w < 40.0 || rect.h < 18.0 {
385                                    continue;
386                                }
387
388                                let label_text = rect.label.clone();
389                                let contrast = if rect.color.l > 0.5 {
390                                    hsla(0.0, 0.0, 0.1, 1.0)
391                                } else {
392                                    hsla(0.0, 0.0, 0.95, 1.0)
393                                };
394
395                                let font_size = if rect.w > 80.0 && rect.h > 30.0 {
396                                    12.0
397                                } else {
398                                    10.0
399                                };
400
401                                let text_style = window.text_style();
402                                let font = text_style.font();
403                                let label_len = label_text.len();
404                                let font_px = px(font_size);
405
406                                let shaped = window.text_system().shape_line(
407                                    label_text,
408                                    font_px,
409                                    &[TextRun {
410                                        len: label_len,
411                                        font,
412                                        color: contrast,
413                                        background_color: None,
414                                        underline: None,
415                                        strikethrough: None,
416                                    }],
417                                    None,
418                                );
419
420                                let text_w = pixels_to_f32(shaped.width);
421                                let max_w = rect.w - 6.0;
422                                if text_w <= max_w {
423                                    let tx = rect.x + 4.0;
424                                    let ty = rect.y + 4.0;
425                                    let _ =
426                                        shaped.paint(point(px(tx), px(ty)), font_px, window, cx);
427                                }
428                            }
429                        }
430                    },
431                )
432                .absolute()
433                .inset_0()
434                .size_full(),
435            )
436    }
437}