lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! [`CalendarHeatmap`]: one cell per day between two ISO dates, shaded by value.

use std::collections::HashMap;

use dioxus::prelude::*;

use super::super::format::js_number;
use super::super::frame::{ChartPresentation, plot_label, render_frame};
use super::super::model::{ChartDomain, ChartLabels, format_with};
use super::super::scale::scale_value;
use super::{empty_status, is_measurement, summary_table};
use crate::class::Glass;

/// One day's measurement for a [`CalendarHeatmap`].
#[derive(Clone, Debug, PartialEq)]
pub struct CalendarHeatmapDatum {
    /// A strict `YYYY-MM-DD` Gregorian date.
    pub date: String,
    /// The value, or `None` for a day without a measurement.
    pub value: Option<f64>,
}

impl CalendarHeatmapDatum {
    /// A measurement for `date`.
    pub fn new(date: impl Into<String>, value: impl Into<Option<f64>>) -> Self {
        Self {
            date: date.into(),
            value: value.into(),
        }
    }
}

/// The first day of each calendar column.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CalendarHeatmapWeekStart {
    /// Weeks start on Sunday.
    #[default]
    Sunday,
    /// Weeks start on Monday.
    Monday,
}

impl CalendarHeatmapWeekStart {
    fn offset(self) -> i64 {
        match self {
            Self::Sunday => 0,
            Self::Monday => 1,
        }
    }
}

/// Props for [`CalendarHeatmap`].
#[derive(Props, Clone, PartialEq)]
pub struct CalendarHeatmapProps {
    /// The daily values. Every date must fall between `start_date` and `end_date`, once.
    #[props(default)]
    pub data: Vec<CalendarHeatmapDatum>,
    /// The first day, as `YYYY-MM-DD`.
    #[props(into)]
    pub start_date: String,
    /// The last day, as `YYYY-MM-DD`. At most 3,660 days after `start_date`.
    #[props(into)]
    pub end_date: String,
    /// The first day of each column.
    #[props(default)]
    pub week_starts_on: CalendarHeatmapWeekStart,
    /// The color scale; defaults to the data extent.
    pub domain: Option<ChartDomain>,
    /// Formats values. Defaults to JavaScript's `String(value)`.
    pub format_value: Option<Callback<f64, String>>,
    /// Formats `YYYY-MM-DD` dates for the range, tooltips, and table.
    pub format_date: Option<Callback<String, String>>,
    /// Seven weekday labels indexed Sunday (0) through Saturday (6).
    pub weekday_labels: Option<Vec<String>>,
    /// Twelve short month names, January first, for the month axis. Defaults to `Jan`…`Dec`;
    /// JavaScript `Intl` is not available on every renderer, so pass them to localize the axis.
    pub month_labels: Option<Vec<String>>,
    /// Visible and assistive text.
    pub labels: Option<ChartLabels>,
    /// Shows the collapsible data table; otherwise a screen reader list carries the values.
    #[props(default = true)]
    pub show_table: bool,
    /// The chart title.
    #[props(into)]
    pub heading: Option<String>,
    /// Supporting text under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// A headline value beside the heading.
    #[props(into)]
    pub value: Option<String>,
    /// A screen reader summary; defaults to the count of available days.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption.
    #[props(into)]
    pub caption: Option<String>,
    /// `Bare` removes the card chrome.
    #[props(default)]
    pub presentation: ChartPresentation,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
}

const MAXIMUM_DAYS: i64 = 3_660;
const DEFAULT_WEEKDAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const DEFAULT_MONTHS: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
/// Week columns (18px each) a month name needs before the next name or the end of the plot.
const MONTH_LABEL_COLUMNS: i64 = 2;
// lumen-react's JSX keeps the indentation of a multi-line class attribute.
const CELL_CLASS: &str = "\n                        ui-calendar-heatmap__cell ui-chart-tone--series-1\n                      ";

