Skip to main content

tui_chart/
treemap.rs

1//! Treemap: squarified treemap of weighted (optionally nested) items.
2
3use crate::theme::{self, ChartThemeExt, Theme};
4use crate::util::format_compact;
5use ratatui::{
6    buffer::Buffer,
7    layout::Rect,
8    style::{Color, Style},
9    widgets::Block,
10};
11
12const PALETTE: [(u8, u8, u8); 8] = [
13    (66, 133, 244),
14    (52, 168, 83),
15    (251, 188, 5),
16    (234, 67, 53),
17    (171, 71, 188),
18    (0, 172, 193),
19    (255, 112, 67),
20    (141, 110, 99),
21];
22
23/// One treemap item. A leaf uses `value`; an item with children is sized by
24/// the sum of its children.
25#[derive(Debug, Clone, PartialEq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct TreemapItem {
28    /// Label drawn inside the cell.
29    pub label: String,
30    /// Weight (leaf items).
31    pub value: f64,
32    /// Explicit color (overrides gradient/palette).
33    pub color: Option<Color>,
34    /// Nested items.
35    pub children: Vec<TreemapItem>,
36}
37
38impl TreemapItem {
39    /// Create a leaf item.
40    pub fn new(label: impl Into<String>, value: f64) -> Self {
41        Self {
42            label: label.into(),
43            value,
44            color: None,
45            children: vec![],
46        }
47    }
48
49    opt_setter!(
50        /// Set an explicit color.
51        color: Color
52    );
53
54    /// Set nested children (turns this item into a group).
55    pub fn children(mut self, c: impl IntoIterator<Item = TreemapItem>) -> Self {
56        self.children = c.into_iter().collect();
57        self
58    }
59
60    /// Effective weight (sum of children when present). Invalid → 0.
61    pub fn weight(&self) -> f64 {
62        let v = if self.children.is_empty() {
63            self.value
64        } else {
65            self.children.iter().map(|c| c.weight()).sum()
66        };
67        if v.is_finite() && v > 0.0 {
68            v
69        } else {
70            0.0
71        }
72    }
73}
74
75/// Squarified treemap widget.
76#[derive(Debug, Clone)]
77pub struct Treemap {
78    items: Vec<TreemapItem>,
79    gradient: Option<(Color, Color)>,
80    border: bool,
81    border_color: Option<Color>,
82    theme: Option<Theme>,
83    base: Option<Style>,
84    show_values: bool,
85    block: Option<Block<'static>>,
86}
87
88impl Treemap {
89    /// Create from items.
90    pub fn new(items: impl IntoIterator<Item = TreemapItem>) -> Self {
91        Self {
92            items: items.into_iter().collect(),
93            gradient: None,
94            border: false,
95            border_color: None,
96            theme: None,
97            base: None,
98            show_values: true,
99            block: None,
100        }
101    }
102
103    /// Color items without explicit color by value, interpolating `low`→`high`
104    /// (use `Color::Rgb` values for smooth results).
105    pub fn gradient(mut self, low: Color, high: Color) -> Self {
106        self.gradient = Some((low, high));
107        self
108    }
109
110    setter!(
111        /// Draw a border around each cell.
112        border: bool
113    );
114
115    opt_setter!(
116        /// Border color.
117        border_color: Color
118    );
119
120    theme_setter!(
121        /// Apply a [`Theme`]: items without a color are colored by value along the
122        /// theme gradient; cell borders use the theme background. Explicit item
123        /// colors, [`Treemap::gradient`] and [`Treemap::border_color`] win.
124        theme
125    );
126
127    base_style_setter!(base);
128
129    setter!(
130        /// Print the value under the label when there is room.
131        show_values: bool
132    );
133
134    block_setter!(block, 'static);
135
136    /// Compute squarified cell rects for `weights` inside `area`, in the
137    /// input order. Zero-weight items get empty rects.
138    pub fn layout(weights: &[f64], area: Rect) -> Vec<Rect> {
139        let mut out = vec![Rect::new(area.x, area.y, 0, 0); weights.len()];
140        let mut order: Vec<usize> = (0..weights.len())
141            .filter(|&i| weights[i].is_finite() && weights[i] > 0.0)
142            .collect();
143        order.sort_by(|&a, &b| weights[b].total_cmp(&weights[a]));
144        let total: f64 = order.iter().map(|&i| weights[i]).sum();
145        if order.is_empty() || area.width == 0 || area.height == 0 || total <= 0.0 {
146            return out;
147        }
148        // Virtual space: cells are ~2x taller than wide.
149        let (ax, ay) = (area.x as f64, area.y as f64 * 2.0);
150        let (mut x, mut y) = (ax, ay);
151        let (mut w, mut h) = (area.width as f64, area.height as f64 * 2.0);
152        let scale = w * h / total;
153        let mut i = 0;
154        let mut rects: Vec<(usize, f64, f64, f64, f64)> = vec![];
155        while i < order.len() {
156            let short = w.min(h);
157            let areas: Vec<f64> = order[i..].iter().map(|&k| weights[k] * scale).collect();
158            let worst = |n: usize| -> f64 {
159                let s: f64 = areas[..n].iter().sum();
160                let mx = areas[..n].iter().cloned().fold(f64::MIN, f64::max);
161                let mn = areas[..n].iter().cloned().fold(f64::MAX, f64::min);
162                let s2 = short * short;
163                ((s2 * mx) / (s * s)).max((s * s) / (s2 * mn))
164            };
165            let mut n = 1;
166            while n < areas.len() && worst(n + 1) <= worst(n) {
167                n += 1;
168            }
169            let s: f64 = areas[..n].iter().sum();
170            if w >= h {
171                let cw = if h > 0.0 { s / h } else { 0.0 };
172                let mut cy = y;
173                for k in 0..n {
174                    let ch = if cw > 0.0 { areas[k] / cw } else { 0.0 };
175                    rects.push((order[i + k], x, cy, cw, ch));
176                    cy += ch;
177                }
178                x += cw;
179                w -= cw;
180            } else {
181                let rh = if w > 0.0 { s / w } else { 0.0 };
182                let mut cx = x;
183                for k in 0..n {
184                    let cw = if rh > 0.0 { areas[k] / rh } else { 0.0 };
185                    rects.push((order[i + k], cx, y, cw, rh));
186                    cx += cw;
187                }
188                y += rh;
189                h -= rh;
190            }
191            i += n;
192        }
193        let (r_right, r_bottom) = (area.right() as f64, area.bottom() as f64);
194        for (k, rx, ry, rw, rh) in rects {
195            let x0 = rx.round().clamp(ax, r_right);
196            let x1 = (rx + rw).round().clamp(ax, r_right);
197            let y0 = (ry / 2.0).round().clamp(area.y as f64, r_bottom);
198            let y1 = ((ry + rh) / 2.0).round().clamp(area.y as f64, r_bottom);
199            out[k] = Rect::new(x0 as u16, y0 as u16, (x1 - x0) as u16, (y1 - y0) as u16);
200        }
201        out
202    }
203
204    fn leaf_range(items: &[TreemapItem], acc: &mut (f64, f64)) {
205        for it in items {
206            if it.children.is_empty() {
207                let w = it.weight();
208                if w > 0.0 {
209                    acc.0 = acc.0.min(w);
210                    acc.1 = acc.1.max(w);
211                }
212            } else {
213                Self::leaf_range(&it.children, acc);
214            }
215        }
216    }
217
218    #[allow(clippy::too_many_arguments)]
219    fn draw(&self, items: &[TreemapItem], area: Rect, buf: &mut Buffer, range: (f64, f64)) {
220        let weights: Vec<f64> = items.iter().map(|i| i.weight()).collect();
221        let rects = Self::layout(&weights, area);
222        for (idx, (it, r)) in items.iter().zip(rects).enumerate() {
223            if r.width == 0 || r.height == 0 {
224                continue;
225            }
226            let color = it
227                .color
228                .unwrap_or_else(|| self.auto_color(idx, weights[idx], range));
229            let bg = Style::default().bg(color).fg(text_color(color));
230            for y in r.y..r.bottom() {
231                for x in r.x..r.right() {
232                    buf[(x, y)].set_symbol(" ").set_style(bg);
233                }
234            }
235            if self.border && r.width >= 2 && r.height >= 2 {
236                self.draw_border(buf, r, color);
237            }
238            let inset = if self.border && r.width >= 2 && r.height >= 2 {
239                1
240            } else {
241                0
242            };
243            let text = Rect::new(
244                r.x + inset,
245                r.y + inset,
246                r.width.saturating_sub(2 * inset),
247                r.height.saturating_sub(2 * inset),
248            );
249            if text.width == 0 || text.height == 0 {
250                continue;
251            }
252            put_text(
253                buf,
254                text,
255                0,
256                &it.label,
257                bg.add_modifier(ratatui::style::Modifier::BOLD),
258            );
259            if it.children.is_empty() {
260                if self.show_values && text.height >= 2 {
261                    put_text(buf, text, 1, &format_compact(weights[idx]), bg);
262                }
263            } else if text.height >= 2 {
264                let sub = Rect::new(text.x, text.y + 1, text.width, text.height - 1);
265                self.draw(&it.children, sub, buf, range);
266            }
267        }
268    }
269
270    fn draw_border(&self, buf: &mut Buffer, r: Rect, bg: Color) {
271        let st = Style::default()
272            .bg(bg)
273            .fg(self.border_color.unwrap_or_else(|| {
274                self.theme
275                    .as_ref()
276                    .and_then(|t| t.background)
277                    .unwrap_or(Color::Black)
278            }));
279        let (x1, y1) = (r.right() - 1, r.bottom() - 1);
280        for x in r.x..=x1 {
281            buf[(x, r.y)].set_symbol("─").set_style(st);
282            buf[(x, y1)].set_symbol("─").set_style(st);
283        }
284        for y in r.y..=y1 {
285            buf[(r.x, y)].set_symbol("│").set_style(st);
286            buf[(x1, y)].set_symbol("│").set_style(st);
287        }
288        buf[(r.x, r.y)].set_symbol("┌");
289        buf[(x1, r.y)].set_symbol("┐");
290        buf[(r.x, y1)].set_symbol("└");
291        buf[(x1, y1)].set_symbol("┘");
292    }
293
294    fn auto_color(&self, idx: usize, weight: f64, range: (f64, f64)) -> Color {
295        if let Some((lo, hi)) = self.gradient {
296            let t = if range.1 > range.0 {
297                ((weight - range.0) / (range.1 - range.0)).clamp(0.0, 1.0)
298            } else {
299                0.5
300            };
301            return lerp_color(lo, hi, t);
302        }
303        if let Some(t) = &self.theme {
304            let f = if range.1 > range.0 {
305                ((weight - range.0) / (range.1 - range.0)).clamp(0.0, 1.0)
306            } else {
307                0.5
308            };
309            return t.gradient().color_at(f);
310        }
311        let p = PALETTE[idx % PALETTE.len()];
312        Color::Rgb(p.0, p.1, p.2)
313    }
314}
315
316fn rgb(c: Color) -> (u8, u8, u8) {
317    match c {
318        Color::Rgb(r, g, b) => (r, g, b),
319        Color::Black => (0, 0, 0),
320        Color::Red => (205, 49, 49),
321        Color::Green => (13, 188, 121),
322        Color::Yellow => (229, 229, 16),
323        Color::Blue => (36, 114, 200),
324        Color::Magenta => (188, 63, 188),
325        Color::Cyan => (17, 168, 205),
326        Color::Gray => (229, 229, 229),
327        Color::DarkGray => (102, 102, 102),
328        Color::White => (255, 255, 255),
329        _ => (200, 200, 200),
330    }
331}
332
333fn lerp_color(a: Color, b: Color, t: f64) -> Color {
334    let (a, b) = (rgb(a), rgb(b));
335    let (r, g, bl) = crate::scale::mix_rgb(a, b, t);
336    Color::Rgb(r, g, bl)
337}
338
339fn text_color(bg: Color) -> Color {
340    let (r, g, b) = rgb(bg);
341    if 0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64 > 140.0 {
342        Color::Black
343    } else {
344        Color::White
345    }
346}
347
348fn put_text(buf: &mut Buffer, area: Rect, row: u16, s: &str, style: Style) {
349    if row >= area.height {
350        return;
351    }
352    for (i, ch) in s.chars().take(area.width as usize).enumerate() {
353        buf[(area.x + i as u16, area.y + row)]
354            .set_symbol(&ch.to_string())
355            .set_style(style);
356    }
357}
358
359impl Treemap {
360    fn render_into(&self, area: Rect, buf: &mut Buffer) {
361        let area = area.intersection(buf.area);
362        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
363        if inner.width == 0 || inner.height == 0 {
364            return;
365        }
366        let mut range = (f64::INFINITY, f64::NEG_INFINITY);
367        Treemap::leaf_range(&self.items, &mut range);
368        self.draw(&self.items, inner, buf, range);
369    }
370}
371
372widget_impls!(Treemap);
373
374#[cfg(feature = "theme")]
375impl tui_nuances::Themed for Treemap {
376    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
377        self.theme(theme)
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use ratatui::widgets::Widget;
385
386    #[test]
387    fn layout_tiles_area() {
388        let area = Rect::new(2, 1, 40, 12);
389        let rects = Treemap::layout(&[6.0, 6.0, 4.0, 3.0, 2.0, 2.0, 1.0], area);
390        let covered: u32 = rects.iter().map(|r| r.width as u32 * r.height as u32).sum();
391        assert_eq!(covered, 40 * 12);
392        for r in &rects {
393            assert!(area.contains((r.x, r.y).into()));
394            assert!(r.right() <= area.right() && r.bottom() <= area.bottom());
395        }
396    }
397
398    #[test]
399    fn area_proportional() {
400        let rects = Treemap::layout(&[3.0, 1.0], Rect::new(0, 0, 40, 10));
401        let a = rects[0].width as u32 * rects[0].height as u32;
402        let b = rects[1].width as u32 * rects[1].height as u32;
403        assert_eq!(a, 300);
404        assert_eq!(b, 100);
405    }
406
407    #[test]
408    fn invalid_weights_empty() {
409        let r = Treemap::layout(&[0.0, f64::NAN, -1.0], Rect::new(0, 0, 10, 10));
410        assert!(r.iter().all(|r| r.width == 0 || r.height == 0));
411    }
412
413    #[test]
414    fn nested_weight() {
415        let g = TreemapItem::new("g", 0.0)
416            .children([TreemapItem::new("a", 2.0), TreemapItem::new("b", 3.0)]);
417        assert_eq!(g.weight(), 5.0);
418    }
419
420    #[test]
421    fn renders_labels_and_colors() {
422        let area = Rect::new(0, 0, 40, 12);
423        let mut buf = Buffer::empty(area);
424        Treemap::new([
425            TreemapItem::new("alpha", 5.0).color(Color::Red),
426            TreemapItem::new("beta", 3.0),
427            TreemapItem::new("gamma", 2.0),
428        ])
429        .render(area, &mut buf);
430        let t: String = (0..12)
431            .flat_map(|y| (0..40).map(move |x| (x, y)))
432            .map(|p| buf[p].symbol().to_string())
433            .collect();
434        assert!(t.contains("alpha") && t.contains("beta"));
435        assert!((0..40).all(|x| (0..12).all(|y| buf[(x, y)].bg != Color::Reset)));
436    }
437
438    #[cfg(feature = "theme")]
439    #[test]
440    fn theme_gradient_and_override() {
441        let t = Theme::dracula();
442        let area = Rect::new(0, 0, 40, 12);
443        let items = || {
444            [
445                TreemapItem::new("alpha", 5.0).color(Color::Red),
446                TreemapItem::new("beta", 3.0),
447                TreemapItem::new("gamma", 1.0),
448            ]
449        };
450        let mut buf = Buffer::empty(area);
451        Treemap::new(items()).theme(&t).render(area, &mut buf);
452        let g = t.gradient();
453        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.bg == c);
454        assert!(has(&buf, Color::Red));
455        assert!(has(&buf, g.color_at(1.0)) || has(&buf, g.color_at(0.5)));
456        assert!(has(&buf, g.color_at(0.0)));
457        let mut buf = Buffer::empty(area);
458        Treemap::new(items())
459            .theme(&t)
460            .gradient(Color::Rgb(1, 2, 3), Color::Rgb(1, 2, 3))
461            .render(area, &mut buf);
462        assert!(has(&buf, Color::Rgb(1, 2, 3)) && !has(&buf, g.color_at(0.0)));
463    }
464
465    #[test]
466    fn border_and_nested() {
467        let area = Rect::new(0, 0, 40, 14);
468        let mut buf = Buffer::empty(area);
469        Treemap::new([
470            TreemapItem::new("grp", 0.0)
471                .children([TreemapItem::new("x", 4.0), TreemapItem::new("y", 2.0)]),
472            TreemapItem::new("solo", 3.0),
473        ])
474        .border(true)
475        .gradient(Color::Rgb(0, 0, 80), Color::Rgb(0, 200, 0))
476        .block(Block::bordered())
477        .render(area, &mut buf);
478        let t: String = (0..14)
479            .flat_map(|y| (0..40).map(move |x| (x, y)))
480            .map(|p| buf[p].symbol().to_string())
481            .collect();
482        assert!(t.contains("grp") && t.contains("solo") && t.contains('┌'));
483    }
484
485    #[test]
486    fn robust() {
487        for (w, h) in [(0, 0), (1, 1), (2, 3), (5, 2)] {
488            let area = Rect::new(0, 0, w, h);
489            let mut buf = Buffer::empty(area);
490            Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", f64::NAN)])
491                .border(true)
492                .block(Block::bordered())
493                .render(area, &mut buf);
494        }
495        let area = Rect::new(0, 0, 10, 5);
496        Treemap::new([]).render(area, &mut Buffer::empty(area));
497    }
498}