Cotton code
381 lines · 14.0 KB · RustRaw
//! The one preset↔RRULE vocabulary — the port of//! `packages/core/src/engine/recurrencePresets.ts`.//!//! Shared by the calendar's event form and the todos tool's repeat picker: two//! tools, one recurrence language. Labels stay app-side; this maps identifiers//! to rules.//!//! **A preset says how often; an END says how long.** They are two axes, and//! that is the model rather than a longer preset list because "weekly" and//! "weekly until December" are the same rhythm — a person picking the second//! has not changed their mind about the first. The split is also what keeps//! [`preset_for_rrule`] honest: it answers about the RHYTHM ALONE and still//! calls `FREQ=DAILY;COUNT=5` custom, because what it is handed is a whole//! rule; [`split_rrule`] is the reader that takes the ending off first and then//! asks. A rule Google authored whose rhythm is beyond the vocabulary//! (`FREQ=MONTHLY;BYDAY=2TU`) still comes back custom and is held VERBATIM by//! its editor — including its own ending. Rewriting half of somebody else's//! rule is worse than declining to touch it at all.use cotton_store::protocol::js::json_stringify;use crate::transforms::rrule::parse_ical_date;use crate::transforms::zoned_clock::{instant_from_zoned, zoned_parts, ZoneError, ZonedParts};/// Every preset, in the order the picker offers them.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum RecurrencePreset {    None,    Daily,    Weekdays,    Weekly,    Biweekly,    Monthly,    Yearly,}impl RecurrencePreset {    /// The identifier stored and passed over the wire.    pub const fn as_str(self) -> &'static str {        match self {            RecurrencePreset::None => "none",            RecurrencePreset::Daily => "daily",            RecurrencePreset::Weekdays => "weekdays",            RecurrencePreset::Weekly => "weekly",            RecurrencePreset::Biweekly => "biweekly",            RecurrencePreset::Monthly => "monthly",            RecurrencePreset::Yearly => "yearly",        }    }    /// `RECURRENCE_PRESETS`, in order.    pub const ALL: [RecurrencePreset; 7] = [        RecurrencePreset::None,        RecurrencePreset::Daily,        RecurrencePreset::Weekdays,        RecurrencePreset::Weekly,        RecurrencePreset::Biweekly,        RecurrencePreset::Monthly,        RecurrencePreset::Yearly,    ];    /// Read an identifier back. (Not `FromStr`: an unknown identifier is a    /// `None` a caller answers with "custom", never an error to propagate.)    pub fn parse(value: &str) -> Option<Self> {        Self::ALL.into_iter().find(|p| p.as_str() == value)    }}impl std::fmt::Display for RecurrencePreset {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// What [`preset_for_rrule`] answers: a preset, or "this is beyond the/// vocabulary and must be shown read-only".#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PresetOrCustom {    Preset(RecurrencePreset),    Custom,}impl PresetOrCustom {    pub const fn as_str(self) -> &'static str {        match self {            PresetOrCustom::Preset(preset) => preset.as_str(),            PresetOrCustom::Custom => "custom",        }    }}/// Preset → the RRULE string the engine expands.////// Monthly and yearly recur on the ANCHOR (dtstart) day — "payment on the 2nd"/// is a monthly rule anchored on the 2nd; months without the day are skipped,/// never rolled (the iCal rule).pub const fn rrule_for_preset(preset: RecurrencePreset) -> Option<&'static str> {    match preset {        RecurrencePreset::None => None,        RecurrencePreset::Daily => Some("FREQ=DAILY"),        RecurrencePreset::Weekdays => Some("FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"),        RecurrencePreset::Weekly => Some("FREQ=WEEKLY"),        RecurrencePreset::Biweekly => Some("FREQ=WEEKLY;INTERVAL=2"),        RecurrencePreset::Monthly => Some("FREQ=MONTHLY"),        RecurrencePreset::Yearly => Some("FREQ=YEARLY"),    }}/// RRULE → preset, for edit screens.////// Any rule beyond the presets (other `INTERVAL`/`BYDAY` shapes, `COUNT`,/// `UNTIL`, …) is custom — shown read-only, never silently rewritten to a/// preset.pub fn preset_for_rrule(rrule: Option<&str>) -> PresetOrCustom {    let Some(rrule) = rrule else {        return PresetOrCustom::Preset(RecurrencePreset::None);    };    let normalised = strip_rrule_prefix(rrule).trim().to_uppercase();    match normalised.as_str() {        "FREQ=DAILY" => PresetOrCustom::Preset(RecurrencePreset::Daily),        "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR" => PresetOrCustom::Preset(RecurrencePreset::Weekdays),        "FREQ=WEEKLY" => PresetOrCustom::Preset(RecurrencePreset::Weekly),        "FREQ=WEEKLY;INTERVAL=2" => PresetOrCustom::Preset(RecurrencePreset::Biweekly),        "FREQ=MONTHLY" => PresetOrCustom::Preset(RecurrencePreset::Monthly),        "FREQ=YEARLY" => PresetOrCustom::Preset(RecurrencePreset::Yearly),        _ => PresetOrCustom::Custom,    }}/// How often a rule comes round, as its line in set `dates` (`repeat.weekly`;/// a rule beyond the presets is `repeat.custom`) — `None` for a rule that/// does not repeat. The one vocabulary every surface says a repeat in,/// never the raw `FREQ=…` (walker 604bcce6: a calendar line read/// "FREQ=MONTHLY").pub fn repeat_line(rrule: Option<&str>) -> Option<&'static str> {    match preset_for_rrule(rrule.map(str::trim).filter(|rule| !rule.is_empty())) {        PresetOrCustom::Preset(RecurrencePreset::None) => None,        PresetOrCustom::Preset(RecurrencePreset::Daily) => Some("repeat.daily"),        PresetOrCustom::Preset(RecurrencePreset::Weekdays) => Some("repeat.weekdays"),        PresetOrCustom::Preset(RecurrencePreset::Weekly) => Some("repeat.weekly"),        PresetOrCustom::Preset(RecurrencePreset::Biweekly) => Some("repeat.biweekly"),        PresetOrCustom::Preset(RecurrencePreset::Monthly) => Some("repeat.monthly"),        PresetOrCustom::Preset(RecurrencePreset::Yearly) => Some("repeat.yearly"),        PresetOrCustom::Custom => Some("repeat.custom"),    }}/// `rrule.replace(/^RRULE:/i, "")`.fn strip_rrule_prefix(rrule: &str) -> &str {    if rrule.len() >= 6 && rrule[..6].eq_ignore_ascii_case("RRULE:") {        &rrule[6..]    } else {        rrule    }}// ── When it stops ────────────────────────────────────────────────────────────/// Where a repeat stops. `On` is inclusive: the named day may still hold one.#[derive(Debug, Clone, PartialEq, Eq)]pub enum RecurrenceEnd {    Never,    /// A `YYYY-MM-DD` day key in the workspace's zone.    On(String),    After(i64),}/// The end an event has until somebody says otherwise.pub const RECURRENCE_END_NEVER: RecurrenceEnd = RecurrenceEnd::Never;/// The three end kinds, in the order the picker offers them.pub const RECURRENCE_END_KINDS: &[&str] = &["never", "on", "after"];/// Why an end could not be turned into a rule.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum RecurrenceEndError {    /// The TypeScript's sentence, verbatim.    #[error("not a date key: {0}")]    NotADateKey(String),    #[error("not an occurrence count: {0}")]    NotAnOccurrenceCount(String),    #[error(transparent)]    Zone(#[from] ZoneError),}/// `YYYYMMDDTHHMMSSZ` — the iCal form [`parse_ical_date`] reads as an instant.fn to_ical_utc(instant: i64) -> Option<String> {    let days = instant.div_euclid(86_400_000);    let rest = instant.rem_euclid(86_400_000);    let (year, month, day) = crate::transforms::zoned_clock::civil_from_days(days);    Some(format!(        "{year:04}{month:02}{day:02}T{:02}{:02}{:02}Z",        rest / 3_600_000,        (rest / 60_000) % 60,        (rest / 1_000) % 60    ))}/// The instant the named local day runs out in `zone`.////// `UNTIL` is compared as an INSTANT by the expansion, so "ends on 31 December"/// has to be turned into one, and only the calendar's own zone can do that. The/// naive `T235959Z` costs a real occurrence either way: five and a half hours/// ahead of UTC it keeps a 2 a.m. event on the 1st, and five behind it drops a/// 7 p.m. event on the 31st — the last occurrence of a series, silently missing/// on the day the person named.fn end_of_local_day(date: &str, zone: &str) -> Result<i64, RecurrenceEndError> {    let trimmed = date.trim();    let parsed = parse_date_key(trimmed)        .ok_or_else(|| RecurrenceEndError::NotADateKey(json_quote(trimmed)))?;    Ok(instant_from_zoned(        ZonedParts {            year: parsed.0,            month: parsed.1,            day: parsed.2,            hour: 23,            minute: 59,            second: 59,        },        0,        zone,    )?)}/// `/^(\d{4})-(\d{2})-(\d{2})$/`.fn parse_date_key(value: &str) -> Option<(i64, i64, i64)> {    let bytes = value.as_bytes();    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {        return None;    }    if !bytes        .iter()        .enumerate()        .all(|(index, b)| index == 4 || index == 7 || b.is_ascii_digit())    {        return None;    }    Some((        value[0..4].parse().ok()?,        value[5..7].parse().ok()?,        value[8..10].parse().ok()?,    ))}/// The local day an `UNTIL` instant falls on in `zone`, as `YYYY-MM-DD`.fn local_day_of(instant: i64, zone: &str) -> Result<String, ZoneError> {    let parts = zoned_parts(instant, zone)?;    Ok(format!(        "{:04}-{:02}-{:02}",        parts.year, parts.month, parts.day    ))}/// Preset + end → the RRULE to store.////// `none` has nothing to end, so its end is ignored rather than refused: a/// person who set "after 5" and then chose "Once" has stopped repeating, not/// made a contradiction.pub fn compose_rrule(    preset: RecurrencePreset,    end: &RecurrenceEnd,    zone: &str,) -> Result<Option<String>, RecurrenceEndError> {    let Some(base) = rrule_for_preset(preset) else {        return Ok(None);    };    Ok(Some(match end {        RecurrenceEnd::Never => base.to_string(),        RecurrenceEnd::On(date) => {            let at = end_of_local_day(date, zone)?;            let ical =                to_ical_utc(at).ok_or_else(|| RecurrenceEndError::NotADateKey(json_quote(date)))?;            format!("{base};UNTIL={ical}")        }        RecurrenceEnd::After(count) => {            // The TypeScript also refuses a non-integer count; an `i64` cannot            // be one, so only the lower bound survives the port.            if *count < 1 {                return Err(RecurrenceEndError::NotAnOccurrenceCount(count.to_string()));            }            format!("{base};COUNT={count}")        }    }))}/// RRULE → the rhythm and the ending, for an edit screen.////// A rule carrying BOTH `UNTIL` and `COUNT` is custom: iCal forbids the pair,/// so whatever wrote it meant something this vocabulary cannot say, and picking/// one of the two would be inventing an answer.pub fn split_rrule(    rrule: Option<&str>,    zone: &str,) -> Result<(PresetOrCustom, RecurrenceEnd), ZoneError> {    let Some(rrule) = rrule else {        return Ok((            PresetOrCustom::Preset(RecurrencePreset::None),            RECURRENCE_END_NEVER,        ));    };    let mut rhythm: Vec<&str> = Vec::new();    let mut until: Option<&str> = None;    let mut count: Option<&str> = None;    for part in strip_rrule_prefix(rrule).trim().split(';') {        let part = part.trim();        if part.is_empty() {            continue;        }        // `part.slice(0, part.indexOf("="))` — with NO `=` that index is -1 and        // JavaScript's `slice` reads it from the END, so `NOPE` keys as `NOP`.        // It falls through to the rhythm either way; the quirk is ported so the        // two implementations cannot answer differently on a malformed part.        let key: String = match part.find('=') {            Some(eq) => part[..eq].to_uppercase(),            None => {                let mut chars: Vec<char> = part.chars().collect();                chars.pop();                chars.into_iter().collect::<String>().to_uppercase()            }        };        match key.as_str() {            "UNTIL" => until = part.find('=').map(|eq| &part[eq + 1..]),            "COUNT" => count = part.find('=').map(|eq| &part[eq + 1..]),            _ => rhythm.push(part),        }    }    if until.is_some() && count.is_some() {        return Ok((PresetOrCustom::Custom, RECURRENCE_END_NEVER));    }    let preset = preset_for_rrule(Some(&rhythm.join(";")));    if preset == PresetOrCustom::Custom {        return Ok((preset, RECURRENCE_END_NEVER));    }    if let Some(count) = count {        let n = js_parse_int_10(count);        return Ok(match n {            Some(n) if n >= 1 => (preset, RecurrenceEnd::After(n)),            _ => (PresetOrCustom::Custom, RECURRENCE_END_NEVER),        });    }    if let Some(until) = until {        let Ok(at) = parse_ical_date(until) else {            return Ok((PresetOrCustom::Custom, RECURRENCE_END_NEVER));        };        return Ok((preset, RecurrenceEnd::On(local_day_of(at, zone)?)));    }    Ok((preset, RECURRENCE_END_NEVER))}fn json_quote(value: &str) -> String {    json_stringify(&serde_json::Value::String(value.to_string()))}/// `Number.parseInt(value, 10)`, answering `None` where it answers `NaN`.fn js_parse_int_10(value: &str) -> Option<i64> {    let trimmed = value.trim_start_matches(cotton_store::protocol::js::is_js_whitespace);    let bytes = trimmed.as_bytes();    let (negative, rest) = match bytes.first() {        Some(b'-') => (true, &bytes[1..]),        Some(b'+') => (false, &bytes[1..]),        _ => (false, bytes),    };    let digits: Vec<u8> = rest        .iter()        .copied()        .take_while(u8::is_ascii_digit)        .collect();    if digits.is_empty() {        return None;    }    let magnitude: i64 = std::str::from_utf8(&digits).ok()?.parse().ok()?;    Some(if negative { -magnitude } else { magnitude })}#[cfg(test)]#[path = "recurrence_presets_tests.rs"]mod tests;