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() {
241 (lo, hi)
242 } else {
243 (0.0, 1.0)
244 }
245 }
246
247 fn render_inner(&self, area: Rect, buf: &mut Buffer) {
248 let mut inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
249 let grad = self.grad();
250 let (lo, hi) = self.scale();
251 let span = if hi > lo { hi - lo } else { 1.0 };
252 if self.legend && inner.height > 4 {
253 let y = inner.bottom() - 1;
254 let (a, b) = (format_compact(lo), format_compact(hi));
255 let (aw, bw) = (text_width(&a), text_width(&b));
256 let lab = Style::default().fg(self.label_color());
257 let bx = inner.right().saturating_sub(bw).max(inner.x);
258 buf.set_stringn(inner.x, y, &a, inner.width as usize, lab);
259 buf.set_stringn(bx, y, &b, (inner.right() - bx) as usize, lab);
260 let bar_x = inner.x + aw + 1;
261 let bar_end = inner.right().saturating_sub(bw + 1);
262 if bar_end > bar_x {
263 let n = (bar_end - bar_x) as f64;
264 for (i, x) in (bar_x..bar_end).enumerate() {
265 let c = grad.color_at(i as f64 / (n - 1.0).max(1.0));
266 buf.set_string(x, y, " ", Style::default().bg(c));
267 }
268 }
269 inner.height -= 1;
270 }
271 let yw = self
272 .row_labels
273 .iter()
274 .map(|l| text_width(l))
275 .max()
276 .unwrap_or(0)
277 .min(12);
278 let Some(a) = layout::compute(inner, yw, !self.col_labels.is_empty(), false, false) else {
279 return;
280 };
281 let plot = a.plot;
282 let cols = self.data.iter().map(Vec::len).max().unwrap_or(1).max(1);
283 let rows = self.data.len().max(1);
284 let span_of = |i: usize, n: usize, total: u16, fixed: u16| -> (u16, u16) {
286 if self.stretch && n as u16 <= total {
287 let a = i * total as usize / n;
288 let b = (i + 1) * total as usize / n;
289 (a as u16, (b - a).max(1) as u16)
290 } else {
291 ((i as u32 * fixed as u32).min(u16::MAX as u32) as u16, fixed)
292 }
293 };
294 let mut y_ticks = vec![];
295 let mut x_ticks = vec![];
296 for (r, row) in self.data.iter().enumerate() {
297 let (dy0, ch) = span_of(r, rows, plot.height, self.cell_height);
298 let y = plot.y as u32 + dy0 as u32;
299 if y + ch as u32 > plot.bottom() as u32 {
300 break;
301 }
302 let y = y as u16;
303 if let Some(l) = self.row_labels.get(r) {
304 y_ticks.push((
305 y - plot.y + ch / 2,
306 l.chars().take(yw as usize).collect::<String>(),
307 ));
308 }
309 for (c, &v) in row.iter().enumerate() {
310 let (dx0, cw) = span_of(c, cols, plot.width, self.cell_width);
311 let x = plot.x as u32 + dx0 as u32;
312 if x + cw as u32 > plot.right() as u32 {
313 break;
314 }
315 let x = x as u16;
316 if r == 0 {
317 if let Some(l) = self.col_labels.get(c) {
318 x_ticks.push((x - plot.x + cw / 2, l.clone()));
319 }
320 }
321 crate::interact::record_point(Rect::new(x, y, cw.max(1), ch.max(1)), r, c, || {
322 let title = match (self.row_labels.get(r), self.col_labels.get(c)) {
323 (Some(a), Some(b)) => format!("{a} / {b}"),
324 (Some(a), None) => a.clone(),
325 (None, Some(b)) => b.clone(),
326 _ => format!("row {} col {}", r + 1, c + 1),
327 };
328 let value = if v.is_finite() {
329 format_compact(v)
330 } else {
331 "no data".to_string()
332 };
333 (title, vec![value])
334 });
335 let color = if v.is_finite() {
336 grad.color_at((v - lo) / span)
337 } else {
338 self.dim_color()
339 };
340 let fg = if luminance(color) > 140.0 {
341 Color::Black
342 } else {
343 Color::White
344 };
345 let text = if self.show_values && v.is_finite() {
346 let s = format_compact(v);
347 if text_width(&s) <= cw {
348 s
349 } else {
350 String::new()
351 }
352 } else {
353 String::new()
354 };
355 for dy in 0..ch {
356 for dx in 0..cw {
357 buf.set_string(x + dx, y + dy, " ", Style::default().bg(color));
358 }
359 }
360 if !text.is_empty() {
361 let tx = x + (cw - text_width(&text)) / 2;
362 buf.set_string(tx, y + ch / 2, &text, Style::default().bg(color).fg(fg));
363 }
364 }
365 }
366 layout::draw_axes(
367 buf,
368 &a,
369 Style::default().fg(self.dim_color()),
370 Style::default().fg(self.dim_color()),
371 );
372 let lab = Style::default().fg(self.label_color());
373 layout::draw_y_labels(buf, a.y_labels, &y_ticks, lab);
374 layout::draw_x_labels(buf, a.x_labels, &x_ticks, lab);
375 }
376}
377
378impl Heatmap {
379 fn render_into(&self, area: Rect, buf: &mut Buffer) {
380 self.render_inner(area, buf);
381 }
382}
383
384widget_impls!(Heatmap);
385
386#[cfg(feature = "theme")]
387impl tui_nuances::Themed for Heatmap {
388 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
389 self.theme(theme)
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396 use ratatui::widgets::Widget;
397
398 fn grid() -> Vec<Vec<f64>> {
399 (0..4)
400 .map(|r| (0..6).map(|c| (r * 6 + c) as f64).collect())
401 .collect()
402 }
403
404 #[test]
405 fn gradient_endpoints() {
406 assert_eq!(Gradient::Grayscale.color_at(0.0), Color::Rgb(0, 0, 0));
407 assert_eq!(Gradient::Grayscale.color_at(1.0), Color::Rgb(255, 255, 255));
408 assert_eq!(Gradient::Grayscale.color_at(0.5), Color::Rgb(128, 128, 128));
409 assert_eq!(Gradient::Grayscale.color_at(f64::NAN), Color::Rgb(0, 0, 0));
410 assert_eq!(Gradient::Grayscale.color_at(9.0), Color::Rgb(255, 255, 255));
411 }
412
413 #[test]
414 fn gradient_custom_and_cycle() {
415 let g = Gradient::Custom(vec![(0, 0, 0), (100, 0, 0), (200, 0, 0)]);
416 assert_eq!(g.color_at(0.5), Color::Rgb(100, 0, 0));
417 assert_eq!(
418 Gradient::Custom(vec![]).color_at(1.0),
419 Color::Rgb(255, 255, 255)
420 );
421 let mut g = Gradient::Viridis;
422 for _ in 0..5 {
423 g = g.next();
424 }
425 assert_eq!(g, Gradient::Viridis);
426 assert_eq!(Gradient::Heat.name(), "heat");
427 }
428
429 #[test]
430 fn scale_auto_and_fixed() {
431 assert_eq!(Heatmap::new(grid()).scale(), (0.0, 23.0));
432 assert_eq!(Heatmap::new(grid()).bounds(-1.0, 1.0).scale(), (-1.0, 1.0));
433 assert_eq!(Heatmap::new(vec![]).scale(), (0.0, 1.0));
434 }
435
436 #[test]
437 fn renders_colored_cells_and_labels() {
438 let area = Rect::new(0, 0, 40, 10);
439 let mut buf = Buffer::empty(area);
440 Heatmap::new(grid())
441 .row_labels(["a", "b", "c", "d"])
442 .col_labels(["1", "2", "3", "4", "5", "6"])
443 .gradient(Gradient::Grayscale)
444 .render(area, &mut buf);
445 let first = buf[(2, 0)].bg;
447 let last = buf[(2 + 5 * 2, 3)].bg;
448 assert_eq!(first, Color::Rgb(0, 0, 0));
449 assert_eq!(last, Color::Rgb(255, 255, 255));
450 assert_eq!(buf[(0, 0)].symbol(), "a");
451 }
452
453 #[test]
454 fn stretch_fills_plot() {
455 let area = Rect::new(0, 0, 40, 12);
456 let mut buf = Buffer::empty(area);
457 Heatmap::new(grid())
458 .stretch(true)
459 .legend(false)
460 .render(area, &mut buf);
461 let filled = |y: u16| (0..40).any(|x| buf[(x, y)].bg != Color::Reset);
462 assert!(filled(0) && filled(10), "grid should span the height");
463 }
464
465 #[test]
466 fn legend_row_drawn() {
467 let area = Rect::new(0, 0, 40, 10);
468 let mut buf = Buffer::empty(area);
469 Heatmap::new(grid()).render(area, &mut buf);
470 assert_eq!(buf[(0, 9)].symbol(), "0");
471 assert_eq!(buf[(39, 9)].symbol(), "3");
472 let mut buf2 = Buffer::empty(area);
473 Heatmap::new(grid()).legend(false).render(area, &mut buf2);
474 assert_eq!(buf2[(0, 9)].symbol(), "└");
475 }
476
477 #[test]
478 fn show_values_when_fit() {
479 let area = Rect::new(0, 0, 40, 10);
480 let mut buf = Buffer::empty(area);
481 Heatmap::new(vec![vec![7.0, 123456.0]])
482 .cell_width(3)
483 .show_values(true)
484 .render(area, &mut buf);
485 let t: String = (0..40).map(|x| buf[(x, 0)].symbol().to_string()).collect();
486 assert!(t.contains('7'));
487 assert!(!t.contains("123"));
488 }
489
490 #[test]
491 fn nan_cell_is_gray() {
492 let area = Rect::new(0, 0, 20, 8);
493 let mut buf = Buffer::empty(area);
494 Heatmap::new(vec![vec![f64::NAN, 1.0]])
495 .legend(false)
496 .render(area, &mut buf);
497 assert_eq!(buf[(1, 0)].bg, Color::DarkGray);
498 }
499
500 #[test]
501 fn tiny_safe() {
502 for (w, h) in [(0, 0), (2, 2), (6, 5)] {
503 let area = Rect::new(0, 0, w, h);
504 let mut buf = Buffer::empty(area);
505 Heatmap::new(grid())
506 .col_labels(["x"])
507 .render(area, &mut buf);
508 }
509 }
510}