//! A record's page as the person reads it (Spec 11): the five parts a
//! definition's `parts` names (`TableDefinition::resolved_parts`), each said
//! in words — never an id, a key or anything the code says.
//!
//! One function for every table ([`record_page`]): it reads through a
//! [`PageSource`] (the app's core reads through the generic verbs) and holds
//! no branch for any kind. What it answers:
//!
//! * head: the title, ONE line of facts joined with " · " (a fact that is the
//! same on every record is left out only for automatic heads, except app
//! attribution; one that says the title again is left out), and the state as one tag
//! with its tone — a column whose `shown_when` fails for the record is
//! left out of the head and the body;
//! * links: a chip per record a link column names, with its title and, where
//! the linked table's slip carries a picture (a person's print), its key;
//! * body: the long text;
//! * lists: each list's heading, count, up to [`LIST_ROWS`] rows and the read
//! that opens the whole list — a list holding nothing is left out; a list
//! over a read (`parts.lists[].read`) draws the read's first rows, each
//! titled by its first line with its trailing words, and counts them all;
//! a list matched by value (`parts.lists[].match`) narrows the other table
//! by its column equal to this record's parent value, empty → no list;
//! * acts: the main act, the others and the act that puts the record away,
//! each a command of the definition offered on the record as it stands.
use serde::Serialize;
use serde_json::{Map, Value};
use crate::definitions::{
key_as_words, Column, ColumnFormat, ColumnType, ColumnUnits, PageParts, PageShape, PartsRead, ReadFormat, RecordCommand, StampTone,
TableDefinition, PAGE_READS, SHORT_HASH,
};
use crate::records::amount::MoneyForm;
use crate::records::receipt::{record_name_in, said_value_in};
/// Most rows a page's list draws; its heading counts the rest.
pub const LIST_ROWS: usize = 10;
/// A fact is opted in by its column and has a reading; explicit head keys
/// set their order. Private, title, state and dealt values have another owner.
pub(crate) fn fact_columns<'a>(definition: &'a TableDefinition, parts: &'a PageParts) -> Vec<&'a String> {
let mut seen = std::collections::BTreeSet::new();
parts.head.facts.iter().chain(definition.columns.iter().map(|column| &column.key))
.filter(|key| {
let key = key.as_str();
key != definition.title && parts.head.state.as_deref() != Some(key)
&& !crate::definitions::parts::STAMPS.contains(&key)
&& !parts.cards.iter().chain(parts.strip.iter()).flatten().any(|card| card.column.as_deref() == Some(key))
&& definition.column(key).is_some_and(|column| column.fact == Some(true) && column.reading.is_some() && column.secret != Some(true))
&& seen.insert(key.to_string())
}).collect()
}
/// The words a page is said in, read once from one database's `lines` rows
/// and handed down: its dates and its money. A page, a list's slips, a
/// face's columns and a group's heads all say the database's own words.
#[derive(Debug, Clone, PartialEq)]
pub struct Words {
pub dates: DateWords,
pub money: crate::records::amount::MoneyWords,
/// The `ident` set: how a record's short reference is said ("#7KQ2").
pub ident: crate::rules::shell_lines::LineSet,
/// The `record` set: what a page's labelled fact says of a switch.
pub record: crate::rules::shell_lines::LineSet,
/// The `format` set: a record kind's mark word (`mark.
`), which
/// [`Words::kind_word`] says.
pub format: crate::rules::shell_lines::LineSet,
}
impl Words {
/// The words a database says: its `lines` rows first, the kit for the rest.
pub fn of_rows(rows: &[crate::rules::shell_lines::LineRow]) -> Words {
Words {
dates: DateWords::of_rows(rows),
money: crate::records::amount::MoneyWords::of_rows(rows),
ident: crate::rules::shell_lines::LineSet::of_rows("ident", rows).expect("the kit ships the ident set"),
record: crate::rules::shell_lines::LineSet::of_rows("record", rows).expect("the kit ships the record set"),
format: crate::rules::shell_lines::LineSet::of_rows("format", rows).expect("the kit ships the format set"),
}
}
/// What a record of `kind` (its table's id) is called beside it: the
/// `format` set's `mark.` ("Money" for a transaction), else the key
/// in words — a kind a newer kit added still says what it is.
pub fn kind_word(&self, kind: &str) -> String {
self.format.say(&format!("mark.{kind}"), &[]).unwrap_or_else(|| key_as_words(kind))
}
/// A record id as its short reference, in the `ident` set's words:
/// "#7KQ2". The card's ident place says a record's own id through this.
pub fn short_ref(&self, id: &str) -> String {
let reference = crate::transforms::short_ref::short_ref(id);
self.ident.say("short_ref", &[("ref", reference.as_str())]).unwrap_or_else(|| reference.as_str().to_string())
}
/// The kit's words, when no database is at hand (a customer's public
/// read, a test).
pub fn shipped() -> &'static Words {
static WORDS: std::sync::OnceLock = std::sync::OnceLock::new();
WORDS.get_or_init(|| Words::of_rows(&[]))
}
}
pub(crate) fn read_fact(definition: &TableDefinition, column: &Column, value: &Value,
data: &Map, zone: Option<&str>, now: Option>, words: &Words) -> Option {
if value.is_null() { return None; }
let template = column.reading.as_deref()?;
let text = if template.contains("{date}") || template.contains("{datetime}") {
let raw = value.as_str()?;
if let Ok(date) = chrono::DateTime::parse_from_rfc3339(raw) {
let at = crate::transforms::zoned_clock::zoned_parts(date.timestamp_millis(), zone.unwrap_or("Etc/UTC")).ok()?;
let day = crate::transforms::zoned_clock::day_number(at.year, at.month, at.day);
if template.contains("{datetime}") {
format!("{}, {}", words.dates.weekday_date(day, at.year), words.dates.clock(at.hour, at.minute))
} else {
words.dates.day_month(day, at.year)
}
} else {
if template.contains("{datetime}") { return None; }
let day = chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d").ok()?;
let year = i64::from(chrono::Datelike::year(&day));
words.dates.day_month(crate::transforms::zoned_clock::day_number(year, i64::from(chrono::Datelike::month(&day)), i64::from(chrono::Datelike::day(&day))), year)
}
} else if value.is_number() && template.replace("{value}", "").trim().len() > 0 {
let number = value.as_f64()?;
if column.column_type == ColumnType::Bytes || matches!(column.format, Some(ColumnFormat::Duration | ColumnFormat::DurationMs)) { number_words(definition, column, number, data, &words.dates)? } else { cotton_rules::computed::figure(number, column.decimals) }
} else {
fact_words(definition, column, value, data, zone, now, words)?
};
if text.trim().is_empty() { return None; }
Some(template.replace("{value}", &text).replace("{date}", &text).replace("{datetime}", &text))
}
/// What joins the head's facts into one line.
pub const FACT_JOIN: &str = " · ";
/// The tone a state tag carries when its column names none.
pub const PLAIN_TONE: &str = "plain";
/// What a page reads, and from where: the reads the app's core answers
/// through the generic verbs, or a test's synthetic rows.
pub trait PageSource {
/// The definition of `table`, or `None` when no read answers it.
fn definition(&mut self, table: &str) -> Option;
/// The record's values, keyed by column.
fn record(&mut self, table: &str, id: &str) -> Result, String>;
/// The live records among `ids`, in that order, as `(id, values)`.
fn records(&mut self, table: &str, ids: &[String]) -> Result)>, String>;
/// How many live records match `filter` (a list read's `where`), and the
/// first `limit` of them in the table's own order.
fn list(
&mut self,
table: &str,
filter: &Map,
limit: usize,
) -> Result<(u64, Vec<(String, Map)>), String>;
/// Every active project's slug: the roster a cap's colour is assigned
/// over.
fn active_project_slugs(&mut self) -> Vec;
/// The reader's own IANA zone, which a timed date is said in; `None`
/// says such a date as its day alone.
fn time_zone(&mut self) -> Option {
None
}
/// The database's `lines` rows (`rules::shell_lines`): a page's dates
/// are said in its `dates` words, the kit's for any line it has no row for.
fn line_rows(&mut self) -> Vec;
/// `read.` answered with `args`: only a [`PAGE_READS`] entry is
/// ever asked.
fn read(&mut self, name: &str, args: &Map) -> Result;
/// The reader's now, for a fact said against it ("read 2 min ago");
/// `None` says such a date as a day.
fn now(&mut self) -> Option> {
None
}
/// Every installed table's definition, in tool order: what finds the
/// lists that link to a record and the views over its table. A source
/// that knows none answers a page with no headed lists.
fn definitions(&mut self) -> Vec {
Vec::new()
}
/// The channels this database holds activity with a `kind` handle on
/// (its `normalised` form), each with its newest stamp: the evidence
/// [`channels_for_handle`] orders. A source that keeps none answers
/// none, and the handle offers its kind's own channels alone.
fn handle_activity(&mut self, _kind: &str, _normalised: &str) -> Vec {
Vec::new()
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RecordPage {
pub table: String,
pub id: String,
pub shape: PageShape,
/// The paper (a sheet) or index tab (a desk) colour: its project's.
pub colour: &'static str,
pub head: PageHead,
pub links: Vec,
pub body: Option,
pub lists: Vec,
pub acts: PageActs,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageHead {
pub title: String,
/// One line, already joined with " · "; empty when there are none.
pub facts: String,
pub state: Option,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageState {
pub label: String,
/// `red`, `amber`, `green`, or `plain`.
pub tone: &'static str,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageLink {
pub table: String,
pub id: String,
pub title: String,
/// The linked record's picture (a person's print), its object key.
#[serde(rename = "printKey")]
pub print_key: Option,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageBody {
pub column: String,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageList {
pub heading: String,
/// The other table; absent on a list over a read.
#[serde(skip_serializing_if = "Option::is_none")]
pub table: Option,
/// The read whose rows these are (`repoCommits`); absent on a table's.
#[serde(skip_serializing_if = "Option::is_none")]
pub read: Option,
pub count: u64,
pub rows: Vec,
/// What opens the whole list.
pub all: PageListAll,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageRow {
pub id: String,
pub title: String,
pub line: Option,
/// Words drawn at the row's right end (a commit's short hash); only a
/// read's row says them.
#[serde(skip_serializing_if = "Option::is_none")]
pub trailing: Option,
pub act: Option,
}
/// What opens a whole list: `records.list {table, where}`, or the read
/// `read. {args}`.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum PageListAll {
Table {
table: String,
#[serde(rename = "where")]
filter: Map,
},
Read { read: String, args: Map },
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageActs {
pub main: Option,
pub more: Vec,
pub away: Option,
}
/// An act: the command id `records.command` runs, and its label.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PageAct {
pub id: String,
pub label: String,
}
/// The page of `table`'s record `id`.
pub fn record_page(source: &mut dyn PageSource, table: &str, id: &str) -> Result {
let definition = source
.definition(table)
.ok_or_else(|| crate::definitions::no_tool_draws_this_table(&source.line_rows()))?;
let mut data = source.record(table, id)?;
super::project_read_data(&definition, &mut data);
let words = Words::of_rows(&source.line_rows());
page_of(source, &definition, &data, id, &words)
}
/// The page of a record already read (its values projected for reading).
fn page_of(source: &mut dyn PageSource, definition: &TableDefinition, data: &Map, id: &str, said_in: &Words) -> Result {
let table = definition.id.as_str();
let data = data.clone();
let zone = source.time_zone();
let zone = zone.as_deref();
let parts = definition.resolved_parts();
let record = Value::Object(data.clone());
// The fallback column declares where an untitled record borrows its
// name. Resolve long text through the shared title rule, never receipt
// wording (which clips names and removes a closing full stop).
let borrowed = text_of(&data, &definition.title).is_none()
.then(|| definition.slip.title_fallback.as_deref())
.flatten()
.filter(|key| definition.column(key).is_some_and(|column| column.column_type == ColumnType::Longtext && column.secret != Some(true) && column.shown_on(&data)))
.and_then(|key| crate::transforms::note_title::note_display_title(None, data.get(key)?.as_str()?).map(|title| (key, title)));
let title = definition
.heads
.iter()
.chain(std::iter::once(&definition.title))
.filter(|key| definition.column(key).is_some_and(|column| matches!(column.column_type, ColumnType::Text | ColumnType::Longtext | ColumnType::Place)))
.find_map(|key| text_of(&data, key))
.or_else(|| borrowed.as_ref().map(|(_, title)| title.clone()))
.unwrap_or_else(|| record_name_in(&definition, &record, &said_in.dates));
let now = source.now();
// The day heads the page when nothing titles the record in words (a
// journal day with no title): the app writes that day by hand as the
// heading, so the date is not said again as a fact under it.
let titled = definition
.heads
.iter()
.chain(std::iter::once(&definition.title))
.filter(|key| definition.date.as_deref() != Some(key.as_str()))
.any(|key| text_of(&data, key).is_some()) || borrowed.is_some();
let day_heads = definition.date.as_deref().filter(|_| !titled);
let mut facts = String::new();
let fact_keys = fact_columns(&definition, &parts);
for key in fact_keys.iter().copied() {
if day_heads == Some(key.as_str()) {
continue;
}
let (Some(column), Some(value)) = (definition.column(key), data.get(key)) else { continue };
if !column.shown_on(&data) {
continue;
}
let Some(words) = read_fact(&definition, column, value, &data, zone, now, said_in) else { continue };
// A fact that says the title again (a code host's address is its
// name) is said once, as the title.
if words.trim() == title {
continue;
}
if definition.parts.is_some()
|| column.format == Some(ColumnFormat::AppName)
|| !same_on_every_record(source, table, key, value)
{
if !facts.is_empty() { facts.push_str(column.fact_join.as_deref().unwrap_or(FACT_JOIN)); }
facts.push_str(&words);
}
}
let state = parts.head.state.as_deref().and_then(|key| {
let column = definition.column(key).filter(|column| column.shown_on(&data))?;
let value = data.get(key)?.as_str().map(str::trim).filter(|value| !value.is_empty())?;
let tone = column.tones.as_ref().and_then(|tones| tones.get(value)).map_or(PLAIN_TONE, |tone| match tone {
StampTone::Red => "red",
StampTone::Amber => "amber",
StampTone::Green => "green",
});
Some(PageState { label: column.choice_label(value), tone })
});
let mut links: Vec = Vec::new();
for key in &parts.links {
if fact_keys.contains(&key) { continue; }
let Some(column) = definition.column(key) else { continue };
let Some(target) = link_target(column, &data) else { continue };
let ids = ids_of(data.get(key));
if ids.is_empty() {
continue;
}
let Some(linked) = source.definition(&target) else { continue };
// A linked table no read answers today draws no chip; the page stands.
let Ok(found) = source.records(&target, &ids) else { continue };
for (linked_id, values) in found {
if links.iter().any(|link| link.table == target && link.id == linked_id) {
continue;
}
let print_key = linked
.slip
.photo
.as_deref()
.filter(|photo| linked.column(photo).is_some_and(|column| column.column_type == ColumnType::Photo))
.and_then(|photo| text_of(&values, photo));
links.push(PageLink {
table: target.clone(),
id: linked_id,
title: record_name_in(&linked, &Value::Object(values), &said_in.dates),
print_key,
});
}
}
let body = parts.body.as_ref().and_then(|key| {
if fact_keys.contains(&key) { return None; }
if definition.column(key).is_some_and(|column| !column.shown_on(&data)) {
return None;
}
let text = data.get(key)?.as_str().filter(|text| !text.trim().is_empty())?;
let text = match borrowed.as_ref() {
Some((from, borrowed_title)) if *from == key && borrowed_title == &title => crate::transforms::note_title::body_after_borrowed_title(text, borrowed_title),
_ => text,
};
if text.trim().is_empty() { return None; }
Some(PageBody { column: key.clone(), text: text.to_string() })
});
let mut lists = Vec::new();
for list in &parts.lists {
if let Some(read) = &list.read {
lists.extend(read_list(source, read, list.heading.as_deref(), id, &data, said_in));
continue;
}
let Some(table) = &list.table else { continue };
// RULE: A list over a table no tool draws, or whose definition lacks the list's relation or match
// column (another package narrowed it), draws no list and the page stands — never a refusal.
let Some(other) = source.definition(table) else { continue };
if list.holds_against(&other).is_err() {
continue;
}
let mut filter = Map::new();
match (&list.relation, &list.matching) {
(Some(relation), None) => {
filter.insert(relation.clone(), Value::from(id));
}
(None, Some(by)) => {
// RULE: A list matched by value lists only the other table's records whose column equals this record's parent value; that value empty, or the column not the other table's, draws no list.
let Some(value) = data.get(&by.parent).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()) else {
continue;
};
filter.insert(by.column.clone(), Value::from(value));
}
_ => continue,
}
let (count, found) = match source.list(table, &filter, LIST_ROWS) {
Ok(found) => found,
Err(error) => return Err(error),
};
if count == 0 {
continue;
}
let act = list.main_act.as_deref().and_then(|act| other.command(act));
let rows = found
.into_iter()
.take(LIST_ROWS)
.map(|(row_id, values)| {
let line = slip_line_in(&other, &values, zone, now, said_in);
let row = Value::Object(values);
PageRow {
id: row_id,
title: record_name_in(&other, &row, &said_in.dates),
line,
trailing: None,
act: act.filter(|act| act.offered_on(&row)).map(page_act),
}
})
.collect();
lists.push(PageList {
heading: list.heading.clone().unwrap_or_else(|| other.plural.clone()),
table: Some(table.clone()),
read: None,
count,
rows,
all: PageListAll::Table { table: table.clone(), filter },
});
}
let offered = |act: &Option| {
act.as_deref()
.and_then(|act| definition.command(act))
.filter(|command| command.offered_on(&record))
.map(page_act)
};
let acts = PageActs {
main: offered(&parts.acts.main),
more: parts.acts.more.iter().filter_map(|act| offered(&Some(act.clone()))).collect(),
away: offered(&parts.acts.away),
};
let colour = colour_of(source, &definition, &data);
Ok(RecordPage {
table: definition.id.clone(),
id: id.to_string(),
shape: parts.shape,
colour,
head: PageHead { title, facts, state },
links,
body,
lists,
acts,
})
}
/// A list over `read.`: its arguments bound from this record, its first
/// [`LIST_ROWS`] rows in the read's own order (newest first for commits), and
/// the count of every row it answered. A read off [`PAGE_READS`], one that
/// fails, or one answering no rows draws no list; the page stands.
fn read_list(
source: &mut dyn PageSource,
read: &PartsRead,
heading: Option<&str>,
id: &str,
data: &Map,
said_in: &Words,
) -> Option {
if !PAGE_READS.contains(&read.name.as_str()) {
return None;
}
let mut args = Map::new();
for (argument, column) in read.bindings.iter() {
let value = match column.as_str() {
"$id" => Value::from(id),
column => data.get(column).cloned().unwrap_or(Value::Null),
};
args.insert(argument.clone(), value);
}
let answer = source.read(&read.name, &args).ok()?;
let all = answer.get(&read.rows)?.as_array()?;
if all.is_empty() {
return None;
}
let text = |row: &Value, key: &str| row.get(key)?.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_string);
let zone = source.time_zone();
let words = |row: &Value, key: &str, format: Option| {
let text = text(row, key)?;
match format {
Some(ReadFormat::ShortHash) => Some(text.chars().take(SHORT_HASH).collect()),
Some(ReadFormat::Date) => calendar_words(&text, zone.as_deref(), false, false, &said_in.dates),
None => Some(text),
}
};
let rows = all
.iter()
.take(LIST_ROWS)
.filter_map(|row| {
let row_id = text(row, &read.id)?;
let title = text(row, &read.title)
.and_then(|title| title.lines().next().map(str::trim).map(str::to_string))
.unwrap_or_else(|| row_id.clone());
let trailing = read.trailing.as_deref().and_then(|key| words(row, key, read.trailing_format));
let line: Vec<_> = read.line.iter().flatten().filter_map(|field| words(row, &field.field, field.format)).collect();
let line = (!line.is_empty()).then(|| line.join(FACT_JOIN));
Some(PageRow { id: row_id, title, line, trailing, act: None })
})
.collect();
Some(PageList {
heading: heading.map_or_else(|| key_as_words(&read.rows), str::to_string),
table: None,
read: Some(read.name.clone()),
count: all.len() as u64,
rows,
all: PageListAll::Read { read: read.name.clone(), args },
})
}
/// An act as its definition says it: an act carries no placeholder.
fn page_act(command: &RecordCommand) -> PageAct {
PageAct { id: command.id.clone(), label: command.label.clone() }
}
/// A value of a column that is a fact the same on every record of the table
/// ("can read and change" on every assistant) says nothing about this one.
/// A table of one record, or a value no read can narrow by, keeps its fact.
fn same_on_every_record(source: &mut dyn PageSource, table: &str, key: &str, value: &Value) -> bool {
if !matches!(value, Value::String(_) | Value::Number(_) | Value::Bool(_)) {
return false;
}
let Ok((all, _)) = source.list(table, &Map::new(), 1) else { return false };
if all < 2 {
return false;
}
let mut filter = Map::new();
filter.insert(key.to_string(), value.clone());
matches!(source.list(table, &filter, 1), Ok((same, _)) if same == all)
}
/// A link column's table: its own `link_to`, or the one its `link_by` choice
/// names on this record.
fn link_target(column: &Column, data: &Map) -> Option {
if let Some(table) = &column.link_to {
return Some(table.clone());
}
let by = column.link_by.as_ref()?;
let choice = data.get(&by.column)?.as_str()?;
by.tables.get(choice).cloned()
}
/// The record ids a link value holds: one, or a list.
fn ids_of(value: Option<&Value>) -> Vec {
let one = |value: &Value| value.as_str().map(str::trim).filter(|id| !id.is_empty()).map(str::to_string);
match value {
Some(Value::Array(items)) => items.iter().filter_map(one).collect(),
Some(value) => one(value).into_iter().collect(),
None => Vec::new(),
}
}
fn text_of(data: &Map, key: &str) -> Option {
data.get(key)?
.as_str()
.map(str::trim)
.filter(|text| !text.is_empty())
.map(str::to_string)
}
/// Resolved display words, carried beside typed record data rather than stored
/// as engine columns. The app draws these strings without composing them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResolvedSlipLines {
pub subtitle: Option,
pub caption: Option,
/// The caption's date is a day gone on a table that owes its records by
/// their day: it reads in red.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub caption_late: bool,
}
pub const SLIP_SUBTITLE_KEY: &str = "@slip_subtitle";
/// The slip's lines from another table (`slip.lines`), one string each.
pub const SLIP_LINES_KEY: &str = "@slip_lines";
pub const SLIP_CAPTION_KEY: &str = "@slip_caption";
/// Whether the caption reads in red (`ResolvedSlipLines::caption_late`).
pub const SLIP_CAPTION_LATE_KEY: &str = "@slip_caption_late";
pub const SLIP_FIGURE_KEY: &str = "@slip_figure";
/// The definition's figure read by the core, including its currency's own
/// grouping. The app draws this beside the unmodified numeric column.
pub fn resolve_slip_figure(definition: &TableDefinition, data: &Map, zone: Option<&str>, now: Option>, words: &Words) -> Option {
let key = definition.slip.figure.as_deref()?;
let column = definition.column(key)?;
if column.secret == Some(true) || !column.shown_on(data) { return None; }
fact_words(definition, column, data.get(key)?, data, zone, now, words)
}
/// A column whose `reading` says more than its bare value ("removed by
/// {value}", "{value} min away"): the slip says it through that reading.
pub(crate) fn says_more_than_its_value(column: &Column) -> bool {
column.reading.as_deref().is_some_and(|reading| {
let reading = reading.trim();
!reading.is_empty() && reading != "{value}"
})
}
/// Whether a slip's subtitle needs the core's words: readings and typed
/// dates must be resolved before a surface receives the line.
pub fn subtitle_reads(definition: &TableDefinition) -> bool {
definition
.slip
.subtitles()
.iter()
.map(String::as_str)
.chain(definition.slip.subtitle_fallback.as_deref())
.filter_map(|key| definition.column(key))
.any(|column| says_more_than_its_value(column) || matches!(column.column_type, ColumnType::Text | ColumnType::Longtext | ColumnType::Amount | ColumnType::Date))
}
/// Read the definition's slip lines from typed values. A named subtitle
/// puts the column's name after its value; date formats use the caller's clock.
/// `day_headed`: the caller draws this slip under a heading that names its
/// day (the definition's `by_day`/`day_grouping`), so that date says its
/// clock time alone; elsewhere the day is said.
pub fn resolve_slip_lines(
definition: &TableDefinition,
data: &Map,
zone: Option<&str>,
now: Option>,
day_headed: bool,
said_in: &Words,
) -> ResolvedSlipLines {
let public = super::public_read_data(definition, data);
let data = public.as_ref();
let fact = |key: &str, named: bool| -> Option {
let column = definition.column(key)?;
if !column.shown_on(data) { return None; }
let value = data.get(key)?;
if column.secret == Some(true) {
// A secret says only its masked tail on a slip: never its raw
// number, a reading of it or a title borrowed from it.
let masked = fact_words(definition, column, value, data, zone, now, said_in)?;
return Some(if named { format!("{masked} {}", column.label()) } else { masked });
}
// A borrowed title owns its opening line on a slip too. Resolving
// native previews must preserve the same split the page uses.
let remainder = (column.column_type == ColumnType::Longtext
&& definition.slip.title_fallback.as_deref() == Some(key)
&& text_of(data, &definition.title).is_none()).then(|| {
let body = value.as_str()?;
let title = crate::transforms::note_title::note_display_title(None, body)?;
Some(Value::from(crate::transforms::note_title::body_after_borrowed_title(body, &title)))
}).flatten();
let value = remainder.as_ref().unwrap_or(value);
if let Some(form) = definition.slip.forms.as_ref().and_then(|forms| forms.get(key)) {
let words = form_words(definition, column, value, data, zone, now, *form, said_in)?;
return Some(if named { format!("{words} {}", column.label()) } else { words });
}
let subtitle = definition.slip.subtitles().iter().any(|line| line == key)
|| definition.slip.subtitle_fallback.as_deref() == Some(key);
let words = if subtitle && !named && says_more_than_its_value(column) {
read_fact(definition, column, value, data, zone, now, said_in)?
} else if named && column.column_type == ColumnType::Number && column.format.is_none() && column.units.is_none() {
let number = value.as_f64()?;
if number.fract() == 0.0 { format!("{}", number as i64) } else { number.to_string() }
} else {
fact_words(definition, column, value, data, zone, now, said_in)?
};
if words.trim().is_empty() { return None; }
Some(if named && column.column_type != ColumnType::Bool { format!("{words} {}", column.label()) } else { words })
};
let mut subtitle: Vec = definition.slip.subtitles().iter().filter_map(|key| fact(key, definition.slip.with_names == Some(true))).collect();
if definition.slip.subtitle_first == Some(true) { subtitle.truncate(1); }
if subtitle.is_empty() {
subtitle.extend(definition.slip.subtitle_fallback.as_deref().and_then(|key| fact(key, definition.slip.with_names == Some(true))));
}
// Under a heading naming the day a line says its own clock time only,
// never the day again (walker 604bcce6: "16 Oct 2026, 14:30" under
// "Today"); a bare day says nothing the heading did not. Only the caller
// knows whether the list it draws has such headings.
let headed = |key: &str| -> Option> {
// An `ago` column keeps its relative words ("3 min ago") under any heading.
(day_headed && (definition.day_grouping.as_deref() == Some(key) || definition.by_day.as_deref() == Some(key)))
.then_some(())
.filter(|_| definition.column(key).is_none_or(|column| !matches!(column.format, Some(ColumnFormat::Ago | ColumnFormat::Countdown))))
.map(|()| data.get(key).and_then(Value::as_str).and_then(|text| clock_only(text, zone, &said_in.dates)))
};
let caption_words = |key: &str| headed(key).unwrap_or_else(|| fact(key, false));
let mut caption = Vec::new();
let mut caption_late = false;
if let Some(layout) = &definition.slip.caption {
// The first date holding a day leads, said against the reader's now
// as the typed relative form; its position names it, so no label.
// A column with its own relative format (ago, countdown) keeps it.
for key in layout.dates.iter().flatten() {
let Some(column) = definition.column(key) else { continue };
if let Some(clock) = headed(key).filter(|_| data.get(key).is_some_and(|value| !value.is_null())) {
caption.extend(clock);
break;
}
let relative = now
.filter(|_| column.column_type == ColumnType::Date && column.secret != Some(true) && column.shown_on(data))
.filter(|_| !matches!(column.format, Some(ColumnFormat::Ago | ColumnFormat::Countdown)))
.and_then(|now| Some((now, data.get(key)?.as_str()?)))
.and_then(|(now, text)| caption_date_line(definition, column, text, zone.unwrap_or("Etc/UTC"), now, &said_in.dates));
if let Some(line) = relative {
caption_late = line.late;
caption.push(line.text);
break;
}
if let Some(line) = fact(key, false) {
caption.push(line);
break;
}
}
caption.extend(layout.columns.iter().flatten().filter_map(|key| caption_words(key)));
if let Some(status) = &layout.status {
let column = definition.column(status);
let value = data.get(status).and_then(Value::as_str);
if value.is_some() && value != column.and_then(|column| column.choices.as_ref()).and_then(|choices| choices.first()).map(String::as_str) {
caption.extend(fact(status, false));
}
}
caption.extend(layout.fields.iter().flatten().filter_map(|key| caption_words(key)));
}
ResolvedSlipLines {
subtitle: (!subtitle.is_empty()).then(|| subtitle.join(FACT_JOIN)),
caption: (!caption.is_empty()).then(|| caption.join(FACT_JOIN)),
caption_late,
}
}
/// Each record's `slip.lines`: the rows of the other table that link to it,
/// each said as that table's slip says it — its title, then its line. A
/// relation that is not a link to this table draws no lines.
pub fn resolve_slip_rows(
source: &mut dyn PageSource,
definition: &TableDefinition,
ids: &[String],
) -> Result>, String> {
let mut said = std::collections::BTreeMap::>::new();
let Some(lines) = &definition.slip.lines else { return Ok(said) };
let dates = DateWords::of_rows(&source.line_rows());
let Some(other) = source.definition(&lines.table) else { return Ok(said) };
let links_here = other.column(&lines.relation).is_some_and(|column| {
column.column_type == ColumnType::Link && column.link_to.as_deref() == Some(definition.id.as_str())
});
if !links_here || ids.is_empty() {
return Ok(said);
}
let zone = source.time_zone();
let now = source.now();
let said_in = Words::of_rows(&source.line_rows());
for id in ids {
let mut filter = Map::new();
filter.insert(lines.relation.clone(), Value::from(id.as_str()));
let (_, rows) = source.list(&lines.table, &filter, lines.rows())?;
let words = rows
.into_iter()
.take(lines.rows())
.map(|(_, values)| {
let line = slip_line_in(&other, &values, zone.as_deref(), now, &said_in);
let title = record_name_in(&other, &Value::Object(values), &dates);
line.map_or_else(|| title.clone(), |line| format!("{title}{FACT_JOIN}{line}"))
})
.collect();
said.insert(id.clone(), words);
}
Ok(said)
}
/// The words a list's row says under its title: what its slip says beside
/// the title, as facts. Public: a business's customer reads its public rows
/// with no local copy and draws each line the same way
/// (`cotton_ffi::phone::customer_sign_in`).
pub fn slip_line(definition: &TableDefinition, data: &Map, zone: Option<&str>, now: Option>) -> Option {
slip_line_in(definition, data, zone, now, Words::shipped())
}
/// [`slip_line`] in one database's words.
pub fn slip_line_in(definition: &TableDefinition, data: &Map, zone: Option<&str>, now: Option>, said_in: &Words) -> Option {
let mut said: Vec = resolve_slip_lines(definition, data, zone, now, false, said_in).subtitle.into_iter().collect();
if let Some(key) = &definition.slip.trailing {
if let Some(words) = definition.column(key).and_then(|column| data.get(key).and_then(|value| fact_words(definition, column, value, data, zone, now, said_in))) { said.push(words); }
}
(!said.is_empty()).then(|| said.join(FACT_JOIN))
}
/// One value as a page's fact line says it, under its label: the label is
/// drawn apart, so the value never repeats it. A switch says on or off (the
/// `record` set's `switch` words), a bare number only its figure; every other
/// value is said as [`fact_words`] says it.
pub fn labelled_fact_words(
definition: &TableDefinition,
column: &Column,
value: &Value,
data: &Map,
zone: Option<&str>,
now: Option>,
words: &Words,
) -> Option {
match column.column_type {
_ if value.is_null() || column.secret == Some(true) => fact_words(definition, column, value, data, zone, now, words),
ColumnType::Bool => words.record.say(if value.as_bool()? { "switch.on" } else { "switch.off" }, &[]),
ColumnType::Number if column.units.is_none() && column.format.is_none() => value.as_f64().filter(|n| n.is_finite()).map(figure_of),
_ => fact_words(definition, column, value, data, zone, now, words),
}
}
/// One value as a fact on the page's line, or `None` when it says nothing.
/// A secret shows only its last four letters; a timed date is said in `zone`.
pub fn fact_words(
definition: &TableDefinition,
column: &Column,
value: &Value,
data: &Map,
zone: Option<&str>,
now: Option>,
words: &Words,
) -> Option {
if value.is_null() {
return None;
}
if column.secret == Some(true) {
let text = value.as_str()?.trim();
if text.is_empty() {
return None;
}
let tail: String = text.chars().rev().take(4).collect::>().into_iter().rev().collect();
return Some(match text.contains('•') {
true => text.to_string(),
false => format!("•••• {tail}"),
});
}
if column.column_type == ColumnType::Text {
if let Some(labels) = &column.labels {
let raw = value.as_str()?.trim();
if raw.is_empty() { return None; }
if let Some(words) = labels.get(raw) {
return (!words.trim().is_empty()).then(|| words.clone());
}
let key = match column.format {
Some(ColumnFormat::RepeatRule) => crate::transforms::recurrence_presets::preset_for_rrule(Some(raw)).as_str(),
_ => raw,
};
// An unmapped engine token is unknown, not a display name.
return labels.get(key).filter(|words| !words.trim().is_empty()).cloned();
}
// An app's token unlabelled is unknown; an unlabelled repeat rule
// reads as its preset below.
if column.format == Some(ColumnFormat::AppName) {
return None;
}
}
match column.column_type {
ColumnType::AccountNumber => value.as_str().map(super::account_number_ending),
ColumnType::Choice => {
let words: Vec = match value {
Value::Array(items) => items.iter().filter_map(Value::as_str).map(|one| column.choice_label(one)).collect(),
Value::String(one) if !one.trim().is_empty() => vec![column.choice_label(one.trim())],
_ => Vec::new(),
};
(!words.is_empty()).then(|| words.join(", "))
}
ColumnType::Text if column.format == Some(ColumnFormat::RepeatRule) => {
words.dates.repeat(value.as_str())
}
ColumnType::Text if column.format == Some(ColumnFormat::Words) => {
value.as_str().map(str::trim).filter(|text| !text.is_empty()).map(key_as_words)
}
ColumnType::Text if value.is_array() => {
let all: Vec<&str> = value.as_array()?.iter().filter_map(Value::as_str).filter(|one| !one.trim().is_empty()).collect();
(!all.is_empty()).then(|| all.join(", "))
}
ColumnType::Date => match (column.format, now) {
(Some(ColumnFormat::Ago), Some(now)) => {
let ago = ago_words(value.as_str()?, now, &words.dates).or_else(|| date_words(column, value.as_str()?, zone, &words.dates))?;
Some(templated(column, &ago).unwrap_or(ago))
}
(Some(ColumnFormat::Countdown), Some(now)) => match countdown_words(value.as_str()?, now, &words.dates) {
Some(left) => Some(templated(column, &left).unwrap_or(left)),
// Passed: the definition's own word, else nothing — a
// countdown that is over is never drawn as one. A day kept
// without its time is over once the reader's day is past it.
None if parsed_instant(value.as_str()?).is_some()
|| day_passed(value.as_str()?, zone.unwrap_or("Etc/UTC"), now) => column
.units
.as_ref()
.and_then(|units| units.zero.clone())
.filter(|zero| !zero.trim().is_empty()),
None => date_words(column, value.as_str()?, zone, &words.dates),
},
// No reader's now: the instant itself, never a countdown.
_ => date_words(column, value.as_str()?, zone, &words.dates),
},
ColumnType::Bool => (value.as_bool() == Some(true)).then(|| column.label()),
ColumnType::Number | ColumnType::Bytes => number_words(definition, column, value.as_f64()?, data, &words.dates),
ColumnType::Amount => {
let form = if column.signed == Some(true) { MoneyForm::MoneySigned } else { MoneyForm::Money };
amount_words(definition, column, value, data, form, &words.money)
}
ColumnType::Text | ColumnType::Longtext => crate::transforms::note_title::plain_preview(value.as_str()?).lines().map(str::trim).find(|line| !line.is_empty()).map(str::to_string),
ColumnType::Link | ColumnType::Photo | ColumnType::File => None,
_ => said_value_in(column, value, &words.dates),
}
}
/// An amount column with `signs`, as its sentences: "Example owes you
/// ₹1,200", "You owe Example ₹300", the zero sentence at nothing — one per
/// amount the value holds (`{minor, currency}`, or a list of them, one per
/// currency, never netted), joined by a middle dot. `{first}` is the first
/// word of the record's title and `{title}` the title.
fn signed_amount_words(definition: &TableDefinition, column: &Column, value: &Value, data: &Map, money: &crate::records::amount::MoneyWords) -> Option {
let signs = column.signs.as_ref()?;
let amounts: Vec<&Value> = match value {
Value::Array(items) => items.iter().collect(),
Value::Null => Vec::new(),
one => vec![one],
};
let title = text_of(data, &definition.slip.title);
let fill = |template: &str| {
let first = title.as_deref().and_then(|title| title.split_whitespace().next()).unwrap_or("them");
let whole = title.clone().unwrap_or_else(|| format!("this {}", definition.name.to_lowercase()));
template.replace("{first}", first).replace("{title}", &whole)
};
let said: Vec = amounts
.into_iter()
.filter_map(|amount| {
let amount = amount.as_object()?;
let minor = amount.get("minor")?.as_f64()?;
if minor == 0.0 {
return Some(fill(signs.zero.as_deref().unwrap_or(&signs.positive)));
}
let code = amount.get("currency")?.as_str()?;
let figure = crate::records::amount::amount(minor.abs().round() as i64, Some(code), money).said(MoneyForm::Money, money);
Some(format!("{} {figure}", fill(if minor > 0.0 { &signs.positive } else { &signs.negative })))
})
.collect();
(!said.is_empty()).then(|| said.join(" \u{b7} "))
}
/// An amount column's value in its row's currency, said in `form`.
fn amount_words(definition: &TableDefinition, column: &Column, value: &Value, data: &Map, form: MoneyForm, money: &crate::records::amount::MoneyWords) -> Option {
let minor = value.as_i64()?;
let currency = column
.currency
.as_deref()
.filter(|key| definition.column(key).is_some_and(|column| column.column_type != ColumnType::Link))
.and_then(|key| text_of(data, key));
Some(crate::records::amount::amount(minor, currency.as_deref(), money).said(form, money))
}
/// A column's value said in the form its definition names for where it is
/// drawn (transforms contract 6): a date form through the `dates` set
/// against the reader's now, money through the amount transform, a count
/// grouped, a duration from its seconds. `None` when there is nothing to say.
#[allow(clippy::too_many_arguments)]
pub fn form_words(
definition: &TableDefinition,
column: &Column,
value: &Value,
data: &Map,
zone: Option<&str>,
now: Option>,
form: crate::definitions::Form,
words: &Words,
) -> Option {
use crate::definitions::Form;
if value.is_null() || column.secret == Some(true) { return None; }
match form {
Form::Money => amount_words(definition, column, value, data, MoneyForm::Money, &words.money),
Form::MoneySigned => amount_words(definition, column, value, data, MoneyForm::MoneySigned, &words.money),
Form::Count => figure_words(value, false, None, &words.money),
Form::ShortRef => value.as_str().map(str::trim).filter(|id| !id.is_empty()).map(|id| words.short_ref(id)),
Form::Duration => words.dates.duration((value.as_f64()? * 1000.0).round() as i64),
Form::Clock => clock_words(column, value.as_f64()?),
Form::Year => value.as_str().map(str::trim).filter(|text| text.len() >= 4 && text.as_bytes()[..4].iter().all(u8::is_ascii_digit)).map(|text| text[..4].to_string()),
Form::DayMonth => {
let zone = zone.unwrap_or("Etc/UTC");
let (day, today) = Moment::parse(value.as_str()?, zone).zip(Moment::now(now?, zone))?;
Some(words.dates.day_month(day.day, crate::transforms::zoned_clock::civil_from_days(today.day).0))
}
Form::Ago => ago_words(value.as_str()?, now?, &words.dates).or_else(|| date_words(column, value.as_str()?, zone, &words.dates)),
Form::Relative
| Form::WeekdayDate
| Form::WeekdayNameDate
| Form::WeekdayDateYear
| Form::Age
| Form::Turns
| Form::Countdown
| Form::Late
| Form::NextOccurrence
| Form::Since => {
date_form_line(definition, column, value.as_str()?, zone.unwrap_or("Etc/UTC"), now?, Some(form), 7, &words.dates).map(|line| line.text)
}
}
}
/// The seconds in one of a length column's stored units: milliseconds where
/// it is kept in them, minutes or hours where its units say so, else seconds.
fn seconds_per_unit(column: &Column) -> f64 {
match column.format {
Some(ColumnFormat::DurationMs) => 0.001,
_ => match column.units.as_ref().map(|units| units.one.as_str()) {
Some("minute" | "min") => 60.0,
Some("hour" | "h") => 3600.0,
_ => 1.0,
},
}
}
/// A length as a player's clock: minutes and seconds ("3:42"), with the
/// hours before them once there are any ("1:04:05"), in the column's own
/// unit ([`seconds_per_unit`]).
fn clock_words(column: &Column, number: f64) -> Option {
clock_said(number * seconds_per_unit(column))
}
/// Seconds as a player's clock: "3:42", "1:04:05"; none for a length that
/// is no length.
pub fn clock_said(seconds: f64) -> Option {
let seconds = seconds.round();
if !seconds.is_finite() || seconds < 0.0 {
return None;
}
let seconds = seconds as i64;
let (hours, minutes, seconds) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
Some(match hours {
0 => format!("{minutes}:{seconds:02}"),
_ => format!("{hours}:{minutes:02}:{seconds:02}"),
})
}
/// A date's `ago` said in its units' template ("read {n}"), when it has one.
fn templated(column: &Column, ago: &str) -> Option {
let template = &column.units.as_ref()?.other;
template.contains("{n}").then(|| template.replace("{n}", ago))
}
/// How long before `now` a stamp is, in the reader's words ("3 min ago");
/// see [`DateWords::ago`].
pub fn ago_words(text: &str, now: chrono::DateTime, dates: &DateWords) -> Option {
let at = chrono::DateTime::parse_from_rfc3339(text.trim()).ok()?.with_timezone(&chrono::Utc);
dates.ago(now.signed_duration_since(at).num_seconds())
}
fn parsed_instant(text: &str) -> Option> {
chrono::DateTime::parse_from_rfc3339(text.trim()).ok().map(|at| at.with_timezone(&chrono::Utc))
}
/// Whether a bare day (`YYYY-MM-DD`) is before the reader's day in `zone`.
fn day_passed(text: &str, zone: &str, now: chrono::DateTime) -> bool {
let text = text.trim();
text.len() == 10
&& Moment::parse(text, zone)
.zip(Moment::now(now, zone))
.is_some_and(|(day, today)| day.day < today.day)
}
/// How long from `now` until the instant `text`, in the reader's words
/// ([`DateWords::left`]). `None` once the instant is at or before now, or
/// when `text` is not an instant: a countdown is always from the reader's
/// now, never from the moment the value was written.
pub fn countdown_words(text: &str, now: chrono::DateTime, dates: &DateWords) -> Option {
dates.left(parsed_instant(text)?.signed_duration_since(now).num_seconds())
}
/// A date as the page says it: "7 Oct 2026"; a yearly one "7 Oct"; a month
/// "Oct 2026"; an instant read in the reader's zone, with its clock time
/// unless that is midnight there (a day is enough): "8 Oct 2026, 16:30".
fn date_words(column: &Column, text: &str, zone: Option<&str>, dates: &DateWords) -> Option {
if column.format == Some(ColumnFormat::CalendarDatetime) && text.trim().as_bytes().get(10) == Some(&b'T') {
let ms = cotton_store::protocol::js::parse_date_ms(text.trim())?;
let at = crate::transforms::zoned_clock::zoned_parts(ms, zone.unwrap_or("Etc/UTC")).ok()?;
let day = crate::transforms::zoned_clock::day_number(at.year, at.month, at.day);
return Some(format!("{}, {}", dates.day_month(day, i64::MIN), dates.clock(at.hour, at.minute)));
}
calendar_words(text, zone, column.month == Some(true), column.yearly == Some(true), dates)
}
/// An instant's clock time alone in `zone` ("4:30 pm"), for a line under a
/// heading that already names its day; `None` for a bare day or midnight.
fn clock_only(text: &str, zone: Option<&str>, dates: &DateWords) -> Option {
let text = text.trim();
if text.as_bytes().get(10) != Some(&b'T') { return None; }
let ms = cotton_store::protocol::js::parse_date_ms(text)?;
let at = crate::transforms::zoned_clock::zoned_parts(ms, zone.unwrap_or("Etc/UTC")).ok()?;
(at.hour, at.minute).ne(&(0, 0)).then(|| dates.clock(at.hour, at.minute))
}
fn calendar_words(text: &str, zone: Option<&str>, month_only: bool, yearly: bool, dates: &DateWords) -> Option {
let text = text.trim();
let instant = text.len() > 10 && text.as_bytes().get(10) == Some(&b'T');
if let (true, Some(zone), false, false) = (instant, zone, month_only, yearly) {
let ms = cotton_store::protocol::js::parse_date_ms(text)?;
let at = crate::transforms::zoned_clock::zoned_parts(ms, zone).ok()?;
let day = dates.day_month(crate::transforms::zoned_clock::day_number(at.year, at.month, at.day), i64::MIN);
return Some(match (at.hour, at.minute) {
(0, 0) => day,
(hour, minute) => format!("{day}, {}", dates.clock(hour, minute)),
});
}
// A yearly day has no year: said in its own year's form, which names none.
let month_of = |month: i64| (1..=12).contains(&month).then(|| dates.month(month));
if let Some(month_day) = text.strip_prefix("--") {
let (month, day) = month_day.split_once('-')?;
let month: i64 = month.parse().ok()?;
let day: i64 = day.get(..2).unwrap_or(day).parse().ok()?;
month_of(month)?;
return Some(dates.day_month(crate::transforms::zoned_clock::day_number(2000, month, day), 2000));
}
let year: i64 = text.get(..4)?.parse().ok()?;
let month: i64 = text.get(5..7)?.parse().ok()?;
let month_name = month_of(month)?;
if month_only {
return Some(format!("{month_name} {year}"));
}
let day: i64 = text.get(8..10)?.parse().ok()?;
let at = crate::transforms::zoned_clock::day_number(year, month, day);
Some(dates.day_month(at, if yearly { year } else { i64::MIN }))
}
/// A number with its units ("3 turns"), its format ("2.1 MB", "1 h 4 min"),
/// else its column's name ("Priority 1").
fn number_words(definition: &TableDefinition, column: &Column, number: f64, data: &Map, dates: &DateWords) -> Option {
let plain = if number.fract() == 0.0 { format!("{}", number as i64) } else { format!("{number}") };
if column.column_type == ColumnType::Bytes || column.format == Some(ColumnFormat::Bytes) { return Some(bytes_words(number)); }
if matches!(column.format, Some(ColumnFormat::Duration | ColumnFormat::DurationMs)) {
return duration_words(column, number, dates);
}
if let Some(units) = &column.units {
if number == 0.0 {
return unit_words(definition, units.zero.as_deref()?, data).map(|zero| zero.replace("{n}", "0")).filter(|zero| !zero.trim().is_empty());
}
let unit = if number == 1.0 { &units.one } else { &units.other };
let unit = unit_words(definition, unit, data)?;
// A unit that names `{n}` is the whole phrase ("done {n} times
// before"); `one` may then say it without the number ("done once").
if units.other.contains("{n}") {
return Some(unit.replace("{n}", &plain));
}
return Some(format!("{plain} {unit}"));
}
Some(format!("{} {plain}", column.label()))
}
/// A duration uses the column's declared input unit and one core reading on every surface.
/// `duration_ms` is milliseconds; `duration` defaults to seconds and can declare minutes or hours.
pub fn duration_words(column: &Column, number: f64, dates: &DateWords) -> Option {
if column.secret == Some(true) || !number.is_finite() || number <= 0.0 { return None; }
let scale = match column.format {
Some(ColumnFormat::DurationMs | ColumnFormat::Duration) => seconds_per_unit(column),
_ => return None,
};
// Round once to the stored precision. Converting seconds through typed
// minutes can otherwise turn 123 seconds into 122.99999999999999.
let millis = (number * scale * 1000.0).round();
if millis < 1.0 || millis >= i64::MAX as f64 { return None; }
dates.duration(millis as i64)
}
/// Resolved numeric column words travel beside typed values; a card must never compact a duration.
pub const COLUMN_WORDS_KEY: &str = "@column_words";
/// What each typed column of a record reads as on a face, resolved here so no
/// face turns a date or a length into words of its own (Swift draws these).
/// A column is named with `null` when it says nothing; a column it leaves
/// out is not read here (a yearly day still reads on the phone).
pub fn column_words(
definition: &TableDefinition,
data: &Map,
zone: Option<&str>,
now: Option>,
words: &Words,
) -> Map {
// A field card that names a form says its column in it (contract 6).
let parts = definition.resolved_parts();
let card_form = |key: &str| {
parts.cards.iter().chain(parts.strip.iter()).flatten()
.find(|card| card.column.as_deref() == Some(key))
.and_then(|card| card.form)
};
definition
.columns
.iter()
.filter(|column| column.secret != Some(true))
.filter_map(|column| {
let value = data.get(&column.key).filter(|value| !value.is_null());
if let Some(form) = card_form(&column.key) {
let words = value.and_then(|value| form_words(definition, column, value, data, zone, now, form, words));
return Some((column.key.clone(), words.map(Value::String).unwrap_or(Value::Null)));
}
let words = match column.column_type {
ColumnType::Date if column.yearly == Some(true) => return None,
ColumnType::Date => value.and_then(|value| match column.format {
Some(ColumnFormat::Ago | ColumnFormat::Countdown | ColumnFormat::CalendarDatetime) => {
fact_words(definition, column, value, data, zone, now, words)
}
_ => face_date_words(column, value.as_str()?, zone, now, &words.dates),
}),
ColumnType::Amount if column.signs.is_some() => value.and_then(|value| signed_amount_words(definition, column, value, data, &words.money)),
ColumnType::Amount if value.is_none_or(|value| value.is_i64()) => {
value.and_then(|value| fact_words(definition, column, value, data, zone, now, words))
}
_ if reads_duration(column) => value.and_then(Value::as_f64).and_then(|number| duration_words(column, number, &words.dates)),
ColumnType::Number | ColumnType::Bytes => value.and_then(Value::as_f64).and_then(|number| face_number_words(definition, column, number, data)),
ColumnType::Time => value.and_then(Value::as_str).and_then(|text| face_clock_words(text, &words.dates)),
// A repeat rule reads as its labels, else the preset's words
// (`fact_words`), so no face spells an RRULE.
ColumnType::Text if column.format == Some(ColumnFormat::RepeatRule) => match value {
Some(value) => fact_words(definition, column, value, data, zone, now, words),
None if column.labels.is_none() => words.dates.repeat(None),
None => None,
},
// A token kept as words reads as a sentence ("inProgress" →
// "In progress"), before any label.
ColumnType::Text | ColumnType::Choice if column.format == Some(ColumnFormat::Words) => {
value.and_then(Value::as_str).map(key_as_words).filter(|words| !words.is_empty())
}
// A zone reads as their clock, only when it is not the reader's.
ColumnType::Text if column.zone == Some(true) && column.labels.is_none() && column.multiple != Some(true) => {
value.and_then(Value::as_str).zip(zone).zip(now)
.and_then(|((theirs, reader), now)| their_time(theirs, reader, now, &words.dates))
}
_ => return None,
};
Some((column.key.clone(), words.map(Value::String).unwrap_or(Value::Null)))
})
.collect()
}
/// Whether any column of the table reads through `column_words`.
pub fn reads_column_words(definition: &TableDefinition) -> bool {
definition.columns.iter().any(|column| {
column.secret != Some(true)
&& (matches!(column.column_type, ColumnType::Date | ColumnType::Amount | ColumnType::Number | ColumnType::Bytes | ColumnType::Time)
|| (column.column_type == ColumnType::Text && (column.format == Some(ColumnFormat::RepeatRule) || column.zone == Some(true)))
|| (matches!(column.column_type, ColumnType::Text | ColumnType::Choice) && column.format == Some(ColumnFormat::Words)))
})
}
/// A computed figure (a chart's bucket, a tile's sum) as a face writes it:
/// an amount in its currency through the money transform, a whole number
/// grouped, a fraction to one place. `None` for a value that is no number.
pub fn figure_words(value: &Value, amount: bool, currency: Option<&str>, money: &crate::records::amount::MoneyWords) -> Option {
if amount {
let minor = value.as_i64().or_else(|| value.as_f64().map(|number| number.round() as i64))?;
return Some(crate::records::amount::amount(minor, currency, money).said(crate::records::amount::MoneyForm::Money, money));
}
let number = value.as_f64()?;
if number.fract() == 0.0 && number.abs() < i64::MAX as f64 {
return Some(crate::rules::shell_lines::number(number as i64));
}
let tenths = (number * 10.0).round() / 10.0;
Some(match tenths.fract() == 0.0 {
true => crate::rules::shell_lines::number(tenths as i64),
false => format!("{tenths:.1}"),
})
}
/// A number as a face says it: a size ("2.1 MB"), else the figure grouped
/// ("1,240") with its units picked by CLDR ("6 orders", "1 order"), a zero as
/// its units' zero sentence ("Sold out"; an empty one says nothing), and a
/// unit that names `{n}` as the whole phrase ("done 3 times before"). A
/// plain number marked as a size that is 0 says nothing: nobody measured it.
fn face_number_words(definition: &TableDefinition, column: &Column, number: f64, data: &Map) -> Option {
if !number.is_finite() { return None; }
if column.column_type == ColumnType::Bytes || column.format == Some(ColumnFormat::Bytes) {
if number == 0.0 {
if let Some(zero) = column.units.as_ref().and_then(|units| units.zero.as_ref()) {
return (!zero.trim().is_empty()).then(|| zero.clone());
}
if column.column_type == ColumnType::Number { return None; }
}
return Some(bytes_words(number));
}
let Some(units) = &column.units else { return Some(figure_of(number)) };
units_count_words(units, number, &|template| unit_words(definition, template, data))
}
/// A number grouped as a person reads it when it is whole ("1,204"), else as
/// written.
fn figure_of(number: f64) -> String {
if number.fract() == 0.0 && number.abs() < i64::MAX as f64 {
crate::rules::shell_lines::number(number as i64)
} else {
format!("{number}")
}
}
/// A count in a definition's units: "6 orders", "1 order", "done once
/// before", and the zero sentence at nothing ("Sold out") when the units
/// have one. The number is grouped and the unit picked by CLDR's plural
/// rules; `fill` says a template's row fields (`{count_other}`), `None` when
/// the row cannot.
pub fn units_count_words(units: &ColumnUnits, number: f64, fill: &dyn Fn(&str) -> Option) -> Option {
let raw = if number.fract() == 0.0 { format!("{}", number as i64) } else { format!("{number}") };
let figure = figure_of(number);
if number == 0.0 {
if let Some(zero) = &units.zero {
return fill(zero).map(|zero| zero.replace("{n}", "0")).filter(|zero| !zero.trim().is_empty());
}
}
let unit = match crate::rules::shell_lines::plural_form(&raw) {
"one" => &units.one,
_ => &units.other,
};
let unit = fill(unit).unwrap_or_default();
let said = if units.other.contains("{n}") {
unit.replace("{n}", &figure)
} else if unit.trim().is_empty() {
figure
} else {
format!("{figure} {unit}")
};
(!said.trim().is_empty()).then_some(said)
}
/// A unit template with no row to read: its row fields (every `{field}` but
/// `{n}`) are left out and the words close up around them.
pub fn unit_without_fields(template: &str) -> Option {
let mut words = template.to_string();
for field in crate::definitions::unit_fields(template)?.into_iter().filter(|field| *field != "n") {
words = words.replace(&format!("{{{field}}}"), "");
}
Some(words.split_whitespace().collect::>().join(" "))
}
/// Where a record's numbers travel as a field card draws them.
pub const NUMBER_PARTS_KEY: &str = "@number_parts";
/// Every counted number column (not a size or a length) as a card draws it:
/// `figure`, short enough to stand on the card ("4.2K"), and `unit`, the
/// word under it ("orders"; the zero sentence at nothing; empty when none).
pub fn number_parts(definition: &TableDefinition, data: &Map) -> Map {
definition
.columns
.iter()
.filter(|column| column.column_type == ColumnType::Number && column.secret != Some(true))
.filter(|column| !reads_duration(column) && column.format != Some(ColumnFormat::Bytes))
.filter_map(|column| {
let number = data.get(&column.key)?.as_f64().filter(|number| number.is_finite())?;
let unit = column.units.as_ref().map(|units| {
let raw = if number.fract() == 0.0 { format!("{}", number as i64) } else { format!("{number}") };
let template = match (number == 0.0, &units.zero) {
(true, Some(zero)) => zero,
_ if crate::rules::shell_lines::plural_form(&raw) == "one" => &units.one,
_ => &units.other,
};
let said = unit_words(definition, template, data).unwrap_or_default();
said.replace("{n}", if number == 0.0 { "0" } else { "" }).split_whitespace().collect::>().join(" ")
});
Some((column.key.clone(), serde_json::json!({ "figure": compact_figure(number), "unit": unit.unwrap_or_default() })))
})
.collect()
}
/// A number short enough to stand on a card: whole below a thousand
/// (grouped), else three significant digits at most with K, M or B ("4.2K",
/// "12K", "1.5M").
pub fn compact_figure(number: f64) -> String {
let size = number.abs();
let (scaled, mark) = match size {
s if s >= 1e9 => (number / 1e9, "B"),
s if s >= 1e6 => (number / 1e6, "M"),
s if s >= 1e3 => (number / 1e3, "K"),
_ => {
return match number.fract() == 0.0 {
true => crate::rules::shell_lines::number(number as i64),
false => format!("{}", (number * 10.0).round() / 10.0),
};
}
};
let places = match scaled.abs() {
s if s >= 100.0 => 0,
s if s >= 10.0 => 1,
_ => 2,
};
let factor = 10f64.powi(places);
let rounded = (scaled * factor).round() / factor;
format!("{rounded}{mark}")
}
/// A clock time ("18:30") as the house clock says it ("6:30 pm").
fn face_clock_words(text: &str, dates: &DateWords) -> Option {
let (hour, minute) = text.trim().split_once(':')?;
let (hour, minute): (i64, i64) = (hour.parse().ok()?, minute.get(..2).unwrap_or(minute).parse().ok()?);
((0..24).contains(&hour) && (0..60).contains(&minute)).then(|| dates.clock(hour, minute))
}
fn reads_duration(column: &Column) -> bool {
matches!(column.format, Some(ColumnFormat::Duration | ColumnFormat::DurationMs))
}
/// A plain date as a face says it (R7): "Wed 1 Oct", the year only outside
/// the reader's, then " · 9:30 am" when it states an hour; a month alone
/// ("2027-11", or a `month` column) as "Nov 2027".
fn face_date_words(column: &Column, text: &str, zone: Option<&str>, now: Option>, dates: &DateWords) -> Option {
if column.month == Some(true) || text.trim().len() == 7 {
return calendar_words(text, None, true, false, dates);
}
face_day_words(text, zone.unwrap_or("Etc/UTC"), now, dates)
}
/// Typed values derived from a record's stored facts. An engine owns the
/// derivation; faces receive the resolved value and only draw it.
pub fn computed_column_values(
definition: &TableDefinition,
data: &Map,
now: Option>,
) -> Map {
let mut values = Map::new();
if definition.id == "outage" && definition.column("elapsed_minutes").is_some() {
let instant = |key: &str| data.get(key).and_then(Value::as_str)
.and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok())
.map(|at| at.with_timezone(&chrono::Utc));
let end = match data.get("ended_at") {
None | Some(Value::Null) => now,
Some(_) => instant("ended_at"),
};
values.insert("elapsed_minutes".into(), Value::Null);
if let Some((start, end)) = instant("started_at").zip(end).filter(|(start, end)| end >= start) {
values.insert("elapsed_minutes".into(), Value::from((end - start).num_milliseconds() as f64 / 60_000.0));
}
}
values
}
fn unit_words(definition: &TableDefinition, template: &str, data: &Map) -> Option {
let mut words = template.to_string();
for field in crate::definitions::unit_fields(template)?.into_iter().filter(|field| *field != "n") {
let column = definition.column(field)?;
if column.secret == Some(true) { return None; }
let value = match column.column_type {
ColumnType::Text => data.get(field)?.as_str()?.trim().to_string(),
ColumnType::Number => {
let number = data.get(field)?.as_f64()?;
if number.fract() == 0.0 { format!("{}", number as i64) } else { format!("{number}") }
}
_ => return None,
};
if value.is_empty() { return None; }
words = words.replace(&format!("{{{field}}}"), &value);
}
Some(words)
}
/// A size as the page says it: "46 GB", "1.5 MB".
pub fn bytes_words(number: f64) -> String {
let units = ["B", "KB", "MB", "GB", "TB"];
let mut size = number;
let mut unit = 0;
while size >= 1000.0 && unit < units.len() - 1 { size /= 1000.0; unit += 1; }
match unit {
0 => format!("{} B", size as u64),
_ if size.fract() == 0.0 => format!("{size:.0} {}", units[unit]),
_ => format!("{size:.1} {}", units[unit]),
}
}
/// The enamels a project's cap comes in, in the board's order — the app's
/// `CapColour`, ported so the page's colour is the one Home paints.
pub const CAP_COLOURS: [&str; 12] = [
"cream", "red", "navy", "yellow", "green", "silver", "orange", "burgundy", "sky", "pink", "black", "teal",
];
/// FNV-1a over the slug's UTF-8 — the app's `CapColour.fnv1a`.
fn fnv1a(text: &str) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in text.bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
/// Each slug's cap, deterministic in the SET of slugs (`CapColour.assign`):
/// walked alphabetically, each takes the enamel its hash names or the next
/// free one, and only once all are taken do two share.
pub fn assign_caps(slugs: &[String]) -> std::collections::BTreeMap {
let walked: std::collections::BTreeSet<&String> = slugs.iter().collect();
let mut taken = std::collections::BTreeSet::new();
let mut caps = std::collections::BTreeMap::new();
for slug in walked {
let start = (fnv1a(slug) % CAP_COLOURS.len() as u64) as usize;
let pick = (0..CAP_COLOURS.len())
.map(|offset| CAP_COLOURS[(start + offset) % CAP_COLOURS.len()])
.find(|cap| !taken.contains(cap))
.unwrap_or(CAP_COLOURS[start]);
taken.insert(pick);
caps.insert(slug.clone(), pick);
}
caps
}
/// The paper a cap dyes (`PaperDye.of`); no cap is cream.
pub fn paper_of(cap: Option<&str>) -> &'static str {
match cap {
Some("navy" | "sky") => "blue",
Some("green" | "teal") => "sage",
Some("red" | "pink" | "burgundy") => "pink",
Some("yellow") => "straw",
Some("orange") => "peach",
_ => "cream",
}
}
/// The record's colour: the paper its project's cap dyes, assigned over the
/// active projects as Home assigns it; cream without a project.
fn colour_of(source: &mut dyn PageSource, definition: &TableDefinition, data: &Map) -> &'static str {
let Some(project) = definition.project.as_deref().and_then(|key| ids_of(data.get(key)).into_iter().next()) else {
return paper_of(None);
};
let Some(slug) = source.records("project", &[project]).ok().and_then(|found| {
found.into_iter().next().and_then(|(_, values)| text_of(&values, "slug"))
}) else {
return paper_of(None);
};
let roster = source.active_project_slugs();
let cap = match roster.contains(&slug) {
true => assign_caps(&roster).get(&slug).copied(),
false => assign_caps(std::slice::from_ref(&slug)).get(&slug).copied(),
};
paper_of(cap)
}
#[path = "page_read.rs"]
mod read;
pub use read::*;
#[path = "page_channels.rs"]
mod channels;
pub use channels::*;
#[path = "page_dates.rs"]
mod dates;
pub use dates::*;
#[cfg(test)]
#[path = "page_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "page_dates_tests.rs"]
mod dates_tests;
#[cfg(test)]
#[path = "page_read_tests.rs"]
mod read_tests;
#[cfg(test)]
#[path = "page_figure_tests.rs"]
mod figure_tests;
#[cfg(test)]
#[path = "page_channels_tests.rs"]
mod channels_tests;