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