Cotton code
215 lines · 7.7 KB · RustRaw
//! Journal date-identity helpers. The port of//! `packages/core/src/engine/journal.ts`.//!//! A journal entry's identity IS its calendar day (one entry per `journal_date`),//! so the app keys "today's entry" off a stable local-date string. The//! canonical journal-date key is `YYYY-MM-DD` — the DB `date` column's own//! spelling.//!//! **The zone is an argument here, where the TypeScript reads the runtime's.**//! Its helpers call `getFullYear`/`getMonth`/`getDate`, which are the process//! zone; this crate may not read one — and the server runs `TZ=UTC`, so a//! TypeScript caller on the host and one on the phone already disagree about//! which day an evening entry belongs to. Naming the zone is the same//! correction the recurrence engine already made.use std::collections::BTreeSet;use crate::transforms::zoned_clock::{    civil_from_days, day_key, day_number, instant_from_zoned, local_day_key, ZoneError, ZonedParts,};/// Not a `YYYY-MM-DD` key.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]#[error("Invalid journal date key: {0:?}")]pub struct InvalidJournalDateKey(pub String);/// The `YYYY-MM-DD` key for an instant, in the given zone.pub fn journal_date_key(instant_ms: i64, zone: &str) -> Result<String, ZoneError> {    local_day_key(instant_ms, zone)}/// Canonical day-key spelling, shared with snapshot calendar-day values.pub fn journal_key_from_parts(year: i64, month: i64, day: i64) -> String {    day_key(day_number(year, month, day))}/// True iff two instants fall on the same calendar day in the given zone.pub fn is_same_journal_date(a_ms: i64, b_ms: i64, zone: &str) -> Result<bool, ZoneError> {    Ok(journal_date_key(a_ms, zone)? == journal_date_key(b_ms, zone)?)}/// Parse a `YYYY-MM-DD` journal key to the instant of its local midnight.////// The TypeScript answers a `Date` at local midnight; the instant is the same/// fact without a clock. On a spring-forward day whose midnight does not exist/// the zoned clock resolves it the way `Intl` does, so both implementations/// land on the same instant.pub fn parse_journal_date(key: &str, zone: &str) -> Result<i64, JournalDateError> {    let trimmed = key.trim_matches(cotton_store::protocol::js::is_js_whitespace);    if !is_day_key(trimmed) {        return Err(JournalDateError::Key(InvalidJournalDateKey(            key.to_string(),        )));    }    let number =        |from: usize, to: usize| -> i64 { trimmed[from..to].parse::<i64>().unwrap_or_default() };    let parts = ZonedParts {        year: number(0, 4),        month: number(5, 7),        day: number(8, 10),        hour: 0,        minute: 0,        second: 0,    };    Ok(instant_from_zoned(parts, 0, zone)?)}#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum JournalDateError {    #[error(transparent)]    Key(#[from] InvalidJournalDateKey),    #[error(transparent)]    Zone(#[from] ZoneError),}// ── The streak ────────────────────────────────────────────────────────────//// The streak rule lives HERE rather than in the phone crate: two surfaces// each carried a copy once, disagreed for the same day and the same data, and// shipped that disagreement — one said "Write today's page" one swipe away// from a Home row reading "Today's page written". Two copies of a rule are two// rules. Putting it in `cotton-ffi/src/phone/` would hide it from the Mac and// start the same clock again// ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule])./// A `YYYY-MM-DD` key, shaped like one. The TypeScript's `DAY_KEY_RE`.fn is_day_key(key: &str) -> bool {    let bytes = key.as_bytes();    bytes.len() == 10        && bytes[4] == b'-'        && bytes[7] == b'-'        && [0, 1, 2, 3, 5, 6, 8, 9]            .into_iter()            .all(|i| bytes[i].is_ascii_digit())}/// The key `offset` days from a `YYYY-MM-DD` key (negative = earlier).////// Civil arithmetic on the key itself, which is what the TypeScript's/// `setHours(12, …)` was reaching for: a date key carries no zone, so stepping/// it cannot be rolled over by a DST shift.fn shift_key(key: &str, offset: i64) -> Option<String> {    if !is_day_key(key) {        return None;    }    let number = |from: usize, to: usize| key[from..to].parse::<i64>().ok();    let days = day_number(number(0, 4)?, number(5, 7)?, number(8, 10)?) + offset;    let (year, month, day) = civil_from_days(days);    Some(journal_key_from_parts(year, month, day))}/// How many days in a row have a written page, as of `now_ms` in `zone`.////// A streak is a run of consecutive local days ending TODAY or YESTERDAY —/// yesterday still counts, because today is not over and a streak that "breaks"/// at midnight would be a lie told at 00:01. A run that ended before yesterday/// is over: 0. Duplicates count once; an unparseable key is ignored.pub fn journal_streak(    written_dates: &[String],    now_ms: i64,    zone: &str,) -> Result<usize, ZoneError> {    let written: BTreeSet<&str> = written_dates        .iter()        .map(String::as_str)        .filter(|key| is_day_key(key))        .collect();    if written.is_empty() {        return Ok(0);    }    let today = journal_date_key(now_ms, zone)?;    let has =        |offset: i64| shift_key(&today, offset).is_some_and(|key| written.contains(key.as_str()));    let mut offset = if has(0) {        0    } else if has(-1) {        -1    } else {        return Ok(0);    };    let mut streak = 0;    while has(offset) {        streak += 1;        offset -= 1;    }    Ok(streak)}/// Whether today's page has been written — the same set, asked differently.pub fn written_today(written_dates: &[String], now_ms: i64, zone: &str) -> Result<bool, ZoneError> {    let today = journal_date_key(now_ms, zone)?;    Ok(written_dates.contains(&today))}/// The shape a journal page has to have to be counted.////// Three fields, because three fields decide the answer — the caller holds/// whole note rows and hands over only what the rule reads.#[derive(Debug, Clone, PartialEq, Eq)]pub struct JournalPage {    pub kind: String,    pub body: Option<String>,    pub journal_date: Option<String>,}/// **What "written" MEANS**, in one predicate: a JOURNAL note that carries a/// day and has something on it — an empty page is a page opened, not a day/// written.pub fn is_written_journal_page(page: &JournalPage) -> bool {    page.kind == "journal"        && page.body.as_deref().is_some_and(|body| {            !body                .trim_matches(cotton_store::protocol::js::is_js_whitespace)                .is_empty()        })        && page            .journal_date            .as_deref()            .is_some_and(|day| !day.is_empty())}/// The day keys that have a written page, out of a mixed note list.pub fn written_journal_days(pages: &[JournalPage]) -> Vec<String> {    pages        .iter()        .filter(|page| is_written_journal_page(page))        .filter_map(|page| page.journal_date.clone())        .collect()}/// Today's state and the run behind it, from one note list.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct JournalDayState {    pub written_today: bool,    pub streak: usize,}/// **The one answer to "is today's page written?"** — the Home row resolves/// through this, and nothing else may re-derive it.pub fn journal_day_state(    pages: &[JournalPage],    now_ms: i64,    zone: &str,) -> Result<JournalDayState, ZoneError> {    let days = written_journal_days(pages);    Ok(JournalDayState {        written_today: written_today(&days, now_ms, zone)?,        streak: journal_streak(&days, now_ms, zone)?,    })}#[cfg(test)]#[path = "journal_tests.rs"]mod tests;