Skip to main content

tui_chart/
calendar.rs

1//! Calendar heatmap: one cell per day laid out in week columns, GitHub style.
2
3use crate::heatmap::Gradient;
4use crate::text::put_str;
5use crate::theme::{self, Theme};
6use crate::timeaxis::civil_from_days;
7use crate::util::dim_text;
8use ratatui::{
9    buffer::Buffer,
10    layout::Rect,
11    style::{Color, Style},
12    widgets::Block,
13};
14
15const MONTHS: [&str; 12] = [
16    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
17];
18
19/// Calendar heatmap widget: consecutive daily values starting at `start_day`.
20///
21/// # Example
22///
23/// ```
24/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
25/// use tui_chart::{CalendarHeatmap, days_from_civil};
26///
27/// let chart = CalendarHeatmap::new(days_from_civil(2024, 1, 1), (0..120).map(|i| (i % 7) as f64));
28/// let area = Rect::new(0, 0, 40, 12);
29/// let mut buf = Buffer::empty(area);
30/// chart.render(area, &mut buf);
31/// ```
32#[derive(Debug, Clone)]
33pub struct CalendarHeatmap {
34    start_day: i64,
35    values: Vec<f64>,
36    gradient: Gradient,
37    levels: Option<usize>,
38    monday_first: bool,
39    show_labels: bool,
40    legend: bool,
41    zero_empty: bool,
42    cell: char,
43    bounds: Option<(f64, f64)>,
44    theme: Option<Theme>,
45    base: Option<Style>,
46    block: Option<Block<'static>>,
47}
48
49impl CalendarHeatmap {
50    /// `start_day` is days since 1970-01-01 (see [`days_from_civil`](crate::days_from_civil));
51    /// `values[i]` is the value of day `start_day + i`. `NaN` draws as a missing
52    /// day (`·`); `±inf` clamp to the top / bottom of the range.
53    pub fn new(start_day: i64, values: impl IntoIterator<Item = f64>) -> Self {
54        Self {
55            start_day,
56            values: values.into_iter().collect(),
57            gradient: Gradient::Custom(vec![
58                (28, 33, 40),
59                (14, 68, 41),
60                (0, 109, 50),
61                (38, 166, 65),
62                (57, 211, 83),
63            ]),
64            levels: Some(5),
65            monday_first: true,
66            show_labels: true,
67            legend: true,
68            zero_empty: false,
69            cell: '■',
70            bounds: None,
71            theme: None,
72            base: None,
73            block: None,
74        }
75    }
76
77    setter!(
78        /// Color gradient (default GitHub greens).
79        gradient: Gradient
80    );
81    opt_setter!(
82        /// Quantise into this many discrete levels (default 5); use
83        /// [`continuous`](Self::continuous) for a smooth gradient.
84        levels: usize
85    );
86    setter!(
87        /// Weeks start on Monday (default) instead of Sunday.
88        monday_first: bool
89    );
90    setter!(
91        /// Month and weekday labels (default on).
92        show_labels: bool
93    );
94    setter!(
95        /// "Less … More" legend on the bottom row (default on, needs height 10+).
96        /// Shows a 9-step ramp in [`continuous`](Self::continuous) mode.
97        legend: bool
98    );
99    setter!(
100        /// Draw exactly-zero days in the dim theme colour instead of the lowest
101        /// gradient colour, so "no activity" is distinct from level 0 (default off).
102        zero_empty: bool
103    );
104    setter!(
105        /// Cell glyph (default `■`).
106        cell: char
107    );
108    theme_setter!(
109        /// Apply a [`Theme`] (labels and empty cells).
110        theme
111    );
112    base_style_setter!(base);
113    block_setter!(block, 'static);
114
115    /// Fixed `(min, max)` value range instead of the data range. Swapped if
116    /// inverted; ignored if either end is not finite.
117    pub fn bounds(mut self, min: f64, max: f64) -> Self {
118        if min.is_finite() && max.is_finite() {
119            self.bounds = Some((min.min(max), min.max(max)));
120        }
121        self
122    }
123
124    /// Smooth gradient instead of discrete levels.
125    pub fn continuous(mut self) -> Self {
126        self.levels = None;
127        self
128    }
129
130    fn color_for(&self, v: f64, lo: f64, hi: f64) -> Color {
131        let v = if v == f64::INFINITY {
132            hi
133        } else if v == f64::NEG_INFINITY {
134            lo
135        } else {
136            v
137        };
138        let t = if hi > lo {
139            ((v - lo) / (hi - lo)).clamp(0.0, 1.0)
140        } else if lo <= 0.0 {
141            // flat data: all-zero is "lowest", anything else sits mid-scale
142            0.0
143        } else {
144            0.5
145        };
146        let t = match self.levels {
147            Some(n) if n >= 2 => (t * (n - 1) as f64).round() / (n - 1) as f64,
148            _ => t,
149        };
150        self.gradient.color_at(t)
151    }
152
153    fn render_into(&self, area: Rect, buf: &mut Buffer) {
154        let area = area.intersection(buf.area);
155        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
156        if inner.width < 6 || inner.height < 7 || self.values.is_empty() {
157            return;
158        }
159        let (dim, text) = dim_text(&self.theme);
160        let (mut lo, mut hi) = self.bounds.unwrap_or((f64::MAX, f64::MIN));
161        if self.bounds.is_none() {
162            for v in self.values.iter().filter(|v| v.is_finite()) {
163                lo = lo.min(*v);
164                hi = hi.max(*v);
165            }
166        }
167        if lo > hi {
168            lo = 0.0;
169            hi = 0.0;
170        }
171
172        // weekday of the first day, Monday = 0
173        let wd = |d: i64| {
174            let m = (d + 3).rem_euclid(7);
175            if self.monday_first { m } else { (m + 1) % 7 }
176        };
177        let off = wd(self.start_day) as usize;
178        let weeks = (off + self.values.len()).div_ceil(7);
179
180        // labels need one extra row; drop them (not the grid) when height is tight
181        let labels = self.show_labels && inner.height >= 8;
182        let label_w: u16 = if labels { 4 } else { 0 };
183        let top = inner.y + u16::from(labels);
184        let legend = self.legend && inner.height >= 10;
185        let grid_h_avail = inner.height - u16::from(labels) - u16::from(legend);
186        if grid_h_avail < 7 {
187            return;
188        }
189        // widen / heighten cells when the whole year fits with room to spare
190        let cw = (((inner.width - label_w) as usize / weeks.max(1)).clamp(2, 4)) as u16;
191        // cells are `cw - 1` glyphs wide (min 1) with a one-column gap
192        let gw = (cw - 1).max(1);
193        let ch = (grid_h_avail / 7).clamp(1, 2);
194        let max_weeks = ((inner.width - label_w) / cw) as usize;
195        if max_weeks == 0 {
196            return;
197        }
198        // show the most recent weeks when the range does not fit
199        let first_week = weeks.saturating_sub(max_weeks);
200        let x0 = inner.x + label_w;
201
202        if labels {
203            let names = if self.monday_first {
204                [(0, "Mon"), (2, "Wed"), (4, "Fri")]
205            } else {
206                [(1, "Mon"), (3, "Wed"), (5, "Fri")]
207            };
208            for (row, n) in names {
209                put_str(buf, inner.x, top + row * ch, x0, n, dim);
210            }
211        }
212        let len = self.values.len() as i64;
213        // month whose 1st falls in week `w`, if any
214        let month_start = |w: usize| -> Option<u32> {
215            (0..7i64).find_map(|r| {
216                let idx = (w * 7) as i64 + r - off as i64;
217                if idx < 0 || idx >= len {
218                    return None;
219                }
220                let (_, m, d) = civil_from_days(self.start_day + idx);
221                (d == 1).then_some(m)
222            })
223        };
224        let label_span = 4usize.div_ceil(cw as usize);
225        let mut last_label_end = 0u16;
226        for w in first_week..weeks {
227            let x = x0 + (w - first_week) as u16 * cw;
228            for r in 0..7usize {
229                let idx = (w * 7 + r) as i64 - off as i64;
230                if idx < 0 || idx >= len {
231                    continue;
232                }
233                let v = self.values[idx as usize];
234                let missing = v.is_nan();
235                let st = if missing || (self.zero_empty && v == 0.0) {
236                    dim
237                } else {
238                    Style::default().fg(self.color_for(v, lo, hi))
239                };
240                let (glyph, width) = if missing { ('·', 1) } else { (self.cell, gw) };
241                crate::interact::record_point(
242                    Rect::new(x, top + r as u16 * ch, width.max(1), ch),
243                    0,
244                    idx as usize,
245                    || {
246                        let day = format!("day {}", idx + 1);
247                        let value = if missing {
248                            "no data".to_string()
249                        } else {
250                            crate::util::format_compact(v)
251                        };
252                        (day, vec![value])
253                    },
254                );
255                for dy in 0..ch {
256                    for dx in 0..width {
257                        buf[(x + dx, top + r as u16 * ch + dy)]
258                            .set_char(glyph)
259                            .set_style(st);
260                    }
261                }
262            }
263            if labels {
264                // label the week holding a 1st; on the first visible week fall
265                // back to its month unless the next label would collide
266                let month = month_start(w).or_else(|| {
267                    if w != first_week {
268                        return None;
269                    }
270                    let crowded =
271                        (1..=label_span).any(|k| w + k < weeks && month_start(w + k).is_some());
272                    let first_idx = (w * 7).saturating_sub(off) as i64;
273                    (!crowded).then(|| civil_from_days(self.start_day + first_idx).1)
274                });
275                if let Some(m) = month
276                    && x >= last_label_end
277                {
278                    let name = MONTHS[(m as usize - 1) % 12];
279                    put_str(buf, x, inner.y, inner.right(), name, text);
280                    last_label_end = x + 4;
281                }
282            }
283        }
284        if legend {
285            let y = inner.bottom() - 1;
286            let n = self.levels.unwrap_or(9).clamp(2, 9);
287            let w = (n * 2 + 9) as u16;
288            let mut x = inner.right().saturating_sub(w).max(inner.x);
289            put_str(buf, x, y, inner.right(), "Less ", dim);
290            x += 5;
291            for i in 0..n {
292                let c = self.gradient.color_at(i as f64 / (n - 1) as f64);
293                if x < inner.right() {
294                    buf[(x, y)]
295                        .set_char(self.cell)
296                        .set_style(Style::default().fg(c));
297                }
298                x += 2;
299            }
300            put_str(buf, x, y, inner.right(), "More", dim);
301        }
302    }
303}
304
305widget_impls!(CalendarHeatmap);
306
307#[cfg(feature = "theme")]
308impl tui_nuances::Themed for CalendarHeatmap {
309    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
310        self.theme(theme)
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317    use crate::days_from_civil;
318    use ratatui::widgets::Widget;
319
320    fn render(c: &CalendarHeatmap, w: u16, h: u16) -> Buffer {
321        let a = Rect::new(0, 0, w, h);
322        let mut b = Buffer::empty(a);
323        c.render(a, &mut b);
324        b
325    }
326
327    fn year() -> CalendarHeatmap {
328        CalendarHeatmap::new(
329            days_from_civil(2024, 1, 1),
330            (0..366).map(|i| (i % 9) as f64),
331        )
332    }
333
334    #[test]
335    fn shows_months_weekdays_and_cells() {
336        let b = render(&year(), 120, 12);
337        let t: String = b.content().iter().map(|c| c.symbol()).collect();
338        assert!(t.contains("Jan") && t.contains("Mon") && t.contains('■'));
339        assert!(t.contains("Less") && t.contains("More"));
340    }
341
342    #[test]
343    fn jan_first_2024_is_monday_row_zero() {
344        // 2024-01-01 was a Monday: first cell lands on the first grid row.
345        let b = render(&year(), 120, 12);
346        assert_eq!(b[(4, 1)].symbol(), "■");
347    }
348
349    #[test]
350    fn sunday_first_shifts_rows() {
351        let b = render(&year().monday_first(false), 120, 12);
352        assert_eq!(b[(4, 1)].symbol(), " ");
353        assert_eq!(b[(4, 2)].symbol(), "■");
354    }
355
356    #[test]
357    fn levels_quantise_colors() {
358        let colors = |c: &CalendarHeatmap| {
359            let mut v: Vec<_> = render(c, 120, 12)
360                .content()
361                .iter()
362                .filter(|c| c.symbol() == "■")
363                .map(|c| format!("{:?}", c.fg))
364                .collect();
365            v.sort();
366            v.dedup();
367            v.len()
368        };
369        assert!(colors(&year().levels(3)) < colors(&year().continuous()));
370    }
371
372    #[test]
373    fn narrow_area_shows_latest_weeks() {
374        let b = render(&year(), 30, 12);
375        let t: String = b.content().iter().map(|c| c.symbol()).collect();
376        assert!(t.contains("Dec") && !t.contains("Feb"));
377    }
378
379    fn text(b: &Buffer) -> String {
380        b.content().iter().map(|c| c.symbol()).collect()
381    }
382
383    fn row(b: &Buffer, y: u16) -> String {
384        (0..b.area.width).map(|x| b[(x, y)].symbol()).collect()
385    }
386
387    #[test]
388    fn height_seven_drops_labels_but_draws_grid() {
389        let b = render(&year(), 120, 7);
390        let t = text(&b);
391        assert!(t.contains('■') && !t.contains("Jan") && !t.contains("Mon"));
392    }
393
394    #[test]
395    fn month_labels_positioned_above_first_of_month() {
396        // Jan 1 2024 is a Monday: week 0 -> x = 4; Feb 1 is a Thursday in week 4.
397        let b = render(&year(), 120, 12);
398        let top = row(&b, 0);
399        assert_eq!(&top[4..7], "Jan");
400        let feb = top.find("Feb").expect("Feb label");
401        assert!(feb > 4 && top.find("Mar").unwrap() > feb);
402    }
403
404    #[test]
405    fn mid_month_start_labels_first_column() {
406        let c = CalendarHeatmap::new(days_from_civil(2024, 1, 20), (0..120).map(|i| i as f64));
407        let top = row(&render(&c, 120, 12), 0);
408        assert_eq!(&top[4..7], "Jan");
409        assert!(top.contains("Feb"));
410    }
411
412    #[test]
413    fn truncated_view_labels_left_edge_month() {
414        let top = row(&render(&year(), 30, 12), 0);
415        assert!(top.contains("Dec"));
416        assert!(
417            top[4..8].trim().len() >= 3,
418            "left edge month unlabeled: {top:?}"
419        );
420    }
421
422    #[test]
423    fn labels_do_not_overlap() {
424        let top = row(&render(&year(), 60, 12), 0);
425        for m in MONTHS {
426            assert!(top.matches(m).count() <= 1, "{top:?}");
427        }
428    }
429
430    #[test]
431    fn flat_data_is_not_max_colour() {
432        let max = Color::Rgb(57, 211, 83);
433        let fg = |vals: Vec<f64>| {
434            let c = CalendarHeatmap::new(days_from_civil(2024, 1, 1), vals);
435            render(&c, 40, 12)[(4, 1)].fg
436        };
437        assert_ne!(fg(vec![5.0; 30]), max);
438        assert_eq!(fg(vec![0.0; 30]), Color::Rgb(28, 33, 40));
439    }
440
441    #[test]
442    fn inverted_and_nan_bounds_are_normalised() {
443        let a = render(&year().bounds(8.0, 0.0), 120, 12);
444        let b = render(&year().bounds(0.0, 8.0), 120, 12);
445        assert_eq!(a, b);
446        let c = render(&year().bounds(f64::NAN, 1.0), 120, 12);
447        assert_eq!(c, render(&year(), 120, 12));
448    }
449
450    #[test]
451    fn nan_is_missing_and_inf_clamps() {
452        let c = CalendarHeatmap::new(
453            days_from_civil(2024, 1, 1),
454            [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, 10.0],
455        );
456        let b = render(&c, 40, 12);
457        assert_eq!(b[(4, 1)].symbol(), "·");
458        assert_eq!(b[(4, 2)].fg, Color::Rgb(57, 211, 83));
459        assert_eq!(b[(4, 3)].fg, Color::Rgb(28, 33, 40));
460    }
461
462    #[test]
463    fn zero_empty_uses_dim_style() {
464        let vals = [0.0, 5.0, 10.0];
465        let mk = |z| CalendarHeatmap::new(days_from_civil(2024, 1, 1), vals).zero_empty(z);
466        let off = render(&mk(false), 40, 12)[(4, 1)].fg;
467        let on = render(&mk(true), 40, 12)[(4, 1)].fg;
468        assert_ne!(off, on);
469    }
470
471    #[test]
472    fn wide_cells_fill_multiple_columns() {
473        // 10 weeks in 60 cols -> cw = 4, glyphs 3 wide
474        let c = CalendarHeatmap::new(days_from_civil(2024, 1, 1), (0..70).map(|i| i as f64));
475        let b = render(&c, 60, 12);
476        assert!((4..7).all(|x| b[(x, 1)].symbol() == "■"));
477        assert_eq!(b[(7, 1)].symbol(), " ");
478    }
479
480    #[test]
481    fn tall_cells_use_two_rows() {
482        let b = render(&year(), 120, 18);
483        assert_eq!(b[(4, 1)].symbol(), "■");
484        assert_eq!(b[(4, 2)].symbol(), "■");
485    }
486
487    #[test]
488    fn legend_sizes_follow_mode() {
489        let swatches = |c: &CalendarHeatmap| {
490            let b = render(c, 120, 12);
491            row(&b, 11).matches('■').count()
492        };
493        assert_eq!(swatches(&year()), 5);
494        assert_eq!(swatches(&year().continuous()), 9);
495        assert_eq!(swatches(&year().levels(3)), 3);
496        let t = row(&render(&year(), 120, 12), 11);
497        assert!(t.trim_end().ends_with("More") && t.contains("Less"));
498    }
499
500    #[test]
501    fn degenerate_inputs_do_not_panic() {
502        let c = CalendarHeatmap::new(-5, [f64::NAN, f64::INFINITY, 1e300, -1e300, 0.0]);
503        for (w, h) in [(0, 0), (1, 1), (5, 7), (12, 12), (40, 9), (300, 80)] {
504            render(&c, w, h);
505            render(&year(), w, h);
506        }
507        render(&CalendarHeatmap::new(0, []), 40, 12);
508        render(
509            &year().show_labels(false).legend(false).bounds(0.0, 1.0),
510            60,
511            8,
512        );
513    }
514}