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 let fits = unicode_width::UnicodeWidthStr::width(label.trim()) <= text.width as usize;
340 if fits || text.width >= 5 {
341 put_text(
342 buf,
343 text,
344 0,
345 &label,
346 bg.add_modifier(ratatui::style::Modifier::BOLD),
347 );
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 use unicode_width::UnicodeWidthChar;
457 if row >= area.height || area.width == 0 {
458 return;
459 }
460 let max = area.width as usize;
461 let s = s.trim();
462 let total: usize = s.chars().map(|c| c.width().unwrap_or(0)).sum();
464 let limit = if total > max {
465 max.saturating_sub(1)
466 } else {
467 max
468 };
469 let y = area.y + row;
470 let mut col = 0usize;
471 for ch in s.chars() {
472 let w = ch.width().unwrap_or(0);
473 if w == 0 {
474 continue;
475 }
476 if col + w > limit {
477 break;
478 }
479 buf[(area.x + col as u16, y)]
480 .set_symbol(ch.encode_utf8(&mut [0; 4]))
481 .set_style(style);
482 for k in 1..w {
484 buf[(area.x + (col + k) as u16, y)]
485 .set_symbol("")
486 .set_style(style);
487 }
488 col += w;
489 }
490 if total > max && max > 0 {
491 buf[(area.x + col as u16, y)]
492 .set_symbol("…")
493 .set_style(style);
494 }
495}
496
497impl Treemap {
498 fn render_into(&self, area: Rect, buf: &mut Buffer) {
499 let area = area.intersection(buf.area);
500 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
501 if inner.width == 0 || inner.height == 0 {
502 return;
503 }
504 let mut range = (f64::INFINITY, f64::NEG_INFINITY);
505 Treemap::leaf_range(&self.items, &mut range);
506 self.draw(&self.items, inner, buf, range);
507 }
508}
509
510widget_impls!(Treemap);
511
512#[cfg(feature = "theme")]
513impl tui_nuances::Themed for Treemap {
514 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
515 self.theme(theme)
516 }
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522 use ratatui::widgets::Widget;
523
524 #[test]
525 fn layout_tiles_area() {
526 let area = Rect::new(2, 1, 40, 12);
527 let rects = Treemap::layout(&[6.0, 6.0, 4.0, 3.0, 2.0, 2.0, 1.0], area);
528 let covered: u32 = rects.iter().map(|r| r.width as u32 * r.height as u32).sum();
529 assert_eq!(covered, 40 * 12);
530 for r in &rects {
531 assert!(area.contains((r.x, r.y).into()));
532 assert!(r.right() <= area.right() && r.bottom() <= area.bottom());
533 }
534 }
535
536 #[test]
537 fn area_proportional() {
538 let rects = Treemap::layout(&[3.0, 1.0], Rect::new(0, 0, 40, 10));
539 let a = rects[0].width as u32 * rects[0].height as u32;
540 let b = rects[1].width as u32 * rects[1].height as u32;
541 assert_eq!(a, 300);
542 assert_eq!(b, 100);
543 }
544
545 #[test]
546 fn invalid_weights_empty() {
547 let r = Treemap::layout(&[0.0, f64::NAN, -1.0], Rect::new(0, 0, 10, 10));
548 assert!(r.iter().all(|r| r.width == 0 || r.height == 0));
549 }
550
551 #[test]
552 fn nested_weight() {
553 let g = TreemapItem::new("g", 0.0)
554 .children([TreemapItem::new("a", 2.0), TreemapItem::new("b", 3.0)]);
555 assert_eq!(g.weight(), 5.0);
556 }
557
558 #[test]
559 fn long_and_wide_labels_stay_inside_tile() {
560 let area = Rect::new(0, 0, 8, 3);
561 let mut b = Buffer::empty(Rect::new(0, 0, 12, 3));
562 put_text(&mut b, area, 0, "Developer Tools", Style::default());
563 assert_eq!(b[(7, 0)].symbol(), "…");
564 assert_eq!(b[(8, 0)].symbol(), " ");
565 let mut b = Buffer::empty(Rect::new(0, 0, 12, 3));
566 put_text(&mut b, area, 0, "游戏游戏游戏游戏", Style::default());
567 assert_eq!(b[(8, 0)].symbol(), " ");
568 assert_eq!(b[(9, 0)].symbol(), " ");
569 }
570
571 #[test]
572 fn renders_labels_and_colors() {
573 let area = Rect::new(0, 0, 40, 12);
574 let mut buf = Buffer::empty(area);
575 Treemap::new([
576 TreemapItem::new("alpha", 5.0).color(Color::Red),
577 TreemapItem::new("beta", 3.0),
578 TreemapItem::new("gamma", 2.0),
579 ])
580 .gap(false)
581 .render(area, &mut buf);
582 let t: String = (0..12)
583 .flat_map(|y| (0..40).map(move |x| (x, y)))
584 .map(|p| buf[p].symbol().to_string())
585 .collect();
586 assert!(t.contains("alpha") && t.contains("beta"));
587 assert!((0..40).all(|x| (0..12).all(|y| buf[(x, y)].bg != Color::Reset)));
588 }
589
590 #[cfg(feature = "theme")]
591 #[test]
592 fn theme_gradient_and_override() {
593 let t = Theme::dracula();
594 let area = Rect::new(0, 0, 40, 12);
595 let items = || {
596 [
597 TreemapItem::new("alpha", 5.0).color(Color::Red),
598 TreemapItem::new("beta", 3.0),
599 TreemapItem::new("gamma", 1.0),
600 ]
601 };
602 let mut buf = Buffer::empty(area);
603 Treemap::new(items()).theme(&t).render(area, &mut buf);
604 let g = t.gradient();
605 let has = |b: &Buffer, c: Color| b.content().iter().any(|x| x.bg == c);
606 assert!(has(&buf, Color::Red));
607 assert!(has(&buf, g.color_at(1.0)) || has(&buf, g.color_at(0.5)));
608 assert!(has(&buf, g.color_at(0.0)));
609 let mut buf = Buffer::empty(area);
610 Treemap::new(items())
611 .theme(&t)
612 .gradient(Color::Rgb(1, 2, 3), Color::Rgb(1, 2, 3))
613 .render(area, &mut buf);
614 assert!(has(&buf, Color::Rgb(1, 2, 3)) && !has(&buf, g.color_at(0.0)));
615 }
616
617 #[test]
618 fn gap_leaves_gutters() {
619 let area = Rect::new(0, 0, 40, 12);
620 let mut buf = Buffer::empty(area);
621 Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", 1.0)])
622 .render(area, &mut buf);
623 let t: String = buf.content().iter().map(|c| c.symbol()).collect();
624 assert!(t.contains('▀'), "bottom half-block gutter expected");
625 }
626
627 #[test]
628 fn border_and_nested() {
629 let area = Rect::new(0, 0, 40, 14);
630 let mut buf = Buffer::empty(area);
631 Treemap::new([
632 TreemapItem::new("grp", 0.0)
633 .children([TreemapItem::new("x", 4.0), TreemapItem::new("y", 2.0)]),
634 TreemapItem::new("solo", 3.0),
635 ])
636 .border(true)
637 .gradient(Color::Rgb(0, 0, 80), Color::Rgb(0, 200, 0))
638 .block(Block::bordered())
639 .render(area, &mut buf);
640 let t: String = (0..14)
641 .flat_map(|y| (0..40).map(move |x| (x, y)))
642 .map(|p| buf[p].symbol().to_string())
643 .collect();
644 assert!(t.contains("grp") && t.contains("solo") && t.contains('┌'));
645 }
646
647 #[test]
648 fn robust() {
649 for (w, h) in [(0, 0), (1, 1), (2, 3), (5, 2)] {
650 let area = Rect::new(0, 0, w, h);
651 let mut buf = Buffer::empty(area);
652 Treemap::new([TreemapItem::new("a", 1.0), TreemapItem::new("b", f64::NAN)])
653 .border(true)
654 .block(Block::bordered())
655 .render(area, &mut buf);
656 }
657 let area = Rect::new(0, 0, 10, 5);
658 Treemap::new([]).render(area, &mut Buffer::empty(area));
659 }
660}