//! A slip line that reads a date, resolved here and drawn as given. //! //! A day is read in the reader's zone against the instant the caller hands //! in: the core never reads a clock. The forms are typed (`RelativeDay`) and //! said in one place, so no face turns a date into words of its own. //! //! THE WORDS ARE LINES (contract 3, lane T1): every word a date is said in — //! month and weekday names, today/tomorrow, "4 days late", the clock — is a //! line of the `dates` set (`kits/shell/lines/dates.json`), said through //! [`DateWords`] from the database's rows first. Nothing here holds English. //! //! THEIR CLOCK ([`their_time`]): a `zone` column (a person's IANA zone) reads //! as the time it is there now, in the `dates` set's clock ("7:30 pm") — only //! when that zone's UTC offset at the instant differs from the reader's zone. //! Offsets, not names: Asia/Calcutta and Asia/Kolkata are one clock, and //! London and New York differ by five hours or four depending on the week. A //! zone nobody can place, or one keeping the reader's clock, says nothing. use serde_json::{Map, Value}; use super::FACT_JOIN; use crate::definitions::{Column, ColumnType, Form, SlipCaption, TableDefinition}; use crate::rules::shell_lines::{number, LineRow, LineSet}; use crate::transforms::zoned_clock::{civil_from_days, day_number, next_yearly_occurrence, weekday_of_day_number, yearly_month_day, zoned_parts}; /// The resolved foot of a slip on an upcoming list (under a day heading). pub const SLIP_FOOT_KEY: &str = "@slip_foot"; /// Whether that foot reads in red: the record is late. pub const SLIP_FOOT_LATE_KEY: &str = "@slip_foot_late"; /// The day an upcoming list files a slip under, as its [`DayParts`]. pub const SLIP_DAY_KEY: &str = "@slip_day"; /// The resolved words of a slip on a tile's strip, where no heading names the day. pub const SLIP_STRIP_KEY: &str = "@slip_strip"; pub const SLIP_STRIP_LATE_KEY: &str = "@slip_strip_late"; /// The `dates` lines naming each month, January first. const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; /// The `dates` lines naming each weekday, Sunday first. const WEEKDAYS: [&str; 7] = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; /// The `dates` line set as one database says it: the words every date form /// is said in. A line the set lacks says nothing, which the guard over the /// kit file keeps from happening. #[derive(Debug, Clone, PartialEq)] pub struct DateWords(LineSet); impl DateWords { /// The kit's words, when no database is at hand. pub fn shipped() -> &'static DateWords { static WORDS: std::sync::OnceLock = std::sync::OnceLock::new(); WORDS.get_or_init(|| DateWords(LineSet::shipped("dates").expect("the kit ships the dates set"))) } /// The words a database says: its `lines` rows first, the kit for the rest. pub fn of_rows(rows: &[LineRow]) -> DateWords { DateWords(LineSet::of_rows("dates", rows).expect("the kit ships the dates set")) } fn say(&self, line: &str, fills: &[(&str, &str)]) -> String { self.0.say(line, fills).unwrap_or_default() } fn counted(&self, line: &str, n: i64) -> String { self.say(line, &[("n", &number(n))]) } /// A month's short name, `month` 1–12. pub fn month(&self, month: i64) -> String { MONTHS.get((month - 1) as usize).map(|line| self.say(&format!("months.{line}"), &[])).unwrap_or_default() } /// A weekday's short name, `weekday` 0 (Sunday) – 6. pub fn weekday(&self, weekday: i64) -> String { WEEKDAYS.get(weekday as usize).map(|line| self.say(&format!("weekdays.{line}"), &[])).unwrap_or_default() } /// A day's parts for a heading drawn as a large numeral: the date of the /// month ("20"), the weekday's whole name ("Friday"), the month's whole /// name ("November") and the year. pub fn numeral_parts(&self, day: i64) -> (String, String, String, i64) { let (year, month, date) = civil_from_days(day); let name = MONTHS.get((month - 1) as usize).map(|line| self.say(&format!("month_names.{line}"), &[])).unwrap_or_default(); (date.to_string(), self.weekday_name(weekday_of_day_number(day)), name, year) } /// A weekday's whole name ("Friday"), `weekday` 0 (Sunday) – 6. pub fn weekday_name(&self, weekday: i64) -> String { WEEKDAYS.get(weekday as usize).map(|line| self.say(&format!("weekday_names.{line}"), &[])).unwrap_or_default() } /// A day named on its own, at the head of a line ("Today"), when it is /// today, tomorrow or yesterday (`offset` from today); else none. pub fn heading(&self, offset: i64) -> Option { let line = match offset { 0 => "heading.today", 1 => "heading.tomorrow", -1 => "heading.yesterday", _ => return None, }; Some(self.say(line, &[])) } /// "1 October", or "1 October 2025" outside the reader's year. pub fn day_long(&self, day: i64, this_year: i64) -> String { let (year, month, date) = civil_from_days(day); let name = MONTHS.get((month - 1) as usize).map(|line| self.say(&format!("month_names.{line}"), &[])).unwrap_or_default(); let fills = [("date", date.to_string()), ("month", name), ("year", year.to_string())]; let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); self.say(if year == this_year { "day_long.this_year" } else { "day_long.other_year" }, &fills) } /// Two ends as one span: "1 Jul – 31 Jul 2026". pub fn span(&self, start: &str, end: &str) -> String { self.say("span", &[("start", start), ("end", end)]) } /// "All day": a day with no hour, under a heading naming the day. pub fn all_day(&self) -> String { self.say("all_day", &[]) } /// "September", or "September 2025" outside the reader's year. pub fn month_title(&self, year: i64, month: i64, this_year: i64) -> String { let name = MONTHS.get((month - 1) as usize).map(|line| self.say(&format!("month_names.{line}"), &[])).unwrap_or_default(); let fills = [("month", name), ("year", year.to_string())]; let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); self.say(if year == this_year { "month_title.this_year" } else { "month_title.other_year" }, &fills) } /// "Nov 2025": a month and its year, short, where a list says an item of another year. pub fn month_year(&self, year: i64, month: i64) -> String { self.say("month_year", &[("month", &self.month(month)), ("year", &year.to_string())]) } /// "11 Oct", or "11 Oct 2025" outside the reader's year. pub fn day_month(&self, day: i64, this_year: i64) -> String { let (year, month, date) = civil_from_days(day); let fills = [("date", date.to_string()), ("month", self.month(month)), ("year", year.to_string())]; let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); self.say(if year == this_year { "day_month.this_year" } else { "day_month.other_year" }, &fills) } /// "1 day late", "4 days late"; "late" for a stated hour passed today. pub fn days_late(&self, days: i64) -> String { match days { d if d <= 0 => self.say("late.now", &[]), d => self.counted("late.days", d), } } /// "Thu 23 Oct", or "Fri 8 Jan 2027" outside the reader's year. pub fn weekday_date(&self, day: i64, this_year: i64) -> String { let (year, month, date) = civil_from_days(day); let fills = [ ("weekday", self.weekday(weekday_of_day_number(day))), ("date", date.to_string()), ("month", self.month(month)), ("year", year.to_string()), ]; let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); let line = if year == this_year { "weekday_date.this_year" } else { "weekday_date.other_year" }; self.say(line, &fills) } /// "Tuesday 27 Oct", or "Friday 8 Jan 2027" outside the reader's year. pub fn weekday_name_date(&self, day: i64, this_year: i64) -> String { let (year, month, date) = civil_from_days(day); let fills = [ ("weekday", self.weekday_name(weekday_of_day_number(day))), ("date", date.to_string()), ("month", self.month(month)), ("year", year.to_string()), ]; let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); let line = if year == this_year { "weekday_date.this_year" } else { "weekday_date.other_year" }; self.say(line, &fills) } /// "Sat 3 Oct 2026": the weekday date with its year, whatever the year. pub fn weekday_date_year(&self, day: i64) -> String { let (year, month, date) = civil_from_days(day); let fills = [ ("weekday", self.weekday(weekday_of_day_number(day))), ("date", date.to_string()), ("month", self.month(month)), ("year", year.to_string()), ]; let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); self.say("weekday_date.other_year", &fills) } /// How long before now `seconds` ago is: "just now", "2 min ago", /// "3 h ago", "yesterday", "4 days ago"; `None` more than a minute ahead /// or 30 days back or more, where a day says it better. pub fn ago(&self, seconds: i64) -> Option { Some(match seconds { s if s < -60 => return None, s if s < 60 => self.say("ago.just_now", &[]), s if s < 3600 => self.counted("ago.minutes", s / 60), s if s < 86_400 => self.counted("ago.hours", s / 3600), s if s < 2 * 86_400 => self.say("ago.yesterday", &[]), s if s < 30 * 86_400 => self.counted("ago.days", s / 86_400), _ => return None, }) } /// `seconds` still to go: "2 d 23 h", "2 h 24 min", "4 min" (a part /// minute rounds up, so "0 min" is never said); `None` once none are left. pub fn left(&self, seconds: i64) -> Option { if seconds <= 0 { return None; } let minutes = (seconds + 59) / 60; let (d, h, m) = ((minutes / 1440).to_string(), ((minutes % 1440) / 60).to_string(), (minutes % 60).to_string()); let fills = [("d", d.as_str()), ("h", h.as_str()), ("m", m.as_str())]; Some(match (d.as_str(), h.as_str(), m.as_str()) { ("0", "0", _) => self.say("left.minutes", &fills), ("0", _, "0") => self.say("left.hours", &fills), ("0", _, _) => self.say("left.hours_minutes", &fills), (_, "0", _) => self.say("left.days", &fills), _ => self.say("left.days_hours", &fills), }) } /// How often a rule comes round ("Weekly", "Custom repeat"), from the /// `repeat.*` lines; `None` for a rule that does not repeat. pub fn repeat(&self, rrule: Option<&str>) -> Option { crate::transforms::recurrence_presets::repeat_line(rrule).map(|line| self.say(line, &[])) } /// A wall-clock time: "7:30 pm". pub fn clock(&self, hour: i64, minute: i64) -> String { let hour12 = match hour % 12 { 0 => 12, hour => hour, }; let line = if hour < 12 { "clock.am" } else { "clock.pm" }; self.say(line, &[("hour", &hour12.to_string()), ("minute", &format!("{minute:02}"))]) } /// A length of time in milliseconds, each unit a `dates.duration` line /// picked by its count ("1 h 4 min", "2 h", "42 s", "1.5 s"); `None` /// under one millisecond. pub fn duration(&self, millis: i64) -> Option { if millis < 1 { return None; } let (hours, minutes, rest) = (millis / 3_600_000, (millis % 3_600_000) / 60_000, millis % 60_000); let mut words = Vec::new(); if hours > 0 { words.push(self.counted("duration.hours", hours)); } if minutes > 0 { words.push(self.counted("duration.minutes", minutes)); } if rest > 0 { let seconds = format!("{:.3}", rest as f64 / 1000.0); let seconds = seconds.trim_end_matches('0').trim_end_matches('.'); words.push(self.say("duration.seconds", &[("n", seconds)])); } Some(words.join(" ")) } /// "missed 3": how many of a series' records went by undone. pub fn missed(&self, count: i64) -> String { self.counted("missed", count) } /// "back tomorrow": when a snoozed record comes back. pub fn back(&self, when: &str) -> String { self.say("back", &[("when", when)]) } /// "in 2 h 30 min": the time left to a near instant. pub fn countdown(&self, left: &str) -> String { self.say("countdown", &[("left", left)]) } } /// A day said against today, as a typed form. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RelativeDay { Today, Tomorrow, Yesterday, /// A day gone, `n` calendar days back (two or more), on a table whose /// records are owed by their day (`upcoming.late`). DaysLate(i64), /// A day gone, `n` calendar days back (two or more). DaysAgo(i64), /// Whole months on (positive) or back (negative), for a count said all /// the way past 35 days. Months(i64), /// A day to come, `n` calendar days on (two or more). InDays(i64), /// Beyond the near window: the short weekday date ("Thu 23 Oct"), with /// the year only when it is not the reader's year. On { day: i64, this_year: i64 }, } impl RelativeDay { /// `day` against `today` (both day numbers). Within `near` days either /// side, the count; beyond it, the weekday date. A `near` of one keeps /// only today, tomorrow and yesterday. pub fn of(day: i64, today: i64, near: i64) -> Self { let this_year = civil_from_days(today).0; match day - today { 0 => Self::Today, 1 => Self::Tomorrow, -1 => Self::Yesterday, n if n > 1 && n <= near => Self::InDays(n), n if n < -1 && -n <= near => Self::DaysLate(-n), _ => Self::On { day, this_year }, } } /// `day` as a slip caption says it: the count within `near` days, past /// days "ago" (or "late" where the table owes its records by their day); /// beyond `near` the weekday date, unless `counted` asks for the count /// all the way (months past 35 days). pub fn caption(day: i64, today: i64, near: i64, counted: bool, owed: bool) -> Self { let back = |n: i64| if owed { Self::DaysLate(n) } else { Self::DaysAgo(n) }; match Self::of(day, today, near) { Self::DaysLate(n) => back(n), Self::On { .. } if counted => match day - today { n if n.abs() > 35 => Self::Months(n / 30), n if n > 0 => Self::InDays(n), n => back(-n), }, other => other, } } /// The day said in `dates`' words. pub fn words(self, dates: &DateWords) -> String { match self { Self::Today => dates.say("relative.today", &[]), Self::Tomorrow => dates.say("relative.tomorrow", &[]), Self::Yesterday => dates.say("relative.yesterday", &[]), Self::DaysLate(n) => dates.days_late(n), Self::DaysAgo(n) => dates.counted("relative.days_ago", n), Self::InDays(n) => dates.counted("relative.in_days", n), Self::Months(n) if n > 0 => dates.counted("relative.in_months", n), Self::Months(n) => dates.counted("relative.months_ago", -n), Self::On { day, this_year } => dates.weekday_date(day, this_year), } } } /// A wall-clock moment in the reader's zone: its day number and minute of /// the day. A bare date is that day with no hour. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Moment { pub day: i64, pub minute: i64, } impl Moment { /// Whether the moment states an hour: midnight is a bare day. pub fn timed(self) -> bool { self.minute != 0 } pub(crate) fn clock(self, dates: &DateWords) -> String { dates.clock(self.minute / 60, self.minute % 60) } /// The instant `now` on the reader's wall clock. pub fn now(now: chrono::DateTime, zone: &str) -> Option { let at = zoned_parts(now.timestamp_millis(), zone).ok()?; Some(Self { day: day_number(at.year, at.month, at.day), minute: at.hour * 60 + at.minute }) } /// A stored date ("2026-10-23") or instant ("2026-10-23T09:30:00+05:30") /// read in `zone`. A bare date is that calendar day wherever the reader is. pub fn parse(text: &str, zone: &str) -> Option { let text = text.trim(); if text.as_bytes().get(10) == Some(&b'T') { let ms = cotton_store::protocol::js::parse_date_ms(text)?; let at = zoned_parts(ms, zone).ok()?; return Some(Self { day: day_number(at.year, at.month, at.day), minute: at.hour * 60 + at.minute }); } if text.len() != 10 { return None; } let year: i64 = text.get(..4)?.parse().ok()?; let month: i64 = text.get(5..7)?.parse().ok()?; let day: i64 = text.get(8..10)?.parse().ok()?; if !(1..=12).contains(&month) || !(1..=31).contains(&day) { return None; } Some(Self { day: day_number(year, month, day), minute: 0 }) } } /// A stored day or instant as a face names it where no heading has: the /// weekday date ("Wed 1 Oct", the year outside the reader's), then /// " · 9:30 am" when it states an hour. Read in `zone` against `now`. pub fn face_day_words(text: &str, zone: &str, now: Option>, dates: &DateWords) -> Option { let at = Moment::parse(text, zone)?; let this_year = now.and_then(|now| Moment::now(now, zone)).map_or(civil_from_days(at.day).0, |today| civil_from_days(today.day).0); let day = dates.weekday_date(at.day, this_year); Some(match at.timed() { true => format!("{day}{FACT_JOIN}{}", at.clock(dates)), false => day, }) } /// Where a record's date parts travel: one [`DayParts`] per date column. pub const DAY_PARTS_KEY: &str = "@day_parts"; /// A stored date as typed parts every surface draws (contract 7): a field /// card picks `near` or `dated` by its page's one form and shows `late` /// only where its definition calls the date overdue; a list heads a day /// with `heading` and a month with `month_title`; a slip under a day /// heading says `under_day`, under a month `weekday_date`, under no heading /// `recent`. Said in the reader's zone against the read's own now, in the /// `dates` set's words. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct DayParts { /// The day as a key ("2026-10-15"), so a surface compares or groups /// days without reading a calendar. pub day: String, /// "Today", "Tomorrow", "Yesterday", else the weekday's name, within a /// week either side; none past it. #[serde(skip_serializing_if = "Option::is_none")] pub near: Option, /// "11 Oct", with the year outside the reader's. pub dated: String, /// A page headed by its day: the weekday's name ("Wednesday") over the /// long day ("1 October", the year outside the reader's). pub weekday_name: String, pub day_long: String, /// "Tue 6 Oct", with the year outside the reader's. pub weekday_date: String, /// The heading over a day's records: "Today", "Tomorrow", "Yesterday", /// else the weekday date. pub heading: String, /// Where no heading names the day: the clock today ("Today" for a bare /// day), "Yesterday", else the weekday date. pub recent: String, /// Under a heading naming the day: the clock, or "All day". pub under_day: String, /// The clock, when the date states an hour. #[serde(skip_serializing_if = "Option::is_none")] pub clock: Option, /// "2 days late", or "late" for a stated hour passed today; none when /// the date is not behind. #[serde(skip_serializing_if = "Option::is_none")] pub late: Option, /// The month as a key ("2026-09") and as a list heads it ("September", /// "September 2025" outside the reader's year). pub month: String, pub month_title: String, /// The calendar leaf: the day of the month and the month's short name. pub leaf_day: i64, pub leaf_month: String, /// A date with an `until` column, as one range: "1 Jul – 31 Jul 2026", /// the year once at the end, both years when the span crosses one; the /// long day alone when both ends are one day or there is no end. #[serde(skip_serializing_if = "Option::is_none")] pub range: Option, /// The weekday date and the clock ("Mon 5 Oct · 3:24 am"); the day /// alone when the moment states no hour. pub full: String, /// How long ago a timed moment in the last two days was ("just now", /// "5 min ago", "3 h ago", "yesterday"), else nil. #[serde(skip_serializing_if = "Option::is_none")] pub ago: Option, /// A yearly date, said by its next time round: "Turns 34 on Mon 17 Aug" /// when its year is known, "Birthday Mon 17 Aug" when it is not. The /// other parts are that next day's. #[serde(skip_serializing_if = "Option::is_none")] pub yearly: Option, /// The same on a field card, whose leaf already says the day: "turns 34 /// tomorrow", "in 21 days". #[serde(skip_serializing_if = "Option::is_none")] pub yearly_card: Option, } /// Every date column of a record, as [`DayParts`] by key; a yearly one as /// its next time round. pub fn day_parts(definition: &TableDefinition, data: &Map, zone: &str, now: chrono::DateTime, dates: &DateWords) -> Map { let Some(today) = Moment::now(now, zone) else { return Map::new() }; definition .columns .iter() .filter(|column| column.column_type == ColumnType::Date && column.secret != Some(true)) .filter_map(|column| { let text = data.get(&column.key)?.as_str()?; if column.yearly == Some(true) { let parts = yearly_parts(text, zone, today, dates)?; return Some((column.key.clone(), serde_json::to_value(parts).ok()?)); } let at = Moment::parse(text, zone)?; let mut parts = day_part(at, today, dates); if let Some(until) = column.until.as_deref() { let end = data.get(until).and_then(Value::as_str).and_then(|text| Moment::parse(text, zone)); parts.range = Some(day_range(at, end, today, dates)); } Some((column.key.clone(), serde_json::to_value(parts).ok()?)) }) .collect() } /// One stamp of any read (an ISO moment or a bare day) as its parts, in the /// reader's zone against the read's now; nil for anything that is not a date. pub fn stamp_parts(text: &str, zone: &str, now: chrono::DateTime, dates: &DateWords) -> Option { let today = Moment::now(now, zone)?; Some(day_part(Moment::parse(text, zone)?, today, dates)) } /// Each named stamp on `object` as its parts, under `@day_parts` beside the /// stamps themselves; a stamp that is absent or not a date is left out. pub fn attach_stamp_parts(object: &mut Map, keys: &[&str], zone: &str, now: chrono::DateTime, dates: &DateWords) { let parts: Map = keys .iter() .filter_map(|key| { let parts = stamp_parts(object.get(*key)?.as_str()?, zone, now, dates)?; Some((key.to_string(), serde_json::to_value(parts).ok()?)) }) .collect(); if !parts.is_empty() { object.insert(DAY_PARTS_KEY.into(), Value::Object(parts)); } } /// A yearly date's parts: its next time round, today counting as next, and /// the sentence that says it (see [`DayParts::yearly`]). pub fn yearly_parts(text: &str, zone: &str, today: Moment, dates: &DateWords) -> Option { let (month, day) = yearly_month_day(text.trim())?; let on = civil_from_days(today.day); let next = next_yearly_occurrence(month, day, on); let next_day = day_number(next.0, next.1, next.2); let mut parts = day_part(Moment { day: next_day, minute: 0 }, today, dates); let said = dates.weekday_date(next_day, next.0); let age = dated(text, zone).and_then(|born| years_completed(born, next)); parts.yearly = Some(match age { Some(age) => dates.0.say("yearly.turns", &[("n", &age.to_string()), ("day", &said)]).unwrap_or_default(), None => dates.0.say("yearly.birthday", &[("day", &said)]).unwrap_or_default(), }); let when = match next_day - today.day { 0 => dates.say("relative.today", &[]), 1 => dates.say("relative.tomorrow", &[]), n => dates.counted("relative.in_days", n), }; parts.yearly_card = Some(match age { Some(age) => dates.0.say("yearly.turns_when", &[("n", &age.to_string()), ("when", &when)]).unwrap_or_default(), None => when, }); Some(parts) } /// Two days as one range (see [`DayParts::range`]). pub fn day_range(from: Moment, until: Option, today: Moment, dates: &DateWords) -> String { match until.filter(|end| end.day != from.day) { None => dates.day_long(from.day, civil_from_days(today.day).0), Some(end) => { let end_year = civil_from_days(end.day).0; // The far end always names its year; the near end only when the // span crosses one. let start = dates.day_month(from.day, end_year); let close = dates.day_month(end.day, end_year + 1); dates.span(&start, &close) } } } /// One moment as its parts, against `today`. pub fn day_part(at: Moment, today: Moment, dates: &DateWords) -> DayParts { let (year, month, date) = civil_from_days(at.day); let this_year = civil_from_days(today.day).0; let offset = at.day - today.day; let near = dates .heading(offset) .or_else(|| (offset.abs() < 7).then(|| dates.weekday_name(weekday_of_day_number(at.day)))); let late = match today.day - at.day { behind if behind > 0 => Some(dates.days_late(behind)), 0 if at.timed() && at.minute < today.minute => Some(dates.days_late(0)), _ => None, }; let weekday_date = dates.weekday_date(at.day, this_year); let clock = at.timed().then(|| at.clock(dates)); let heading = dates.heading(offset).unwrap_or_else(|| weekday_date.clone()); let recent = match (offset, &clock) { (0, Some(clock)) => clock.clone(), (0 | -1, _) => heading.clone(), _ => weekday_date.clone(), }; let full = match &clock { Some(clock) => dates.say("full", &[("day", &weekday_date), ("clock", clock)]), None => weekday_date.clone(), }; let gone = (today.day - at.day) * 1440 + today.minute - at.minute; let ago = at.timed().then_some(gone).and_then(|gone| match gone { 0 => Some(dates.say("ago.now", &[])), 1..60 => Some(dates.counted("ago.minutes", gone)), 60..1440 => Some(dates.counted("ago.hours", gone / 60)), 1440..2880 => Some(dates.say("relative.yesterday", &[])), _ => None, }); DayParts { day: format!("{year:04}-{month:02}-{date:02}"), full, ago, near, dated: dates.day_month(at.day, this_year), weekday_name: dates.weekday_name(weekday_of_day_number(at.day)), day_long: dates.day_long(at.day, this_year), heading, recent, under_day: clock.clone().unwrap_or_else(|| dates.all_day()), weekday_date, clock, late, month: format!("{year:04}-{month:02}"), month_title: dates.month_title(year, month, this_year), leaf_day: date, leaf_month: dates.month(month), range: None, yearly: None, yearly_card: None, } } /// A resolved line and whether it reads in red. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DatedLine { pub text: String, pub late: bool, } impl DatedLine { fn plain(text: String) -> Self { Self { text, late: false } } } /// Whether the slip's toggle is on (done, dropped): its foot is its own date. fn toggled(definition: &TableDefinition, data: &Map) -> bool { let Some(column) = definition.slip.toggle.as_deref().and_then(|key| definition.column(key)) else { return false }; let value = data.get(&column.key); match column.column_type { ColumnType::Bool => value.and_then(Value::as_bool).unwrap_or(false), ColumnType::Choice => { let (Some(first), Some(value)) = (column.choices.as_ref().and_then(|choices| choices.first()), value.and_then(Value::as_str)) else { return false }; match &definition.slip.toggle_on { Some(on) => on.iter().any(|one| one == value), None => value != first, } } _ => false, } } /// The moment a record is next due — the latest of its `upcoming` dates /// holding one — and which date it was (0 is the record's own day). A later /// date (a snooze) counts only while it ends today or after: one that ended /// on a day gone is over, and the record is owed from its own day. pub fn upcoming_at(definition: &TableDefinition, data: &Map, zone: &str, today: i64) -> Option<(Moment, usize)> { let dates = definition.upcoming.as_ref()?.dates.as_ref()?; let mut best: Option<(Moment, usize)> = None; for (index, key) in dates.iter().enumerate() { let Some(at) = data.get(key).and_then(Value::as_str).and_then(|text| Moment::parse(text, zone)) else { continue }; if index > 0 && at.day < today { continue; } if best.is_some_and(|(held, _)| held >= at) { continue; } best = Some((at, index)); } best } /// Whether a moment falls past the last day standing under its own heading /// (under the closed "Later" group of a list that has one). fn is_later(definition: &TableDefinition, at: Moment, today: i64) -> bool { let Some(upcoming) = &definition.upcoming else { return false }; upcoming.later.is_some() && at.day.max(today) > today + i64::from(upcoming.horizon.unwrap_or(7)) } /// The foot of a slip on an upcoming list, whose day heading already names /// the day: for a day gone, that day and how late ("Sun 27 Sep · 4 days /// late", then " · missed 3" for a series standing for several), in red; for /// a snooze ending today or later, when it comes back, in that date column's /// reading ("Snoozed until 3:00 pm"); under Later the day and its hour; else /// the hour when the record states one, red once passed; else nothing. pub fn upcoming_foot( definition: &TableDefinition, data: &Map, zone: &str, now: chrono::DateTime, missed: Option, dates: &DateWords, ) -> Option { if toggled(definition, data) { return None; } let now = Moment::now(now, zone)?; let today = now.day; let this_year = civil_from_days(today).0; let (next, index) = upcoming_at(definition, data, zone, today)?; if next.day < today { let mut said = vec![dates.weekday_date(next.day, this_year), dates.days_late(today - next.day)]; said.extend(missed.filter(|count| *count > 1).map(|count| dates.missed(count))); return Some(DatedLine { text: said.join(FACT_JOIN), late: true }); } if index > 0 { let when = match (next.day == today, next.timed()) { (true, true) => next.clock(dates), (true, false) => RelativeDay::Today.words(dates), (false, _) => dates.weekday_date(next.day, this_year), }; let key = definition.upcoming.as_ref()?.dates.as_ref()?.get(index)?; let reading = definition.column(key).and_then(|column| column.reading.as_deref()).filter(|reading| reading.contains("{value}")); return Some(DatedLine::plain(reading.map_or_else(|| when.clone(), |reading| reading.replace("{value}", &when)))); } if is_later(definition, next, today) { let day = dates.weekday_date(next.day, this_year); return Some(DatedLine::plain(match next.timed() { true => format!("{day}{FACT_JOIN}{}", next.clock(dates)), false => day, })); } next.timed().then(|| DatedLine { text: next.clock(dates), late: next < now }) } /// A tile strip's words for work still to do, where no heading names the /// day: how late in red, the hour (red once passed), today, tomorrow, the /// weekday date, or when a snooze brings it back. pub fn upcoming_strip( definition: &TableDefinition, data: &Map, zone: &str, now: chrono::DateTime, dates: &DateWords, ) -> Option { if toggled(definition, data) { return None; } let now = Moment::now(now, zone)?; let today = now.day; let (next, index) = upcoming_at(definition, data, zone, today)?; if next.day < today { return Some(DatedLine { text: dates.days_late(today - next.day), late: true }); } let today_timed = next.day == today && next.timed(); let day = RelativeDay::of(next.day, today, 1).words(dates); if index > 0 { return Some(DatedLine::plain(dates.back(&if today_timed { next.clock(dates) } else { day }))); } Some(match today_timed { true => DatedLine { text: next.clock(dates), late: next < now }, false => DatedLine::plain(day), }) } /// How many late open records each series holds in one answer, so the one /// slip standing for them says how many were missed. pub fn missed_by_series<'a>( definition: &TableDefinition, records: impl IntoIterator>, zone: &str, now: chrono::DateTime, ) -> std::collections::BTreeMap { let mut missed = std::collections::BTreeMap::new(); let (Some(key), Some(today)) = ( definition.upcoming.as_ref().and_then(|upcoming| upcoming.series.as_deref()), Moment::now(now, zone).map(|now| now.day), ) else { return missed }; for data in records { let Some(series) = data.get(key).and_then(Value::as_str).filter(|series| !series.is_empty()) else { continue }; if toggled(definition, data) { continue; } if upcoming_at(definition, data, zone, today).is_some_and(|(at, _)| at.day < today) { *missed.entry(series.to_string()).or_insert(0) += 1; } } missed } /// Write the foot and strip lines into a record's data, beside its typed /// columns, for a table whose list is split by day. pub fn attach_dated_lines( definition: &TableDefinition, data: &mut Map, zone: &str, now: chrono::DateTime, missed: &std::collections::BTreeMap, dates: &DateWords, ) { if definition.upcoming.is_none() { return; } let series = definition.upcoming.as_ref().and_then(|upcoming| upcoming.series.as_deref()) .and_then(|key| data.get(key)).and_then(Value::as_str).and_then(|series| missed.get(series)).copied(); // The day an upcoming list files the record under, as its parts: the // list heads that day with `heading` and never reads a calendar. let day = Moment::now(now, zone).and_then(|today| upcoming_at(definition, data, zone, today.day).map(|(at, _)| day_part(at, today, dates))); data.insert(SLIP_DAY_KEY.into(), day.and_then(|day| serde_json::to_value(day).ok()).unwrap_or(Value::Null)); let foot = upcoming_foot(definition, data, zone, now, series, dates); let strip = upcoming_strip(definition, data, zone, now, dates); for (text_key, late_key, line) in [(SLIP_FOOT_KEY, SLIP_FOOT_LATE_KEY, foot), (SLIP_STRIP_KEY, SLIP_STRIP_LATE_KEY, strip)] { data.insert(late_key.into(), Value::Bool(line.as_ref().is_some_and(|line| line.late))); data.insert(text_key.into(), line.map(|line| Value::String(line.text)).unwrap_or(Value::Null)); } } /// How near an instant ahead must be for a caption to say the time left /// ("in 2 h 30 min") rather than its day and clock. const COUNTDOWN_SECONDS: i64 = 6 * 3600; /// A date's age, as a typed form: the years completed by the reader's day /// (`caption.date_form` "age": "34"), or the age it comes round to next on a /// yearly date ("turns": "turns 35"). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DateAge { Age(i64), Turns(i64), } impl DateAge { /// The age said in `dates`' words. pub fn words(self, dates: &DateWords) -> String { match self { Self::Age(years) => dates.counted("age.years", years), Self::Turns(years) => dates.counted("age.turns", years), } } } /// The whole years from `born` to `on` (each year, month, day): a year is /// completed on its day, or on the 28th of February for the 29th in a /// common year, as a yearly date comes round. None before `born`. pub fn years_completed(born: (i64, i64, i64), on: (i64, i64, i64)) -> Option { let (year, month, day) = next_yearly_occurrence(born.1, born.2, (on.0, 1, 1)); let reached = day_number(on.0, on.1, on.2) >= day_number(year, month, day); let years = on.0 - born.0 - i64::from(!reached); (years >= 0 && day_number(on.0, on.1, on.2) >= day_number(born.0, born.1, born.2)).then_some(years) } /// The day a stored date names, with its year: none for a yearly date /// kept without one ("--08-17"). fn dated(text: &str, zone: &str) -> Option<(i64, i64, i64)> { if text.trim().starts_with("--") { return None; } Moment::parse(text, zone).map(|at| civil_from_days(at.day)) } /// A date under a slip's `caption.dates`, said against the reader's now in /// their zone: "in 2 h 30 min" within six hours ahead; else the day as /// `RelativeDay` says it, then the clock time when the value states one /// ("in 5 days · 4:00 pm", "today · 4:00 pm"). Red for a day gone on a table /// that owes its records by their day (`upcoming.late`). A yearly date is /// said by the next time it comes round ("in 12 days"), never late. /// /// `caption.date_form` may choose the date's age instead ([`DateAge`]): /// "age" says the years completed alone ("34"); "turns", on a yearly date, /// its next day then the age it comes round to ("in 12 days · turns 35"). A /// date with no year says its day as without them. pub fn caption_date_line( definition: &TableDefinition, column: &Column, text: &str, zone: &str, now: chrono::DateTime, dates: &DateWords, ) -> Option { let caption = definition.slip.caption.as_ref(); let form = caption.and_then(SlipCaption::leading_form); let near = caption.and_then(|caption| caption.near).map_or(7, i64::from); date_form_line(definition, column, text, zone, now, form, near, dates) } /// A date said in the form a definition names for it (contract 6), or with /// none in the caption's default: the count within `near` days, the hour /// when it states one, a countdown within six hours ahead. `weekday_date` /// says the weekday date always; `countdown` counts any instant ahead down; /// `since` says the whole weeks gone alone ("3 weeks"), under a week /// the relative day; /// `late` says a day gone as how late, in red, on any table; `relative` /// counts all the way; `age`, `turns` and `next_occurrence` as above. #[allow(clippy::too_many_arguments)] pub fn date_form_line( definition: &TableDefinition, column: &Column, text: &str, zone: &str, now: chrono::DateTime, form: Option
, near: i64, dates: &DateWords, ) -> Option { let today = Moment::now(now, zone)?.day; let this_year = civil_from_days(today).0; let counted = matches!(form, Some(Form::Relative | Form::NextOccurrence)); let on = civil_from_days(today); if form == Some(Form::Age) { if let Some(age) = dated(text, zone).and_then(|born| years_completed(born, on)) { return Some(DatedLine::plain(DateAge::Age(age).words(dates))); } } if column.yearly == Some(true) { let (month, day) = yearly_month_day(text.trim())?; let next = next_yearly_occurrence(month, day, on); let next_day = day_number(next.0, next.1, next.2); let mut said = vec![match form { Some(Form::WeekdayDate) => dates.weekday_date(next_day, this_year), Some(Form::WeekdayNameDate) => dates.weekday_name_date(next_day, this_year), Some(Form::WeekdayDateYear) => dates.weekday_date_year(next_day), _ => RelativeDay::caption(next_day, today, near, counted, false).words(dates), }]; if form == Some(Form::Turns) { said.extend(dated(text, zone).and_then(|born| years_completed(born, next)).map(|age| DateAge::Turns(age).words(dates))); } return Some(DatedLine::plain(said.join(FACT_JOIN))); } let at = Moment::parse(text, zone)?; if at.timed() { let ms = cotton_store::protocol::js::parse_date_ms(text.trim())?; let seconds = (ms - now.timestamp_millis()).div_euclid(1000); let reach = if form == Some(Form::Countdown) { i64::MAX } else { COUNTDOWN_SECONDS }; if let Some(left) = dates.left(seconds).filter(|_| seconds <= reach && !matches!(form, Some(Form::WeekdayDate | Form::WeekdayNameDate | Form::WeekdayDateYear))) { return Some(DatedLine::plain(dates.countdown(&left))); } } if form == Some(Form::Since) && today - at.day >= 7 { return Some(DatedLine::plain(dates.counted("since.weeks", (today - at.day) / 7))); } let owed = form == Some(Form::Late) || definition.upcoming.as_ref().is_some_and(|upcoming| upcoming.late.is_some()); let day = match form { Some(Form::WeekdayDate) => dates.weekday_date(at.day, this_year), Some(Form::WeekdayNameDate) => dates.weekday_name_date(at.day, this_year), Some(Form::WeekdayDateYear) => dates.weekday_date_year(at.day), // The late form says any day gone as how late: "1 day late", never // "yesterday"; "40 days late", never the date. Some(Form::Late) if at.day < today => dates.days_late(today - at.day), _ => RelativeDay::caption(at.day, today, near, counted, owed).words(dates), }; let text = match at.timed() { true => format!("{day}{FACT_JOIN}{}", at.clock(dates)), false => day, }; Some(DatedLine { text, late: owed && at.day < today }) } /// Their clock: the time at `now` in `zone`, said only when `zone`'s offset at /// that instant differs from `reader`'s; nothing for a zone keeping the /// reader's clock or one that cannot be placed. pub fn their_time(zone: &str, reader: &str, now: chrono::DateTime, dates: &DateWords) -> Option { let zone = zone.trim(); if zone.is_empty() { return None; } let at = now.timestamp_millis(); let theirs = zoned_parts(at, zone).ok()?; let ours = zoned_parts(at, reader).ok()?; let wall = |parts: &crate::transforms::zoned_clock::ZonedParts| (day_number(parts.year, parts.month, parts.day), parts.hour, parts.minute); (wall(&theirs) != wall(&ours)).then(|| dates.clock(theirs.hour, theirs.minute)) } /// The day `iso` falls on in `zone` (an IANA name; the host runs `TZ=UTC`, /// so the zone is always explicit), as days since the epoch. A day-only value /// ("2026-08-20") or a zoneless stamp is already a wall-clock day and is read /// as written. `None` for a value that is not a moment, or a zone that is not /// one. pub fn day_of_iso(iso: &str, zone: &str) -> Option { let iso = iso.trim(); let (year, month, day) = if let Ok(at) = chrono::DateTime::parse_from_rfc3339(iso) { let parts = zoned_parts(at.timestamp_millis(), zone).ok()?; (parts.year, parts.month, parts.day) } else { // Refuse an unknown zone here too, so the answer never depends on // which shape the moment was written in. zoned_parts(0, zone).ok()?; let date = chrono::NaiveDate::parse_from_str(iso, "%Y-%m-%d") .ok() .or_else(|| { ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M"] .iter() .find_map(|pattern| chrono::NaiveDateTime::parse_from_str(iso, pattern).ok()) .map(|at| at.date()) })?; use chrono::Datelike; ( i64::from(date.year()), i64::from(date.month()), i64::from(date.day()), ) }; Some(day_number(year, month, day)) } /// "Wed 20 Aug" — [`day_of_iso`] said in the reader's `dates` words, its year /// never named (a bin row's title). pub fn weekday_date_of(iso: &str, zone: &str, dates: &DateWords) -> Option { let day = day_of_iso(iso, zone)?; let (year, _, _) = crate::transforms::zoned_clock::civil_from_days(day); Some(dates.weekday_date(day, year)) }