/// Days since 1970-01-01 for a proleptic Gregorian date.
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let year = if month <= 2 { year - 1 } else { year };
    let era = year.div_euclid(400);
    let year_of_era = year - era * 400;
    let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;

    era * 146_097 + day_of_era - 719_468
}

/// The `YYYY-MM-DD` date of a day number from [`days_from_civil`].
fn civil_from_days(days: i64) -> String {
    let shifted = days + 719_468;
    let era = shifted.div_euclid(146_097);
    let day_of_era = shifted - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_index = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
    let month = if month_index < 10 {
        month_index + 3
    } else {
        month_index - 9
    };
    let year = year_of_era + era * 400 + i64::from(month <= 2);

    format!("{year:04}-{month:02}-{day:02}")
}

fn is_leap_year(year: i64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

fn days_in_month(year: i64, month: i64) -> i64 {
    match month {
        2 if is_leap_year(year) => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// `parseLumenCalendarDate`: a strict `YYYY-MM-DD` Gregorian date as a day number since the
/// Unix epoch, read with one linear scan.
pub(crate) fn parse_calendar_date(value: &str) -> Option<i64> {
    let bytes = value.as_bytes();

    if bytes.len() != 10 {
        return None;
    }

    let mut parts = [0_i64; 3];
    let mut part = 0;

    for (index, byte) in bytes.iter().enumerate() {
        if index == 4 || index == 7 {
            if *byte != b'-' {
                return None;
            }

            part += 1;
            continue;
        }

        if !byte.is_ascii_digit() {
            return None;
        }

        parts[part] = parts[part] * 10 + i64::from(byte - b'0');
    }

    let [year, month, day] = parts;

    if year < 1 || !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
        return None;
    }

    Some(days_from_civil(year, month, day))
}

/// One day cell.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CalendarCell {
    pub(crate) date: String,
    pub(crate) value: Option<f64>,
    pub(crate) week: i64,
    pub(crate) day: i64,
    pub(crate) ratio: Option<f64>,
}

/// `createLumenCalendarHeatmapGeometry`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CalendarModel {
    pub(crate) valid: bool,
    pub(crate) domain: ChartDomain,
    pub(crate) cells: Vec<CalendarCell>,
    pub(crate) week_count: i64,
}

impl CalendarModel {
    fn invalid() -> Self {
        Self {
            valid: false,
            domain: ChartDomain::new(0.0, 1.0),
            cells: Vec::new(),
            week_count: 0,
        }
    }
}

/// The extent of the available values, padded by 1% (at least 1) when they are all equal.
fn automatic_domain(values: &[f64]) -> ChartDomain {
    let Some(first) = values.first() else {
        return ChartDomain::new(0.0, 1.0);
    };
    let mut min = *first;
    let mut max = min;

    for value in values {
        min = min.min(*value);
        max = max.max(*value);
    }

    // Both bounds are finite, so a zero span means they are equal (0 and -0 included).
    if max - min == 0.0 {
        let padding = (min.abs() * 0.01).max(1.0);
        let lower = min - padding;
        let upper = max + padding;
        min = if lower.is_finite() { lower } else { min };
        max = if upper.is_finite() { upper } else { max };
    }

    ChartDomain::new(min, max)
}

fn valid_domain(domain: ChartDomain, values: &[f64]) -> bool {
    domain.min.is_finite()
        && domain.max.is_finite()
        && domain.min < domain.max
        && values
            .iter()
            .all(|value| domain.min <= *value && *value <= domain.max)
}

