Skip to main content

lumen_dioxus/charts/extended/
calendar.rs

1//! [`CalendarHeatmap`]: one cell per day between two ISO dates, shaded by value.
2
3use std::collections::HashMap;
4
5use dioxus::prelude::*;
6
7use super::super::format::js_number;
8use super::super::frame::{ChartPresentation, plot_label, render_frame};
9use super::super::model::{ChartDomain, ChartLabels, format_with};
10use super::super::scale::scale_value;
11use super::{empty_status, is_measurement, summary_table};
12use crate::class::Glass;
13
14/// One day's measurement for a [`CalendarHeatmap`].
15#[derive(Clone, Debug, PartialEq)]
16pub struct CalendarHeatmapDatum {
17    /// A strict `YYYY-MM-DD` Gregorian date.
18    pub date: String,
19    /// The value, or `None` for a day without a measurement.
20    pub value: Option<f64>,
21}
22
23impl CalendarHeatmapDatum {
24    /// A measurement for `date`.
25    pub fn new(date: impl Into<String>, value: impl Into<Option<f64>>) -> Self {
26        Self {
27            date: date.into(),
28            value: value.into(),
29        }
30    }
31}
32
33/// The first day of each calendar column.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum CalendarHeatmapWeekStart {
37    /// Weeks start on Sunday.
38    #[default]
39    Sunday,
40    /// Weeks start on Monday.
41    Monday,
42}
43
44impl CalendarHeatmapWeekStart {
45    fn offset(self) -> i64 {
46        match self {
47            Self::Sunday => 0,
48            Self::Monday => 1,
49        }
50    }
51}
52
53/// Props for [`CalendarHeatmap`].
54#[derive(Props, Clone, PartialEq)]
55pub struct CalendarHeatmapProps {
56    /// The daily values. Every date must fall between `start_date` and `end_date`, once.
57    #[props(default)]
58    pub data: Vec<CalendarHeatmapDatum>,
59    /// The first day, as `YYYY-MM-DD`.
60    #[props(into)]
61    pub start_date: String,
62    /// The last day, as `YYYY-MM-DD`. At most 3,660 days after `start_date`.
63    #[props(into)]
64    pub end_date: String,
65    /// The first day of each column.
66    #[props(default)]
67    pub week_starts_on: CalendarHeatmapWeekStart,
68    /// The color scale; defaults to the data extent.
69    pub domain: Option<ChartDomain>,
70    /// Formats values. Defaults to JavaScript's `String(value)`.
71    pub format_value: Option<Callback<f64, String>>,
72    /// Formats `YYYY-MM-DD` dates for the range, tooltips, and table.
73    pub format_date: Option<Callback<String, String>>,
74    /// Seven weekday labels indexed Sunday (0) through Saturday (6).
75    pub weekday_labels: Option<Vec<String>>,
76    /// Twelve short month names, January first, for the month axis. Defaults to `Jan`…`Dec`;
77    /// JavaScript `Intl` is not available on every renderer, so pass them to localize the axis.
78    pub month_labels: Option<Vec<String>>,
79    /// Visible and assistive text.
80    pub labels: Option<ChartLabels>,
81    /// Shows the collapsible data table; otherwise a screen reader list carries the values.
82    #[props(default = true)]
83    pub show_table: bool,
84    /// The chart title.
85    #[props(into)]
86    pub heading: Option<String>,
87    /// Supporting text under the heading.
88    #[props(into)]
89    pub description: Option<String>,
90    /// A headline value beside the heading.
91    #[props(into)]
92    pub value: Option<String>,
93    /// A screen reader summary; defaults to the count of available days.
94    #[props(into)]
95    pub summary: Option<String>,
96    /// A visible caption.
97    #[props(into)]
98    pub caption: Option<String>,
99    /// `Bare` removes the card chrome.
100    #[props(default)]
101    pub presentation: ChartPresentation,
102    /// Glass intensity.
103    #[props(default, into)]
104    pub glass: Glass,
105    /// Extra classes appended after the Lumen classes.
106    #[props(into)]
107    pub class: Option<String>,
108    /// Any other `<figure>` or global attribute.
109    #[props(extends = GlobalAttributes, extends = figure)]
110    pub attributes: Vec<Attribute>,
111}
112
113const MAXIMUM_DAYS: i64 = 3_660;
114const DEFAULT_WEEKDAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
115const DEFAULT_MONTHS: [&str; 12] = [
116    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
117];
118/// Week columns (18px each) a month name needs before the next name or the end of the plot.
119const MONTH_LABEL_COLUMNS: i64 = 2;
120// lumen-react's JSX keeps the indentation of a multi-line class attribute.
121const CELL_CLASS: &str = "\n                        ui-calendar-heatmap__cell ui-chart-tone--series-1\n                      ";
122
123/// Days since 1970-01-01 for a proleptic Gregorian date.
124fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
125    let year = if month <= 2 { year - 1 } else { year };
126    let era = year.div_euclid(400);
127    let year_of_era = year - era * 400;
128    let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1;
129    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
130
131    era * 146_097 + day_of_era - 719_468
132}
133
134/// The `YYYY-MM-DD` date of a day number from [`days_from_civil`].
135fn civil_from_days(days: i64) -> String {
136    let shifted = days + 719_468;
137    let era = shifted.div_euclid(146_097);
138    let day_of_era = shifted - era * 146_097;
139    let year_of_era =
140        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
141    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
142    let month_index = (5 * day_of_year + 2) / 153;
143    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
144    let month = if month_index < 10 {
145        month_index + 3
146    } else {
147        month_index - 9
148    };
149    let year = year_of_era + era * 400 + i64::from(month <= 2);
150
151    format!("{year:04}-{month:02}-{day:02}")
152}
153
154fn is_leap_year(year: i64) -> bool {
155    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
156}
157
158fn days_in_month(year: i64, month: i64) -> i64 {
159    match month {
160        2 if is_leap_year(year) => 29,
161        2 => 28,
162        4 | 6 | 9 | 11 => 30,
163        _ => 31,
164    }
165}
166
167/// `parseLumenCalendarDate`: a strict `YYYY-MM-DD` Gregorian date as a day number since the
168/// Unix epoch, read with one linear scan.
169pub(crate) fn parse_calendar_date(value: &str) -> Option<i64> {
170    let bytes = value.as_bytes();
171
172    if bytes.len() != 10 {
173        return None;
174    }
175
176    let mut parts = [0_i64; 3];
177    let mut part = 0;
178
179    for (index, byte) in bytes.iter().enumerate() {
180        if index == 4 || index == 7 {
181            if *byte != b'-' {
182                return None;
183            }
184
185            part += 1;
186            continue;
187        }
188
189        if !byte.is_ascii_digit() {
190            return None;
191        }
192
193        parts[part] = parts[part] * 10 + i64::from(byte - b'0');
194    }
195
196    let [year, month, day] = parts;
197
198    if year < 1 || !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
199        return None;
200    }
201
202    Some(days_from_civil(year, month, day))
203}
204
205/// One day cell.
206#[derive(Clone, Debug, PartialEq)]
207pub(crate) struct CalendarCell {
208    pub(crate) date: String,
209    pub(crate) value: Option<f64>,
210    pub(crate) week: i64,
211    pub(crate) day: i64,
212    pub(crate) ratio: Option<f64>,
213}
214
215/// `createLumenCalendarHeatmapGeometry`.
216#[derive(Clone, Debug, PartialEq)]
217pub(crate) struct CalendarModel {
218    pub(crate) valid: bool,
219    pub(crate) domain: ChartDomain,
220    pub(crate) cells: Vec<CalendarCell>,
221    pub(crate) week_count: i64,
222}
223
224impl CalendarModel {
225    fn invalid() -> Self {
226        Self {
227            valid: false,
228            domain: ChartDomain::new(0.0, 1.0),
229            cells: Vec::new(),
230            week_count: 0,
231        }
232    }
233}
234
235/// The extent of the available values, padded by 1% (at least 1) when they are all equal.
236fn automatic_domain(values: &[f64]) -> ChartDomain {
237    let Some(first) = values.first() else {
238        return ChartDomain::new(0.0, 1.0);
239    };
240    let mut min = *first;
241    let mut max = min;
242
243    for value in values {
244        min = min.min(*value);
245        max = max.max(*value);
246    }
247
248    // Both bounds are finite, so a zero span means they are equal (0 and -0 included).
249    if max - min == 0.0 {
250        let padding = (min.abs() * 0.01).max(1.0);
251        let lower = min - padding;
252        let upper = max + padding;
253        min = if lower.is_finite() { lower } else { min };
254        max = if upper.is_finite() { upper } else { max };
255    }
256
257    ChartDomain::new(min, max)
258}
259
260fn valid_domain(domain: ChartDomain, values: &[f64]) -> bool {
261    domain.min.is_finite()
262        && domain.max.is_finite()
263        && domain.min < domain.max
264        && values
265            .iter()
266            .all(|value| domain.min <= *value && *value <= domain.max)
267}
268
269pub(crate) fn calendar_geometry(
270    data: &[CalendarHeatmapDatum],
271    start_date: &str,
272    end_date: &str,
273    week_starts_on: CalendarHeatmapWeekStart,
274    requested: Option<ChartDomain>,
275) -> CalendarModel {
276    let (Some(start), Some(end)) = (
277        parse_calendar_date(start_date),
278        parse_calendar_date(end_date),
279    ) else {
280        return CalendarModel::invalid();
281    };
282    let count = end - start + 1;
283
284    if !(1..=MAXIMUM_DAYS).contains(&count) {
285        return CalendarModel::invalid();
286    }
287
288    let mut dates: HashMap<&str, Option<f64>> = HashMap::new();
289    let mut ordered: Vec<f64> = Vec::new();
290
291    for item in data {
292        let Some(day) = parse_calendar_date(&item.date) else {
293            return CalendarModel::invalid();
294        };
295
296        if !is_measurement(item.value)
297            || dates.contains_key(item.date.as_str())
298            || day < start
299            || day > end
300        {
301            return CalendarModel::invalid();
302        }
303
304        dates.insert(item.date.as_str(), item.value);
305
306        if let Some(value) = item.value {
307            ordered.push(value);
308        }
309    }
310
311    let domain = requested.unwrap_or_else(|| automatic_domain(&ordered));
312
313    if !valid_domain(domain, &ordered) {
314        return CalendarModel::invalid();
315    }
316
317    let offset = (start + 4 - week_starts_on.offset()).rem_euclid(7);
318    let cells = (0..count)
319        .map(|index| {
320            let iso = civil_from_days(start + index);
321            let value = dates.get(iso.as_str()).copied().flatten();
322
323            CalendarCell {
324                ratio: value.map(|value| scale_value(value, domain, 0.0, 1.0)),
325                date: iso,
326                value,
327                week: (offset + index) / 7,
328                day: (offset + index) % 7,
329            }
330        })
331        .collect();
332
333    CalendarModel {
334        valid: true,
335        domain,
336        cells,
337        week_count: (offset + count + 6) / 7,
338    }
339}
340
341/// A month named on the axis: its first day in the range and that day's week column.
342#[derive(Clone, Debug, PartialEq, Eq)]
343pub(crate) struct CalendarMonth {
344    pub(crate) date: String,
345    pub(crate) week: i64,
346    /// Zero-based: January is 0.
347    pub(crate) month: usize,
348}
349
350/// `resolveLumenCalendarHeatmapMonthLabels`: each month at the week column of its first day in
351/// the range. A name that would collide with the next one or run past the end of the plot is
352/// dropped, so a partial first or last month gives way; a plot too narrow for any name keeps its
353/// first month. Months come from the `YYYY-MM-DD` identities, never from local time.
354pub(crate) fn calendar_months(model: &CalendarModel) -> Vec<CalendarMonth> {
355    let mut starts: Vec<CalendarMonth> = Vec::new();
356    let mut previous = "";
357    let mut last_week = -1;
358
359    for cell in &model.cells {
360        if cell.week < 0 || parse_calendar_date(&cell.date).is_none() {
361            continue;
362        }
363
364        last_week = last_week.max(cell.week);
365
366        let (Some(key), Some(month)) = (cell.date.get(..7), cell.date.get(5..7)) else {
367            continue;
368        };
369
370        if key == previous {
371            continue;
372        }
373
374        previous = key;
375
376        if let Some(month) = month
377            .parse::<usize>()
378            .ok()
379            .and_then(|month| month.checked_sub(1))
380        {
381            starts.push(CalendarMonth {
382                date: cell.date.clone(),
383                week: cell.week,
384                month,
385            });
386        }
387    }
388
389    let mut boundary = model.week_count.max(last_week + 1);
390    let mut kept: Vec<CalendarMonth> = Vec::new();
391
392    for start in starts.iter().rev() {
393        if boundary - start.week >= MONTH_LABEL_COLUMNS {
394            kept.push(start.clone());
395            boundary = start.week;
396        }
397    }
398
399    if kept.is_empty()
400        && let Some(first) = starts.first()
401    {
402        kept.push(first.clone());
403    }
404
405    kept.reverse();
406    kept
407}
408
409fn month_label(labels: Option<&Vec<String>>, month: usize) -> String {
410    labels
411        .and_then(|labels| labels.get(month).cloned())
412        .unwrap_or_else(|| {
413            DEFAULT_MONTHS
414                .get(month)
415                .copied()
416                .unwrap_or_default()
417                .to_string()
418        })
419}
420
421fn weekday_label(labels: Option<&Vec<String>>, day: i64, week_starts_on: i64) -> String {
422    let index = usize::try_from((day + week_starts_on) % 7).unwrap_or(0);
423
424    labels
425        .and_then(|labels| labels.get(index).cloned())
426        .unwrap_or_else(|| DEFAULT_WEEKDAYS[index].to_string())
427}
428
429/// A prepared day cell with its display strings.
430#[derive(Clone, PartialEq)]
431struct DayView {
432    date: String,
433    missing: bool,
434    x: String,
435    y: String,
436    missing_x: String,
437    missing_y: String,
438    opacity: String,
439    date_label: String,
440    value_label: String,
441}
442
443/// A year of daily activity: one square per day, grouped into week columns, shaded by value.
444/// Days without a measurement show a cross and read "Not available".
445#[component]
446pub fn CalendarHeatmap(props: CalendarHeatmapProps) -> Element {
447    let labels = props.labels.clone().unwrap_or_default();
448    let format_value = props.format_value;
449    let format_date = props.format_date;
450    let model = calendar_geometry(
451        &props.data,
452        &props.start_date,
453        &props.end_date,
454        props.week_starts_on,
455        props.domain,
456    );
457    let date_label = move |date: &str| match format_date {
458        Some(format) => format.call(date.to_string()),
459        None => date.to_string(),
460    };
461    let available = model
462        .cells
463        .iter()
464        .filter(|cell| cell.value.is_some())
465        .count();
466    let summary = props.summary.clone().or_else(|| {
467        Some(if model.valid {
468            labels.heatmap_summary(available)
469        } else {
470            labels.invalid_data.clone()
471        })
472    });
473    let class = crate::class::compose([Some("ui-calendar-heatmap"), props.class.as_deref()]);
474    let frame = super::super::frame::chart_frame!(props, class, summary);
475    let plot_name = plot_label(
476        &props.attributes,
477        props.heading.as_ref(),
478        &labels.chart_data,
479    );
480
481    if !model.valid {
482        return render_frame(frame, empty_status(&labels.invalid_data));
483    }
484
485    let size = (model.week_count * 18 + 36).to_string();
486    let view_box = format!("0 0 {size} 146");
487    let week_start = props.week_starts_on.offset();
488    let weekdays: Vec<(String, String)> = (0..7)
489        .map(|day| {
490            (
491                (day * 18 + 16).to_string(),
492                weekday_label(props.weekday_labels.as_ref(), day, week_start),
493            )
494        })
495        .collect();
496    let range = format!(
497        "{} – {}",
498        date_label(&props.start_date),
499        date_label(&props.end_date)
500    );
501    let days: Vec<DayView> = model
502        .cells
503        .iter()
504        .map(|cell| DayView {
505            date: cell.date.clone(),
506            missing: cell.value.is_none(),
507            x: (cell.week * 18 + 36).to_string(),
508            y: (cell.day * 18 + 4).to_string(),
509            missing_x: (cell.week * 18 + 43).to_string(),
510            missing_y: (cell.day * 18 + 15).to_string(),
511            opacity: fill_opacity(cell.ratio),
512            date_label: date_label(&cell.date),
513            value_label: match cell.value {
514                Some(value) => format_with(format_value.as_ref(), value),
515                None => labels.not_available.clone(),
516            },
517        })
518        .collect();
519    let months: Vec<(String, String, String)> = calendar_months(&model)
520        .into_iter()
521        .map(|month| {
522            (
523                (month.week * 18 + 36).to_string(),
524                month_label(props.month_labels.as_ref(), month.month),
525                month.date,
526            )
527        })
528        .collect();
529    let low = format_with(format_value.as_ref(), model.domain.min);
530    let high = format_with(format_value.as_ref(), model.domain.max);
531    let headings = [
532        ("category", labels.category.clone()),
533        ("value", labels.value.clone()),
534    ];
535    let details = if props.show_table {
536        summary_table(
537            &labels,
538            &headings,
539            rsx! {
540                for day in days.iter() {
541                    tr { key: "{day.date}",
542                        th { scope: "row", "{day.date_label}" }
543                        td { "{day.value_label}" }
544                    }
545                }
546            },
547        )
548    } else {
549        rsx! {
550            ul { class: "ui-sr-only",
551                for day in days.iter() {
552                    li { key: "{day.date}", "{day.date_label}: {day.value_label}" }
553                }
554            }
555        }
556    };
557    let body = rsx! {
558        if available == 0 {
559            {empty_status(&labels.empty)}
560        }
561        p { class: "ui-calendar-heatmap__range", "{range}" }
562        div {
563            class: "ui-calendar-heatmap__plot",
564            role: "group",
565            tabindex: "0",
566            aria_label: "{plot_name}",
567            svg {
568                "aria-hidden": "true",
569                "width": "{size}",
570                "height": "146",
571                "viewBox": "{view_box}",
572                for (y, label) in weekdays {
573                    text {
574                        key: "{y}",
575                        "x": "0",
576                        "y": "{y}",
577                        class: "ui-calendar-heatmap__weekday",
578                        "{label}"
579                    }
580                }
581                for day in days.iter() {
582                    g { key: "{day.date}",
583                        rect {
584                            class: CELL_CLASS,
585                            "data-missing": day.missing.then_some("true"),
586                            "x": "{day.x}",
587                            "y": "{day.y}",
588                            "width": "14",
589                            "height": "14",
590                            "rx": "3",
591                            style: "fill-opacity:{day.opacity}",
592                            title { "{day.date_label}: {day.value_label}" }
593                        }
594                        if day.missing {
595                            text {
596                                class: "ui-calendar-heatmap__missing",
597                                "x": "{day.missing_x}",
598                                "y": "{day.missing_y}",
599                                "text-anchor": "middle",
600                                "×"
601                            }
602                        }
603                    }
604                }
605                for (x, label, date) in months {
606                    text {
607                        key: "{date}",
608                        class: "ui-calendar-heatmap__month",
609                        "x": "{x}",
610                        "y": "142",
611                        "{label}"
612                    }
613                }
614            }
615        }
616        div { class: "ui-calendar-heatmap__legend",
617            span { "{labels.low}: {low}" }
618            span { class: "ui-calendar-heatmap__scale", aria_hidden: "true" }
619            span { "{labels.high}: {high}" }
620            span {
621                span { aria_hidden: "true", "×" }
622                " {labels.not_available}"
623            }
624        }
625        {details}
626    };
627
628    render_frame(frame, body)
629}
630
631/// `fill-opacity` of a cell: full for missing days, 0.15 to 1 for values.
632fn fill_opacity(ratio: Option<f64>) -> String {
633    js_number(ratio.map_or(1.0, |ratio| 0.15 + ratio * 0.85))
634}
635
636#[cfg(test)]
637mod tests {
638    use super::{
639        CalendarHeatmapDatum, CalendarHeatmapWeekStart, calendar_geometry, calendar_months,
640        civil_from_days, month_label, parse_calendar_date,
641    };
642    use crate::charts::model::ChartDomain;
643
644    /// `(label, first date, week column)` of each named month.
645    fn months(
646        start: &str,
647        end: &str,
648        week_start: CalendarHeatmapWeekStart,
649    ) -> Vec<(String, String, i64)> {
650        let model = calendar_geometry(&[], start, end, week_start, None);
651
652        calendar_months(&model)
653            .into_iter()
654            .map(|month| (month_label(None, month.month), month.date, month.week))
655            .collect()
656    }
657
658    fn expected(rows: &[(&str, &str, i64)]) -> Vec<(String, String, i64)> {
659        rows.iter()
660            .map(|(label, date, week)| ((*label).to_string(), (*date).to_string(), *week))
661            .collect()
662    }
663
664    #[test]
665    fn months_are_named_once_at_the_column_of_their_first_day() {
666        let sunday = CalendarHeatmapWeekStart::Sunday;
667        assert_eq!(
668            months("2024-01-01", "2024-12-31", sunday),
669            expected(&[
670                ("Jan", "2024-01-01", 0),
671                ("Feb", "2024-02-01", 4),
672                ("Mar", "2024-03-01", 8),
673                ("Apr", "2024-04-01", 13),
674                ("May", "2024-05-01", 17),
675                ("Jun", "2024-06-01", 21),
676                ("Jul", "2024-07-01", 26),
677                ("Aug", "2024-08-01", 30),
678                ("Sep", "2024-09-01", 35),
679                ("Oct", "2024-10-01", 39),
680                ("Nov", "2024-11-01", 43),
681                ("Dec", "2024-12-01", 48),
682            ])
683        );
684        let monday = months("2023-01-01", "2023-12-31", CalendarHeatmapWeekStart::Monday);
685        assert_eq!(
686            monday[..3],
687            expected(&[
688                ("Jan", "2023-01-01", 0),
689                ("Feb", "2023-02-01", 5),
690                ("Mar", "2023-03-01", 9),
691            ])
692        );
693    }
694
695    #[test]
696    fn months_cross_year_and_leap_day_boundaries() {
697        let sunday = CalendarHeatmapWeekStart::Sunday;
698        assert_eq!(
699            months("2024-12-01", "2025-02-28", sunday),
700            expected(&[
701                ("Dec", "2024-12-01", 0),
702                ("Jan", "2025-01-01", 4),
703                ("Feb", "2025-02-01", 8),
704            ])
705        );
706        assert_eq!(
707            months("2024-02-01", "2024-04-30", sunday),
708            expected(&[
709                ("Feb", "2024-02-01", 0),
710                ("Mar", "2024-03-01", 4),
711                ("Apr", "2024-04-01", 9),
712            ])
713        );
714        assert_eq!(
715            months("2023-02-01", "2023-04-30", sunday),
716            expected(&[
717                ("Feb", "2023-02-01", 0),
718                ("Mar", "2023-03-01", 4),
719                ("Apr", "2023-04-01", 8),
720            ])
721        );
722    }
723
724    #[test]
725    fn colliding_or_clipped_months_are_dropped() {
726        let sunday = CalendarHeatmapWeekStart::Sunday;
727        assert_eq!(
728            months("2024-01-29", "2024-03-05", sunday),
729            expected(&[("Feb", "2024-02-01", 0), ("Mar", "2024-03-01", 4)])
730        );
731        let year = months("2024-01-01", "2024-12-03", sunday);
732        assert_eq!(year.len(), 11);
733        assert_eq!(
734            year.last(),
735            Some(&("Nov".to_string(), "2024-11-01".to_string(), 43))
736        );
737        assert_eq!(
738            months("2024-03-15", "2024-03-15", sunday),
739            expected(&[("Mar", "2024-03-15", 0)])
740        );
741        assert_eq!(
742            months("2024-01-31", "2024-02-01", sunday),
743            expected(&[("Jan", "2024-01-31", 0)])
744        );
745        let invalid = calendar_geometry(&[], "bad", "2024-01-01", sunday, None);
746        assert_eq!(calendar_months(&invalid), []);
747    }
748
749    #[test]
750    fn month_names_fall_back_to_english_per_index() {
751        let spanish: Vec<String> = ["ene", "feb"].map(String::from).to_vec();
752        assert_eq!(month_label(Some(&spanish), 0), "ene");
753        assert_eq!(month_label(Some(&spanish), 2), "Mar");
754        assert_eq!(month_label(None, 11), "Dec");
755    }
756
757    #[test]
758    fn dates_parse_strictly() {
759        assert_eq!(parse_calendar_date("1970-01-01"), Some(0));
760        assert_eq!(parse_calendar_date("2024-02-29"), Some(19_782));
761        assert_eq!(parse_calendar_date("2023-02-29"), None);
762        assert_eq!(parse_calendar_date("1900-02-29"), None);
763        assert!(parse_calendar_date("2000-02-29").is_some());
764        assert_eq!(parse_calendar_date("0000-01-01"), None);
765        assert!(parse_calendar_date("0001-01-01").is_some());
766        assert_eq!(parse_calendar_date("2024-13-01"), None);
767        assert_eq!(parse_calendar_date("2024-04-31"), None);
768        assert_eq!(parse_calendar_date("2024-1-01"), None);
769        assert_eq!(parse_calendar_date("2024/01/01"), None);
770        assert_eq!(parse_calendar_date("2024-01-01T"), None);
771        assert_eq!(parse_calendar_date("2024-01-01"), None);
772        assert_eq!(parse_calendar_date(""), None);
773        assert_eq!(parse_calendar_date(&"9".repeat(1_000_000)), None);
774        assert_eq!(parse_calendar_date(&"2024-01-01".repeat(100_000)), None);
775    }
776
777    #[test]
778    fn days_round_trip_to_iso_dates() {
779        for date in [
780            "0001-01-01",
781            "1969-12-31",
782            "1970-01-01",
783            "2024-02-29",
784            "9999-12-31",
785        ] {
786            let days = parse_calendar_date(date).unwrap();
787            assert_eq!(civil_from_days(days), date);
788        }
789    }
790
791    fn data() -> Vec<CalendarHeatmapDatum> {
792        vec![
793            CalendarHeatmapDatum::new("2024-02-28", 7.0),
794            CalendarHeatmapDatum::new("2024-02-29", None),
795            CalendarHeatmapDatum::new("2024-03-02", -4.5),
796        ]
797    }
798
799    #[test]
800    fn cells_cover_every_day_in_week_columns() {
801        let model = calendar_geometry(
802            &data(),
803            "2024-02-26",
804            "2024-03-05",
805            CalendarHeatmapWeekStart::Sunday,
806            None,
807        );
808        assert!(model.valid);
809        assert_eq!(model.cells.len(), 9);
810        assert_eq!(model.domain, ChartDomain::new(-4.5, 7.0));
811        // 2024-02-26 is a Monday.
812        assert_eq!((model.cells[0].week, model.cells[0].day), (0, 1));
813        assert_eq!(model.cells[3].date, "2024-02-29");
814        assert_eq!(model.cells[3].ratio, None);
815        assert_eq!(model.week_count, 2);
816        let monday = calendar_geometry(
817            &data(),
818            "2024-02-26",
819            "2024-03-05",
820            CalendarHeatmapWeekStart::Monday,
821            None,
822        );
823        assert_eq!((monday.cells[0].week, monday.cells[0].day), (0, 0));
824    }
825
826    #[test]
827    fn invalid_calendars_fail_closed() {
828        let sunday = CalendarHeatmapWeekStart::Sunday;
829        assert!(!calendar_geometry(&[], "2024-03-05", "2024-03-01", sunday, None).valid);
830        assert!(!calendar_geometry(&[], "2024-01-01", "2034-12-31", sunday, None).valid);
831        assert!(calendar_geometry(&[], "2024-01-01", "2034-01-07", sunday, None).valid);
832        assert!(!calendar_geometry(&[], "2024-01-01", "2034-01-08", sunday, None).valid);
833        assert!(!calendar_geometry(&[], "bad", "2024-01-01", sunday, None).valid);
834        let outside = [CalendarHeatmapDatum::new("2024-04-01", 1.0)];
835        assert!(!calendar_geometry(&outside, "2024-03-01", "2024-03-05", sunday, None).valid);
836        let duplicate = [
837            CalendarHeatmapDatum::new("2024-03-01", 1.0),
838            CalendarHeatmapDatum::new("2024-03-01", 2.0),
839        ];
840        assert!(!calendar_geometry(&duplicate, "2024-03-01", "2024-03-05", sunday, None).valid);
841        let infinite = [CalendarHeatmapDatum::new("2024-03-01", f64::INFINITY)];
842        assert!(!calendar_geometry(&infinite, "2024-03-01", "2024-03-05", sunday, None).valid);
843        let narrow = Some(ChartDomain::new(0.0, 5.0));
844        assert!(!calendar_geometry(&data(), "2024-02-26", "2024-03-05", sunday, narrow).valid);
845    }
846
847    #[test]
848    fn flat_and_empty_data_get_usable_domains() {
849        let sunday = CalendarHeatmapWeekStart::Sunday;
850        let empty = calendar_geometry(&[], "2024-01-01", "2024-01-01", sunday, None);
851        assert_eq!(empty.domain, ChartDomain::new(0.0, 1.0));
852        assert_eq!(empty.cells.len(), 1);
853        let flat = [CalendarHeatmapDatum::new("2024-01-01", 500.0)];
854        let model = calendar_geometry(&flat, "2024-01-01", "2024-01-02", sunday, None);
855        assert_eq!(model.domain, ChartDomain::new(495.0, 505.0));
856        let tiny = [CalendarHeatmapDatum::new("2024-01-01", 0.0)];
857        let model = calendar_geometry(&tiny, "2024-01-01", "2024-01-02", sunday, None);
858        assert_eq!(model.domain, ChartDomain::new(-1.0, 1.0));
859    }
860}