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 { v } else { 0.0 }
68    }
69}
70
71/// Squarified treemap widget.
72///
73/// # Example
74///
75/// ```
76/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
77/// use tui_chart::{Treemap, TreemapItem};
78///
79/// let chart = Treemap::new([TreemapItem::new("a", 5.0), TreemapItem::new("b", 3.0)]);
80/// let area = Rect::new(0, 0, 40, 12);
81/// let mut buf = Buffer::empty(area);
82/// chart.render(area, &mut buf);
83/// ```
84#[derive(Debug, Clone)]
85pub struct Treemap {
86    items: Vec<TreemapItem>,
87    gradient: Option<(Color, Color)>,
88    border: bool,
89    gap: bool,
90    border_color: Option<Color>,
91    theme: Option<Theme>,
92    base: Option<Style>,
93    show_values: bool,
94    block: Option<Block<'static>>,
95}
96
97impl Treemap {
98    /// Create from items.
99    pub fn new(items: impl IntoIterator<Item = TreemapItem>) -> Self {
100        Self {
101            items: items.into_iter().collect(),
102            gradient: None,
103            border: false,
104            gap: true,
105            border_color: None,
106            theme: None,
107            base: None,
108            show_values: true,
109            block: None,
110        }
111    }
112
113    setter!(
114        /// Leave a thin gutter (one column, half a row) between leaf tiles so
115        /// neighbours stay distinguishable (default on).
116        gap: bool
117    );
118
119    /// Color items without explicit color by value, interpolating `low`→`high`
120    /// (use `Color::Rgb` values for smooth results).
121    pub fn gradient(mut self, low: Color, high: Color) -> Self {
122        self.gradient = Some((low, high));
123        self
124    }
125
126    setter!(
127        /// Draw a border around each cell.
128        border: bool
129    );
130
131    opt_setter!(
132        /// Border color.
133        border_color: Color
134    );
135
136    theme_setter!(
137        /// Apply a [`Theme`]: items without a color are colored by value along the
138        /// theme gradient; cell borders use the theme background. Explicit item
139        /// colors, [`Treemap::gradient`] and [`Treemap::border_color`] win.
140        theme
141    );
142
143    base_style_setter!(base);
144
145    setter!(
146        /// Print the value under the label when there is room.
147        show_values: bool
148    );
149
150    block_setter!(block, 'static);
151
152    /// Compute squarified cell rects for `weights` inside `area`, in the
153    /// input order. Zero-weight items get empty rects.
154    pub fn layout(weights: &[f64], area: Rect) -> Vec<Rect> {
155        let mut out = vec![Rect::new(area.x, area.y, 0, 0); weights.len()];
156        let mut order: Vec<usize> = (0..weights.len())
157            .filter(|&i| weights[i].is_finite() && weights[i] > 0.0)
158            .collect();
159        order.sort_by(|&a, &b| weights[b].total_cmp(&weights[a]));
160        let total: f64 = order.iter().map(|&i| weights[i]).sum();
161        if order.is_empty() || area.width == 0 || area.height == 0 || total <= 0.0 {
162            return out;
163        }
164        // Virtual space: cells are ~2x taller than wide.
165        let (ax, ay) = (area.x as f64, area.y as f64 * 2.0);
166        let (mut x, mut y) = (ax, ay);
167        let (mut w, mut h) = (area.width as f64, area.height as f64 * 2.0);
168        let scale = w * h / total;
169        let mut i = 0;
170        let mut rects: Vec<(usize, f64, f64, f64, f64)> = vec![];
171        while i < order.len() {
172            let short = w.min(h);
173            let areas: Vec<f64> = order[i..].iter().map(|&k| weights[k] * scale).collect();
174            let worst = |n: usize| -> f64 {
175                let s: f64 = areas[..n].iter().sum();
176                let mx = areas[..n].iter().cloned().fold(f64::MIN, f64::max);
177                let mn = areas[..n].iter().cloned().fold(f64::MAX, f64::min);
178                let s2 = short * short;
179                ((s2 * mx) / (s * s)).max((s * s) / (s2 * mn))
180            };
181            let mut n = 1;
182            while n < areas.len() && worst(n + 1) <= worst(n) {
183                n += 1;
184            }
185            let s: f64 = areas[..n].iter().sum();
186            if w >= h {
187                let cw = if h > 0.0 { s / h } else { 0.0 };
188                let mut cy = y;
189                for k in 0..n {
190                    let ch = if cw > 0.0 { areas[k] / cw } else { 0.0 };
191                    rects.push((order[i + k], x, cy, cw, ch));
192                    cy += ch;
193                }
194                x += cw;
195                w -= cw;
196            } else {
197                let rh = if w > 0.0 { s / w } else { 0.0 };
198                let mut cx = x;
199                for k in 0..n {
200                    let cw = if rh > 0.0 { areas[k] / rh } else { 0.0 };
201                    rects.push((order[i + k], cx, y, cw, rh));
202                    cx += cw;
203                }
204                y += rh;
205                h -= rh;
206            }
207            i += n;
208        }
209        let (r_right, r_bottom) = (area.right() as f64, area.bottom() as f64);
210        for (k, rx, ry, rw, rh) in rects {
211            let x0 = rx.round().clamp(ax, r_right);
212            let x1 = (rx + rw).round().clamp(ax, r_right);
213            let y0 = (ry / 2.0).round().clamp(area.y as f64, r_bottom);
214            let y1 = ((ry + rh) / 2.0).round().clamp(area.y as f64, r_bottom);
215            out[k] = Rect::new(x0 as u16, y0 as u16, (x1 - x0) as u16, (y1 - y0) as u16);
216        }
217        out
218    }
219
220    fn leaf_range(items: &[TreemapItem], acc: &mut (f64, f64)) {
221        for it in items {
222            if it.children.is_empty() {
223                let w = it.weight();
224                if w > 0.0 {
225                    acc.0 = acc.0.min(w);
226                    acc.1 = acc.1.max(w);
227                }
228            } else {
229                Self::leaf_range(&it.children, acc);
230            }
231        }
232    }
233
234    #[allow(clippy::too_many_arguments)]
235    fn draw(&self, items: &[TreemapItem], area: Rect, buf: &mut Buffer, range: (f64, f64)) {
236        let weights: Vec<f64> = items.iter().map(|i| i.weight()).collect();
237        let rects = Self::layout(&weights, area);
238        for (idx, (it, r)) in items.iter().zip(rects).enumerate() {
239            if r.width == 0 || r.height == 0 {
240                continue;
241            }
242            let color = it
243                .color
244                .unwrap_or_else(|| self.auto_color(idx, weights[idx], range));
245            let is_group = !it.children.is_empty();
246            if !is_group {
247                let total: f64 = weights.iter().sum();
248                crate::interact::record_point(
249                    r,
250                    0,
251                    (usize::from(r.y) << 16) | usize::from(r.x),
252                    || {
253                        let share = if total > 0.0 {
254                            weights[idx] / total * 100.0
255                        } else {
256                            0.0
257                        };
258                        (
259                            it.label.clone(),
260                            vec![
261                                format!("value {}", format_compact(weights[idx])),
262                                format!("share {share:.0}%"),
263                            ],
264                        )
265                    },
266                );
267            }
268            // groups get a dark header strip; leaves fill with their color
269            let color = if is_group { self.header_color() } else { color };
270            let bg = Style::default().bg(color).fg(text_color(color));
271            let bordered = self.border && !is_group && r.width >= 2 && r.height >= 2;
272            let gutter = self.gap && !is_group && !bordered && r.width >= 4 && r.height >= 2;
273            let base = self.canvas_bg();
274            for y in r.y..r.bottom() {
275                for x in r.x..r.right() {
276                    let last_col = gutter && x == r.right() - 1;
277                    let last_row = gutter && y == r.bottom() - 1;
278                    if last_col {
279                        buf[(x, y)]
280                            .set_symbol(" ")
281                            .set_style(Style::default().bg(base));
282                    } else if last_row {
283                        buf[(x, y)]
284                            .set_symbol("▀")
285                            .set_style(Style::default().fg(color).bg(base));
286                    } else if !(is_group && y > r.y) {
287                        buf[(x, y)].set_symbol(" ").set_style(bg);
288                    }
289                }
290            }
291            if bordered {
292                self.draw_border(buf, r, color);
293            }
294            let inset = if bordered { 1 } else { 0 };
295            let text = Rect::new(
296                r.x + inset,
297                r.y + inset,
298                r.width.saturating_sub(2 * inset + u16::from(gutter)),
299                r.height.saturating_sub(2 * inset + u16::from(gutter)),
300            );
301            if text.width == 0 || text.height == 0 {
302                continue;
303            }
304            let label = if is_group {
305                format!("▾ {} · {}", it.label, format_compact(it.weight()))
306            } else {
307                it.label.clone()
308            };
309            // A sliver too narrow for its label shows nothing: "We…" is noise.
310            let fits = unicode_width::UnicodeWidthStr::width(label.trim()) <= text.width as usize;
311            if fits || text.width >= 5 {
312                put_text(
313                    buf,
314                    text,
315                    0,
316                    &label,
317                    bg.add_modifier(ratatui::style::Modifier::BOLD),
318                );
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    use unicode_width::UnicodeWidthChar;
428    if row >= area.height || area.width == 0 {
429        return;
430    }
431    let max = area.width as usize;
432    let s = s.trim();
433    // Clip by display width (wide glyphs take two cells), `…` when cut.
434    let total: usize = s.chars().map(|c| c.width().unwrap_or(0)).sum();
435    let limit = if total > max {
436        max.saturating_sub(1)
437    } else {
438        max
439    };
440    let y = area.y + row;
441    let mut col = 0usize;
442    for ch in s.chars() {
443        let w = ch.width().unwrap_or(0);
444        if w == 0 {
445            continue;
446        }
447        if col + w > limit {
448            break;
449        }
450        buf[(area.x + col as u16, y)]
451            .set_symbol(ch.encode_utf8(&mut [0; 4]))
452            .set_style(style);
453        // blank the continuation cell of a wide glyph
454        for k in 1..w {
455            buf[(area.x + (col + k) as u16, y)]
456                .set_symbol("")
457                .set_style(style);
458        }
459        col += w;
460    }
461    if total > max && max > 0 {
462        buf[(area.x + col as u16, y)]
463            .set_symbol("…")
464            .set_style(style);
465    }
466}
467
468impl Treemap {
469    fn render_into(&self, area: Rect, buf: &mut Buffer) {
470        let area = area.intersection(buf.area);
471        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
472        if inner.width == 0 || inner.height == 0 {
473            return;
474        }
475        let mut range = (f64::INFINITY, f64::NEG_INFINITY);
476        Treemap::leaf_range(&self.items, &mut range);
477        self.draw(&self.items, inner, buf, range);
478    }
479}
480
481widget_impls!(Treemap);
482
483#[cfg(feature = "theme")]
484impl tui_nuances::Themed for Treemap {
485    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
486        self.theme(theme)
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use ratatui::widgets::Widget;
494
495    #[test]
496    fn layout_tiles_area() {
497        let area = Rect::new(2, 1, 40, 12);
498        let rects = Treemap::layout(&[6.0, 6.0, 4.0, 3.0, 2.0, 2.0, 1.0], area);
499        let covered: u32 = rects.iter().map(|r| r.width as u32 * r.height as u32).sum();
500        assert_eq!(covered, 40 * 12);
501        for r in &rects {
502            assert!(area.contains((r.x, r.y).into()));
503            assert!(r.right() <= area.right() && r.bottom() <= area.bottom());
504        }
505    }
506
507    #[test]
508    fn area_proportional() {
509        let rects = Treemap::layout(&[3.0, 1.0], Rect::new(0, 0, 40, 10));
510        let a = rects[0].width as u32 * rects[0].height as u32;
511        let b = rects[1].width as u32 * rects[1].height as u32;
512        assert_eq!(a, 300);
513        assert_eq!(b, 100);
514    }
515
516    #[test]
517    fn invalid_weights_empty() {
518        let r = Treemap::layout(&[0.0, f64::NAN, -1.0], Rect::new(0, 0, 10, 10));
519        assert!(r.iter().all(|r| r.width == 0 || r.height == 0));
520    }
521
522    #[test]
523    fn nested_weight() {
524        let g = TreemapItem::new("g", 0.0)
525            .children([TreemapItem::new("a", 2.0), TreemapItem::new("b", 3.0)]);
526        assert_eq!(g.weight(), 5.0);
527    }
528
529    #[test]
530    fn long_and_wide_labels_stay_inside_tile() {
531        let area = Rect::new(0, 0, 8, 3);
532        let mut b = Buffer::empty(Rect::new(0, 0, 12, 3));
533        put_text(&mut b, area, 0, "Developer Tools", Style::default());
534        assert_eq!(b[(7, 0)].symbol(), "…");
535        assert_eq!(b[(8, 0)].symbol(), " ");
536        let mut b = Buffer::empty(Rect::new(0, 0, 12, 3));
537        put_text(&mut b, area, 0, "游戏游戏游戏游戏", Style::default());
538        assert_eq!(b[(8, 0)].symbol(), " ");
539        assert_eq!(b[(9, 0)].symbol(), " ");
540    }
541
542    #[test]
543    fn renders_labels_and_colors() {
544        let area = Rect::new(0, 0, 40, 12);
545        let mut buf = Buffer::empty(area);
546        Treemap::new([
547            TreemapItem::new("alpha", 5.0).color(Color::Red),
548            TreemapItem::new("beta", 3.0),
549            TreemapItem::new("gamma", 2.0),
550        ])
551        .gap(false)
552        .render(area, &mut buf);
553        let t: String = (0..12)
554            .flat_map(|y| (0..40).map(move |x| (x, y)))
555            .map(|p| buf[p].symbol().to_string())
556            .collect();
557        assert!(t.contains("alpha") && t.contains("beta"));
558        assert!((0..40).all(|x| (0..12).all(|y| buf[(x, y)].bg != Color::Reset)));
559    }
560
561    #[cfg(feature = "theme")]
562    #[test]
563    fn theme_gradient_and_override() {
564        let t = Theme::dracula();
565        let area = Rect::new(0, 0, 40, 12);
566        let items = || {
567            [
568                TreemapItem::new("alpha", 5.0).color(Color::Red),
569                TreemapItem::new("beta", 3.0),
570                TreemapItem::new("gamma", 1.0),
571            ]
572        };
573        let mut buf = Buffer::empty(area);
574        Treemap::new(items()).theme(&t).render(area, &mut buf);
575        let g = t.gradient();
576        let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.bg == c);
577        assert!(has(&buf, Color::Red));
578        assert!(has(&buf, g.color_at(1.0)) || has(&buf, g.color_at(0.5)));
579        assert!(has(&buf, g.color_at(0.0)));
580        let mut buf = Buffer::empty(area);
581        Treemap::new(items())
582            .theme(&t)
583            .gradient(Color::Rgb(1, 2, 3), Color::Rgb(1, 2, 3))
584            .render(area, &mut buf);
585        assert!(has(&buf, Color::Rgb(1, 2, 3)) && !has(&buf, g.color_at(0.0)));
586    }
587
588    #[test]
589    fn gap_leaves_gutters() {
590        let area = Rect::new(0, 0, 40, 12);
591        let mut buf = Buffer::empty(area);
592        Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", 1.0)])
593            .render(area, &mut buf);
594        let t: String = buf.content().iter().map(|c| c.symbol()).collect();
595        assert!(t.contains('▀'), "bottom half-block gutter expected");
596    }
597
598    #[test]
599    fn border_and_nested() {
600        let area = Rect::new(0, 0, 40, 14);
601        let mut buf = Buffer::empty(area);
602        Treemap::new([
603            TreemapItem::new("grp", 0.0)
604                .children([TreemapItem::new("x", 4.0), TreemapItem::new("y", 2.0)]),
605            TreemapItem::new("solo", 3.0),
606        ])
607        .border(true)
608        .gradient(Color::Rgb(0, 0, 80), Color::Rgb(0, 200, 0))
609        .block(Block::bordered())
610        .render(area, &mut buf);
611        let t: String = (0..14)
612            .flat_map(|y| (0..40).map(move |x| (x, y)))
613            .map(|p| buf[p].symbol().to_string())
614            .collect();
615        assert!(t.contains("grp") && t.contains("solo") && t.contains('┌'));
616    }
617
618    #[test]
619    fn robust() {
620        for (w, h) in [(0, 0), (1, 1), (2, 3), (5, 2)] {
621            let area = Rect::new(0, 0, w, h);
622            let mut buf = Buffer::empty(area);
623            Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", f64::NAN)])
624                .border(true)
625                .block(Block::bordered())
626                .render(area, &mut buf);
627        }
628        let area = Rect::new(0, 0, 10, 5);
629        Treemap::new([]).render(area, &mut Buffer::empty(area));
630    }
631}