//! Home's "today" band, as a pure selection so the screen stays dumb and the//! semantics stay unit-tested — the port of `apps/cotton/src/lib/homeToday.ts`.//!//! Home is a GLANCE, not a tool: the band answers "what is left of today" in//! one look, and every deeper question belongs to a tool. Home's own screen no//! longer draws it, but the tool counts and the person page's chat card both//! still read this selection — which is exactly why it is one function and not//! two readings of the same day.//!//! Semantics (the honesty rule applied to time)://! - overdue todos come first and are marked late — they ARE late;//! - a todo due earlier TODAY at a stated time that has passed is LATE: it//! keeps its place in the day's time order but reads as late (a 9:00 am todo//! at 1:30 pm used to render exactly like an evening one). A date-only todo//! due today is never late — the day isn't over;//! - a todo snoozed past today is hidden (that is what snooze means), one//! snoozed to a moment inside today arrives today and shows;//! - undated todos live in their lists, never here;//! - events already finished are past, not "today's remaining" — an occurrence//! shows while it is still ahead or still running;//! - all-day events always show while their day is today.//!//! **Both seams are arguments.** The TypeScript injects the wall clock (`now`)//! so the file is deterministic under fake timers, but it reads the DAY off the//! process's own zone through `Date`'s local setters (`setHours(0, 0, 0, 0)`,//! `getHours()`). This crate may read neither a clock nor a machine zone, so//! the IANA zone is an argument too — the phone stands where its owner does and//! the host runs `TZ=UTC`, and a band that guessed would put the same todo in a//! different day on the two. Given the owner's zone the two agree by//! construction.use cotton_store::protocol::js::parse_date_ms;usecrate::transforms::zoned_clock::{ instant_from_zoned, zoned_parts, ZoneError, ZonedParts,};/// `overdue` = due before today. `late` = due earlier today at a time that has/// passed. `today` = still ahead (or date-only). `snoozed` = arriving today off/// a snooze.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pubenumTodayTodoState {Overdue,Late,Today,Snoozed,}implTodayTodoState {/// The TypeScript union's member, for a caller putting the state on a wire/// or into a snapshot.pubconstfn as_str(self) -> &'static str {matchself {TodayTodoState::Overdue => "overdue",TodayTodoState::Late => "late",TodayTodoState::Today => "today",TodayTodoState::Snoozed => "snoozed", } }}/// States that wear the honest late treatment.pubfn reads_late(state: TodayTodoState) -> bool { state == TodayTodoState::Overdue || state == TodayTodoState::Late}/// The columns the band reads off a todo row.////// A shape rather than the whole `ITodo`: the server's rows and the app's/// records both qualify, and a caller bands its OWN row type through [`AsRef`]/// rather than copying fields out.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructBandTodo {pub id: String,/// `open` | `done` | `dropped` — a string, because the file's todo status/// has no ported union yet and this module only ever asks one question of/// it.pub status: String,/// The stored ISO instant, or nothing — an undated todo lives in its list.pub due_at: Option<String>,pub snoozed_until: Option<String>,}implAsRef<BandTodo> forBandTodo {fn as_ref(&self) -> &BandTodo {self }}/// The columns the band reads off ONE occurrence of an event.////// `all_day` is flattened up from the occurrence's `event` — the TypeScript/// reaches through `occurrence.event.allDay`, and an expanded occurrence has no/// separate flag of its own. `id` is likewise the EVENT's id, which is what the/// band's rows navigate to.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructBandOccurrence {pub id: String,pub all_day: bool,/// ISO start of THIS occurrence. Unparseable is skipped, never guessed.pub starts_at: String,pub ends_at: Option<String>,}implAsRef<BandOccurrence> forBandOccurrence {fn as_ref(&self) -> &BandOccurrence {self }}#[derive(Debug, Clone, PartialEq, Eq)]pubstructTodayTodo<T> {pub todo: T,pub state: TodayTodoState,/// The instant that orders the row.pub sort_at: i64,}#[derive(Debug, Clone, PartialEq, Eq)]pubstructTodayEvent<E> {pub occurrence: E,pub sort_at: i64,}/// One row of the band. The band is ONE timeline, not a todo list stacked on an/// event list — reading it top-to-bottom must mean "in the order the rest of/// today happens". (It used to render all todos then all events, so a 6pm todo/// sat above a 3:30pm meeting while looking like one sorted list.)#[derive(Debug, Clone, PartialEq, Eq)]pubenumTodayEntry<T, E> {Todo(TodayTodo<T>),Event(TodayEvent<E>),}impl<T, E> TodayEntry<T, E> {/// The TypeScript discriminant — `"todo"` / `"event"`.pubconstfn kind(&self) -> &'static str {matchself {TodayEntry::Todo(_) => "todo",TodayEntry::Event(_) => "event", } }/// The ordering field every arm of the union carries.pubconstfn sort_at(&self) -> i64 {matchself {TodayEntry::Todo(todo) => todo.sort_at,TodayEntry::Event(event) => event.sort_at, } }}#[derive(Debug, Clone, PartialEq, Eq)]pubstructTodayBand<T, E> {/// Overdue first (the day opens with its debts), then strict time order.pub entries: Vec<TodayEntry<T, E>>,/// True when nothing is left of today — home shows its rest state.pub is_clear: bool,}/// What [`select_today_band`] is asked, one struct so the call site names its/// arguments the way the TypeScript's object literal does.#[derive(Debug, Clone)]pubstructTodayBandInput<'a, T, E> {pub todos: &'a [T],pub occurrences: &'a [E],pub now_ms: i64,/// The IANA zone the day is read in. Never guessed — see the module note.pub timezone: &'a str,}/// Local midnight of the day `now_ms` falls in, in `timezone` —/// `d.setHours(0, 0, 0, 0)`.////// Built from the zone's wall clock rather than by flooring to a 24-hour/// boundary: a DST day is not 86,400,000 ms long, and the arithmetic form would/// move the whole band an hour on exactly the two days a year it matters.fn start_of_day_ms(now_ms: i64, timezone: &str) -> Result<i64, ZoneError> {let parts = zoned_parts(now_ms, timezone)?; instant_from_zoned(ZonedParts { hour: 0, minute: 0, second: 0, ..parts },0, timezone, )}/// The last instant of the day — `d.setHours(23, 59, 59, 999)`, the wall clock/// again rather than day start plus a constant.////// INCLUSIVE: the todo filter's `due <= dayEnd` and the event filter's/// `startsAt > dayEnd` both lean on this being the last instant that is still/// today rather than the first that is tomorrow.fn end_of_day_ms(now_ms: i64, timezone: &str) -> Result<i64, ZoneError> {let parts = zoned_parts(now_ms, timezone)?; instant_from_zoned(ZonedParts { hour: 23, minute: 59, second: 59, ..parts },999, timezone, )}/// True when the instant carries a real clock time rather than the 00:00 an/// all-day record defaults to — `dateFormats.hasClockTime`.////// The TypeScript routes a BARE `YYYY-MM-DD` through `parseISO` (local/// midnight) and everything else through `new Date`; this port reads the/// instant once, with `parse_date_ms` (which is `new Date`), so a date-only/// string would read as UTC midnight here where `hasClockTime` alone reads it/// as local. No column this module is given holds one — `due_at` and/// `starts_at` are instants — and the TypeScript is already inconsistent about/// it (`daysLate` and the `EEE` format both use `new Date`), so reading it once/// is the honest spelling of what the callers actually pass.fn has_clock_time(at_ms: i64, timezone: &str) -> Result<bool, ZoneError> {let parts = zoned_parts(at_ms, timezone)?;Ok(parts.hour != 0 || parts.minute != 0)}/// Open todos that belong to today, ordered: oldest debt first, then the day.pubfn select_today_todos<T: AsRef<BandTodo> + Clone>( todos: &[T], now_ms: i64, timezone: &str,) -> Result<Vec<TodayTodo<T>>, ZoneError> {let day_start = start_of_day_ms(now_ms, timezone)?;let day_end = end_of_day_ms(now_ms, timezone)?;letmut picked: Vec<TodayTodo<T>> = Vec::new();for todo in todos {let row = todo.as_ref();if row.status != "open" {continue; }let snoozed = row.snoozed_until.as_deref().and_then(parse_date_ms);let due = row.due_at.as_deref().and_then(parse_date_ms);ifletSome(snoozed) = snoozed {// Snoozed past today: hidden. That is what snooze means, and it// wins over a due date that would otherwise put the row here.if snoozed > day_end {continue; }if snoozed >= day_start { picked.push(TodayTodo { todo: todo.clone(), state: TodayTodoState::Snoozed, sort_at: snoozed, });continue; } }letSome(due) = due else { continue };if due < day_start { picked.push(TodayTodo { todo: todo.clone(), state: TodayTodoState::Overdue, sort_at: due, }); } elseif due <= day_end {// A stated hour that has passed reads as late; a date-only todo due// today never does — the day is not over.let late = has_clock_time(due, timezone)? && due < now_ms; picked.push(TodayTodo { todo: todo.clone(), state: if late {TodayTodoState::Late } else {TodayTodoState::Today }, sort_at: due, }); } }// Overdue first, then the day's own order. Stable, like// `Array.prototype.sort`, so two debts at one instant keep the caller's// order. picked.sort_by(|a, b| {let over = |state: TodayTodoState| u8::from(state != TodayTodoState::Overdue); over(a.state) .cmp(&over(b.state)) .then(a.sort_at.cmp(&b.sort_at)) });Ok(picked)}/// Today's occurrences that haven't finished yet, in time order.pubfn select_today_events<E: AsRef<BandOccurrence> + Clone>( occurrences: &[E], now_ms: i64, timezone: &str,) -> Result<Vec<TodayEvent<E>>, ZoneError> {let day_start = start_of_day_ms(now_ms, timezone)?;let day_end = end_of_day_ms(now_ms, timezone)?;letmut picked: Vec<TodayEvent<E>> = Vec::new();for occurrence in occurrences {let row = occurrence.as_ref();letSome(starts_at) = parse_date_ms(&row.starts_at) else {continue; };if starts_at > day_end || starts_at < day_start {continue; }if row.all_day {// An all-day event is present for the whole day and anchors to its// start, so it leads whatever else the day holds. picked.push(TodayEvent { occurrence: occurrence.clone(), sort_at: day_start, });continue; }// Still ahead, or started but not yet finished.let ends_at = row.ends_at.as_deref().and_then(parse_date_ms);let finished = match ends_at {Some(ends_at) => ends_at <= now_ms,None => starts_at <= now_ms, };if finished {continue; } picked.push(TodayEvent { occurrence: occurrence.clone(), sort_at: starts_at, }); } picked.sort_by_key(|picked| picked.sort_at);Ok(picked)}/// The whole band home renders: todos and events interleaved into ONE/// chronological run, with overdue todos held at the top.////// Ordering, in full:/// 1. overdue todos, oldest debt first;/// 2. everything else by its instant — a todo due at 3pm sits above a 4pm/// meeting and below a 2pm one;/// 3. ties (an all-day event and an undated-but-snoozed todo both anchored to/// midnight) keep events first, since an all-day event frames the day the/// rest of the rows sit inside.pubfn select_today_band<T, E>( args: &TodayBandInput<'_, T, E>,) -> Result<TodayBand<T, E>, ZoneError>where T: AsRef<BandTodo> + Clone, E: AsRef<BandOccurrence> + Clone,{let todos = select_today_todos(args.todos, args.now_ms, args.timezone)?;let events = select_today_events(args.occurrences, args.now_ms, args.timezone)?;letmut entries: Vec<TodayEntry<T, E>> = todos .iter() .filter(|t| t.state == TodayTodoState::Overdue) .cloned() .map(TodayEntry::Todo) .collect();letmut rest: Vec<TodayEntry<T, E>> = todos .into_iter() .filter(|t| t.state != TodayTodoState::Overdue) .map(TodayEntry::Todo) .chain(events.into_iter().map(TodayEntry::Event)) .collect(); rest.sort_by(|a, b| {// The tie-break is load-bearing, not cosmetic: at one instant the event// comes first, because an all-day event frames the day the other rows// sit inside.let event_first = |entry: &TodayEntry<T, E>| u8::from(entry.kind() != "event"); a.sort_at() .cmp(&b.sort_at()) .then(event_first(a).cmp(&event_first(b))) }); entries.extend(rest);let is_clear = entries.is_empty();Ok(TodayBand { entries, is_clear })}#[cfg(test)]#[path = "home_today_tests.rs"]mod tests;