pub(crate) fn calendar_geometry(
    data: &[CalendarHeatmapDatum],
    start_date: &str,
    end_date: &str,
    week_starts_on: CalendarHeatmapWeekStart,
    requested: Option<ChartDomain>,
) -> CalendarModel {
    let (Some(start), Some(end)) = (
        parse_calendar_date(start_date),
        parse_calendar_date(end_date),
    ) else {
        return CalendarModel::invalid();
    };
    let count = end - start + 1;

    if !(1..=MAXIMUM_DAYS).contains(&count) {
        return CalendarModel::invalid();
    }

    let mut dates: HashMap<&str, Option<f64>> = HashMap::new();
    let mut ordered: Vec<f64> = Vec::new();

    for item in data {
        let Some(day) = parse_calendar_date(&item.date) else {
            return CalendarModel::invalid();
        };

        if !is_measurement(item.value)
            || dates.contains_key(item.date.as_str())
            || day < start
            || day > end
        {
            return CalendarModel::invalid();
        }

        dates.insert(item.date.as_str(), item.value);

        if let Some(value) = item.value {
            ordered.push(value);
        }
    }

    let domain = requested.unwrap_or_else(|| automatic_domain(&ordered));

    if !valid_domain(domain, &ordered) {
        return CalendarModel::invalid();
    }

    let offset = (start + 4 - week_starts_on.offset()).rem_euclid(7);
    let cells = (0..count)
        .map(|index| {
            let iso = civil_from_days(start + index);
            let value = dates.get(iso.as_str()).copied().flatten();

            CalendarCell {
                ratio: value.map(|value| scale_value(value, domain, 0.0, 1.0)),
                date: iso,
                value,
                week: (offset + index) / 7,
                day: (offset + index) % 7,
            }
        })
        .collect();

    CalendarModel {
        valid: true,
        domain,
        cells,
        week_count: (offset + count + 6) / 7,
    }
}

/// A month named on the axis: its first day in the range and that day's week column.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CalendarMonth {
    pub(crate) date: String,
    pub(crate) week: i64,
    /// Zero-based: January is 0.
    pub(crate) month: usize,
}

/// `resolveLumenCalendarHeatmapMonthLabels`: each month at the week column of its first day in
/// the range. A name that would collide with the next one or run past the end of the plot is
/// dropped, so a partial first or last month gives way; a plot too narrow for any name keeps its
/// first month. Months come from the `YYYY-MM-DD` identities, never from local time.
pub(crate) fn calendar_months(model: &CalendarModel) -> Vec<CalendarMonth> {
    let mut starts: Vec<CalendarMonth> = Vec::new();
    let mut previous = "";
    let mut last_week = -1;

    for cell in &model.cells {
        if cell.week < 0 || parse_calendar_date(&cell.date).is_none() {
            continue;
        }

        last_week = last_week.max(cell.week);

        let (Some(key), Some(month)) = (cell.date.get(..7), cell.date.get(5..7)) else {
            continue;
        };

        if key == previous {
            continue;
        }

        previous = key;

        if let Some(month) = month
            .parse::<usize>()
            .ok()
            .and_then(|month| month.checked_sub(1))
        {
            starts.push(CalendarMonth {
                date: cell.date.clone(),
                week: cell.week,
                month,
            });
        }
    }

    let mut boundary = model.week_count.max(last_week + 1);
    let mut kept: Vec<CalendarMonth> = Vec::new();

    for start in starts.iter().rev() {
        if boundary - start.week >= MONTH_LABEL_COLUMNS {
            kept.push(start.clone());
            boundary = start.week;
        }
    }

    if kept.is_empty()
        && let Some(first) = starts.first()
    {
        kept.push(first.clone());
    }

    kept.reverse();
    kept
}

fn month_label(labels: Option<&Vec<String>>, month: usize) -> String {
    labels
        .and_then(|labels| labels.get(month).cloned())
        .unwrap_or_else(|| {
            DEFAULT_MONTHS
                .get(month)
                .copied()
                .unwrap_or_default()
                .to_string()
        })
}

fn weekday_label(labels: Option<&Vec<String>>, day: i64, week_starts_on: i64) -> String {
    let index = usize::try_from((day + week_starts_on) % 7).unwrap_or(0);

    labels
        .and_then(|labels| labels.get(index).cloned())
        .unwrap_or_else(|| DEFAULT_WEEKDAYS[index].to_string())
}

