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    cell: char,
42    bounds: Option<(f64, f64)>,
43    theme: Option<Theme>,
44    base: Option<Style>,
45    block: Option<Block<'static>>,
46}
47
48impl CalendarHeatmap {
49    /// `start_day` is days since 1970-01-01 (see [`days_from_civil`](crate::days_from_civil));
50    /// `values[i]` is the value of day `start_day + i`. Non-finite values draw as empty.
51    pub fn new(start_day: i64, values: impl IntoIterator<Item = f64>) -> Self {
52        Self {
53            start_day,
54            values: values.into_iter().collect(),
55            gradient: Gradient::Custom(vec![
56                (28, 33, 40),
57                (14, 68, 41),
58                (0, 109, 50),
59                (38, 166, 65),
60                (57, 211, 83),
61            ]),
62            levels: Some(5),
63            monday_first: true,
64            show_labels: true,
65            legend: true,
66            cell: '■',
67            bounds: None,
68            theme: None,
69            base: None,
70            block: None,
71        }
72    }
73
74    setter!(
75        /// Color gradient (default GitHub greens).
76        gradient: Gradient
77    );
78    opt_setter!(
79        /// Quantise into this many discrete levels (default 5); use
80        /// [`continuous`](Self::continuous) for a smooth gradient.
81        levels: usize
82    );
83    setter!(
84        /// Weeks start on Monday (default) instead of Sunday.
85        monday_first: bool
86    );
87    setter!(
88        /// Month and weekday labels (default on).
89        show_labels: bool
90    );
91    setter!(
92        /// "Less … More" legend on the bottom row (default on, needs height 10+).
93        legend: bool
94    );
95    setter!(
96        /// Cell glyph (default `■`).
97        cell: char
98    );
99    theme_setter!(
100        /// Apply a [`Theme`] (labels and empty cells).
101        theme
102    );
103    base_style_setter!(base);
104    block_setter!(block, 'static);
105
106    /// Fixed `(min, max)` value range instead of the data range.
107    pub fn bounds(mut self, min: f64, max: f64) -> Self {
108        self.bounds = Some((min, max));
109        self
110    }
111
112    /// Smooth gradient instead of discrete levels.
113    pub fn continuous(mut self) -> Self {
114        self.levels = None;
115        self
116    }
117
118    fn color_for(&self, v: f64, lo: f64, hi: f64) -> Color {
119        let t = if hi > lo {
120            ((v - lo) / (hi - lo)).clamp(0.0, 1.0)
121        } else {
122            1.0
123        };
124        let t = match self.levels {
125            Some(n) if n >= 2 => (t * (n - 1) as f64).round() / (n - 1) as f64,
126            _ => t,
127        };
128        self.gradient.color_at(t)
129    }
130
131    fn render_into(&self, area: Rect, buf: &mut Buffer) {
132        let area = area.intersection(buf.area);
133        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
134        if inner.width < 6 || inner.height < 7 || self.values.is_empty() {
135            return;
136        }
137        let (dim, text) = dim_text(&self.theme);
138        let (mut lo, mut hi) = self.bounds.unwrap_or((f64::MAX, f64::MIN));
139        if self.bounds.is_none() {
140            for v in self.values.iter().filter(|v| v.is_finite()) {
141                lo = lo.min(*v);
142                hi = hi.max(*v);
143            }
144        }
145        if lo > hi {
146            lo = 0.0;
147            hi = 0.0;
148        }
149
150        // weekday of the first day, Monday = 0
151        let wd = |d: i64| {
152            let m = (d + 3).rem_euclid(7);
153            if self.monday_first {
154                m
155            } else {
156                (m + 1) % 7
157            }
158        };
159        let off = wd(self.start_day) as usize;
160        let weeks = (off + self.values.len()).div_ceil(7);
161
162        let label_w: u16 = if self.show_labels { 4 } else { 0 };
163        let top = inner.y + u16::from(self.show_labels);
164        let legend = self.legend && inner.height >= 10;
165        let grid_h_avail = inner.height - u16::from(self.show_labels) - u16::from(legend);
166        if grid_h_avail < 7 {
167            return;
168        }
169        // widen / heighten cells when the whole year fits with room to spare
170        let cw = (((inner.width - label_w) as usize / weeks.max(1)).clamp(2, 4)) as u16;
171        let ch = (grid_h_avail / 7).clamp(1, 2);
172        let max_weeks = ((inner.width - label_w) / cw) as usize;
173        if max_weeks == 0 {
174            return;
175        }
176        // show the most recent weeks when the range does not fit
177        let first_week = weeks.saturating_sub(max_weeks);
178        let x0 = inner.x + label_w;
179
180        if self.show_labels {
181            let names = if self.monday_first {
182                [(0, "Mon"), (2, "Wed"), (4, "Fri")]
183            } else {
184                [(1, "Mon"), (3, "Wed"), (5, "Fri")]
185            };
186            for (row, n) in names {
187                put_str(buf, inner.x, top + row * ch, x0, n, dim);
188            }
189        }
190        let mut last_label_end = 0u16;
191        for w in first_week..weeks {
192            let x = x0 + (w - first_week) as u16 * cw;
193            for r in 0..7usize {
194                let idx = (w * 7 + r) as i64 - off as i64;
195                if idx < 0 || idx as usize >= self.values.len() {
196                    continue;
197                }
198                let v = self.values[idx as usize];
199                let st = if v.is_finite() {
200                    Style::default().fg(self.color_for(v, lo, hi))
201                } else {
202                    dim
203                };
204                let glyph = if v.is_finite() { self.cell } else { '·' };
205                for dy in 0..ch {
206                    buf[(x, top + r as u16 * ch + dy)]
207                        .set_char(glyph)
208                        .set_style(st);
209                }
210                // month label above the week containing the 1st of a month
211                if self.show_labels {
212                    let (_, m, d) = civil_from_days(self.start_day + idx);
213                    if d == 1 && r < 7 && x >= last_label_end {
214                        let name = MONTHS[(m as usize - 1) % 12];
215                        put_str(buf, x, inner.y, inner.right(), name, text);
216                        last_label_end = x + 4;
217                    }
218                }
219            }
220        }
221        if legend {
222            let y = inner.bottom() - 1;
223            let n = self.levels.unwrap_or(5).clamp(2, 9);
224            let w = (n * 2 + 11) as u16;
225            let mut x = inner.right().saturating_sub(w).max(inner.x);
226            put_str(buf, x, y, inner.right(), "Less ", dim);
227            x += 5;
228            for i in 0..n {
229                let c = self.gradient.color_at(i as f64 / (n - 1) as f64);
230                if x < inner.right() {
231                    buf[(x, y)]
232                        .set_char(self.cell)
233                        .set_style(Style::default().fg(c));
234                }
235                x += 2;
236            }
237            put_str(buf, x, y, inner.right(), "More", dim);
238        }
239    }
240}
241
242widget_impls!(CalendarHeatmap);
243
244#[cfg(feature = "theme")]
245impl tui_nuances::Themed for CalendarHeatmap {
246    fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
247        self.theme(theme)
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::days_from_civil;
255    use ratatui::widgets::Widget;
256
257    fn render(c: &CalendarHeatmap, w: u16, h: u16) -> Buffer {
258        let a = Rect::new(0, 0, w, h);
259        let mut b = Buffer::empty(a);
260        c.render(a, &mut b);
261        b
262    }
263
264    fn year() -> CalendarHeatmap {
265        CalendarHeatmap::new(
266            days_from_civil(2024, 1, 1),
267            (0..366).map(|i| (i % 9) as f64),
268        )
269    }
270
271    #[test]
272    fn shows_months_weekdays_and_cells() {
273        let b = render(&year(), 120, 12);
274        let t: String = b.content().iter().map(|c| c.symbol()).collect();
275        assert!(t.contains("Jan") && t.contains("Mon") && t.contains('■'));
276        assert!(t.contains("Less") && t.contains("More"));
277    }
278
279    #[test]
280    fn jan_first_2024_is_monday_row_zero() {
281        // 2024-01-01 was a Monday: first cell lands on the first grid row.
282        let b = render(&year(), 120, 12);
283        assert_eq!(b[(4, 1)].symbol(), "■");
284    }
285
286    #[test]
287    fn sunday_first_shifts_rows() {
288        let b = render(&year().monday_first(false), 120, 12);
289        assert_eq!(b[(4, 1)].symbol(), " ");
290        assert_eq!(b[(4, 2)].symbol(), "■");
291    }
292
293    #[test]
294    fn levels_quantise_colors() {
295        let colors = |c: &CalendarHeatmap| {
296            let mut v: Vec<_> = render(c, 120, 12)
297                .content()
298                .iter()
299                .filter(|c| c.symbol() == "■")
300                .map(|c| format!("{:?}", c.fg))
301                .collect();
302            v.sort();
303            v.dedup();
304            v.len()
305        };
306        assert!(colors(&year().levels(3)) < colors(&year().continuous()));
307    }
308
309    #[test]
310    fn narrow_area_shows_latest_weeks() {
311        let b = render(&year(), 30, 12);
312        let t: String = b.content().iter().map(|c| c.symbol()).collect();
313        assert!(t.contains("Dec") && !t.contains("Feb"));
314    }
315
316    #[test]
317    fn degenerate_inputs_do_not_panic() {
318        let c = CalendarHeatmap::new(-5, [f64::NAN, f64::INFINITY, 1e300, -1e300, 0.0]);
319        for (w, h) in [(0, 0), (1, 1), (5, 7), (12, 12), (40, 9), (300, 80)] {
320            render(&c, w, h);
321            render(&year(), w, h);
322        }
323        render(&CalendarHeatmap::new(0, []), 40, 12);
324        render(
325            &year().show_labels(false).legend(false).bounds(0.0, 1.0),
326            60,
327            8,
328        );
329    }
330}