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 {
176                m
177            } else {
178                (m + 1) % 7
179            }
180        };
181        let off = wd(self.start_day) as usize;
182        let weeks = (off + self.values.len()).div_ceil(7);
183
184        // labels need one extra row; drop them (not the grid) when height is tight
185        let labels = self.show_labels && inner.height >= 8;
186        let label_w: u16 = if labels { 4 } else { 0 };
187        let top = inner.y + u16::from(labels);
188        let legend = self.legend && inner.height >= 10;
189        let grid_h_avail = inner.height - u16::from(labels) - u16::from(legend);
190        if grid_h_avail < 7 {
191            return;
192        }
193        // widen / heighten cells when the whole year fits with room to spare
194        let cw = (((inner.width - label_w) as usize / weeks.max(1)).clamp(2, 4)) as u16;
195        // cells are `cw - 1` glyphs wide (min 1) with a one-column gap
196        let gw = (cw - 1).max(1);
197        let ch = (grid_h_avail / 7).clamp(1, 2);
198        let max_weeks = ((inner.width - label_w) / cw) as usize;
199        if max_weeks == 0 {
200            return;
201        }
202        // show the most recent weeks when the range does not fit
203        let first_week = weeks.saturating_sub(max_weeks);
204        let x0 = inner.x + label_w;
205
206        if labels {
207            let names = if self.monday_first {
208                [(0, "Mon"), (2, "Wed"), (4, "Fri")]
209            } else {
210                [(1, "Mon"), (3, "Wed"), (5, "Fri")]
211            };
212            for (row, n) in names {
213                put_str(buf, inner.x, top + row * ch, x0, n, dim);
214            }
215        }
216        let len = self.values.len() as i64;
217        // month whose 1st falls in week `w`, if any
218        let month_start = |w: usize| -> Option<u32> {
219            (0..7i64).find_map(|r| {
220                let idx = (w * 7) as i64 + r - off as i64;
221                if idx < 0 || idx >= len {
222                    return None;
223                }
224                let (_, m, d) = civil_from_days(self.start_day + idx);
225                (d == 1).then_some(m)
226            })
227        };
228        let label_span = 4usize.div_ceil(cw as usize);
229        let mut last_label_end = 0u16;
230        for w in first_week..weeks {
231            let x = x0 + (w - first_week) as u16 * cw;
232            for r in 0..7usize {
233                let idx = (w * 7 + r) as i64 - off as i64;
234                if idx < 0 || idx >= len {
235                    continue;
236                }
237                let v = self.values[idx as usize];
238                let missing = v.is_nan();
239                let st = if missing || (self.zero_empty && v == 0.0) {
240                    dim
241                } else {
242                    Style::default().fg(self.color_for(v, lo, hi))
243                };
244                let (glyph, width) = if missing { ('·', 1) } else { (self.cell, gw) };
245                for dy in 0..ch {
246                    for dx in 0..width {
247                        buf[(x + dx, top + r as u16 * ch + dy)]
248                            .set_char(glyph)
249                            .set_style(st);
250                    }
251                }
252            }
253            if labels {
254                // label the week holding a 1st; on the first visible week fall
255                // back to its month unless the next label would collide
256                let month = month_start(w).or_else(|| {
257                    if w != first_week {
258                        return None;
259                    }
260                    let crowded =
261                        (1..=label_span).any(|k| w + k < weeks && month_start(w + k).is_some());
262                    let first_idx = (w * 7).saturating_sub(off) as i64;
263                    (!crowded).then(|| civil_from_days(self.start_day + first_idx).1)
264                });
265                if let Some(m) = month {
266                    if x >= last_label_end {
267                        let name = MONTHS[(m as usize - 1) % 12];
268                        put_str(buf, x, inner.y, inner.right(), name, text);
269                        last_label_end = x + 4;
270                    }
271                }
272            }
273        }
274        if legend {
275            let y = inner.bottom() - 1;
276            let n = self.levels.unwrap_or(9).clamp(2, 9);
277            let w = (n * 2 + 9) as u16;
278            let mut x = inner.right().saturating_sub(w).max(inner.x);
279            put_str(buf, x, y, inner.right(), "Less ", dim);
280            x += 5;
281            for i in 0..n {
282                let c = self.gradient.color_at(i as f64 / (n - 1) as f64);
283                if x < inner.right() {
284                    buf[(x, y)]
285                        .set_char(self.cell)
286                        .set_style(Style::default().fg(c));
287                }
288                x += 2;
289            }
290            put_str(buf, x, y, inner.right(), "More", dim);
291        }
292    }
293}
294
295widget_impls!(CalendarHeatmap);
296
297#[cfg(feature = "theme")]
298impl tui_nuances::Themed for CalendarHeatmap {
299    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
300        self.theme(theme)
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use crate::days_from_civil;
308    use ratatui::widgets::Widget;
309
310    fn render(c: &CalendarHeatmap, w: u16, h: u16) -> Buffer {
311        let a = Rect::new(0, 0, w, h);
312        let mut b = Buffer::empty(a);
313        c.render(a, &mut b);
314        b
315    }
316
317    fn year() -> CalendarHeatmap {
318        CalendarHeatmap::new(
319            days_from_civil(2024, 1, 1),
320            (0..366).map(|i| (i % 9) as f64),
321        )
322    }
323
324    #[test]
325    fn shows_months_weekdays_and_cells() {
326        let b = render(&year(), 120, 12);
327        let t: String = b.content().iter().map(|c| c.symbol()).collect();
328        assert!(t.contains("Jan") && t.contains("Mon") && t.contains('■'));
329        assert!(t.contains("Less") && t.contains("More"));
330    }
331
332    #[test]
333    fn jan_first_2024_is_monday_row_zero() {
334        // 2024-01-01 was a Monday: first cell lands on the first grid row.
335        let b = render(&year(), 120, 12);
336        assert_eq!(b[(4, 1)].symbol(), "■");
337    }
338
339    #[test]
340    fn sunday_first_shifts_rows() {
341        let b = render(&year().monday_first(false), 120, 12);
342        assert_eq!(b[(4, 1)].symbol(), " ");
343        assert_eq!(b[(4, 2)].symbol(), "■");
344    }
345
346    #[test]
347    fn levels_quantise_colors() {
348        let colors = |c: &CalendarHeatmap| {
349            let mut v: Vec<_> = render(c, 120, 12)
350                .content()
351                .iter()
352                .filter(|c| c.symbol() == "■")
353                .map(|c| format!("{:?}", c.fg))
354                .collect();
355            v.sort();
356            v.dedup();
357            v.len()
358        };
359        assert!(colors(&year().levels(3)) < colors(&year().continuous()));
360    }
361
362    #[test]
363    fn narrow_area_shows_latest_weeks() {
364        let b = render(&year(), 30, 12);
365        let t: String = b.content().iter().map(|c| c.symbol()).collect();
366        assert!(t.contains("Dec") && !t.contains("Feb"));
367    }
368
369    fn text(b: &Buffer) -> String {
370        b.content().iter().map(|c| c.symbol()).collect()
371    }
372
373    fn row(b: &Buffer, y: u16) -> String {
374        (0..b.area.width).map(|x| b[(x, y)].symbol()).collect()
375    }
376
377    #[test]
378    fn height_seven_drops_labels_but_draws_grid() {
379        let b = render(&year(), 120, 7);
380        let t = text(&b);
381        assert!(t.contains('■') && !t.contains("Jan") && !t.contains("Mon"));
382    }
383
384    #[test]
385    fn month_labels_positioned_above_first_of_month() {
386        // Jan 1 2024 is a Monday: week 0 -> x = 4; Feb 1 is a Thursday in week 4.
387        let b = render(&year(), 120, 12);
388        let top = row(&b, 0);
389        assert_eq!(&top[4..7], "Jan");
390        let feb = top.find("Feb").expect("Feb label");
391        assert!(feb > 4 && top.find("Mar").unwrap() > feb);
392    }
393
394    #[test]
395    fn mid_month_start_labels_first_column() {
396        let c = CalendarHeatmap::new(days_from_civil(2024, 1, 20), (0..120).map(|i| i as f64));
397        let top = row(&render(&c, 120, 12), 0);
398        assert_eq!(&top[4..7], "Jan");
399        assert!(top.contains("Feb"));
400    }
401
402    #[test]
403    fn truncated_view_labels_left_edge_month() {
404        let top = row(&render(&year(), 30, 12), 0);
405        assert!(top.contains("Dec"));
406        assert!(
407            top[4..8].trim().len() >= 3,
408            "left edge month unlabeled: {top:?}"
409        );
410    }
411
412    #[test]
413    fn labels_do_not_overlap() {
414        let top = row(&render(&year(), 60, 12), 0);
415        for m in MONTHS {
416            assert!(top.matches(m).count() <= 1, "{top:?}");
417        }
418    }
419
420    #[test]
421    fn flat_data_is_not_max_colour() {
422        let max = Color::Rgb(57, 211, 83);
423        let fg = |vals: Vec<f64>| {
424            let c = CalendarHeatmap::new(days_from_civil(2024, 1, 1), vals);
425            render(&c, 40, 12)[(4, 1)].fg
426        };
427        assert_ne!(fg(vec![5.0; 30]), max);
428        assert_eq!(fg(vec![0.0; 30]), Color::Rgb(28, 33, 40));
429    }
430
431    #[test]
432    fn inverted_and_nan_bounds_are_normalised() {
433        let a = render(&year().bounds(8.0, 0.0), 120, 12);
434        let b = render(&year().bounds(0.0, 8.0), 120, 12);
435        assert_eq!(a, b);
436        let c = render(&year().bounds(f64::NAN, 1.0), 120, 12);
437        assert_eq!(c, render(&year(), 120, 12));
438    }
439
440    #[test]
441    fn nan_is_missing_and_inf_clamps() {
442        let c = CalendarHeatmap::new(
443            days_from_civil(2024, 1, 1),
444            [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, 10.0],
445        );
446        let b = render(&c, 40, 12);
447        assert_eq!(b[(4, 1)].symbol(), "·");
448        assert_eq!(b[(4, 2)].fg, Color::Rgb(57, 211, 83));
449        assert_eq!(b[(4, 3)].fg, Color::Rgb(28, 33, 40));
450    }
451
452    #[test]
453    fn zero_empty_uses_dim_style() {
454        let vals = [0.0, 5.0, 10.0];
455        let mk = |z| CalendarHeatmap::new(days_from_civil(2024, 1, 1), vals).zero_empty(z);
456        let off = render(&mk(false), 40, 12)[(4, 1)].fg;
457        let on = render(&mk(true), 40, 12)[(4, 1)].fg;
458        assert_ne!(off, on);
459    }
460
461    #[test]
462    fn wide_cells_fill_multiple_columns() {
463        // 10 weeks in 60 cols -> cw = 4, glyphs 3 wide
464        let c = CalendarHeatmap::new(days_from_civil(2024, 1, 1), (0..70).map(|i| i as f64));
465        let b = render(&c, 60, 12);
466        assert!((4..7).all(|x| b[(x, 1)].symbol() == "■"));
467        assert_eq!(b[(7, 1)].symbol(), " ");
468    }
469
470    #[test]
471    fn tall_cells_use_two_rows() {
472        let b = render(&year(), 120, 18);
473        assert_eq!(b[(4, 1)].symbol(), "■");
474        assert_eq!(b[(4, 2)].symbol(), "■");
475    }
476
477    #[test]
478    fn legend_sizes_follow_mode() {
479        let swatches = |c: &CalendarHeatmap| {
480            let b = render(c, 120, 12);
481            row(&b, 11).matches('■').count()
482        };
483        assert_eq!(swatches(&year()), 5);
484        assert_eq!(swatches(&year().continuous()), 9);
485        assert_eq!(swatches(&year().levels(3)), 3);
486        let t = row(&render(&year(), 120, 12), 11);
487        assert!(t.trim_end().ends_with("More") && t.contains("Less"));
488    }
489
490    #[test]
491    fn degenerate_inputs_do_not_panic() {
492        let c = CalendarHeatmap::new(-5, [f64::NAN, f64::INFINITY, 1e300, -1e300, 0.0]);
493        for (w, h) in [(0, 0), (1, 1), (5, 7), (12, 12), (40, 9), (300, 80)] {
494            render(&c, w, h);
495            render(&year(), w, h);
496        }
497        render(&CalendarHeatmap::new(0, []), 40, 12);
498        render(
499            &year().show_labels(false).legend(false).bounds(0.0, 1.0),
500            60,
501            8,
502        );
503    }
504}