/// A prepared day cell with its display strings.
#[derive(Clone, PartialEq)]
struct DayView {
    date: String,
    missing: bool,
    x: String,
    y: String,
    missing_x: String,
    missing_y: String,
    opacity: String,
    date_label: String,
    value_label: String,
}

/// A year of daily activity: one square per day, grouped into week columns, shaded by value.
/// Days without a measurement show a cross and read "Not available".
#[component]
pub fn CalendarHeatmap(props: CalendarHeatmapProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value;
    let format_date = props.format_date;
    let model = calendar_geometry(
        &props.data,
        &props.start_date,
        &props.end_date,
        props.week_starts_on,
        props.domain,
    );
    let date_label = move |date: &str| match format_date {
        Some(format) => format.call(date.to_string()),
        None => date.to_string(),
    };
    let available = model
        .cells
        .iter()
        .filter(|cell| cell.value.is_some())
        .count();
    let summary = props.summary.clone().or_else(|| {
        Some(if model.valid {
            labels.heatmap_summary(available)
        } else {
            labels.invalid_data.clone()
        })
    });
    let class = crate::class::compose([Some("ui-calendar-heatmap"), props.class.as_deref()]);
    let frame = super::super::frame::chart_frame!(props, class, summary);
    let plot_name = plot_label(
        &props.attributes,
        props.heading.as_ref(),
        &labels.chart_data,
    );

    if !model.valid {
        return render_frame(frame, empty_status(&labels.invalid_data));
    }

    let size = (model.week_count * 18 + 36).to_string();
    let view_box = format!("0 0 {size} 146");
    let week_start = props.week_starts_on.offset();
    let weekdays: Vec<(String, String)> = (0..7)
        .map(|day| {
            (
                (day * 18 + 16).to_string(),
                weekday_label(props.weekday_labels.as_ref(), day, week_start),
            )
        })
        .collect();
    let range = format!(
        "{} – {}",
        date_label(&props.start_date),
        date_label(&props.end_date)
    );
    let days: Vec<DayView> = model
        .cells
        .iter()
        .map(|cell| DayView {
            date: cell.date.clone(),
            missing: cell.value.is_none(),
            x: (cell.week * 18 + 36).to_string(),
            y: (cell.day * 18 + 4).to_string(),
            missing_x: (cell.week * 18 + 43).to_string(),
            missing_y: (cell.day * 18 + 15).to_string(),
            opacity: fill_opacity(cell.ratio),
            date_label: date_label(&cell.date),
            value_label: match cell.value {
                Some(value) => format_with(format_value.as_ref(), value),
                None => labels.not_available.clone(),
            },
        })
        .collect();
    let months: Vec<(String, String, String)> = calendar_months(&model)
        .into_iter()
        .map(|month| {
            (
                (month.week * 18 + 36).to_string(),
                month_label(props.month_labels.as_ref(), month.month),
                month.date,
            )
        })
        .collect();
    let low = format_with(format_value.as_ref(), model.domain.min);
    let high = format_with(format_value.as_ref(), model.domain.max);
    let headings = [
        ("category", labels.category.clone()),
        ("value", labels.value.clone()),
    ];
    let details = if props.show_table {
        summary_table(
            &labels,
            &headings,
            rsx! {
                for day in days.iter() {
                    tr { key: "{day.date}",
                        th { scope: "row", "{day.date_label}" }
                        td { "{day.value_label}" }
                    }
                }
            },
        )
    } else {
        rsx! {
            ul { class: "ui-sr-only",
                for day in days.iter() {
                    li { key: "{day.date}", "{day.date_label}: {day.value_label}" }
                }
            }
        }
    };
    let body = rsx! {
        if available == 0 {
            {empty_status(&labels.empty)}
        }
        p { class: "ui-calendar-heatmap__range", "{range}" }
        div {
            class: "ui-calendar-heatmap__plot",
            role: "group",
            tabindex: "0",
            aria_label: "{plot_name}",
            svg {
                "aria-hidden": "true",
                "width": "{size}",
                "height": "146",
                "viewBox": "{view_box}",
                for (y, label) in weekdays {
                    text {
                        key: "{y}",
                        "x": "0",
                        "y": "{y}",
                        class: "ui-calendar-heatmap__weekday",
                        "{label}"
                    }
                }
                for day in days.iter() {
                    g { key: "{day.date}",
                        rect {
                            class: CELL_CLASS,
                            "data-missing": day.missing.then_some("true"),
                            "x": "{day.x}",
                            "y": "{day.y}",
                            "width": "14",
                            "height": "14",
                            "rx": "3",
                            style: "fill-opacity:{day.opacity}",
                            title { "{day.date_label}: {day.value_label}" }
                        }
                        if day.missing {
                            text {
                                class: "ui-calendar-heatmap__missing",
                                "x": "{day.missing_x}",
                                "y": "{day.missing_y}",
                                "text-anchor": "middle",
                                "×"
                            }
                        }
                    }
                }
                for (x, label, date) in months {
                    text {
                        key: "{date}",
                        class: "ui-calendar-heatmap__month",
                        "x": "{x}",
                        "y": "142",
                        "{label}"
                    }
                }
            }
        }
        div { class: "ui-calendar-heatmap__legend",
            span { "{labels.low}: {low}" }
            span { class: "ui-calendar-heatmap__scale", aria_hidden: "true" }
            span { "{labels.high}: {high}" }
            span {
                span { aria_hidden: "true", "×" }
                " {labels.not_available}"
            }
        }
        {details}
    };

    render_frame(frame, body)
}

