lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! A dependency-free proleptic Gregorian civil date, ported from the UTC date math in
//! `@santi020k/lumen-core` (`parseLumenDate`) and the `useCalendar` hook of `@santi020k/lumen-react`.
//!
//! Values are ISO `YYYY-MM-DD` strings, like the web adapters. JavaScript `Intl` is not available
//! on every Dioxus renderer, so month and weekday names are English (en-US); apps localize them
//! through [`CalendarLabels`](super::CalendarLabels).

// cspell:words Hinnant

use std::fmt;

/// A calendar day without a time zone.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct CivilDate {
    year: i64,
    month: u32,
    day: u32,
}

pub(crate) const MONTH_NAMES: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

pub(crate) const MONTH_SHORT_NAMES: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

/// Monday-first, like the Lumen calendar grid.
pub(crate) const WEEKDAY_SHORT_NAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

/// Monday-first, like the Lumen calendar grid.
pub(crate) const WEEKDAY_NAMES: [&str; 7] = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
];

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

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

/// Reads exactly `count` ASCII digits starting at `start`.
fn read_digits(bytes: &[u8], start: usize, count: usize) -> Option<u32> {
    let digits = bytes.get(start..start + count)?;
    let mut value = 0_u32;

    for digit in digits {
        if !digit.is_ascii_digit() {
            return None;
        }

        value = value * 10 + u32::from(digit - b'0');
    }

    Some(value)
}

impl CivilDate {
    /// A date from parts that are already known to be valid.
    pub(crate) fn new(year: i64, month: u32, day: u32) -> Option<Self> {
        if !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) {
            return None;
        }

        Some(Self { year, month, day })
    }

    /// Parses a complete `YYYY-MM-DD` date, rejecting overflowing days and the year `0000`, like
    /// `parseLumenDate`. Reads at most ten bytes, so any input length is safe.
    pub(crate) fn parse(value: &str) -> Option<Self> {
        let bytes = value.as_bytes();

        if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
            return None;
        }

        let year = read_digits(bytes, 0, 4)?;
        let month = read_digits(bytes, 5, 2)?;
        let day = read_digits(bytes, 8, 2)?;

        if year == 0 {
            return None;
        }

        Self::new(i64::from(year), month, day)
    }

    /// Parses a `YYYY-MM` month into its first day.
    pub(crate) fn parse_month(value: &str) -> Option<Self> {
        let bytes = value.as_bytes();

        if bytes.len() != 7 || bytes[4] != b'-' {
            return None;
        }

        let year = read_digits(bytes, 0, 4)?;
        let month = read_digits(bytes, 5, 2)?;

        if year == 0 {
            return None;
        }

        Self::new(i64::from(year), month, 1)
    }

    pub(crate) fn year(self) -> i64 {
        self.year
    }

    pub(crate) fn month(self) -> u32 {
        self.month
    }

    pub(crate) fn day(self) -> u32 {
        self.day
    }

    /// Days since 1970-01-01 (Howard Hinnant's `days_from_civil`).
    fn to_days(self) -> i64 {
        let year = if self.month <= 2 {
            self.year - 1
        } else {
            self.year
        };
        let era = year.div_euclid(400);
        let year_of_era = year - era * 400;
        let month = i64::from(self.month);
        let day_of_year =
            (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + i64::from(self.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 date `days` after 1970-01-01 (Howard Hinnant's `civil_from_days`).
    fn from_days(days: i64) -> Self {
        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 / 1460 + 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);

        Self {
            year,
            month: u32::try_from(month).unwrap_or(1),
            day: u32::try_from(day).unwrap_or(1),
        }
    }

    /// The date for a Unix timestamp in whole seconds (UTC).
    pub(crate) fn from_unix_seconds(seconds: i64) -> Self {
        Self::from_days(seconds.div_euclid(86_400))
    }

    pub(crate) fn add_days(self, days: i64) -> Self {
        Self::from_days(self.to_days() + days)
    }

    /// Moves by whole months and clamps the day to the target month, like `addCalendarMonths`.
    pub(crate) fn add_months(self, months: i64) -> Self {
        let index = self.year * 12 + i64::from(self.month) - 1 + months;
        let year = index.div_euclid(12);
        let month = u32::try_from(index.rem_euclid(12)).unwrap_or(0) + 1;
        let day = self.day.min(days_in_month(year, month));

        Self { year, month, day }
    }

    pub(crate) fn start_of_month(self) -> Self {
        Self { day: 1, ..self }
    }

    pub(crate) fn days_in_month(self) -> u32 {
        days_in_month(self.year, self.month)
    }

    /// The Monday-first column: Monday is 0 and Sunday is 6.
    pub(crate) fn weekday_index(self) -> usize {
        // 1970-01-01 was a Thursday (column 3).
        usize::try_from((self.to_days() + 3).rem_euclid(7)).unwrap_or(0)
    }

    pub(crate) fn same_month(self, other: Self) -> bool {
        self.year == other.year && self.month == other.month
    }

    /// `YYYY-MM`.
    pub(crate) fn month_key(self) -> String {
        let iso = self.to_string();

        iso[..iso.len() - 3].to_string()
    }

    /// The first day of the calendar grid that shows this date's month (a Monday).
    pub(crate) fn grid_start(self) -> Self {
        let first = self.start_of_month();

        first.add_days(-i64::try_from(first.weekday_index()).unwrap_or(0))
    }

    pub(crate) fn clamp_to(self, min: Option<Self>, max: Option<Self>) -> Self {
        if let Some(min) = min
            && self < min
        {
            return min;
        }

        if let Some(max) = max
            && self > max
        {
            return max;
        }

        self
    }
}

/// `YYYY-MM-DD`, with JavaScript's expanded-year form outside `0000..=9999`.
impl fmt::Display for CivilDate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if (0..=9999).contains(&self.year) {
            write!(
                formatter,
                "{:04}-{:02}-{:02}",
                self.year, self.month, self.day
            )
        } else if self.year > 9999 {
            write!(
                formatter,
                "+{:06}-{:02}-{:02}",
                self.year, self.month, self.day
            )
        } else {
            write!(
                formatter,
                "-{:06}-{:02}-{:02}",
                self.year.unsigned_abs(),
                self.month,
                self.day
            )
        }
    }
}

