1use crate::layout::{self, text_width};
4use crate::theme::{self, ChartThemeExt, Theme};
5use crate::util::format_compact;
6use ratatui::{
7 buffer::Buffer,
8 layout::Rect,
9 style::{Color, Style},
10 widgets::Block,
11};
12
13#[derive(Debug, Clone, PartialEq, Default)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum Gradient {
17 #[default]
19 Viridis,
20 Heat,
22 Cool,
24 RedBlue,
26 Grayscale,
28 Custom(Vec<(u8, u8, u8)>),
30}
31
32impl Gradient {
33 fn stops(&self) -> Vec<(u8, u8, u8)> {
34 match self {
35 Gradient::Viridis => vec![
36 (68, 1, 84),
37 (59, 82, 139),
38 (33, 145, 140),
39 (94, 201, 98),
40 (253, 231, 37),
41 ],
42 Gradient::Heat => vec![
43 (0, 0, 0),
44 (180, 0, 0),
45 (255, 140, 0),
46 (255, 255, 80),
47 (255, 255, 255),
48 ],
49 Gradient::Cool => vec![
50 (10, 20, 80),
51 (30, 100, 200),
52 (60, 200, 230),
53 (255, 255, 255),
54 ],
55 Gradient::RedBlue => vec![(30, 60, 200), (255, 255, 255), (200, 30, 30)],
56 Gradient::Grayscale => vec![(0, 0, 0), (255, 255, 255)],
57 Gradient::Custom(s) if s.len() >= 2 => s.clone(),
58 Gradient::Custom(_) => vec![(0, 0, 0), (255, 255, 255)],
59 }
60 }
61
62 pub fn color_at(&self, t: f64) -> Color {
64 let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
65 let stops = self.stops();
66 let pos = t * (stops.len() - 1) as f64;
67 let i = (pos.floor() as usize).min(stops.len() - 2);
68 let f = pos - i as f64;
69 let (a, b) = (stops[i], stops[i + 1]);
70 let (r, g, bl) = crate::scale::mix_rgb(a, b, f);
71 Color::Rgb(r, g, bl)
72 }
73
74 pub fn next(&self) -> Gradient {
76 match self {
77 Gradient::Viridis => Gradient::Heat,
78 Gradient::Heat => Gradient::Cool,
79 Gradient::Cool => Gradient::RedBlue,
80 Gradient::RedBlue => Gradient::Grayscale,
81 _ => Gradient::Viridis,
82 }
83 }
84
85 pub fn name(&self) -> &'static str {
87 match self {
88 Gradient::Viridis => "viridis",
89 Gradient::Heat => "heat",
90 Gradient::Cool => "cool",
91 Gradient::RedBlue => "red-blue",
92 Gradient::Grayscale => "grayscale",
93 Gradient::Custom(_) => "custom",
94 }
95 }
96}
97
98fn luminance(c: Color) -> f64 {
99 match c {
100 Color::Rgb(r, g, b) => 0.299 * r as f64 + 0.587 * g as f64 + 0.114 * b as f64,
101 _ => 128.0,
102 }
103}
104
105#[derive(Debug, Clone, Default)]
119pub struct Heatmap {
120 data: Vec<Vec<f64>>,
121 row_labels: Vec<String>,
122 col_labels: Vec<String>,
123 gradient: Option<Gradient>,
124 theme: Option<Theme>,
125 style: Option<Style>,
126 cell_width: u16,
127 cell_height: u16,
128 bounds: Option<(f64, f64)>,
129 show_values: bool,
130 stretch: bool,
131 legend: bool,
132 block: Option<Block<'static>>,
133}
134
135impl Heatmap {
136 pub fn new(data: Vec<Vec<f64>>) -> Self {
138 Self {
139 data,
140 cell_width: 2,
141 cell_height: 1,
142 legend: true,
143 ..Default::default()
144 }
145 }
146
147 pub fn row_labels<I, S>(mut self, l: I) -> Self
149 where
150 I: IntoIterator<Item = S>,
151 S: Into<String>,
152 {
153 self.row_labels = l.into_iter().map(Into::into).collect();
154 self
155 }
156
157 pub fn col_labels<I, S>(mut self, l: I) -> Self
159 where
160 I: IntoIterator<Item = S>,
161 S: Into<String>,
162 {
163 self.col_labels = l.into_iter().map(Into::into).collect();
164 self
165 }
166
167 opt_setter!(
168 gradient: Gradient
170 );
171
172 theme_setter!(
173 theme
176 );
177
178 base_style_setter!(style);
179
180 fn grad(&self) -> Gradient {
181 match (&self.gradient, &self.theme) {
182 (Some(g), _) => g.clone(),
183 (None, Some(t)) => t.gradient(),
184 _ => Gradient::default(),
185 }
186 }
187
188 fn label_color(&self) -> Color {
189 self.theme.as_ref().map_or(Color::Gray, |t| t.muted)
190 }
191
192 fn dim_color(&self) -> Color {
193 self.theme.as_ref().map_or(Color::DarkGray, |t| t.axis)
194 }
195
196 pub fn cell_width(mut self, w: u16) -> Self {
198 self.cell_width = w.max(1);
199 self
200 }
201
202 pub fn cell_height(mut self, h: u16) -> Self {
204 self.cell_height = h.max(1);
205 self
206 }
207
208 pub fn bounds(mut self, min: f64, max: f64) -> Self {
210 self.bounds = Some((min, max));
211 self
212 }
213
214 setter!(
215 show_values: bool
217 );
218
219 setter!(
220 stretch: bool
223 );
224
225 setter!(
226 legend: bool
228 );
229
230 block_setter!(block, 'static);
231
232 pub fn scale(&self) -> (f64, f64) {
234 if let Some(b) = self.bounds {
235 return b;
236 }
237 let vals = self.data.iter().flatten().filter(|v| v.is_finite());
238 let lo = vals.clone().cloned().fold(f64::INFINITY, f64::min);
239 let hi = vals.cloned().fold(f64::NEG_INFINITY, f64::max);
240 if lo.is_finite() { (lo, hi) } else { (0.0, 1.0) }
241 }
242
243 fn render_inner(&self, area: Rect, buf: &mut Buffer) {
244 let mut inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
245 let grad = self.grad();
246 let (lo, hi) = self.scale();
247 let span = if hi > lo { hi - lo } else { 1.0 };
248 if self.legend && inner.height > 4 {
249 let y = inner.bottom() - 1;
250 let (a, b) = (format_compact(lo), format_compact(hi));
251 let (aw, bw) = (text_width(&a), text_width(&b));
252 let lab = Style::default().fg(self.label_color());
253 let bx = inner.right().saturating_sub(bw).max(inner.x);
254 buf.set_stringn(inner.x, y, &a, inner.width as usize, lab);
255 buf.set_stringn(bx, y, &b, (inner.right() - bx) as usize, lab);
256 let bar_x = inner.x + aw + 1;
257 let bar_end = inner.right().saturating_sub(bw + 1);
258 if bar_end > bar_x {
259 let n = (bar_end - bar_x) as f64;
260 for (i, x) in (bar_x..bar_end).enumerate() {
261 let c = grad.color_at(i as f64 / (n - 1.0).max(1.0));
262 buf.set_string(x, y, " ", Style::default().bg(c));
263 }
264 }
265 inner.height -= 1;
266 }
267 let yw = self
268 .row_labels
269 .iter()
270 .map(|l| text_width(l))
271 .max()
272 .unwrap_or(0)
273 .min(12);
274 let Some(a) = layout::compute(inner, yw, !self.col_labels.is_empty(), false, false) else {
275 return;
276 };
277 let plot = a.plot;
278 let cols = self.data.iter().map(Vec::len).max().unwrap_or(1).max(1);
279 let rows = self.data.len().max(1);
280 let span_of = |i: usize, n: usize, total: u16, fixed: u16| -> (u16, u16) {
282 if self.stretch && n as u16 <= total {
283 let a = i * total as usize / n;
284 let b = (i + 1) * total as usize / n;
285 (a as u16, (b - a).max(1) as u16)
286 } else {
287 ((i as u32 * fixed as u32).min(u16::MAX as u32) as u16, fixed)
288 }
289 };
290 let mut y_ticks = vec![];
291 let mut x_ticks = vec![];
292 for (r, row) in self.data.iter().enumerate() {
293 let (dy0, ch) = span_of(r, rows, plot.height, self.cell_height);
294 let y = plot.y as u32 + dy0 as u32;
295 if y + ch as u32 > plot.bottom() as u32 {
296 break;
297 }
298 let y = y as u16;
299 if let Some(l) = self.row_labels.get(r) {
300 y_ticks.push((
301 y - plot.y + ch / 2,
302 l.chars().take(yw as usize).collect::<String>(),
303 ));
304 }
305 for (c, &v) in row.iter().enumerate() {
306 let (dx0, cw) = span_of(c, cols, plot.width, self.cell_width);
307 let x = plot.x as u32 + dx0 as u32;
308 if x + cw as u32 > plot.right() as u32 {
309 break;
310 }
311 let x = x as u16;
312 if r == 0
313 && let Some(l) = self.col_labels.get(c)
314 {
315 x_ticks.push((x - plot.x + cw / 2, l.clone()));
316 }
317 crate::interact::record_point(Rect::new(x, y, cw.max(1), ch.max(1)), r, c, || {
318 let title = match (self.row_labels.get(r), self.col_labels.get(c)) {
319 (Some(a), Some(b)) => format!("{a} / {b}"),
320 (Some(a), None) => a.clone(),
321 (None, Some(b)) => b.clone(),
322 _ => format!("row {} col {}", r + 1, c + 1),
323 };
324 let value = if v.is_finite() {
325 format_compact(v)
326 } else {
327 "no data".to_string()
328 };
329 (title, vec![value])
330 });
331 let color = if v.is_finite() {
332 grad.color_at((v - lo) / span)
333 } else {
334 self.dim_color()
335 };
336 let fg = if luminance(color) > 140.0 {
337 Color::Black
338 } else {
339 Color::White
340 };
341 let text = if self.show_values && v.is_finite() {
342 let s = format_compact(v);
343 if text_width(&s) <= cw {
344 s
345 } else {
346 String::new()
347 }
348 } else {
349 String::new()
350 };
351 for dy in 0..ch {
352 for dx in 0..cw {
353 buf.set_string(x + dx, y + dy, " ", Style::default().bg(color));
354 }
355 }
356 if !text.is_empty() {
357 let tx = x + (cw - text_width(&text)) / 2;
358 buf.set_string(tx, y + ch / 2, &text, Style::default().bg(color).fg(fg));
359 }
360 }
361 }
362 layout::draw_axes(
363 buf,
364 &a,
365 Style::default().fg(self.dim_color()),
366 Style::default().fg(self.dim_color()),
367 );
368 let lab = Style::default().fg(self.label_color());
369 layout::draw_y_labels(buf, a.y_labels, &y_ticks, lab);
370 layout::draw_x_labels(buf, a.x_labels, &x_ticks, lab);
371 }
372}
373
374impl Heatmap {
375 fn render_into(&self, area: Rect, buf: &mut Buffer) {
376 self.render_inner(area, buf);
377 }
378}
379
380widget_impls!(Heatmap);
381
382#[cfg(feature = "theme")]
383impl tui_nuances::Themed for Heatmap {
384 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
385 self.theme(theme)
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392 use ratatui::widgets::Widget;
393
394 fn grid() -> Vec<Vec<f64>> {
395 (0..4)
396 .map(|r| (0..6).map(|c| (r * 6 + c) as f64).collect())
397 .collect()
398 }
399
400 #[test]
401 fn gradient_endpoints() {
402 assert_eq!(Gradient::Grayscale.color_at(0.0), Color::Rgb(0, 0, 0));
403 assert_eq!(Gradient::Grayscale.color_at(1.0), Color::Rgb(255, 255, 255));
404 assert_eq!(Gradient::Grayscale.color_at(0.5), Color::Rgb(128, 128, 128));
405 assert_eq!(Gradient::Grayscale.color_at(f64::NAN), Color::Rgb(0, 0, 0));
406 assert_eq!(Gradient::Grayscale.color_at(9.0), Color::Rgb(255, 255, 255));
407 }
408
409 #[test]
410 fn gradient_custom_and_cycle() {
411 let g = Gradient::Custom(vec![(0, 0, 0), (100, 0, 0), (200, 0, 0)]);
412 assert_eq!(g.color_at(0.5), Color::Rgb(100, 0, 0));
413 assert_eq!(
414 Gradient::Custom(vec![]).color_at(1.0),
415 Color::Rgb(255, 255, 255)
416 );
417 let mut g = Gradient::Viridis;
418 for _ in 0..5 {
419 g = g.next();
420 }
421 assert_eq!(g, Gradient::Viridis);
422 assert_eq!(Gradient::Heat.name(), "heat");
423 }
424
425 #[test]
426 fn scale_auto_and_fixed() {
427 assert_eq!(Heatmap::new(grid()).scale(), (0.0, 23.0));
428 assert_eq!(Heatmap::new(grid()).bounds(-1.0, 1.0).scale(), (-1.0, 1.0));
429 assert_eq!(Heatmap::new(vec![]).scale(), (0.0, 1.0));
430 }
431
432 #[test]
433 fn renders_colored_cells_and_labels() {
434 let area = Rect::new(0, 0, 40, 10);
435 let mut buf = Buffer::empty(area);
436 Heatmap::new(grid())
437 .row_labels(["a", "b", "c", "d"])
438 .col_labels(["1", "2", "3", "4", "5", "6"])
439 .gradient(Gradient::Grayscale)
440 .render(area, &mut buf);
441 let first = buf[(2, 0)].bg;
443 let last = buf[(2 + 5 * 2, 3)].bg;
444 assert_eq!(first, Color::Rgb(0, 0, 0));
445 assert_eq!(last, Color::Rgb(255, 255, 255));
446 assert_eq!(buf[(0, 0)].symbol(), "a");
447 }
448
449 #[test]
450 fn stretch_fills_plot() {
451 let area = Rect::new(0, 0, 40, 12);
452 let mut buf = Buffer::empty(area);
453 Heatmap::new(grid())
454 .stretch(true)
455 .legend(false)
456 .render(area, &mut buf);
457 let filled = |y: u16| (0..40).any(|x| buf[(x, y)].bg != Color::Reset);
458 assert!(filled(0) && filled(10), "grid should span the height");
459 }
460
461 #[test]
462 fn legend_row_drawn() {
463 let area = Rect::new(0, 0, 40, 10);
464 let mut buf = Buffer::empty(area);
465 Heatmap::new(grid()).render(area, &mut buf);
466 assert_eq!(buf[(0, 9)].symbol(), "0");
467 assert_eq!(buf[(39, 9)].symbol(), "3");
468 let mut buf2 = Buffer::empty(area);
469 Heatmap::new(grid()).legend(false).render(area, &mut buf2);
470 assert_eq!(buf2[(0, 9)].symbol(), "└");
471 }
472
473 #[test]
474 fn show_values_when_fit() {
475 let area = Rect::new(0, 0, 40, 10);
476 let mut buf = Buffer::empty(area);
477 Heatmap::new(vec![vec![7.0, 123456.0]])
478 .cell_width(3)
479 .show_values(true)
480 .render(area, &mut buf);
481 let t: String = (0..40).map(|x| buf[(x, 0)].symbol().to_string()).collect();
482 assert!(t.contains('7'));
483 assert!(!t.contains("123"));
484 }
485
486 #[test]
487 fn nan_cell_is_gray() {
488 let area = Rect::new(0, 0, 20, 8);
489 let mut buf = Buffer::empty(area);
490 Heatmap::new(vec![vec![f64::NAN, 1.0]])
491 .legend(false)
492 .render(area, &mut buf);
493 assert_eq!(buf[(1, 0)].bg, Color::DarkGray);
494 }
495
496 #[test]
497 fn tiny_safe() {
498 for (w, h) in [(0, 0), (2, 2), (6, 5)] {
499 let area = Rect::new(0, 0, w, h);
500 let mut buf = Buffer::empty(area);
501 Heatmap::new(grid())
502 .col_labels(["x"])
503 .render(area, &mut buf);
504 }
505 }
506}