//! ONE SLIP ANSWER: what a record says wherever it is drawn (the shell //! boundary). `shell.list` rows carry it as `slip`, and every record a //! `records.*` read asked with `said: true` answers carries it under `@said`, //! so a tile, a section, a search hit, a cover or a receipt draws the record //! it already holds, whole, on its first paint, and asks nothing more. //! //! ```json //! "@said": { //! "slip": { "title"?, "subtitle"?, "subtitle_one"?, "caption"?, "caption_late"?, //! "figure"?, "foot"?, "foot_late"?, "day_foot"?, "trailing"?, "stub"?: { "day", "month" }, //! "byline"?: { "words", "red" }, "badge"?: { "symbol", "spoken" }, "unread", //! "name"?, "fallback"?, "spoken", "weekday"?, "cover_footer"?: [part], //! "stock"?, "pin"?: { "lat", "lng" } }, //! "toggled"?, "toggle"?: { column: value }, "dimmed", "stamp"?, "deletes", //! "read_only", "types_into", "archived", "listed", "project"?, //! "layout"?: SlipLayout, "red"?: [column], "unit_words"?: { key: words } } //! ``` //! //! - `title` is what heads the slip: the record's day, its slip's title //! column, its own title, what names it meanwhile. `name` is the record's //! own title alone and `fallback` what names it where that holds nothing; //! `spoken` is never empty: `name`, `fallback`, its first date, the table's name. //! - `trailing` is the slip's trailing column and status, away from a list //! (a list's rows leave it out: their headings and captions say it). //! - `weekday` is the day heading the record where it has no title of its own. //! - `subtitle_one` is one line where `subtitle` joins several columns. //! - `cover_footer` is what a cover says at its foot, part by part, so a //! narrow cover drops whole parts from the end. //! - `stock` is the paper the record's state chooses, `pin` the map a slip's //! trailing picture draws. //! - `listed` says the record stands on its table's own list: not archived, //! not answered away, `listed_when` holding and not `hidden`. //! - A list narrowed to one link's records (`where {link: id}`, a store's //! orders) does not say that link on each slip (`without_links`). //! - A `slip_by` table's words are the record's own variant's, and `layout` //! is the slip that variant draws; absent, the table's own slip stands. //! - `red` names the columns whose value this record's `red_when` holds. //! - `unit_words` is the row's own words its columns' units name //! (`{count_other}`), text columns only and never a secret. //! - `project_words` (in `slip`) is the project's name where the slip's //! trailing column is not already the project. use cotton_core::definitions::{ColumnFormat, ColumnType, TableDefinition}; use cotton_core::records::page::{self, Words}; use cotton_core::transforms::note_title::note_display_title; use serde_json::{json, Map, Value}; use super::shell_deck; use super::shell_list::{blank, set, text}; /// Where a record carries its answer. pub(crate) const SAID_KEY: &str = "@said"; /// What every slip of one read is said against. pub(crate) struct Reading<'a> { definition: &'a TableDefinition, zone: &'a str, now: Option>, day_headed: bool, words: &'a Words, /// The record's stored words do not apply: its slip was narrowed. narrowed: bool, /// The definition whose subtitle is the cover's footer, where it names one. cover: Option, /// The definition whose subtitle stops at its first column, where it joins several. one_line: Option, } impl<'a> Reading<'a> { /// This reading says its own words, never those stored on the record. pub(super) fn narrowed(mut self) -> Self { self.narrowed = true; self } pub(crate) fn new(definition: &'a TableDefinition, zone: &'a str, now: Option>, day_headed: bool, words: &'a Words) -> Reading<'a> { let cover = definition.cover.as_ref().and_then(|cover| cover.footer.clone()).map(|keys| { let mut footed = definition.clone(); footed.slip.subtitle = Some(cotton_core::definitions::SlipSubtitle::Several(keys)); footed.slip.subtitle_first = None; footed.slip.subtitle_fallback = None; footed.slip.with_names = None; footed }); let one_line = (definition.slip.subtitles().len() > 1 && definition.slip.subtitle_first != Some(true)).then(|| { let mut one = definition.clone(); one.slip.subtitle_first = Some(true); one }); Reading { definition, zone, now, day_headed, words, narrowed: false, cover, one_line } } } /// `definition` with `keys` left off its slip: a store's orders, listed under /// the store, do not each say the store's name. pub(super) fn without_links(definition: &TableDefinition, keys: &[String]) -> TableDefinition { use cotton_core::definitions::SlipSubtitle; let mut narrowed = definition.clone(); let slip = &mut narrowed.slip; let left: Vec = slip.subtitles().iter().filter(|key| !keys.contains(key)).cloned().collect(); slip.subtitle = (!left.is_empty()).then_some(SlipSubtitle::Several(left)); for slot in [&mut slip.subtitle_fallback, &mut slip.trailing, &mut slip.figure] { if slot.as_ref().is_some_and(|key| keys.contains(key)) { *slot = None; } } if let Some(columns) = slip.caption.as_mut().and_then(|caption| caption.columns.as_mut()) { columns.retain(|key| !keys.contains(key)); } if let Some(footer) = narrowed.cover.as_mut().and_then(|cover| cover.footer.as_mut()) { footer.retain(|key| !keys.contains(key)); } narrowed } /// The record's whole answer, beside its row's acts. pub(crate) fn said_of(reading: &Reading, row: &Value) -> Value { let definition = reading.definition; let empty = Map::new(); let record = row["data"].as_object().unwrap_or(&empty); let toggled = toggled_of(definition, record); let kept = definition.readonly_when.as_ref().and_then(|key| record.get(key)).is_some_and(set); let read_only = kept || (!definition.columns.is_empty() && definition.columns.iter().all(|column| column.readonly == Some(true))); let archived = definition.archived.as_ref().and_then(|key| record.get(key)).is_some_and(set); let mut said = json!({ "slip": slip_of(reading, row), "toggled": toggled, "toggle": toggled.is_some().then(|| shell_deck::toggled(definition, record)).filter(|write| !write.is_null()), "dimmed": dimmed(definition, record), "stamp": stamp_of(definition, record), "deletes": deletes(definition, record) && row["deletable"] != json!(false), "read_only": read_only, "types_into": !read_only && definition.columns.iter().any(|column| column.column_type != ColumnType::Bool && column.readonly != Some(true)), "archived": archived, "listed": !archived && !leaves_answered(definition, record) && !hidden(definition, record) && definition.listed_when.as_ref().is_none_or(|key| record.get(key).is_some_and(|value| !blank(value))), "project": definition.project.as_ref().and_then(|key| record.get(key)).and_then(Value::as_str), "layout": definition.slip_by.as_ref() .and_then(|by| by.slips.get(record.get(&by.column)?.as_str()?)) .and_then(|variant| serde_json::to_value(definition.slip.with_variant(variant)).ok()), "red": Some(red_of(definition, record)).filter(|red| !red.is_empty()), "unit_words": Some(unit_words(definition, record)).filter(|words| !words.is_empty()), }); if let Some(said) = said.as_object_mut() { said.retain(|_, value| !value.is_null()); } said } /// The columns whose value this record's `red_when` holds. fn red_of<'a>(definition: &'a TableDefinition, record: &Map) -> Vec<&'a str> { definition.columns.iter() .filter(|column| column.red_when.as_ref().is_some_and(|red| record.get(&column.key).and_then(text).is_some_and(|value| red.contains(&value)))) .map(|column| column.key.as_str()) .collect() } /// The row's own words the columns' units name, by key: only a text column /// that is not secret and holds words. fn unit_words(definition: &TableDefinition, record: &Map) -> Map { let mut words = Map::new(); for units in definition.columns.iter().filter_map(|column| column.units.as_ref()) { for template in [Some(&units.one), Some(&units.other), units.zero.as_ref()].into_iter().flatten() { let mut rest = template.as_str(); while let Some(open) = rest.find('{') { let Some(close) = rest[open..].find('}') else { break }; let key = &rest[open + 1..open + close]; rest = &rest[open + close + 1..]; let source = definition.column(key).filter(|column| column.column_type == ColumnType::Text && column.secret != Some(true)); let held = source.and_then(|_| record.get(key)).and_then(Value::as_str).map(str::trim).filter(|held| !held.is_empty()); if let (true, Some(held)) = (key != "n", held) { words.entry(key).or_insert_with(|| json!(held)); } } } } words } /// Whether an answered record leaves its list: its question is answered, and /// its answers do not keep it. fn leaves_answered(definition: &TableDefinition, record: &Map) -> bool { if definition.slip.answers.as_ref().and_then(|answers| answers.leaves) == Some(false) { return false; } if definition.slip.reply.as_ref().is_some_and(|reply| record.get(&reply.column).is_some_and(|value| !blank(value))) { return true; } let Some(answers) = &definition.slip.answers else { return false }; let Some(value) = record.get(&answers.column).filter(|value| !blank(value)).and_then(Value::as_str) else { return false }; !answers.when.iter().flatten().any(|held| held == value) } /// Whether the table never lists this record. fn hidden(definition: &TableDefinition, record: &Map) -> bool { definition.hidden.as_ref().is_some_and(|hidden| record.get(&hidden.column).and_then(Value::as_str).is_some_and(|value| hidden.values.iter().any(|held| held == value))) } /// Whether a list draws the record faded. fn dimmed(definition: &TableDefinition, record: &Map) -> bool { definition.dimmed.as_ref().is_some_and(|dimmed| record.get(&dimmed.column).and_then(Value::as_str).is_some_and(|value| dimmed.values.iter().any(|held| held == value))) } /// The words a slip draws, resolved here (the module's `slip`). pub(crate) fn slip_of(reading: &Reading, row: &Value) -> Value { let empty = Map::new(); let record = row["data"].as_object().unwrap_or(&empty); // A slip typed by a choice column says this record's variant. let variant = reading.definition.slip_by.as_ref() .and_then(|by| by.slips.get(record.get(&by.column)?.as_str()?)); let typed = variant.map(|variant| { let mut typed = reading.definition.clone(); typed.slip = typed.slip.with_variant(variant); typed }); let definition = typed.as_ref().unwrap_or(reading.definition); let said = |key: &str| -> Option { let words = record.get(page::COLUMN_WORDS_KEY).and_then(|words| words.get(key)).and_then(Value::as_str).map(str::to_string); // A secret says only what the core masked, never its raw value. let raw = || record.get(key).and_then(text).filter(|_| definition.column(key).is_none_or(|column| column.secret != Some(true))); words.or_else(raw).filter(|words| !words.trim().is_empty()) }; let date = definition.date.as_deref(); let parts = |key: &str| record.get(page::DAY_PARTS_KEY).and_then(|parts| parts.get(key)).cloned().unwrap_or(Value::Null); // The record's own title: where the slip is titled by a read-only column // falling back to it (a movement, by who it was with), that column's words. let engine = (definition.slip.title != definition.title && definition.slip.title_fallback.as_deref() == Some(definition.title.as_str()) && definition.column(&definition.slip.title).is_some_and(|column| column.readonly == Some(true))) .then(|| said(&definition.slip.title)).flatten(); let named = engine.or_else(|| said(&definition.title)); // What names it where its title holds nothing: a long text's first line, else the column. let fallback = definition.slip.title_fallback.as_ref().and_then(|key| { let long = definition.column(key).is_some_and(|column| column.column_type == ColumnType::Longtext); match (long, &named, record.get(key).and_then(Value::as_str)) { (true, None, Some(body)) => note_display_title(None, body), _ => said(key), } }); // The day that names a record with no title of its own; a title column // that IS the date column is no title of its own. let heads = definition.heads.as_deref().filter(|heads| *heads != definition.title).and_then(said); let unmade = row["id"].as_str() == Some("") && date != Some(definition.title.as_str()) && definition.column(&definition.title).is_some_and(|column| column.required == Some(true) && column.readonly != Some(true)); let day_heading = date .filter(|date| heads.is_none() && !unmade && (*date == definition.title || (named.is_none() && fallback.is_none()))) .filter(|_| !definition.column(&definition.title).is_some_and(|column| matches!(column.format, Some(ColumnFormat::CalendarDatetime)))) .map(parts).filter(Value::is_object); let weekday = day_heading.as_ref().and_then(|parts| parts["weekday_name"].as_str().map(str::to_string)); let day_long = day_heading.as_ref().and_then(|parts| { let day = parts["day_long"].as_str()?; Some(match parts["clock"].as_str().filter(|_| date == Some(definition.title.as_str())) { Some(clock) => format!("{day}{}{clock}", page::FACT_JOIN), None => day.to_string(), }) }); let mut title = weekday.clone() .or_else(|| said(&definition.slip.title).map(|words| { let heading = definition.column(&definition.slip.title).and_then(|column| column.presentation.as_ref()) .is_some_and(|presentation| serde_json::to_value(presentation).ok() == Some(json!("heading"))); if heading { words.to_uppercase() } else { words } })) .or_else(|| named.clone()) .or_else(|| fallback.clone()); if title.is_none() && definition.slip.ordinal == Some(true) { title = row["@ordinal"].as_u64().map(|place| format!("{} {place}", definition.name)); } let zone = Some(reading.zone); let lines = page::resolve_slip_lines(definition, record, zone, reading.now, reading.day_headed, reading.words); // What the read already said of this record stands, unless its variant says otherwise. let kept = |key: &str| record.get(key).filter(|_| variant.is_none() && !reading.narrowed); let subtitle = kept(page::SLIP_SUBTITLE_KEY).map(|said| said.as_str().map(str::to_string)).unwrap_or(lines.subtitle); let caption = kept(page::SLIP_CAPTION_KEY).map(|said| said.as_str().map(str::to_string)).unwrap_or(lines.caption); let subtitle_one = reading.one_line.as_ref().filter(|_| variant.is_none()) .and_then(|one| page::resolve_slip_lines(one, record, zone, reading.now, false, reading.words).subtitle) .filter(|one| Some(one) != subtitle.as_ref()); let footer = match &reading.cover { Some(cover) => page::resolve_slip_lines(cover, record, zone, reading.now, false, reading.words).subtitle, None => subtitle.clone(), }; let cover_footer = footer.filter(|line| Some(line) != title.as_ref()).map(|line| { line.split(page::FACT_JOIN).filter(|part| !part.is_empty()).map(str::to_string).collect::>() }).filter(|parts| !parts.is_empty()); let day_foot = day_long.filter(|_| definition.slip.trailing.is_none() || definition.slip.trailing.as_deref() == date); let trailing = definition.slip.caption.is_none().then(|| { let words: Vec = [definition.slip.trailing.as_deref(), definition.slip.status.as_deref()].into_iter().flatten().filter_map(said).collect(); (!words.is_empty()).then(|| words.join(page::FACT_JOIN)) }).flatten(); let stub = definition.slip.stub.as_ref().map(|key| parts(key)).filter(|parts| parts.is_object()) .map(|parts| json!({"day": parts["leaf_day"], "month": parts["leaf_month"]})); let byline = definition.slip.byline.as_ref().and_then(|byline| { let mut words = record.get(&byline.column).and_then(Value::as_str).and_then(|value| byline.words.get(value)).cloned()?; while let (Some(open), Some(close)) = (words.find('{'), words.find('}')) { if close < open { break; } let key = words[open + 1..close].to_string(); let filled = said(&key)?; words.replace_range(open..=close, &filled); } Some(json!({"words": words, "red": byline.ink.is_some_and(|ink| serde_json::to_value(ink).ok() == Some(json!("red")))})) }); let badge = definition.slip.badge.as_ref().filter(|badge| match (&badge.values, record.get(&badge.column)) { (Some(values), Some(Value::String(value))) => values.contains(value), (Some(_), _) => false, (None, Some(Value::Bool(on))) => *on, (None, Some(value)) => text(value).is_some() || value.as_array().is_some_and(|items| !items.is_empty()), (None, None) => false, }).map(|badge| json!({"symbol": badge.symbol, "spoken": badge.spoken})); let unread = match (&definition.opened, &definition.slip.unread) { (Some(opened), _) => record.get(opened).is_none_or(blank), (None, Some(unread)) if definition.column(unread).is_some_and(|column| column.column_type == ColumnType::Choice) => record.get(unread).and_then(Value::as_str) == Some("unread"), (None, Some(unread)) => record.get(unread).is_none_or(blank), (None, None) => false, }; let stock = definition.slip.stock_by.as_ref() .filter(|by| definition.column(&by.column).is_some_and(|column| column.secret != Some(true) && column.shown_on(record))) .and_then(|by| by.values.get(record.get(&by.column)?.as_str()?)) .or(definition.slip.stock.as_ref()); let pin = definition.slip.trailing_picture.as_ref().and_then(|key| { let latitude = definition.column(key).filter(|column| column.column_type == ColumnType::Number)?; let longitude = definition.column(latitude.pair.as_deref()?)?; let (lat, lng) = (record.get(&latitude.key)?.as_f64()?, record.get(&longitude.key)?.as_f64()?); ((-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lng)).then(|| json!({"lat": lat, "lng": lng})) }); let spoken = named.clone().or_else(|| fallback.clone()) .or_else(|| definition.columns.iter().find(|column| column.column_type == ColumnType::Date && record.get(&column.key).is_some_and(|value| !blank(value))).and_then(|column| said(&column.key))) .unwrap_or_else(|| definition.name.clone()); let mut slip = json!({ "title": title, "subtitle": subtitle, "subtitle_one": subtitle_one, "caption": caption, "caption_late": lines.caption_late.then_some(true), "figure": record.get(page::SLIP_FIGURE_KEY), "foot": record.get(page::SLIP_FOOT_KEY), "foot_late": record.get(page::SLIP_FOOT_LATE_KEY), "day_foot": day_foot, "trailing": trailing, "stub": stub, "byline": byline, "badge": badge, "unread": unread, "name": named, "fallback": fallback, "spoken": spoken, "weekday": weekday, "cover_footer": cover_footer, "stock": stock, "pin": pin, "project_words": definition.project.as_deref().filter(|key| Some(*key) != definition.slip.trailing.as_deref()).and_then(said), }); if let Some(slip) = slip.as_object_mut() { slip.retain(|_, value| !value.is_null()); } slip } /// Whether the slip's toggle is on; None for a table with no toggle. fn toggled_of(definition: &TableDefinition, record: &Map) -> Option { let column = definition.column(definition.slip.toggle.as_deref()?)?; match column.column_type { ColumnType::Bool => Some(record.get(&column.key).and_then(Value::as_bool).unwrap_or(false)), ColumnType::Choice => { let (Some(first), Some(value)) = (column.choices.as_ref().and_then(|choices| choices.first()), record.get(&column.key).and_then(Value::as_str)) else { return Some(false) }; Some(match &definition.slip.toggle_on { Some(on) => on.iter().any(|held| held == value), None => value != first, }) } _ => None, } } /// The stamp a record wears, as its word: its stamped choice column's, else /// a choice toggle's value (done, dropped). fn stamp_of(definition: &TableDefinition, record: &Map) -> Option { if let Some(column) = definition.columns.iter().find(|column| column.column_type == ColumnType::Choice && column.stamps.is_some()) { let value = record.get(&column.key).and_then(Value::as_str)?; return column.stamps.as_ref()?.get(value).map(|stamp| stamp.words().to_string()); } let toggle = definition.column(definition.slip.toggle.as_deref()?)?; if toggle.column_type != ColumnType::Choice { return None; } let value = record.get(&toggle.key).and_then(Value::as_str)?; ["done", "dropped"].contains(&value).then(|| value.to_string()) } /// Whether Select's Delete may take the record: the table deletes, the core /// has not said it cannot go alone, its `delete_when` holds, nothing else keeps it. pub(super) fn deletes(definition: &TableDefinition, record: &Map) -> bool { if definition.delete == Some(false) || record.get("deletable") == Some(&json!(false)) || record.get("repeats") == Some(&json!(true)) { return false; } if definition.readonly_when.as_ref().and_then(|key| record.get(key)).is_some_and(set) { return false; } let Some(when) = &definition.delete_when else { return !definition.columns.iter().all(|column| column.readonly == Some(true)) }; let value = record.get(&when.column).cloned().unwrap_or(Value::Null); if when.present.is_some_and(|present| present == blank(&value)) { return false; } match &when.values { Some(values) => value.as_str().is_some_and(|text| values.iter().any(|held| held == text)), None => true, } } #[cfg(test)] #[path = "shell_slip_tests.rs"] mod tests;