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