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