/// `fill-opacity` of a cell: full for missing days, 0.15 to 1 for values.
fn fill_opacity(ratio: Option<f64>) -> String {
    js_number(ratio.map_or(1.0, |ratio| 0.15 + ratio * 0.85))
}

#[cfg(test)]
mod tests {
    use super::{
        CalendarHeatmapDatum, CalendarHeatmapWeekStart, calendar_geometry, calendar_months,
        civil_from_days, month_label, parse_calendar_date,
    };
    use crate::charts::model::ChartDomain;

    /// `(label, first date, week column)` of each named month.
    fn months(
        start: &str,
        end: &str,
        week_start: CalendarHeatmapWeekStart,
    ) -> Vec<(String, String, i64)> {
        let model = calendar_geometry(&[], start, end, week_start, None);

        calendar_months(&model)
            .into_iter()
            .map(|month| (month_label(None, month.month), month.date, month.week))
            .collect()
    }

    fn expected(rows: &[(&str, &str, i64)]) -> Vec<(String, String, i64)> {
        rows.iter()
            .map(|(label, date, week)| ((*label).to_string(), (*date).to_string(), *week))
            .collect()
    }

    #[test]
    fn months_are_named_once_at_the_column_of_their_first_day() {
        let sunday = CalendarHeatmapWeekStart::Sunday;
        assert_eq!(
            months("2024-01-01", "2024-12-31", sunday),
            expected(&[
                ("Jan", "2024-01-01", 0),
                ("Feb", "2024-02-01", 4),
                ("Mar", "2024-03-01", 8),
                ("Apr", "2024-04-01", 13),
                ("May", "2024-05-01", 17),
                ("Jun", "2024-06-01", 21),
                ("Jul", "2024-07-01", 26),
                ("Aug", "2024-08-01", 30),
                ("Sep", "2024-09-01", 35),
                ("Oct", "2024-10-01", 39),
                ("Nov", "2024-11-01", 43),
                ("Dec", "2024-12-01", 48),
            ])
        );
        let monday = months("2023-01-01", "2023-12-31", CalendarHeatmapWeekStart::Monday);
        assert_eq!(
            monday[..3],
            expected(&[
                ("Jan", "2023-01-01", 0),
                ("Feb", "2023-02-01", 5),
                ("Mar", "2023-03-01", 9),
            ])
        );
    }

