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                crate::interact::record_point(
246                    Rect::new(x, top + r as u16 * ch, width.max(1), ch),
247                    0,
248                    idx as usize,
249                    || {
250                        let day = format!("day {}", idx + 1);
251                        let value = if missing {
252                            "no data".to_string()
253                        } else {
254                            crate::util::format_compact(v)
255                        };
256                        (day, vec![value])
257                    },
258                );
259                for dy in 0..ch {
260                    for dx in 0..width {
261                        buf[(x + dx, top + r as u16 * ch + dy)]
262                            .set_char(glyph)
263                            .set_style(st);
264                    }
265                }
266            }
267            if labels {
268                // label the week holding a 1st; on the first visible week fall
269                // back to its month unless the next label would collide
270                let month = month_start(w).or_else(|| {
271                    if w != first_week {
272                        return None;
273                    }
274                    let crowded =
275                        (1..=label_span).any(|k| w + k < weeks && month_start(w + k).is_some());
276                    let first_idx = (w * 7).saturating_sub(off) as i64;
277                    (!crowded).then(|| civil_from_days(self.start_day + first_idx).1)
278                });
279                if let Some(m) = month {
280                    if x >= last_label_end {
281                        let name = MONTHS[(m as usize - 1) % 12];
282                        put_str(buf, x, inner.y, inner.right(), name, text);
283                        last_label_end = x + 4;
284                    }
285                }
286            }
287        }
288        if legend {
289            let y = inner.bottom() - 1;
290            let n = self.levels.unwrap_or(9).clamp(2, 9);
291            let w = (n * 2 + 9) as u16;
292            let mut x = inner.right().saturating_sub(w).max(inner.x);
293            put_str(buf, x, y, inner.right(), "Less ", dim);
294            x += 5;
295            for i in 0..n {
296                let c = self.gradient.color_at(i as f64 / (n - 1) as f64);
297                if x < inner.right() {
298                    buf[(x, y)]
299                        .set_char(self.cell)
300                        .set_style(Style::default().fg(c));
301                }
302                x += 2;
303            }
304            put_str(buf, x, y, inner.right(), "More", dim);
305        }
306    }
307}
308
309widget_impls!(CalendarHeatmap);
310
311#[cfg(feature = "theme")]
312impl tui_nuances::Themed for CalendarHeatmap {
313    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
314        self.theme(theme)
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::days_from_civil;
322    use ratatui::widgets::Widget;
323
324    fn render(c: &CalendarHeatmap, w: u16, h: u16) -> Buffer {
325        let a = Rect::new(0, 0, w, h);
326        let mut b = Buffer::empty(a);
327        c.render(a, &mut b);
328        b
329    }
330
331    fn year() -> CalendarHeatmap {
332        CalendarHeatmap::new(
333            days_from_civil(2024, 1, 1),
334            (0..366).map(|i| (i % 9) as f64),
335        )
336    }
337
338    #[test]
339    fn shows_months_weekdays_and_cells() {
340        let b = render(&year(), 120, 12);
341        let t: String = b.content().iter().map(|c| c.symbol()).collect();
342        assert!(t.contains("Jan") && t.contains("Mon") && t.contains('■'));
343        assert!(t.contains("Less") && t.contains("More"));
344    }
345
346    #[test]
347    fn jan_first_2024_is_monday_row_zero() {
348        // 2024-01-01 was a Monday: first cell lands on the first grid row.
349        let b = render(&year(), 120, 12);
350        assert_eq!(b[(4, 1)].symbol(), "■");
351    }
352
353    #[test]
354    fn sunday_first_shifts_rows() {
355        let b = render(&year().monday_first(false), 120, 12);
356        assert_eq!(b[(4, 1)].symbol(), " ");
357        assert_eq!(b[(4, 2)].symbol(), "■");
358    }
359
360    #[test]
361    fn levels_quantise_colors() {
362        let colors = |c: &CalendarHeatmap| {
363            let mut v: Vec<_> = render(c, 120, 12)
364                .content()
365                .iter()
366                .filter(|c| c.symbol() == "■")
367                .map(|c| format!("{:?}", c.fg))
368                .collect();
369            v.sort();
370            v.dedup();
371            v.len()
372        };
373        assert!(colors(&year().levels(3)) < colors(&year().continuous()));
374    }
375
376    #[test]
377    fn narrow_area_shows_latest_weeks() {
378        let b = render(&year(), 30, 12);
379        let t: String = b.content().iter().map(|c| c.symbol()).collect();
380        assert!(t.contains("Dec") && !t.contains("Feb"));
381    }
382
383    fn text(b: &Buffer) -> String {
384        b.content().iter().map(|c| c.symbol()).collect()
385    }
386
387    fn row(b: &Buffer, y: u16) -> String {
388        (0..b.area.width).map(|x| b[(x, y)].symbol()).collect()
389    }
390
391    #[test]
392    fn height_seven_drops_labels_but_draws_grid() {
393        let b = render(&year(), 120, 7);
394        let t = text(&b);
395        assert!(t.contains('■') && !t.contains("Jan") && !t.contains("Mon"));
396    }
397
398    #[test]
399    fn month_labels_positioned_above_first_of_month() {
400        // Jan 1 2024 is a Monday: week 0 -> x = 4; Feb 1 is a Thursday in week 4.
401        let b = render(&year(), 120, 12);
402        let top = row(&b, 0);
403        assert_eq!(&top[4..7], "Jan");
404        let feb = top.find("Feb").expect("Feb label");
405        assert!(feb > 4 && top.find("Mar").unwrap() > feb);
406    }
407
408    #[test]
409    fn mid_month_start_labels_first_column() {
410        let c = CalendarHeatmap::new(days_from_civil(2024, 1, 20), (0..120).map(|i| i as f64));
411        let top = row(&render(&c, 120, 12), 0);
412        assert_eq!(&top[4..7], "Jan");
413        assert!(top.contains("Feb"));
414    }
415
416    #[test]
417    fn truncated_view_labels_left_edge_month() {
418        let top = row(&render(&year(), 30, 12), 0);
419        assert!(top.contains("Dec"));
420        assert!(
421            top[4..8].trim().len() >= 3,
422            "left edge month unlabeled: {top:?}"
423        );
424    }
425
426    #[test]
427    fn labels_do_not_overlap() {
428        let top = row(&render(&year(), 60, 12), 0);
429        for m in MONTHS {
430            assert!(top.matches(m).count() <= 1, "{top:?}");
431        }
432    }
433
434    #[test]
435    fn flat_data_is_not_max_colour() {
436        let max = Color::Rgb(57, 211, 83);
437        let fg = |vals: Vec<f64>| {
438            let c = CalendarHeatmap::new(days_from_civil(2024, 1, 1), vals);
439            render(&c, 40, 12)[(4, 1)].fg
440        };
441        assert_ne!(fg(vec![5.0; 30]), max);
442        assert_eq!(fg(vec![0.0; 30]), Color::Rgb(28, 33, 40));
443    }
444
445    #[test]
446    fn inverted_and_nan_bounds_are_normalised() {
447        let a = render(&year().bounds(8.0, 0.0), 120, 12);
448        let b = render(&year().bounds(0.0, 8.0), 120, 12);
449        assert_eq!(a, b);
450        let c = render(&year().bounds(f64::NAN, 1.0), 120, 12);
451        assert_eq!(c, render(&year(), 120, 12));
452    }
453
454    #[test]
455    fn nan_is_missing_and_inf_clamps() {
456        let c = CalendarHeatmap::new(
457            days_from_civil(2024, 1, 1),
458            [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, 10.0],
459        );
460        let b = render(&c, 40, 12);
461        assert_eq!(b[(4, 1)].symbol(), "·");
462        assert_eq!(b[(4, 2)].fg, Color::Rgb(57, 211, 83));
463        assert_eq!(b[(4, 3)].fg, Color::Rgb(28, 33, 40));
464    }
465
466    #[test]
467    fn zero_empty_uses_dim_style() {
468        let vals = [0.0, 5.0, 10.0];
469        let mk = |z| CalendarHeatmap::new(days_from_civil(2024, 1, 1), vals).zero_empty(z);
470        let off = render(&mk(false), 40, 12)[(4, 1)].fg;
471        let on = render(&mk(true), 40, 12)[(4, 1)].fg;
472        assert_ne!(off, on);
473    }
474
475    #[test]
476    fn wide_cells_fill_multiple_columns() {
477        // 10 weeks in 60 cols -> cw = 4, glyphs 3 wide
478        let c = CalendarHeatmap::new(days_from_civil(2024, 1, 1), (0..70).map(|i| i as f64));
479        let b = render(&c, 60, 12);
480        assert!((4..7).all(|x| b[(x, 1)].symbol() == "■"));
481        assert_eq!(b[(7, 1)].symbol(), " ");
482    }
483
484    #[test]
485    fn tall_cells_use_two_rows() {
486        let b = render(&year(), 120, 18);
487        assert_eq!(b[(4, 1)].symbol(), "■");
488        assert_eq!(b[(4, 2)].symbol(), "■");
489    }
490
491    #[test]
492    fn legend_sizes_follow_mode() {
493        let swatches = |c: &CalendarHeatmap| {
494            let b = render(c, 120, 12);
495            row(&b, 11).matches('■').count()
496        };
497        assert_eq!(swatches(&year()), 5);
498        assert_eq!(swatches(&year().continuous()), 9);
499        assert_eq!(swatches(&year().levels(3)), 3);
500        let t = row(&render(&year(), 120, 12), 11);
501        assert!(t.trim_end().ends_with("More") && t.contains("Less"));
502    }
503
504    #[test]
505    fn degenerate_inputs_do_not_panic() {
506        let c = CalendarHeatmap::new(-5, [f64::NAN, f64::INFINITY, 1e300, -1e300, 0.0]);
507        for (w, h) in [(0, 0), (1, 1), (5, 7), (12, 12), (40, 9), (300, 80)] {
508            render(&c, w, h);
509            render(&year(), w, h);
510        }
511        render(&CalendarHeatmap::new(0, []), 40, 12);
512        render(
513            &year().show_labels(false).legend(false).bounds(0.0, 1.0),
514            60,
515            8,
516        );
517    }
518}