Cotton code
319 lines · 13.5 KB · RustRaw
//! A row as Cotton Data shows it: one line in a table's list ([`sentence`]),//! and every field on its own page ([`field`]). Values are said as every other//! app says them (`records::page::fact_words`); Data adds what a developer//! wants beside them: the column as stored, its type in words, and "As stored"//! ([`stored`]).use serde_json::{Map, Value};use super::say;use crate::definitions::{Column, ColumnType, SlipSubtitle, TableDefinition};use crate::records::page::{fact_words, Words};/// A row's line in its table's list.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Sentence {    /// The slip's title, else the definition's title column, else the id.    pub title: String,    /// The two or three fields that tell rows apart, joined by a middle dot.    pub line: String,    /// The columns the line was made from, as stored, for the list's foot.    pub from: Vec<String>,}/// How many fields a line holds after its title.const LINE_FIELDS: usize = 3;/// The line of `row` (its opened fields) in `definition`'s list. A link/// column says the linked row's name when `link_names` knows it.pub fn sentence(definition: &TableDefinition, row: &Map<String, Value>, link_names: &dyn Fn(&str, &str) -> Option<String>) -> Sentence {    let words = Words::shipped();    let id = row.get("id").and_then(Value::as_str).unwrap_or_default();    let said = |key: &str| -> Option<String> {        let column = definition.column(key)?;        let value = row.get(key)?;        value_line(definition, column, value, row, words, link_names)    };    let title = [Some(definition.slip.title.as_str()), definition.slip.title_fallback.as_deref(), Some(definition.title.as_str())]        .into_iter()        .flatten()        .find_map(|key| said(key).filter(|t| !t.trim().is_empty()))        .unwrap_or_else(|| id.to_string());    let mut keys: Vec<String> = match &definition.slip.subtitle {        Some(SlipSubtitle::One(key)) => vec![key.clone()],        Some(SlipSubtitle::Several(keys)) => keys.clone(),        None => Vec::new(),    };    if let Some(trailing) = &definition.slip.trailing {        keys.push(trailing.clone());    }    // A slip with too little to say is filled from the definition's own columns, in order, as a developer reads them.    for column in &definition.columns {        if keys.len() >= LINE_FIELDS {            break;        }        let telling = matches!(column.column_type, ColumnType::Text | ColumnType::Choice | ColumnType::Date | ColumnType::Amount | ColumnType::Link | ColumnType::Number);        if telling && column.key != definition.slip.title && !keys.contains(&column.key) && column.secret != Some(true) {            keys.push(column.key.clone());        }    }    let mut parts = Vec::new();    let mut from = Vec::new();    for key in &keys {        if parts.len() >= LINE_FIELDS {            break;        }        if let Some(words) = said(key).filter(|w| !w.trim().is_empty() && *w != title) {            parts.push(words);            from.push(key.clone());        }    }    Sentence { title, line: parts.join(" \u{b7} "), from }}/// How a field is drawn.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]#[serde(rename_all = "lowercase")]pub enum Kind {    Text,    Long,    Link,    Amount,    Date,    Time,    Choice,    Bool,    Several,    Url,    Place,    Photo,    File,    Number,    Bytes,    Account,}/// One field of a row's page.#[derive(Debug, Clone, PartialEq, serde::Serialize)]pub struct Field {    /// The column as stored.    pub column: String,    /// Its type in plain words ("date", "long text, 12 lines", "text, several").    pub type_line: String,    pub kind: Kind,    /// The value said, or "Nothing yet".    pub value_line: String,    /// A second line: a date's day ("A Saturday"), a choice's others, a bool's day.    #[serde(skip_serializing_if = "Option::is_none")]    pub sub: Option<String>,    /// The values one by one, for a column holding several.    #[serde(skip_serializing_if = "Vec::is_empty")]    pub items: Vec<String>,    /// A link's target: `{ table, id }`, the name being `value_line`.    #[serde(skip_serializing_if = "Option::is_none")]    pub link: Option<Value>,    /// A url to open.    #[serde(skip_serializing_if = "Option::is_none")]    pub url: Option<String>,    /// A photo or file's stored key, to fetch on Open.    #[serde(skip_serializing_if = "Option::is_none")]    pub media: Option<String>,    /// Long text: how many lines it has, and the words to show them all.    #[serde(skip_serializing_if = "Option::is_none")]    pub folded: Option<Value>,    /// Whether the server can read this field.    pub clear: bool,    /// Empty: nothing stored.    pub empty: bool,}/// Every field of `row`, in the definition's column order. `clear` names the/// columns the server reads. A secret table's values are never said (Secrets/// opens them); `secret` columns of any table show only their ending.pub fn fields(definition: &TableDefinition, row: &Map<String, Value>, clear: &[String], link_names: &dyn Fn(&str, &str) -> Option<String>) -> Vec<Field> {    definition.columns.iter().filter(|c| c.computed.is_none() || row.contains_key(&c.key)).map(|column| field(definition, column, row, clear.contains(&column.key), link_names)).collect()}/// One field.pub fn field(definition: &TableDefinition, column: &Column, row: &Map<String, Value>, clear: bool, link_names: &dyn Fn(&str, &str) -> Option<String>) -> Field {    let words = Words::shipped();    let value = row.get(&column.key).cloned().unwrap_or(Value::Null);    let several = value.is_array() && column.column_type != ColumnType::Choice;    let kind = if several && !matches!(column.column_type, ColumnType::Link | ColumnType::Photo | ColumnType::File) { Kind::Several } else { kind_of(column, &value) };    let empty = match &value {        Value::Null => true,        Value::String(s) => s.trim().is_empty(),        Value::Array(a) => a.is_empty(),        _ => false,    };    let base_type = say(&format!("row.type.{}", type_key(column)), &[]);    let lines_n = value.as_str().map(|s| s.lines().count()).unwrap_or(0);    let type_line = if several {        say("row.type.several", &[("type", &base_type)])    } else if kind == Kind::Long && lines_n > 3 {        say("row.type.long_lines", &[("n", &lines_n.to_string())])    } else {        base_type    };    let mut f = Field { column: column.key.clone(), type_line, kind, value_line: String::new(), sub: None, items: Vec::new(), link: None, url: None, media: None, folded: None, clear, empty };    if empty {        f.value_line = say("row.nothing", &[]);        return f;    }    if super::secret_table(&definition.id) && column.secret == Some(true) {        f.value_line = say("row.secret_elsewhere", &[]);        return f;    }    match column.column_type {        ColumnType::Link => {            let target = column.link_to.clone().unwrap_or_default();            let ids: Vec<String> = match &value {                Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),                Value::String(s) => vec![s.clone()],                _ => Vec::new(),            };            let names: Vec<String> = ids.iter().map(|id| link_names(&target, id).unwrap_or_else(|| id.clone())).collect();            f.value_line = names.join(", ");            if ids.len() == 1 {                f.link = Some(serde_json::json!({ "table": target, "id": ids[0] }));            } else {                f.items = names;                f.link = Some(serde_json::json!({ "table": target, "ids": ids }));            }        }        ColumnType::Url => {            let url = value.as_str().unwrap_or_default().trim().to_string();            f.value_line = url.trim_start_matches("https://").trim_start_matches("http://").trim_start_matches("www.").split('/').next().unwrap_or(&url).to_string();            f.url = Some(url);        }        ColumnType::Photo | ColumnType::File => {            let key = match &value {                Value::String(s) => s.clone(),                Value::Object(o) => o.get("key").or_else(|| o.get("path")).and_then(Value::as_str).unwrap_or_default().to_string(),                Value::Array(a) => a.first().and_then(Value::as_str).unwrap_or_default().to_string(),                _ => String::new(),            };            f.value_line = key.rsplit('/').next().unwrap_or(&key).to_string();            f.media = Some(key);        }        ColumnType::Longtext => {            let text = value.as_str().unwrap_or_default();            f.value_line = text.to_string();            if lines_n > 3 {                f.folded = Some(serde_json::json!({ "lines": lines_n, "all_line": say("row.show_all", &[("n", &lines_n.to_string())]) }));            }        }        ColumnType::Choice => {            f.value_line = fact_words(definition, column, &value, row, None, None, words).unwrap_or_default();            if let Some(choices) = &column.choices {                let all: Vec<String> = choices.iter().map(|c| column.choice_label(c)).collect();                f.sub = Some(say("row.of_choices", &[("choices", &all.join(", "))]));            }        }        ColumnType::Bool => {            f.value_line = if value.as_bool() == Some(true) { say("row.yes", &[]) } else { say("row.no", &[]) };        }        _ if several => {            f.items = value.as_array().into_iter().flatten().map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).collect();            f.value_line = f.items.join(", ");        }        ColumnType::Date => {            f.value_line = fact_words(definition, column, &value, row, None, None, words).unwrap_or_else(|| value.as_str().unwrap_or_default().to_string());            f.sub = value.as_str().and_then(weekday);        }        _ => {            f.value_line = value_line(definition, column, &value, row, words, &|_, _| None).unwrap_or_else(|| stored_text(&value));        }    }    f}/// A field's value as it sits in the row: a string as it is, anything else as JSON.pub fn stored_text(value: &Value) -> String {    match value {        Value::String(s) => s.clone(),        Value::Null => "null".into(),        other => other.to_string(),    }}/// "As stored": every column of `row`, in the definition's order then any the/// definition no longer names, each exactly as it sits in the row. A secret/// table's secret columns say the Secrets line, never the value.pub fn stored(definition: &TableDefinition, row: &Map<String, Value>) -> Vec<(String, String)> {    let mut out: Vec<(String, String)> = Vec::new();    for column in &definition.columns {        if let Some(value) = row.get(&column.key) {            let text = if super::secret_table(&definition.id) && column.secret == Some(true) { say("row.secret_elsewhere", &[]) } else { stored_text(value) };            out.push((column.key.clone(), text));        }    }    for (key, value) in row {        if !out.iter().any(|(k, _)| k == key) {            out.push((key.clone(), stored_text(value)));        }    }    out}fn value_line(definition: &TableDefinition, column: &Column, value: &Value, row: &Map<String, Value>, words: &Words, link_names: &dyn Fn(&str, &str) -> Option<String>) -> Option<String> {    if super::secret_table(&definition.id) && column.secret == Some(true) {        return None;    }    match column.column_type {        ColumnType::Link => {            let id = value.as_str()?;            Some(link_names(column.link_to.as_deref().unwrap_or_default(), id).unwrap_or_else(|| id.to_string()))        }        ColumnType::Bool => (value.as_bool() == Some(true)).then(|| column.label()),        ColumnType::Longtext => value.as_str().and_then(|t| t.lines().map(str::trim).find(|l| !l.is_empty())).map(|l| l.chars().take(80).collect()),        _ => fact_words(definition, column, value, row, None, None, words),    }}fn kind_of(column: &Column, value: &Value) -> Kind {    match column.column_type {        ColumnType::Text if value.is_array() => Kind::Several,        ColumnType::Text => Kind::Text,        ColumnType::AccountNumber => Kind::Account,        ColumnType::Longtext => Kind::Long,        ColumnType::Date => Kind::Date,        ColumnType::Time => Kind::Time,        ColumnType::Number => Kind::Number,        ColumnType::Bytes => Kind::Bytes,        ColumnType::Amount => Kind::Amount,        ColumnType::Choice => Kind::Choice,        ColumnType::Link => Kind::Link,        ColumnType::Photo => Kind::Photo,        ColumnType::File => Kind::File,        ColumnType::Bool => Kind::Bool,        ColumnType::Url => Kind::Url,        ColumnType::Place => Kind::Place,    }}fn type_key(column: &Column) -> &'static str {    match column.column_type {        ColumnType::Text => "text",        ColumnType::AccountNumber => "account",        ColumnType::Longtext => "long",        ColumnType::Date => "date",        ColumnType::Time => "time",        ColumnType::Number => "number",        ColumnType::Bytes => "bytes",        ColumnType::Amount => "amount",        ColumnType::Choice => "choice",        ColumnType::Link => "link",        ColumnType::Photo => "photo",        ColumnType::File => "file",        ColumnType::Bool => "bool",        ColumnType::Url => "url",        ColumnType::Place => "place",    }}/// The weekday of a stored date ("2026-10-03" or an instant): "A Saturday".fn weekday(text: &str) -> Option<String> {    let day = chrono::NaiveDate::parse_from_str(text.get(..10)?, "%Y-%m-%d").ok()?;    Some(say("row.weekday", &[("day", &day.format("%A").to_string())]))}