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    gap: bool,
82    border_color: Option<Color>,
83    theme: Option<Theme>,
84    base: Option<Style>,
85    show_values: bool,
86    block: Option<Block<'static>>,
87}
88
89impl Treemap {
90    /// Create from items.
91    pub fn new(items: impl IntoIterator<Item = TreemapItem>) -> Self {
92        Self {
93            items: items.into_iter().collect(),
94            gradient: None,
95            border: false,
96            gap: true,
97            border_color: None,
98            theme: None,
99            base: None,
100            show_values: true,
101            block: None,
102        }
103    }
104
105    setter!(
106        /// Leave a thin gutter (one column, half a row) between leaf tiles so
107        /// neighbours stay distinguishable (default on).
108        gap: bool
109    );
110
111    /// Color items without explicit color by value, interpolating `low`→`high`
112    /// (use `Color::Rgb` values for smooth results).
113    pub fn gradient(mut self, low: Color, high: Color) -> Self {
114        self.gradient = Some((low, high));
115        self
116    }
117
118    setter!(
119        /// Draw a border around each cell.
120        border: bool
121    );
122
123    opt_setter!(
124        /// Border color.
125        border_color: Color
126    );
127
128    theme_setter!(
129        /// Apply a [`Theme`]: items without a color are colored by value along the
130        /// theme gradient; cell borders use the theme background. Explicit item
131        /// colors, [`Treemap::gradient`] and [`Treemap::border_color`] win.
132        theme
133    );
134
135    base_style_setter!(base);
136
137    setter!(
138        /// Print the value under the label when there is room.
139        show_values: bool
140    );
141
142    block_setter!(block, 'static);
143
144    /// Compute squarified cell rects for `weights` inside `area`, in the
145    /// input order. Zero-weight items get empty rects.
146    pub fn layout(weights: &[f64], area: Rect) -> Vec<Rect> {
147        let mut out = vec![Rect::new(area.x, area.y, 0, 0); weights.len()];
148        let mut order: Vec<usize> = (0..weights.len())
149            .filter(|&i| weights[i].is_finite() && weights[i] > 0.0)
150            .collect();
151        order.sort_by(|&a, &b| weights[b].total_cmp(&weights[a]));
152        let total: f64 = order.iter().map(|&i| weights[i]).sum();
153        if order.is_empty() || area.width == 0 || area.height == 0 || total <= 0.0 {
154            return out;
155        }
156        // Virtual space: cells are ~2x taller than wide.
157        let (ax, ay) = (area.x as f64, area.y as f64 * 2.0);
158        let (mut x, mut y) = (ax, ay);
159        let (mut w, mut h) = (area.width as f64, area.height as f64 * 2.0);
160        let scale = w * h / total;
161        let mut i = 0;
162        let mut rects: Vec<(usize, f64, f64, f64, f64)> = vec![];
163        while i < order.len() {
164            let short = w.min(h);
165            let areas: Vec<f64> = order[i..].iter().map(|&k| weights[k] * scale).collect();
166            let worst = |n: usize| -> f64 {
167                let s: f64 = areas[..n].iter().sum();
168                let mx = areas[..n].iter().cloned().fold(f64::MIN, f64::max);
169                let mn = areas[..n].iter().cloned().fold(f64::MAX, f64::min);
170                let s2 = short * short;
171                ((s2 * mx) / (s * s)).max((s * s) / (s2 * mn))
172            };
173            let mut n = 1;
174            while n < areas.len() && worst(n + 1) <= worst(n) {
175                n += 1;
176            }
177            let s: f64 = areas[..n].iter().sum();
178            if w >= h {
179                let cw = if h > 0.0 { s / h } else { 0.0 };
180                let mut cy = y;
181                for k in 0..n {
182                    let ch = if cw > 0.0 { areas[k] / cw } else { 0.0 };
183                    rects.push((order[i + k], x, cy, cw, ch));
184                    cy += ch;
185                }
186                x += cw;
187                w -= cw;
188            } else {
189                let rh = if w > 0.0 { s / w } else { 0.0 };
190                let mut cx = x;
191                for k in 0..n {
192                    let cw = if rh > 0.0 { areas[k] / rh } else { 0.0 };
193                    rects.push((order[i + k], cx, y, cw, rh));
194                    cx += cw;
195                }
196                y += rh;
197                h -= rh;
198            }
199            i += n;
200        }
201        let (r_right, r_bottom) = (area.right() as f64, area.bottom() as f64);
202        for (k, rx, ry, rw, rh) in rects {
203            let x0 = rx.round().clamp(ax, r_right);
204            let x1 = (rx + rw).round().clamp(ax, r_right);
205            let y0 = (ry / 2.0).round().clamp(area.y as f64, r_bottom);
206            let y1 = ((ry + rh) / 2.0).round().clamp(area.y as f64, r_bottom);
207            out[k] = Rect::new(x0 as u16, y0 as u16, (x1 - x0) as u16, (y1 - y0) as u16);
208        }
209        out
210    }
211
212    fn leaf_range(items: &[TreemapItem], acc: &mut (f64, f64)) {
213        for it in items {
214            if it.children.is_empty() {
215                let w = it.weight();
216                if w > 0.0 {
217                    acc.0 = acc.0.min(w);
218                    acc.1 = acc.1.max(w);
219                }
220            } else {
221                Self::leaf_range(&it.children, acc);
222            }
223        }
224    }
225
226    #[allow(clippy::too_many_arguments)]
227    fn draw(&self, items: &[TreemapItem], area: Rect, buf: &mut Buffer, range: (f64, f64)) {
228        let weights: Vec<f64> = items.iter().map(|i| i.weight()).collect();
229        let rects = Self::layout(&weights, area);
230        for (idx, (it, r)) in items.iter().zip(rects).enumerate() {
231            if r.width == 0 || r.height == 0 {
232                continue;
233            }
234            let color = it
235                .color
236                .unwrap_or_else(|| self.auto_color(idx, weights[idx], range));
237            let is_group = !it.children.is_empty();
238            // groups get a dark header strip; leaves fill with their color
239            let color = if is_group { self.header_color() } else { color };
240            let bg = Style::default().bg(color).fg(text_color(color));
241            let bordered = self.border && !is_group && r.width >= 2 && r.height >= 2;
242            let gutter = self.gap && !is_group && !bordered && r.width >= 4 && r.height >= 2;
243            let base = self.canvas_bg();
244            for y in r.y..r.bottom() {
245                for x in r.x..r.right() {
246                    let last_col = gutter && x == r.right() - 1;
247                    let last_row = gutter && y == r.bottom() - 1;
248                    if last_col {
249                        buf[(x, y)]
250                            .set_symbol(" ")
251                            .set_style(Style::default().bg(base));
252                    } else if last_row {
253                        buf[(x, y)]
254                            .set_symbol("▀")
255                            .set_style(Style::default().fg(color).bg(base));
256                    } else if !(is_group && y > r.y) {
257                        buf[(x, y)].set_symbol(" ").set_style(bg);
258                    }
259                }
260            }
261            if bordered {
262                self.draw_border(buf, r, color);
263            }
264            let inset = if bordered { 1 } else { 0 };
265            let text = Rect::new(
266                r.x + inset,
267                r.y + inset,
268                r.width.saturating_sub(2 * inset + u16::from(gutter)),
269                r.height.saturating_sub(2 * inset + u16::from(gutter)),
270            );
271            if text.width == 0 || text.height == 0 {
272                continue;
273            }
274            let label = if is_group {
275                format!("▾ {} · {}", it.label, format_compact(it.weight()))
276            } else {
277                it.label.clone()
278            };
279            put_text(
280                buf,
281                text,
282                0,
283                &label,
284                bg.add_modifier(ratatui::style::Modifier::BOLD),
285            );
286            if it.children.is_empty() {
287                if self.show_values && text.height >= 2 {
288                    put_text(buf, text, 1, &format_compact(weights[idx]), bg);
289                }
290            } else if text.height >= 2 {
291                let sub = Rect::new(text.x, text.y + 1, text.width, text.height - 1);
292                self.draw(&it.children, sub, buf, range);
293            }
294        }
295    }
296
297    fn canvas_bg(&self) -> Color {
298        self.theme
299            .as_ref()
300            .and_then(|t| t.background)
301            .unwrap_or(Color::Reset)
302    }
303
304    fn header_color(&self) -> Color {
305        let (r, g, b) = rgb(self.canvas_bg());
306        let lift = |c: u8| c.saturating_add(34);
307        if matches!(self.canvas_bg(), Color::Reset) {
308            Color::Rgb(48, 52, 64)
309        } else {
310            Color::Rgb(lift(r), lift(g), lift(b))
311        }
312    }
313
314    fn draw_border(&self, buf: &mut Buffer, r: Rect, bg: Color) {
315        let st = Style::default()
316            .bg(bg)
317            .fg(self.border_color.unwrap_or_else(|| {
318                self.theme
319                    .as_ref()
320                    .and_then(|t| t.background)
321                    .unwrap_or(Color::Black)
322            }));
323        let (x1, y1) = (r.right() - 1, r.bottom() - 1);
324        for x in r.x..=x1 {
325            buf[(x, r.y)].set_symbol("─").set_style(st);
326            buf[(x, y1)].set_symbol("─").set_style(st);
327        }
328        for y in r.y..=y1 {
329            buf[(r.x, y)].set_symbol("│").set_style(st);
330            buf[(x1, y)].set_symbol("│").set_style(st);
331        }
332        buf[(r.x, r.y)].set_symbol("┌");
333        buf[(x1, r.y)].set_symbol("┐");
334        buf[(r.x, y1)].set_symbol("└");
335        buf[(x1, y1)].set_symbol("┘");
336    }
337
338    fn auto_color(&self, idx: usize, weight: f64, range: (f64, f64)) -> Color {
339        if let Some((lo, hi)) = self.gradient {
340            let t = if range.1 > range.0 {
341                ((weight - range.0) / (range.1 - range.0)).clamp(0.0, 1.0)
342            } else {
343                0.5
344            };
345            return lerp_color(lo, hi, t);
346        }
347        if let Some(t) = &self.theme {
348            let f = if range.1 > range.0 {
349                ((weight - range.0) / (range.1 - range.0)).clamp(0.0, 1.0)
350            } else {
351                0.5
352            };
353            return t.gradient().color_at(f);
354        }
355        let p = PALETTE[idx % PALETTE.len()];
356        Color::Rgb(p.0, p.1, p.2)
357    }
358}
359
360fn rgb(c: Color) -> (u8, u8, u8) {
361    match c {
362        Color::Rgb(r, g, b) => (r, g, b),
363        Color::Black => (0, 0, 0),
364        Color::Red => (205, 49, 49),
365        Color::Green => (13, 188, 121),
366        Color::Yellow => (229, 229, 16),
367        Color::Blue => (36, 114, 200),
368        Color::Magenta => (188, 63, 188),
369        Color::Cyan => (17, 168, 205),
370        Color::Gray => (229, 229, 229),
371        Color::DarkGray => (102, 102, 102),
372        Color::White => (255, 255, 255),
373        _ => (200, 200, 200),
374    }
375}
376
377fn lerp_color(a: Color, b: Color, t: f64) -> Color {
378    let (a, b) = (rgb(a), rgb(b));
379    let (r, g, bl) = crate::scale::mix_rgb(a, b, t);
380    Color::Rgb(r, g, bl)
381}
382
383fn text_color(bg: Color) -> Color {
384    let (r, g, b) = rgb(bg);
385    if 0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64 > 140.0 {
386        Color::Black
387    } else {
388        Color::White
389    }
390}
391
392fn put_text(buf: &mut Buffer, area: Rect, row: u16, s: &str, style: Style) {
393    if row >= area.height {
394        return;
395    }
396    for (i, ch) in s.chars().take(area.width as usize).enumerate() {
397        buf[(area.x + i as u16, area.y + row)]
398            .set_symbol(&ch.to_string())
399            .set_style(style);
400    }
401}
402
403impl Treemap {
404    fn render_into(&self, area: Rect, buf: &mut Buffer) {
405        let area = area.intersection(buf.area);
406        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
407        if inner.width == 0 || inner.height == 0 {
408            return;
409        }
410        let mut range = (f64::INFINITY, f64::NEG_INFINITY);
411        Treemap::leaf_range(&self.items, &mut range);
412        self.draw(&self.items, inner, buf, range);
413    }
414}
415
416widget_impls!(Treemap);
417
418#[cfg(feature = "theme")]
419impl tui_nuances::Themed for Treemap {
420    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
421        self.theme(theme)
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use ratatui::widgets::Widget;
429
430    #[test]
431    fn layout_tiles_area() {
432        let area = Rect::new(2, 1, 40, 12);
433        let rects = Treemap::layout(&[6.0, 6.0, 4.0, 3.0, 2.0, 2.0, 1.0], area);
434        let covered: u32 = rects.iter().map(|r| r.width as u32 * r.height as u32).sum();
435        assert_eq!(covered, 40 * 12);
436        for r in &rects {
437            assert!(area.contains((r.x, r.y).into()));
438            assert!(r.right() <= area.right() && r.bottom() <= area.bottom());
439        }
440    }
441
442    #[test]
443    fn area_proportional() {
444        let rects = Treemap::layout(&[3.0, 1.0], Rect::new(0, 0, 40, 10));
445        let a = rects[0].width as u32 * rects[0].height as u32;
446        let b = rects[1].width as u32 * rects[1].height as u32;
447        assert_eq!(a, 300);
448        assert_eq!(b, 100);
449    }
450
451    #[test]
452    fn invalid_weights_empty() {
453        let r = Treemap::layout(&[0.0, f64::NAN, -1.0], Rect::new(0, 0, 10, 10));
454        assert!(r.iter().all(|r| r.width == 0 || r.height == 0));
455    }
456
457    #[test]
458    fn nested_weight() {
459        let g = TreemapItem::new("g", 0.0)
460            .children([TreemapItem::new("a", 2.0), TreemapItem::new("b", 3.0)]);
461        assert_eq!(g.weight(), 5.0);
462    }
463
464    #[test]
465    fn renders_labels_and_colors() {
466        let area = Rect::new(0, 0, 40, 12);
467        let mut buf = Buffer::empty(area);
468        Treemap::new([
469            TreemapItem::new("alpha", 5.0).color(Color::Red),
470            TreemapItem::new("beta", 3.0),
471            TreemapItem::new("gamma", 2.0),
472        ])
473        .gap(false)
474        .render(area, &mut buf);
475        let t: String = (0..12)
476            .flat_map(|y| (0..40).map(move |x| (x, y)))
477            .map(|p| buf[p].symbol().to_string())
478            .collect();
479        assert!(t.contains("alpha") && t.contains("beta"));
480        assert!((0..40).all(|x| (0..12).all(|y| buf[(x, y)].bg != Color::Reset)));
481    }
482
483    #[cfg(feature = "theme")]
484    #[test]
485    fn theme_gradient_and_override() {
486        let t = Theme::dracula();
487        let area = Rect::new(0, 0, 40, 12);
488        let items = || {
489            [
490                TreemapItem::new("alpha", 5.0).color(Color::Red),
491                TreemapItem::new("beta", 3.0),
492                TreemapItem::new("gamma", 1.0),
493            ]
494        };
495        let mut buf = Buffer::empty(area);
496        Treemap::new(items()).theme(&t).render(area, &mut buf);
497        let g = t.gradient();
498        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.bg == c);
499        assert!(has(&buf, Color::Red));
500        assert!(has(&buf, g.color_at(1.0)) || has(&buf, g.color_at(0.5)));
501        assert!(has(&buf, g.color_at(0.0)));
502        let mut buf = Buffer::empty(area);
503        Treemap::new(items())
504            .theme(&t)
505            .gradient(Color::Rgb(1, 2, 3), Color::Rgb(1, 2, 3))
506            .render(area, &mut buf);
507        assert!(has(&buf, Color::Rgb(1, 2, 3)) && !has(&buf, g.color_at(0.0)));
508    }
509
510    #[test]
511    fn gap_leaves_gutters() {
512        let area = Rect::new(0, 0, 40, 12);
513        let mut buf = Buffer::empty(area);
514        Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", 1.0)])
515            .render(area, &mut buf);
516        let t: String = buf.content().iter().map(|c| c.symbol()).collect();
517        assert!(t.contains('▀'), "bottom half-block gutter expected");
518    }
519
520    #[test]
521    fn border_and_nested() {
522        let area = Rect::new(0, 0, 40, 14);
523        let mut buf = Buffer::empty(area);
524        Treemap::new([
525            TreemapItem::new("grp", 0.0)
526                .children([TreemapItem::new("x", 4.0), TreemapItem::new("y", 2.0)]),
527            TreemapItem::new("solo", 3.0),
528        ])
529        .border(true)
530        .gradient(Color::Rgb(0, 0, 80), Color::Rgb(0, 200, 0))
531        .block(Block::bordered())
532        .render(area, &mut buf);
533        let t: String = (0..14)
534            .flat_map(|y| (0..40).map(move |x| (x, y)))
535            .map(|p| buf[p].symbol().to_string())
536            .collect();
537        assert!(t.contains("grp") && t.contains("solo") && t.contains('┌'));
538    }
539
540    #[test]
541    fn robust() {
542        for (w, h) in [(0, 0), (1, 1), (2, 3), (5, 2)] {
543            let area = Rect::new(0, 0, w, h);
544            let mut buf = Buffer::empty(area);
545            Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", f64::NAN)])
546                .border(true)
547                .block(Block::bordered())
548                .render(area, &mut buf);
549        }
550        let area = Rect::new(0, 0, 10, 5);
551        Treemap::new([]).render(area, &mut Buffer::empty(area));
552    }
553}