1use 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#[derive(Debug, Clone, PartialEq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct TreemapItem {
28 pub label: String,
30 pub value: f64,
32 pub color: Option<Color>,
34 pub children: Vec<TreemapItem>,
36}
37
38impl TreemapItem {
39 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 color: Color
52 );
53
54 pub fn children(mut self, c: impl IntoIterator<Item = TreemapItem>) -> Self {
56 self.children = c.into_iter().collect();
57 self
58 }
59
60 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#[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 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 gap: bool
121 );
122
123 pub fn gradient(mut self, low: Color, high: Color) -> Self {
126 self.gradient = Some((low, high));
127 self
128 }
129
130 setter!(
131 border: bool
133 );
134
135 opt_setter!(
136 border_color: Color
138 );
139
140 theme_setter!(
141 theme
145 );
146
147 base_style_setter!(base);
148
149 setter!(
150 show_values: bool
152 );
153
154 block_setter!(block, 'static);
155
156 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 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 let color = if is_group { self.header_color() } else { color };
252 let bg = Style::default().bg(color).fg(text_color(color));
253 let bordered = self.border && !is_group && r.width >= 2 && r.height >= 2;
254 let gutter = self.gap && !is_group && !bordered && r.width >= 4 && r.height >= 2;
255 let base = self.canvas_bg();
256 for y in r.y..r.bottom() {
257 for x in r.x..r.right() {
258 let last_col = gutter && x == r.right() - 1;
259 let last_row = gutter && y == r.bottom() - 1;
260 if last_col {
261 buf[(x, y)]
262 .set_symbol(" ")
263 .set_style(Style::default().bg(base));
264 } else if last_row {
265 buf[(x, y)]
266 .set_symbol("▀")
267 .set_style(Style::default().fg(color).bg(base));
268 } else if !(is_group && y > r.y) {
269 buf[(x, y)].set_symbol(" ").set_style(bg);
270 }
271 }
272 }
273 if bordered {
274 self.draw_border(buf, r, color);
275 }
276 let inset = if bordered { 1 } else { 0 };
277 let text = Rect::new(
278 r.x + inset,
279 r.y + inset,
280 r.width.saturating_sub(2 * inset + u16::from(gutter)),
281 r.height.saturating_sub(2 * inset + u16::from(gutter)),
282 );
283 if text.width == 0 || text.height == 0 {
284 continue;
285 }
286 let label = if is_group {
287 format!("▾ {} · {}", it.label, format_compact(it.weight()))
288 } else {
289 it.label.clone()
290 };
291 put_text(
292 buf,
293 text,
294 0,
295 &label,
296 bg.add_modifier(ratatui::style::Modifier::BOLD),
297 );
298 if it.children.is_empty() {
299 if self.show_values && text.height >= 2 {
300 put_text(buf, text, 1, &format_compact(weights[idx]), bg);
301 }
302 } else if text.height >= 2 {
303 let sub = Rect::new(text.x, text.y + 1, text.width, text.height - 1);
304 self.draw(&it.children, sub, buf, range);
305 }
306 }
307 }
308
309 fn canvas_bg(&self) -> Color {
310 self.theme
311 .as_ref()
312 .and_then(|t| t.background)
313 .unwrap_or(Color::Reset)
314 }
315
316 fn header_color(&self) -> Color {
317 let (r, g, b) = rgb(self.canvas_bg());
318 let lift = |c: u8| c.saturating_add(34);
319 if matches!(self.canvas_bg(), Color::Reset) {
320 Color::Rgb(48, 52, 64)
321 } else {
322 Color::Rgb(lift(r), lift(g), lift(b))
323 }
324 }
325
326 fn draw_border(&self, buf: &mut Buffer, r: Rect, bg: Color) {
327 let st = Style::default()
328 .bg(bg)
329 .fg(self.border_color.unwrap_or_else(|| {
330 self.theme
331 .as_ref()
332 .and_then(|t| t.background)
333 .unwrap_or(Color::Black)
334 }));
335 let (x1, y1) = (r.right() - 1, r.bottom() - 1);
336 for x in r.x..=x1 {
337 buf[(x, r.y)].set_symbol("─").set_style(st);
338 buf[(x, y1)].set_symbol("─").set_style(st);
339 }
340 for y in r.y..=y1 {
341 buf[(r.x, y)].set_symbol("│").set_style(st);
342 buf[(x1, y)].set_symbol("│").set_style(st);
343 }
344 buf[(r.x, r.y)].set_symbol("┌");
345 buf[(x1, r.y)].set_symbol("┐");
346 buf[(r.x, y1)].set_symbol("└");
347 buf[(x1, y1)].set_symbol("┘");
348 }
349
350 fn auto_color(&self, idx: usize, weight: f64, range: (f64, f64)) -> Color {
351 if let Some((lo, hi)) = self.gradient {
352 let t = if range.1 > range.0 {
353 ((weight - range.0) / (range.1 - range.0)).clamp(0.0, 1.0)
354 } else {
355 0.5
356 };
357 return lerp_color(lo, hi, t);
358 }
359 if let Some(t) = &self.theme {
360 let f = if range.1 > range.0 {
361 ((weight - range.0) / (range.1 - range.0)).clamp(0.0, 1.0)
362 } else {
363 0.5
364 };
365 return t.gradient().color_at(f);
366 }
367 let p = PALETTE[idx % PALETTE.len()];
368 Color::Rgb(p.0, p.1, p.2)
369 }
370}
371
372fn rgb(c: Color) -> (u8, u8, u8) {
373 match c {
374 Color::Rgb(r, g, b) => (r, g, b),
375 Color::Black => (0, 0, 0),
376 Color::Red => (205, 49, 49),
377 Color::Green => (13, 188, 121),
378 Color::Yellow => (229, 229, 16),
379 Color::Blue => (36, 114, 200),
380 Color::Magenta => (188, 63, 188),
381 Color::Cyan => (17, 168, 205),
382 Color::Gray => (229, 229, 229),
383 Color::DarkGray => (102, 102, 102),
384 Color::White => (255, 255, 255),
385 _ => (200, 200, 200),
386 }
387}
388
389fn lerp_color(a: Color, b: Color, t: f64) -> Color {
390 let (a, b) = (rgb(a), rgb(b));
391 let (r, g, bl) = crate::scale::mix_rgb(a, b, t);
392 Color::Rgb(r, g, bl)
393}
394
395fn text_color(bg: Color) -> Color {
396 let (r, g, b) = rgb(bg);
397 if 0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64 > 140.0 {
398 Color::Black
399 } else {
400 Color::White
401 }
402}
403
404fn put_text(buf: &mut Buffer, area: Rect, row: u16, s: &str, style: Style) {
405 if row >= area.height {
406 return;
407 }
408 for (i, ch) in s.chars().take(area.width as usize).enumerate() {
409 buf[(area.x + i as u16, area.y + row)]
410 .set_symbol(&ch.to_string())
411 .set_style(style);
412 }
413}
414
415impl Treemap {
416 fn render_into(&self, area: Rect, buf: &mut Buffer) {
417 let area = area.intersection(buf.area);
418 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
419 if inner.width == 0 || inner.height == 0 {
420 return;
421 }
422 let mut range = (f64::INFINITY, f64::NEG_INFINITY);
423 Treemap::leaf_range(&self.items, &mut range);
424 self.draw(&self.items, inner, buf, range);
425 }
426}
427
428widget_impls!(Treemap);
429
430#[cfg(feature = "theme")]
431impl tui_nuances::Themed for Treemap {
432 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
433 self.theme(theme)
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440 use ratatui::widgets::Widget;
441
442 #[test]
443 fn layout_tiles_area() {
444 let area = Rect::new(2, 1, 40, 12);
445 let rects = Treemap::layout(&[6.0, 6.0, 4.0, 3.0, 2.0, 2.0, 1.0], area);
446 let covered: u32 = rects.iter().map(|r| r.width as u32 * r.height as u32).sum();
447 assert_eq!(covered, 40 * 12);
448 for r in &rects {
449 assert!(area.contains((r.x, r.y).into()));
450 assert!(r.right() <= area.right() && r.bottom() <= area.bottom());
451 }
452 }
453
454 #[test]
455 fn area_proportional() {
456 let rects = Treemap::layout(&[3.0, 1.0], Rect::new(0, 0, 40, 10));
457 let a = rects[0].width as u32 * rects[0].height as u32;
458 let b = rects[1].width as u32 * rects[1].height as u32;
459 assert_eq!(a, 300);
460 assert_eq!(b, 100);
461 }
462
463 #[test]
464 fn invalid_weights_empty() {
465 let r = Treemap::layout(&[0.0, f64::NAN, -1.0], Rect::new(0, 0, 10, 10));
466 assert!(r.iter().all(|r| r.width == 0 || r.height == 0));
467 }
468
469 #[test]
470 fn nested_weight() {
471 let g = TreemapItem::new("g", 0.0)
472 .children([TreemapItem::new("a", 2.0), TreemapItem::new("b", 3.0)]);
473 assert_eq!(g.weight(), 5.0);
474 }
475
476 #[test]
477 fn renders_labels_and_colors() {
478 let area = Rect::new(0, 0, 40, 12);
479 let mut buf = Buffer::empty(area);
480 Treemap::new([
481 TreemapItem::new("alpha", 5.0).color(Color::Red),
482 TreemapItem::new("beta", 3.0),
483 TreemapItem::new("gamma", 2.0),
484 ])
485 .gap(false)
486 .render(area, &mut buf);
487 let t: String = (0..12)
488 .flat_map(|y| (0..40).map(move |x| (x, y)))
489 .map(|p| buf[p].symbol().to_string())
490 .collect();
491 assert!(t.contains("alpha") && t.contains("beta"));
492 assert!((0..40).all(|x| (0..12).all(|y| buf[(x, y)].bg != Color::Reset)));
493 }
494
495 #[cfg(feature = "theme")]
496 #[test]
497 fn theme_gradient_and_override() {
498 let t = Theme::dracula();
499 let area = Rect::new(0, 0, 40, 12);
500 let items = || {
501 [
502 TreemapItem::new("alpha", 5.0).color(Color::Red),
503 TreemapItem::new("beta", 3.0),
504 TreemapItem::new("gamma", 1.0),
505 ]
506 };
507 let mut buf = Buffer::empty(area);
508 Treemap::new(items()).theme(&t).render(area, &mut buf);
509 let g = t.gradient();
510 let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.bg == c);
511 assert!(has(&buf, Color::Red));
512 assert!(has(&buf, g.color_at(1.0)) || has(&buf, g.color_at(0.5)));
513 assert!(has(&buf, g.color_at(0.0)));
514 let mut buf = Buffer::empty(area);
515 Treemap::new(items())
516 .theme(&t)
517 .gradient(Color::Rgb(1, 2, 3), Color::Rgb(1, 2, 3))
518 .render(area, &mut buf);
519 assert!(has(&buf, Color::Rgb(1, 2, 3)) && !has(&buf, g.color_at(0.0)));
520 }
521
522 #[test]
523 fn gap_leaves_gutters() {
524 let area = Rect::new(0, 0, 40, 12);
525 let mut buf = Buffer::empty(area);
526 Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", 1.0)])
527 .render(area, &mut buf);
528 let t: String = buf.content().iter().map(|c| c.symbol()).collect();
529 assert!(t.contains('▀'), "bottom half-block gutter expected");
530 }
531
532 #[test]
533 fn border_and_nested() {
534 let area = Rect::new(0, 0, 40, 14);
535 let mut buf = Buffer::empty(area);
536 Treemap::new([
537 TreemapItem::new("grp", 0.0)
538 .children([TreemapItem::new("x", 4.0), TreemapItem::new("y", 2.0)]),
539 TreemapItem::new("solo", 3.0),
540 ])
541 .border(true)
542 .gradient(Color::Rgb(0, 0, 80), Color::Rgb(0, 200, 0))
543 .block(Block::bordered())
544 .render(area, &mut buf);
545 let t: String = (0..14)
546 .flat_map(|y| (0..40).map(move |x| (x, y)))
547 .map(|p| buf[p].symbol().to_string())
548 .collect();
549 assert!(t.contains("grp") && t.contains("solo") && t.contains('┌'));
550 }
551
552 #[test]
553 fn robust() {
554 for (w, h) in [(0, 0), (1, 1), (2, 3), (5, 2)] {
555 let area = Rect::new(0, 0, w, h);
556 let mut buf = Buffer::empty(area);
557 Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", f64::NAN)])
558 .border(true)
559 .block(Block::bordered())
560 .render(area, &mut buf);
561 }
562 let area = Rect::new(0, 0, 10, 5);
563 Treemap::new([]).render(area, &mut Buffer::empty(area));
564 }
565}