//! The rows of each day, in the decided order, and the folds.//!//! **One rule** (DECISIONS.md, Structure): a day is a date and one list, and//! every row is the same: a time or nothing, a mark, the words. Inside a day://! things for the whole day, then things at a time in order, then to-dos with//! no time. A many-day thing is a row on each day it covers. An end is a quiet//! "to 12:00" only where an end exists on that day. Every empty day that is//! not today folds, one alone too, a run into one line. A timed event under//! a day that ends after midnight is one row on its first day, and one event//! held twice on a day (same words, start and end) is one row.use std::collections::BTreeMap;use serde::Serialize;use serde_json::{json, Value};usesuper::words::{fill, Words};usesuper::weekday_monday_first;usecrate::zoned_clock::{civil_from_days, local_day, zoned_parts, ZoneError};#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pubenumKind {Event,Todo,Birthday,}/// Whose an item is: what its sheet may change.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pubenumWhose {Yours,Google,Birthday,}/// Where an item falls.#[derive(Debug, Clone, PartialEq, Eq)]pubenumPlace {/// One occurrence of an event: its instants (epoch ms) and whether it is/// all-day. An all-day event ends at its last day's 23:59:59.999.Event { starts: i64, ends: Option<i64>, all_day: bool },/// A to-do on a day (a day number in the reader's zone), at a minute of/// that day or none. `from` is the day it was due, when it was brought/// onto today undone.Todo { day: i64, minute: Option<i64>, from: Option<i64> },/// A birthday on a day.Birthday { day: i64 },}/// One thing that may be a row, as the core read it.#[derive(Debug, Clone, PartialEq)]pubstructItem {pub key: String,pub kind: Kind,pub whose: Whose,pub words: String,/// The drawn mark's id the person gave it, if any.pub mark: Option<String>,pub done: bool,pub place: Place,/// What a tap opens, as the phone takes it.pub opens: Value,/// The tie-break among equals (the order the core read them in).pub order: i64,}/// One row as a phone draws it (CONTRACT.md section 1).#[derive(Debug, Clone, PartialEq, Serialize)]pubstructRow {pub key: String,pub kind: Kind,pub time: Option<String>,pub end: Option<String>,pub mark: Value,/// A to-do's drawn mark, beside its tick circle. #[serde(rename = "drawnMark", skip_serializing_if = "Option::is_none")]pub drawn_mark: Option<String>,pub words: String,pub suffix: Option<String>,pub done: bool,pub whose: Whose,pub opens: Value, #[serde(skip)] sort: (u8, i64, u8, i64, i64),}implRow {/// The drawn mark this row shows on the month sheet, if any.pubfn drawn(&self) -> Option<&str> {self.drawn_mark.as_deref().or_else(|| self.mark.get("id").and_then(Value::as_str)) }}/// One entry of the Days read: a day, or a fold of quiet days.#[derive(Debug, Clone, PartialEq, Serialize)]#[serde(untagged)]pubenumEntry {Day(Day),Fold { fold: Fold },}#[derive(Debug, Clone, PartialEq, Serialize)]pubstructDay {pub day: String,pub number: String,pub weekday: String,pub month: String,pub today: bool,pub rows: Vec<Row>,}#[derive(Debug, Clone, PartialEq, Serialize)]pubstructFold {pub from: String,pub to: String,pub count: i64,pub words: String,}/// `9:00`, `19:00`: the clock as Days writes it, 24-hour, no leading zero.pubfn clock(minute_of_day: i64) -> String { format!("{}:{:02}", minute_of_day / 60, minute_of_day % 60)}fn minute_of(instant: i64, zone: &str) -> Result<i64, ZoneError> {let parts = zoned_parts(instant, zone)?;Ok(parts.hour * 60 + parts.minute)}/// "Tue" within the last six days, else "12 Nov".pubfn day_words(day: i64, today: i64, words: &Words) -> String {if (0..=6).contains(&(today - day)) {return words.weekdays_short[weekday_monday_first(day)].clone(); }let (_, month, date) = civil_from_days(day); format!("{date} {}", words.months_short[(month - 1) as usize])}/// Every item's rows, by day, for the days `from..=to`, each day's rows in/// the decided order.pubfn rows_by_day(items: &[Item], from: i64, to: i64, today: i64, zone: &str, words: &Words) -> Result<BTreeMap<i64, Vec<Row>>, ZoneError> {letmut out: BTreeMap<i64, Vec<Row>> = BTreeMap::new();for item in items {for (day, row) in rows_of(item, today, zone, words)? {if day >= from && day <= to { out.entry(day).or_default().push(row); } } }for rows in out.values_mut() { rows.sort_by(|a, b| a.sort.cmp(&b.sort).then_with(|| a.words.cmp(&b.words)));// One event held twice (two shared calendars, an import over a pull):// the same words, start and end on the day are one row, the first read.letmut seen: Vec<(String, Option<String>, Option<String>, Option<String>)> = Vec::new(); rows.retain(|row| {if row.kind != Kind::Event {returntrue; }let same = (row.words.trim().to_lowercase(), row.time.clone(), row.end.clone(), row.suffix.clone());if seen.contains(&same) {returnfalse; } seen.push(same);true }); }Ok(out)}/// The rows one item makes, with the day each falls on.fn rows_of(item: &Item, today: i64, zone: &str, words: &Words) -> Result<Vec<(i64, Row)>, ZoneError> {let kind_rank = match item.kind {Kind::Event => 0,Kind::Birthday => 1,Kind::Todo => 2, };let (mark, drawn_mark) = match (item.kind, &item.mark) { (Kind::Todo, drawn) => (json!({ "kind": "tick", "done": item.done }), drawn.clone()), (Kind::Birthday, _) => (json!({ "kind": "drawn", "id": item.mark.clone().unwrap_or_else(|| "cake".to_string()) }), None), (Kind::Event, Some(id)) => (json!({ "kind": "drawn", "id": id }), None), (Kind::Event, None) => (json!({ "kind": "dot" }), None), };let row = |time: Option<i64>, end: Option<i64>, suffix: Option<String>, sort: (u8, i64, u8, i64, i64)| Row { key: item.key.clone(), kind: item.kind, time: time.map(clock), end: end.map(clock), mark: mark.clone(), drawn_mark: drawn_mark.clone(), words: item.words.clone(), suffix, done: item.done, whose: item.whose, opens: item.opens.clone(), sort, };let to = |minute: i64| Some(fill(&words.to, &[("time", &clock(minute))]));let whole = (0u8, 0i64, kind_rank, item.order, 0i64);letmut out = Vec::new();match item.place {Place::Birthday { day } => out.push((day, row(None, None, None, whole))),Place::Todo { day, minute, from } => {let sort = match (minute, from) { (Some(minute), _) => (1, minute, kind_rank, item.order, 0), (None, None) => (2, 0, 0, item.order, 0), (None, Some(from)) => (2, 1, 0, from, item.order), };let suffix = from.map(|from| fill(&words.from, &[("day", &day_words(from, today, words))])); out.push((day, row(minute, None, suffix, sort))); }Place::Event { starts, ends, all_day } => {let first = local_day(starts, zone)?;// The end belongs to the day it is in, and an end exactly at a// midnight to the day before it: 18:00 to 00:00 is one evening.let ends = ends.filter(|ends| *ends > starts);// A timed event shorter than a day that runs past midnight// (22:00 to 2:00) is one evening: one row on its first day.let overnight = !all_day && ends.is_some_and(|ends| ends - starts < DAY_MS);let last = match ends {Some(_) if overnight => first,Some(ends) => local_day(ends - 1, zone)?.max(first),None => first, };let end_minute = match ends {Some(ends) if !all_day => {let minute = minute_of(ends, zone)?; (minute != 0).then_some(minute) } _ => None, };let start_minute = if all_day { None } else { Some(minute_of(starts, zone)?) };for day in first..=last {let timed_start = start_minute.filter(|minute| day == first && !(*minute == 0 && last > first));let (time, end, suffix) = match timed_start {Some(start) if last == first => (Some(start), end_minute, end_minute.and_then(to)),Some(start) => (Some(start), None, None),Noneif day == last && last > first => (None, end_minute, end_minute.and_then(to)),None => (None, None, None), };let sort = match time {Some(minute) => (1, minute, kind_rank, item.order, 0),None => whole, }; out.push((day, row(time, end, suffix, sort))); } } }Ok(out)}const DAY_MS: i64 = 86_400_000;/// The Days read's entries for `from..=to`: each day with its rows, and each/// run of empty days that does not hold today, one alone too, as one fold.pubfn days(items: &[Item], from: i64, to: i64, today: i64, zone: &str, words: &Words) -> Result<Vec<Entry>, ZoneError> {letmut by_day = rows_by_day(items, from, to, today, zone, words)?;letmut out = Vec::new();letmut quiet: Vec<i64> = Vec::new();let flush = |quiet: &mutVec<i64>, out: &mutVec<Entry>| {iflet (Some(first), Some(last)) = (quiet.first(), quiet.last()) { out.push(Entry::Fold { fold: fold_of(*first, *last, words) }); } quiet.clear(); };for day in from..=to {let rows = by_day.remove(&day).unwrap_or_default();if rows.is_empty() && day != today { quiet.push(day);continue; } flush(&mut quiet, &mut out); out.push(Entry::Day(day_of(day, today, rows, words))); } flush(&mut quiet, &mut out);Ok(out)}fn day_of(day: i64, today: i64, rows: Vec<Row>, words: &Words) -> Day {let (_, month, date) = civil_from_days(day);Day { day: crate::zoned_clock::day_key(day), number: date.to_string(), weekday: words.weekdays[weekday_monday_first(day)].clone(), month: words.months[(month - 1) as usize].clone(), today: day == today, rows, }}/// "22 – 25 · four quiet days"; across a month, "30 Nov – 2 Dec · …"; one/// day alone, "11 · a quiet day".pubfn fold_of(first: i64, last: i64, words: &Words) -> Fold {if first == last {let (_, _, date) = civil_from_days(first);returnFold { from: crate::zoned_clock::day_key(first), to: crate::zoned_clock::day_key(last), count: 1, words: fill(&words.quiet_one, &[("day", &date.to_string())]), }; }let (y1, m1, d1) = civil_from_days(first);let (y2, m2, d2) = civil_from_days(last);let (from, to) = if (y1, m1) == (y2, m2) { (d1.to_string(), d2.to_string()) } elseif y1 != y2 {// Across a year, each end says its year. ( format!("{d1} {} {y1}", words.months_short[(m1 - 1) as usize]), format!("{d2} {} {y2}", words.months_short[(m2 - 1) as usize]), ) } else { ( format!("{d1} {}", words.months_short[(m1 - 1) as usize]), format!("{d2} {}", words.months_short[(m2 - 1) as usize]), ) };let count = last - first + 1;Fold { from: crate::zoned_clock::day_key(first), to: crate::zoned_clock::day_key(last), count, words: fill(&words.quiet, &[("from", &from), ("to", &to), ("count", &words.count(count))]), }}