Cotton code
607 lines · 26.0 KB · RustRaw
//! What a change says on its receipt.//!//! One place words every receipt, so every tool says the same thing: a verb//! and the record's name ("Added Call the plumber", "Archived Bike shed//! list", "Deleted Kite flying"). A before → after is answered only for a//! change of WORDS (a title, a body) — never for a switch, a state or a//! stamp, and never a timestamp. The app draws `said` and `words` as given.//!//! `values` is the rest of a `changed` receipt's before → after: each other//! column that changed and a person reads (a day, a clock, a number, an//! amount, a link), said as the page says it ([`value_changes`], through//! `page::fact_words` in the ask's zone) — never a state, a switch, the//! list's order, the store's stamps or a secret. Empty on every other kind.use serde::Serialize;use serde_json::Value;use super::Verb;use crate::constants::BinKind;use crate::definitions::{    key_as_words, Column, ColumnType, SlipSubtitle, TableDefinition, ToggleStyle,};/// The `receipts` set's words: the database's rows first, the kit's for the/// rest. Every receipt's verb is a line of it, so a rewording is a row.#[derive(Debug, Clone, PartialEq)]pub struct ReceiptWords(crate::rules::shell_lines::LineSet);impl ReceiptWords {    /// The kit's words, when no database is at hand.    pub fn shipped() -> &'static ReceiptWords {        static WORDS: std::sync::OnceLock<ReceiptWords> = std::sync::OnceLock::new();        WORDS.get_or_init(|| ReceiptWords::of_rows(&[]))    }    /// The words a database says: its `lines` rows first, the kit for the rest.    pub fn of_rows(rows: &[crate::rules::shell_lines::LineRow]) -> ReceiptWords {        ReceiptWords(crate::rules::shell_lines::LineSet::of_rows("receipts", rows).expect("the kit ships the receipts set"))    }    /// One line, filled; a line the set lacks says its own path.    fn say(&self, line: &str, fills: &[(&str, &str)]) -> String {        self.0.say(line, fills).unwrap_or_else(|| format!("receipts.{line}"))    }    /// A delete into the bin ([`binned_said`]).    pub fn binned(&self, name: &str, bin_shown: bool) -> String {        self.say(if bin_shown { "binned" } else { "deleted" }, &[("name", name)])    }    /// A bin receipt worded again for a Bin whose tile is off Home; `None`    /// for any other sentence ([`binned_said_put_away`]).    pub fn binned_put_away(&self, said: &str) -> Option<String> {        let (before, after) = self.say("binned", &[]).split_once("{name}").map(|(a, b)| (a.to_string(), b.to_string()))?;        let name = said.strip_prefix(&before)?.strip_suffix(&after)?;        Some(self.binned(name, false))    }    /// A refusal about a record that is gone ([`no_longer_here`]).    pub fn no_longer_here(&self, definition: &TableDefinition) -> String {        self.say("no_longer_here", &[("kind", &lower_first(&definition.name))])    }    /// Whether `reason` is a [`ReceiptWords::no_longer_here`] refusal.    pub fn says_no_longer_here(&self, reason: &str) -> bool {        let template = self.say("no_longer_here", &[]);        template.split_once("{kind}").is_some_and(|(before, after)| reason.starts_with(before) && reason.ends_with(after))    }}/// The longest name a receipt carries before it is cut with "…".const NAME_LENGTH: usize = 60;/// What kind of thing happened, for the face that draws it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum ReceiptKind {    Added,    /// Words were added to the end of a record (a journal day): `said` is    /// "Added" and the added words.    Appended,    Deleted,    /// An add was taken back by its own Undo: the record is gone as if it    /// was never made, and nothing offers to bring it back.    Removed,    PutBack,    Archived,    /// A switch or a state changed.    Switched,    /// Words changed: `words` holds each before and after.    Edited,    /// Something that is neither words nor a state changed (a day, a link).    Changed,    Reordered,    /// The record moved to another database; the database name is data on    /// the move tombstone, not a sentence composed by this engine.    Moved,    /// The destination database received a record through a move.    MovedIn,}/// One changed column of words.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct WordsChange {    pub name: String,    /// `None` when the column held nothing.    pub before: Option<String>,    /// `None` when the column was cleared.    pub after: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Receipt {    pub kind: ReceiptKind,    pub said: String,    pub words: Vec<WordsChange>,    /// The other columns a `changed` receipt read, before and after in words.    pub values: Vec<WordsChange>,}/// A write that is not made until the person picks one value: what to ask,/// the column of the write the pick fills, and the choices. Answered in place/// of `{change, record}` — nothing is written — and the caller sends the same/// write again with `column` set to the picked option's `id`.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Ask {    pub question: String,    pub column: String,    pub options: Vec<AskOption>,}/// One choice an [`Ask`] offers: the value it fills its column with, and/// what the person reads.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct AskOption {    pub id: String,    pub label: String,}/// The receipt of a change of `verb` to a record of `definition`. `record`/// is the record's data as it now stands, when the caller has it.pub fn receipt(    definition: &TableDefinition,    verb: Verb,    before: &Value,    after: &Value,    record: Option<&Value>,    dates: &crate::records::page::DateWords,    words: &ReceiptWords,) -> Receipt {    let plain = |kind: ReceiptKind, said: String| Receipt {        kind,        said,        words: Vec::new(),        values: Vec::new(),    };    let named = |data: &Value| record_name_in(definition, data, dates);    match verb {        // The app resolves the destination from the move metadata. Keeping        // this receipt static means the core does not compose a sentence from        // a database name whose display wording belongs to definitions.        Verb::Move => plain(ReceiptKind::Moved, words.say("moved", &[])),        Verb::MoveIn => plain(ReceiptKind::MovedIn, words.say("moved_in", &[])),        Verb::Reorder => plain(ReceiptKind::Reordered, words.say("reordered", &[("plural", &definition.plural)])),        // A thought is kept, never "added": the words name what was done        // with what was said (Spec 7), and the screen it was said on adds        // where ("on this todo").        Verb::Create if definition.id == "thought" => {            plain(ReceiptKind::Added, words.say("kept_as_thought", &[]))        }        Verb::Create => plain(ReceiptKind::Added, words.say("added", &[("name", &named(record.unwrap_or(after)))])),        // The verb is the act's own: a delete that lands in the bin moved the        // record there, and saying "Deleted" would tell the person it is gone.        Verb::Delete if lands_in_bin(definition) => plain(ReceiptKind::Deleted, words.binned(&named(before), true)),        Verb::Delete => plain(ReceiptKind::Deleted, words.say("deleted", &[("name", &named(before))])),        Verb::Restore => plain(ReceiptKind::PutBack, words.say("put_back", &[("name", &named(record.unwrap_or(after)))])),        Verb::Update | Verb::Link => {            let mut receipt = changed(definition, before, after, record, dates, words);            if let Some(cleared) = missed_cleared(after) {                let said = receipt.said.clone();                receipt.said = words.say("missed_cleared", &[("said", &said), ("n", &cleared.to_string())]);            }            receipt        }    }}/// Whether a delete of this table's record moves it to the bin rather than/// erasing it: a built-in the bin keeps ([`BinKind`]), so the bin lists it/// and brings it back. The media library is photos and videos read as one,/// and its delete lands each in the bin as its own kind.pub fn lands_in_bin(definition: &TableDefinition) -> bool {    definition.has_engine() && (BinKind::parse(&definition.id).is_some() || definition.id == MEDIA_LIBRARY)}/// What a delete into the bin says. While the Bin's tile is on Home: "Moved/// <name> to the bin". While it is not, the bin is not a thing on this/// phone, so the receipt says what the person sees — "Deleted/// <name>" — and the way back is its Undo and the list's "Deleted" link/// (mini RJ11 sev 2). Every bin receipt is worded here.pub fn binned_said(name: &str, bin_shown: bool) -> String {    ReceiptWords::shipped().binned(name, bin_shown)}/// A bin receipt worded for a Bin that is on Home ([`binned_said`] with/// `true`), worded again for one whose tile is off Home; `None` for any other sentence.pub fn binned_said_put_away(said: &str) -> Option<String> {    ReceiptWords::shipped().binned_put_away(said)}/// The built-in that reads photos and videos as one library: its rows are/// a [`BinKind::Photo`]'s or a [`BinKind::Video`]'s.pub const MEDIA_LIBRARY: &str = "media";/// How many earlier occurrences a tick marked missed: the ids the change's/// `@missed` gained. One tick clears the run, and the receipt says so.fn missed_cleared(after: &Value) -> Option<usize> {    let moved = after.get(super::MISSED)?;    let ids = |side: &str| -> Vec<&str> {        moved            .get(side)            .and_then(Value::as_array)            .map(|ids| ids.iter().filter_map(Value::as_str).collect())            .unwrap_or_default()    };    let was = ids("was");    let cleared = ids("now").into_iter().filter(|id| !was.contains(id)).count();    (cleared > 0).then_some(cleared)}/// The receipt of an add taken back by its own Undo: "Removed <name>", by/// the name the record had (`before`).pub fn removed(definition: &TableDefinition, before: &Value, dates: &crate::records::page::DateWords, words: &ReceiptWords) -> Receipt {    Receipt {        kind: ReceiptKind::Removed,        said: words.say("removed", &[("name", &record_name_in(definition, before, dates))]),        words: Vec::new(),        values: Vec::new(),    }}fn changed(    definition: &TableDefinition,    before: &Value,    after: &Value,    record: Option<&Value>,    dates: &crate::records::page::DateWords,    words: &ReceiptWords,) -> Receipt {    // The name is the record's as it now stands: a renamed record is called    // by its new name.    let mut now = before.clone();    for source in [Some(after), record].into_iter().flatten() {        if let (Some(now), Some(source)) = (now.as_object_mut(), source.as_object()) {            now.extend(                source                    .iter()                    .map(|(key, value)| (key.clone(), value.clone())),            );        }    }    let name = record_name_in(definition, &now, dates);    // What changed, less what a person never reads: values kept beside the    // record, its place in the list, and the store's own stamps.    let columns: Vec<&Column> = definition        .columns        .iter()        .filter(|column| definition.order.as_deref() != Some(column.key.as_str()))        .filter(|column| !["created_at", "updated_at"].contains(&column.key.as_str()))        .filter(|column| before.get(&column.key).is_some() || after.get(&column.key).is_some())        .filter(|column| before.get(&column.key) != after.get(&column.key))        .collect();    let plain = |kind: ReceiptKind, said: String| Receipt {        kind,        said,        words: Vec::new(),        values: Vec::new(),    };    let held =        |data: &Value, column: &Column| data.get(&column.key).cloned().unwrap_or(Value::Null);    if let Some(column) = columns        .iter()        .find(|column| definition.archived.as_deref() == Some(column.key.as_str()))    {        return match is_set(&held(after, column)) {            true => plain(ReceiptKind::Archived, words.say("archived", &[("name", &name)])),            false => plain(ReceiptKind::PutBack, words.say("put_back", &[("name", &name)])),        };    }    // Words added to the end (a journal day): the receipt is "Added" and the    // added words — a verb first, as every receipt is.    // A lengthened title is an edit; an append is new lines under a body.    if let [column] = columns        .iter()        .filter(|column| column.column_type == ColumnType::Longtext)        .collect::<Vec<_>>()        .as_slice()    {        let (was, is) = (held(before, column), held(after, column));        if let (Some(was), Some(is)) = (was.as_str(), is.as_str()) {            let added = is                .strip_prefix(was.trim_end())                .filter(|added| added.starts_with('\n') && !was.trim().is_empty())                .map(str::trim)                .filter(|added| !added.is_empty());            if let Some(added) = added {                return plain(ReceiptKind::Appended, words.say("added", &[("name", added)]));            }        }    }    // A switch or a state, with whatever day stamps ride along with it    // (a todo done also stamps when): the receipt says what the record now is.    let is_state = |column: &&&Column| match column.column_type {        ColumnType::Bool => true,        ColumnType::Choice => column.multiple != Some(true),        _ => false,    };    let rides_along = columns        .iter()        .filter(|column| !is_state(column))        .all(|column| column.column_type == ColumnType::Date);    if let ([column], true) = (        columns            .iter()            .filter(is_state)            .collect::<Vec<_>>()            .as_slice(),        rides_along,    ) {        let is = held(after, column);        match column.column_type {            ColumnType::Bool => {                let on = is_set(&is);                let toggle = definition.slip.toggle.as_deref() == Some(column.key.as_str());                let label = lower_first(&column.label());                let said = match (toggle, definition.slip.toggle_style, on) {                    (true, Some(ToggleStyle::Switch), true) => words.say("turned_on", &[("name", &name)]),                    (true, Some(ToggleStyle::Switch), false) => words.say("turned_off", &[("name", &name)]),                    (_, _, true) => words.say("marked", &[("name", &name), ("label", &label)]),                    (_, _, false) => words.say("marked_not", &[("name", &name), ("label", &label)]),                };                return plain(ReceiptKind::Switched, said);            }            ColumnType::Choice => {                if let Some(state) = is.as_str().filter(|state| !state.is_empty()) {                    // A command that sets exactly this state names what was                    // done in its own receipt word ("Done Water the plants").                    if let Some(word) = commanded(definition, &column.key, &is) {                        let said = if word.contains(crate::definitions::RECEIPT_NAME) {                            word.replace(crate::definitions::RECEIPT_NAME, &name)                        } else { format!("{word} {name}") };                        return plain(ReceiptKind::Switched, said);                    }                    // The column's kind picks the form, by the definition and                    // never by the look of a label: a state column (the slip's                    // status, caption status or answers column) is said as the                    // verb under the name ("Restored Dentist", "Kept <album>"),                    // any other choice is said of the record ("Marked Ada                    // Tamil", never "… ta"; "Marked … done").                    let said_as = key_as_words(state);                    let label = column.own_choice_label(state);                    let said = if definition.is_state_column(&column.key) {                        format!("{} {name}", label.unwrap_or(said_as))                    } else {                        words.say("marked", &[("name", &name), ("label", &label.unwrap_or_else(|| lower_first(&said_as)))])                    };                    return plain(ReceiptKind::Switched, said);                }            }            _ => {}        }    }    let changes: Vec<WordsChange> = columns        .iter()        .filter(|column| is_words(column))        .map(|column| WordsChange {            name: column.label(),            before: said_words(&held(before, column)),            after: said_words(&held(after, column)),        })        .collect();    let kind = if !changes.is_empty() && changes.len() == columns.len() {        ReceiptKind::Edited    } else {        ReceiptKind::Changed    };    let said = match kind {        ReceiptKind::Edited => words.say("edited", &[("name", &name)]),        _ => words.say("changed", &[("name", &name)]),    };    Receipt { kind, said, words: changes, values: Vec::new() }}/// A `changed` receipt's other columns, before and after in words: each/// column that changed and is neither words ([`is_words`]) nor a state, the/// list's order, a store stamp or a secret, said by `page::fact_words` in/// `zone` against `now`. A column that says nothing either side is left out.pub fn value_changes(    definition: &TableDefinition,    before: &Value,    after: &Value,    zone: Option<&str>,    now: Option<chrono::DateTime<chrono::Utc>>,    words: &crate::records::page::Words,) -> Vec<WordsChange> {    let empty = serde_json::Map::new();    let held = |data: &Value, key: &str| data.get(key).cloned().unwrap_or(Value::Null);    let said = |data: &Value, column: &Column| {        let value = held(data, &column.key);        crate::records::page::fact_words(definition, column, &value, data.as_object().unwrap_or(&empty), zone, now, words)    };    definition        .columns        .iter()        .filter(|column| definition.order.as_deref() != Some(column.key.as_str()))        .filter(|column| !["created_at", "updated_at"].contains(&column.key.as_str()))        .filter(|column| column.secret != Some(true) && !is_words(column))        .filter(|column| !matches!(column.column_type, ColumnType::Bool) && !(column.column_type == ColumnType::Choice && column.multiple != Some(true)))        .filter(|column| after.get(&column.key).is_some() && before.get(&column.key) != after.get(&column.key))        .filter_map(|column| {            let (was, is) = (said(before, column), said(after, column));            (was.is_some() || is.is_some()).then(|| WordsChange { name: column.label(), before: was, after: is })        })        .collect()}/// The receipt word of the definition's command whose data is exactly/// `{column: state}` — the definition, not this file, says what a tick is.fn commanded<'a>(definition: &'a TableDefinition, column: &str, state: &Value) -> Option<&'a str> {    definition        .commands        .iter()        .flatten()        .filter(|command| {            command.data.as_ref().is_some_and(|data| {                data.0.len() == 1 && data.get(column) == Some(state)            })        })        .find_map(|command| command.receipt.as_deref())}/// Words a person wrote and may read back: never a secret, never a key.fn is_words(column: &Column) -> bool {    matches!(        column.column_type,        ColumnType::Text | ColumnType::Longtext | ColumnType::Url | ColumnType::Place    ) && column.secret != Some(true)}fn said_words(value: &Value) -> Option<String> {    value        .as_str()        .map(str::trim)        .filter(|words| !words.is_empty())        .map(str::to_string)}fn is_set(value: &Value) -> bool {    !matches!(value, Value::Null | Value::Bool(false)) && value.as_str() != Some("")}fn lower_first(words: &str) -> String {    let mut letters = words.chars();    match letters.next() {        Some(first) => first.to_lowercase().chain(letters).collect(),        None => String::new(),    }}/// What a refusal says of a record that is gone or in the bin: what it was/// ("That todo is no longer here"), never its id — an id is nothing a person/// can read, and the record has no name left to say.pub fn no_longer_here(definition: &TableDefinition) -> String {    ReceiptWords::shipped().no_longer_here(definition)}/// Whether `reason` is a [`no_longer_here`] refusal; the phone tells "gone"/// from "could not be read" by it.pub fn says_no_longer_here(reason: &str) -> bool {    ReceiptWords::shipped().says_no_longer_here(reason)}/// The name a receipt calls a record by: its title's first line, else the/// slip's fallback title, else what its slip shows first — the slip's title,/// subtitle, then trailing ("the 7:00 am alarm") — else what it is ("a mood")./// Never its id, never a raw date or number. The name stands inside a/// sentence ("Moved Felt calm to the bin"), so it never brings its own/// closing full stop ([`without_full_stop`]).pub fn record_name(definition: &TableDefinition, data: &Value) -> String {    record_name_in(definition, data, crate::records::page::DateWords::shipped())}/// [`record_name`] in one database's date words: a clock column it is/// named by ("the 7:00 am alarm") is said as that database says a time.pub fn record_name_in(definition: &TableDefinition, data: &Value, dates: &crate::records::page::DateWords) -> String {    without_full_stop(named(definition, data, dates))}/// A name as it stands mid-sentence: one closing full stop dropped ("Felt/// calm after the walk." reads "Felt calm after the walk"). A question mark,/// an exclamation mark and an ellipsis ("...", "…") are kept as typed — they/// say how the words were meant, and a full stop says nothing a receipt needs.fn without_full_stop(name: String) -> String {    match name.strip_suffix('.') {        Some(kept) if !kept.ends_with('.') && !kept.trim_end().is_empty() => kept.trim_end().to_string(),        _ => name,    }}fn named(definition: &TableDefinition, data: &Value, dates: &crate::records::page::DateWords) -> String {    let own_words = |key: &str| -> Option<String> {        let column = definition.column(key)?;        if !matches!(column.column_type, ColumnType::Text | ColumnType::Longtext | ColumnType::Place | ColumnType::AccountNumber) {            return None;        }        said_value_in(column, data.get(key)?, dates)    };    let subtitle: Vec<&str> = match &definition.slip.subtitle {        Some(SlipSubtitle::One(key)) => vec![key.as_str()],        Some(SlipSubtitle::Several(keys)) => keys.iter().map(String::as_str).collect(),        None => Vec::new(),    };    // A value that is not the record's own words (a time, a choice) is said    // of the record: "the 7:00 am alarm". Words are its name as they are.    let slip_shows = |key: &str| -> Option<String> {        let column = definition.column(key)?;        let said = said_value_in(column, data.get(key)?, dates)?;        Some(match is_words(column) {            true => said,            false => format!("the {said} {}", lower_first(&definition.name)),        })    };    own_words(&definition.title)        .or_else(|| definition.slip.title_fallback.as_deref().and_then(own_words))        .or_else(|| {            std::iter::once(definition.slip.title.as_str())                .chain(subtitle)                .chain(definition.slip.trailing.as_deref())                .find_map(slip_shows)        })        .unwrap_or_else(|| {            let name = lower_first(&definition.name);            let article = if name.starts_with(['a', 'e', 'i', 'o', 'u']) {                "an"            } else {                "a"            };            format!("{article} {name}")        })}/// A value as a sentence says it, or `None` when it is empty or has no/// spelling here yet: words by their first line (cut at 60 letters), a clock/// time as "7:00 am", a choice by its words ("calm", several joined with/// ", "). A date, a number or an amount is not said — their spellings/// belong to the faces, and a raw one names nothing.////// Said in one database's date words (its clock spelling); a reader with no/// database says the kit's ([`crate::records::page::DateWords::shipped`]).pub fn said_value_in(column: &Column, value: &Value, dates: &crate::records::page::DateWords) -> Option<String> {    if column.secret == Some(true) {        return None;    }    match column.column_type {        ColumnType::AccountNumber => value.as_str().map(super::account_number_ending),        ColumnType::Text | ColumnType::Longtext | ColumnType::Url | ColumnType::Place => {            let line = value                .as_str()?                .lines()                .map(str::trim)                .find(|line| !line.is_empty())?;            Some(match line.char_indices().nth(NAME_LENGTH) {                Some((cut, _)) => format!("{}…", line[..cut].trim_end()),                None => line.to_string(),            })        }        ColumnType::Time => {            let mut parts = value.as_str()?.trim().splitn(3, ':');            let hour: i64 = parts.next()?.parse().ok()?;            let minute: i64 = parts.next()?.parse().ok()?;            ((0..24).contains(&hour) && (0..60).contains(&minute)).then(|| dates.clock(hour, minute))        }        ColumnType::Choice => {            // Mid-sentence a choice keeps its own case: "calm", "Mon"; one            // the definition names is said by that name ("Tamil").            let said = |key: &str| column.own_choice_label(key).unwrap_or_else(|| choice_words(key));            let words: Vec<String> = match value {                Value::Array(items) => items.iter().filter_map(Value::as_str).map(said).collect(),                Value::String(one) => vec![said(one)],                _ => Vec::new(),            };            let words: Vec<String> = words.into_iter().filter(|word| !word.is_empty()).collect();            (!words.is_empty()).then(|| words.join(", "))        }        _ => None,    }}/// A choice key as words inside a sentence: its underscores as spaces.fn choice_words(key: &str) -> String {    key.trim().replace('_', " ")}#[cfg(test)]#[path = "receipt_tests.rs"]mod tests;