/// Whether optional `YYYY-MM-DD` bounds parse and are ordered, like `isLumenDateBoundsValid`.
pub(crate) fn bounds_valid(min: Option<&str>, max: Option<&str>) -> bool {
    let min_date = min.map(CivilDate::parse);
    let max_date = max.map(CivilDate::parse);

    if matches!(min_date, Some(None)) || matches!(max_date, Some(None)) {
        return false;
    }

    match (min, max) {
        (Some(min), Some(max)) if !min.is_empty() && !max.is_empty() => min <= max,
        _ => true,
    }
}

/// Today's date in UTC from the system clock, or `None` where the platform has no clock (the
/// browser renderer reads the local date through `eval` instead).
pub(crate) fn utc_today() -> Option<CivilDate> {
    #[cfg(not(target_family = "wasm"))]
    {
        let seconds = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_secs();

        Some(CivilDate::from_unix_seconds(i64::try_from(seconds).ok()?))
    }

    #[cfg(target_family = "wasm")]
    {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::{CivilDate, bounds_valid};

    fn date(value: &str) -> CivilDate {
        CivilDate::parse(value).expect("valid test date")
    }

    #[test]
    fn parses_only_complete_real_dates() {
        assert_eq!(date("2024-02-29").to_string(), "2024-02-29");
        assert!(CivilDate::parse("2023-02-29").is_none());
        assert!(CivilDate::parse("2024-13-01").is_none());
        assert!(CivilDate::parse("2024-00-10").is_none());
        assert!(CivilDate::parse("0000-01-01").is_none());
        assert!(CivilDate::parse("2024-1-01").is_none());
        assert!(CivilDate::parse("2024-01-01").is_none());
        assert!(CivilDate::parse("2024-01-01T").is_none());
        assert!(CivilDate::parse(&"9".repeat(100_000)).is_none());
        assert_eq!(
            CivilDate::parse_month("2024-03").map(|value| value.to_string()),
            Some("2024-03-01".to_string())
        );
        assert!(CivilDate::parse_month("2024-3").is_none());
    }

    #[test]
    fn date_math_matches_the_utc_calendar() {
        assert_eq!(date("2024-03-01").add_days(-1).to_string(), "2024-02-29");
        assert_eq!(date("2023-12-31").add_days(1).to_string(), "2024-01-01");
        assert_eq!(date("2024-01-31").add_months(1).to_string(), "2024-02-29");
        assert_eq!(date("2024-03-31").add_months(-1).to_string(), "2024-02-29");
        assert_eq!(date("2024-01-15").add_months(-13).to_string(), "2022-12-15");
        assert_eq!(date("9999-12-31").add_days(1).to_string(), "+010000-01-01");
        assert_eq!(date("2024-03-01").month_key(), "2024-03");
        assert_eq!(CivilDate::from_unix_seconds(0).to_string(), "1970-01-01");
        assert_eq!(
            CivilDate::from_unix_seconds(1_709_251_200).to_string(),
            "2024-03-01"
        );
    }

    #[test]
    fn weeks_start_on_monday() {
        // 2026-01-05 is a Monday; 2024-03-01 is a Friday.
        assert_eq!(date("2026-01-05").weekday_index(), 0);
        assert_eq!(date("2024-03-01").weekday_index(), 4);
        assert_eq!(date("2024-03-17").grid_start().to_string(), "2024-02-26");
        assert_eq!(date("2024-04-10").grid_start().to_string(), "2024-04-01");
    }

    #[test]
    fn clamps_and_validates_bounds() {
        let min = Some(date("2024-03-05"));
        let max = Some(date("2024-03-20"));
        assert_eq!(
            date("2024-03-01").clamp_to(min, max).to_string(),
            "2024-03-05"
        );
        assert_eq!(
            date("2024-03-25").clamp_to(min, max).to_string(),
            "2024-03-20"
        );
        assert!(bounds_valid(Some("2024-01-01"), Some("2024-12-31")));
        assert!(!bounds_valid(Some("2024-12-31"), Some("2024-01-01")));
        assert!(!bounds_valid(Some("nope"), None));
        assert!(bounds_valid(None, None));
    }
}