    #[test]
    fn months_cross_year_and_leap_day_boundaries() {
        let sunday = CalendarHeatmapWeekStart::Sunday;
        assert_eq!(
            months("2024-12-01", "2025-02-28", sunday),
            expected(&[
                ("Dec", "2024-12-01", 0),
                ("Jan", "2025-01-01", 4),
                ("Feb", "2025-02-01", 8),
            ])
        );
        assert_eq!(
            months("2024-02-01", "2024-04-30", sunday),
            expected(&[
                ("Feb", "2024-02-01", 0),
                ("Mar", "2024-03-01", 4),
                ("Apr", "2024-04-01", 9),
            ])
        );
        assert_eq!(
            months("2023-02-01", "2023-04-30", sunday),
            expected(&[
                ("Feb", "2023-02-01", 0),
                ("Mar", "2023-03-01", 4),
                ("Apr", "2023-04-01", 8),
            ])
        );
    }

    #[test]
    fn colliding_or_clipped_months_are_dropped() {
        let sunday = CalendarHeatmapWeekStart::Sunday;
        assert_eq!(
            months("2024-01-29", "2024-03-05", sunday),
            expected(&[("Feb", "2024-02-01", 0), ("Mar", "2024-03-01", 4)])
        );
        let year = months("2024-01-01", "2024-12-03", sunday);
        assert_eq!(year.len(), 11);
        assert_eq!(
            year.last(),
            Some(&("Nov".to_string(), "2024-11-01".to_string(), 43))
        );
        assert_eq!(
            months("2024-03-15", "2024-03-15", sunday),
            expected(&[("Mar", "2024-03-15", 0)])
        );
        assert_eq!(
            months("2024-01-31", "2024-02-01", sunday),
            expected(&[("Jan", "2024-01-31", 0)])
        );
        let invalid = calendar_geometry(&[], "bad", "2024-01-01", sunday, None);
        assert_eq!(calendar_months(&invalid), []);
    }

    #[test]
    fn month_names_fall_back_to_english_per_index() {
        let spanish: Vec<String> = ["ene", "feb"].map(String::from).to_vec();
        assert_eq!(month_label(Some(&spanish), 0), "ene");
        assert_eq!(month_label(Some(&spanish), 2), "Mar");
        assert_eq!(month_label(None, 11), "Dec");
    }

    #[test]
    fn dates_parse_strictly() {
        assert_eq!(parse_calendar_date("1970-01-01"), Some(0));
        assert_eq!(parse_calendar_date("2024-02-29"), Some(19_782));
        assert_eq!(parse_calendar_date("2023-02-29"), None);
        assert_eq!(parse_calendar_date("1900-02-29"), None);
        assert!(parse_calendar_date("2000-02-29").is_some());
        assert_eq!(parse_calendar_date("0000-01-01"), None);
        assert!(parse_calendar_date("0001-01-01").is_some());
        assert_eq!(parse_calendar_date("2024-13-01"), None);
        assert_eq!(parse_calendar_date("2024-04-31"), None);
        assert_eq!(parse_calendar_date("2024-1-01"), None);
        assert_eq!(parse_calendar_date("2024/01/01"), None);
        assert_eq!(parse_calendar_date("2024-01-01T"), None);
        assert_eq!(parse_calendar_date("ï¼’024-01-01"), None);
        assert_eq!(parse_calendar_date(""), None);
        assert_eq!(parse_calendar_date(&"9".repeat(1_000_000)), None);
        assert_eq!(parse_calendar_date(&"2024-01-01".repeat(100_000)), None);
    }

    #[test]
    fn days_round_trip_to_iso_dates() {
        for date in [
            "0001-01-01",
            "1969-12-31",
            "1970-01-01",
            "2024-02-29",
            "9999-12-31",
        ] {
            let days = parse_calendar_date(date).unwrap();
            assert_eq!(civil_from_days(days), date);
        }
    }

    fn data() -> Vec<CalendarHeatmapDatum> {
        vec![
            CalendarHeatmapDatum::new("2024-02-28", 7.0),
            CalendarHeatmapDatum::new("2024-02-29", None),
            CalendarHeatmapDatum::new("2024-03-02", -4.5),
        ]
    }

    #[test]
    fn cells_cover_every_day_in_week_columns() {
        let model = calendar_geometry(
            &data(),
            "2024-02-26",
            "2024-03-05",
            CalendarHeatmapWeekStart::Sunday,
            None,
        );
        assert!(model.valid);
        assert_eq!(model.cells.len(), 9);
        assert_eq!(model.domain, ChartDomain::new(-4.5, 7.0));
        // 2024-02-26 is a Monday.
        assert_eq!((model.cells[0].week, model.cells[0].day), (0, 1));
        assert_eq!(model.cells[3].date, "2024-02-29");
        assert_eq!(model.cells[3].ratio, None);
        assert_eq!(model.week_count, 2);
        let monday = calendar_geometry(
            &data(),
            "2024-02-26",
            "2024-03-05",
            CalendarHeatmapWeekStart::Monday,
            None,
        );
        assert_eq!((monday.cells[0].week, monday.cells[0].day), (0, 0));
    }

    #[test]
    fn invalid_calendars_fail_closed() {
        let sunday = CalendarHeatmapWeekStart::Sunday;
        assert!(!calendar_geometry(&[], "2024-03-05", "2024-03-01", sunday, None).valid);
        assert!(!calendar_geometry(&[], "2024-01-01", "2034-12-31", sunday, None).valid);
        assert!(calendar_geometry(&[], "2024-01-01", "2034-01-07", sunday, None).valid);
        assert!(!calendar_geometry(&[], "2024-01-01", "2034-01-08", sunday, None).valid);
        assert!(!calendar_geometry(&[], "bad", "2024-01-01", sunday, None).valid);
        let outside = [CalendarHeatmapDatum::new("2024-04-01", 1.0)];
        assert!(!calendar_geometry(&outside, "2024-03-01", "2024-03-05", sunday, None).valid);
        let duplicate = [
            CalendarHeatmapDatum::new("2024-03-01", 1.0),
            CalendarHeatmapDatum::new("2024-03-01", 2.0),
        ];
        assert!(!calendar_geometry(&duplicate, "2024-03-01", "2024-03-05", sunday, None).valid);
        let infinite = [CalendarHeatmapDatum::new("2024-03-01", f64::INFINITY)];
        assert!(!calendar_geometry(&infinite, "2024-03-01", "2024-03-05", sunday, None).valid);
        let narrow = Some(ChartDomain::new(0.0, 5.0));
        assert!(!calendar_geometry(&data(), "2024-02-26", "2024-03-05", sunday, narrow).valid);
    }

    #[test]
    fn flat_and_empty_data_get_usable_domains() {
        let sunday = CalendarHeatmapWeekStart::Sunday;
        let empty = calendar_geometry(&[], "2024-01-01", "2024-01-01", sunday, None);
        assert_eq!(empty.domain, ChartDomain::new(0.0, 1.0));
        assert_eq!(empty.cells.len(), 1);
        let flat = [CalendarHeatmapDatum::new("2024-01-01", 500.0)];
        let model = calendar_geometry(&flat, "2024-01-01", "2024-01-02", sunday, None);
        assert_eq!(model.domain, ChartDomain::new(495.0, 505.0));
        let tiny = [CalendarHeatmapDatum::new("2024-01-01", 0.0)];
        let model = calendar_geometry(&tiny, "2024-01-01", "2024-01-02", sunday, None);
        assert_eq!(model.domain, ChartDomain::new(-1.0, 1.0));
    }
}