Cotton code
361 lines · 16.8 KB · RustRaw
//! The record page in one read (the record-page proposal, 21 Oct 2026): what//! it opens on, the head's lines, its fact slips, every list that links to//! it with its count and newest few, its views, its acts, and the channels//! each handle reaches by — everything a person reads on it, resolved here,//! so the face composes no sentence and nothing reflows after paint.use serde::Serialize;use serde_json::{Map, Value};use super::{labelled_fact_words, ids_of, link_target, page_of, resolve_slip_lines, PageAct, PageListAll, PageSource, RecordPage, ResolvedSlipLines};use crate::definitions::{    record_views, Column, CommandDoes, CommandKind, PageGroup, PageOpens, RecordCommand, RecordView, TableDefinition, OVERVIEW,};use crate::records::receipt::record_name_in;/// The dye a slip takes where its table names none.pub const PLAIN_DYE: &str = "cream";/// Most handle rows the reach slip lists.pub const REACH_ROWS: usize = 50;/// The handle table's column holding a handle in the form evidence is/// matched by; a table without it is matched by the handle as written.pub const HANDLE_NORMALISED: &str = "normalised";/// A record's page, resolved whole.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct RecordPageRead {    /// The parts read as before (head, links, body, lists, acts).    #[serde(flatten)]    pub page: RecordPage,    pub opens: PageOpens,    /// The thing the record is, when it opens on it: its column and value.    #[serde(skip_serializing_if = "Option::is_none")]    pub thing: Option<PageThing>,    /// The record's own table's dye.    pub dye: String,    /// The view the read stands on (`overview` unless one was named).    pub view: String,    /// The head's lines: the table's slip, and the view's head line as its    /// caption where the view names one.    #[serde(rename = "headLines")]    pub head_lines: ResolvedSlipLines,    pub groups: Vec<GroupRead>,    pub views: Vec<ViewRead>,    /// Each view but Overview as a headed list: count and newest few.    pub headed: Vec<HeadedList>,    /// The acts tapping the head lifts: the tray's, less what destroys or    /// puts the record away.    #[serde(rename = "headActs")]    pub head_acts: Vec<PageAct>,    /// The primary handle — the first that reaches the record, by its    /// position — whose channels the head lifts after its acts: a person's    /// head lifts Call, WhatsApp and Email from it.    #[serde(rename = "headReach", skip_serializing_if = "Option::is_none")]    pub head_reach: Option<ReachRow>,    /// Every act, Archive and Delete last.    #[serde(rename = "trayActs")]    pub tray_acts: Vec<PageAct>,}#[derive(Debug, Clone, PartialEq, Serialize)]pub struct PageThing {    pub column: String,    pub key: String,}/// One fact slip, resolved.#[derive(Debug, Clone, PartialEq, Serialize)]#[serde(tag = "form", rename_all = "lowercase")]pub enum GroupRead {    /// The group's lines, every column of it: the slip draws a line that    /// holds a value or is invited (`value` absent, `invited`); the lifted    /// group draws them all, a blank in pencil, so it can be written.    Facts { lines: Vec<GroupLine> },    /// One long text, set for reading; `folded`, behind its label until    /// one tap unfolds it.    Reads {        column: String,        label: String,        text: String,        #[serde(skip_serializing_if = "std::ops::Not::not")]        folded: bool,    },    /// Every handle that reaches the record, one row each.    Reach { table: String, rows: Vec<ReachRow> },}#[derive(Debug, Clone, PartialEq, Serialize)]pub struct GroupLine {    pub column: String,    pub label: String,    #[serde(skip_serializing_if = "Option::is_none")]    pub value: Option<String>,    #[serde(skip_serializing_if = "std::ops::Not::not")]    pub invited: bool,    /// Why the fact lifts with no editor — an engine keeps it, the core    /// works it out, or the record is closed; absent when it may be written.    #[serde(skip_serializing_if = "Option::is_none")]    pub locked: Option<String>,}/// The line a fact that is never written by hand lifts with, or none, in/// the `record` set's `locked` lines (`said`).fn locked_line(definition: &TableDefinition, column: &Column, data: &Map<String, Value>, said: &crate::rules::shell_lines::LineSet) -> Option<String> {    let say = |line: &str, fills: &[(&str, &str)]| said.say(&format!("locked.{line}"), fills).unwrap_or_else(|| format!("record.locked.{line}"));    let closed = definition.readonly_when.as_deref().and_then(|key| data.get(key)).is_some_and(|value| match value {        Value::Null | Value::Bool(false) => false,        Value::String(text) => !text.trim().is_empty(),        _ => true,    });    if closed {        return Some(say("closed", &[("kind", &definition.name.to_lowercase())]));    }    if column.computed.is_some() {        return Some(say("computed", &[]));    }    if column.readonly == Some(true) {        return Some(match definition.engine {            Some(_) => say("engine", &[("plural", &definition.plural)]),            None => say("kept", &[]),        });    }    None}#[derive(Debug, Clone, PartialEq, Serialize)]pub struct ReachRow {    pub id: String,    /// Where it reaches: its kind's words ("Phone").    pub label: String,    pub value: String,    /// The channels it reaches by: those this database holds activity with    /// it on, newest first, then its kind's own ([`super::channels_for_handle`]).    pub channels: Vec<super::Channel>,}#[derive(Debug, Clone, PartialEq, Serialize)]pub struct ViewRead {    pub id: String,    pub label: String,}/// A list another table makes of the record, under its heading.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct HeadedList {    /// The view the heading turns the ring to.    pub view: String,    pub heading: String,    pub table: String,    pub count: u64,    pub peek: Vec<PeekSlip>,    pub all: PageListAll,}/// One of a headed list's newest records, said by its OWN table's slip and/// dyed by its own table.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct PeekSlip {    pub id: String,    pub title: String,    pub lines: ResolvedSlipLines,    pub dye: String,}/// The dye a table's slips take on a record page.pub fn dye_of(definition: &TableDefinition) -> String {    definition.slip.dye.clone().unwrap_or_else(|| PLAIN_DYE.to_string())}/// The page of `table`'s record `id`, standing on `view` (a view id from/// its views; absent or unknown, Overview), in one read.pub fn record_page_read(source: &mut dyn PageSource, table: &str, id: &str, view: Option<&str>) -> Result<RecordPageRead, String> {    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::super::project_read_data(&definition, &mut data);    // One bundle of the database's words, read once, said by every part.    let rows = source.line_rows();    let words = super::Words::of_rows(&rows);    let record_lines = crate::rules::shell_lines::LineSet::of_rows("record", &rows).expect("the kit ships the record set");    let page = page_of(source, &definition, &data, id, &words)?;    let tables = source.definitions();    let zone = source.time_zone();    let zone = zone.as_deref();    let now = source.now();    let opens = definition.resolved_opens();    let thing = (opens == PageOpens::Thing)        .then(|| definition.thing_column())        .flatten()        .and_then(|column| Some(PageThing { column: column.to_string(), key: super::text_of(&data, column)? }));    let views = record_views(&tables, table);    let standing = view.and_then(|wanted| views.iter().find(|view| view.id == wanted)).map_or(OVERVIEW, |view| view.id.as_str()).to_string();    let mut head_lines = resolve_slip_lines(&definition, &data, zone, now, false, &words);    let head_line = views        .iter()        .find(|view| view.id == standing)        .and_then(|view| view.tool_view.as_ref())        .and_then(|(home, view)| tables.iter().find(|table| &table.id == home)?.tool.as_ref()?.views.iter().find(|v| &v.id == view)?.head_line.clone());    if let Some(caption) = head_line {        let mut over = definition.clone();        over.slip.caption = Some(caption);        head_lines.caption = resolve_slip_lines(&over, &data, zone, now, false, &words).caption;    }    let mut groups = Vec::new();    for group in definition.resolved_groups(&tables) {        match group {            PageGroup::Columns(group) => {                let mut lines = Vec::new();                for key in &group.columns {                    let Some(column) = definition.column(key).filter(|column| column.shown_on(&data) && column.secret != Some(true)) else { continue };                    let value = match column.column_type {                        crate::definitions::ColumnType::Link => link_words(source, column, &data, &words.dates),                        _ => data.get(key).and_then(|value| labelled_fact_words(&definition, column, value, &data, zone, now, &words)),                    }                    .filter(|words| !words.trim().is_empty());                    let invited = group.invites.contains(key);                    let locked = locked_line(&definition, column, &data, &record_lines);                    lines.push(GroupLine { column: key.clone(), label: column.label(), invited: invited && value.is_none(), value, locked });                }                // A group with nothing to draw stays off the page.                if lines.iter().any(|line| line.value.is_some() || line.invited) {                    groups.push(GroupRead::Facts { lines });                }            }            PageGroup::Reads(group) => {                let Some(column) = definition.column(&group.column).filter(|column| column.shown_on(&data) && column.secret != Some(true)) else { continue };                if let Some(text) = super::text_of(&data, &group.column) {                    groups.push(GroupRead::Reads { column: group.column.clone(), label: column.label(), text, folded: group.folded });                }            }            PageGroup::Reach(_) => {                let Some((handles, link, kind)) = definition.reach_table(&tables) else { continue };                let mut filter = Map::new();                filter.insert(link.to_string(), Value::from(id));                let (_, found) = source.list(&handles.id, &filter, REACH_ROWS)?;                let kind_column = handles.column(kind);                let mut rows: Vec<ReachRow> = Vec::new();                for (row_id, values) in found {                    let (Some(value), Some(handle_kind)) = (super::text_of(&values, &handles.title), super::text_of(&values, kind)) else { continue };                    let label = kind_column.map_or_else(|| handle_kind.clone(), |column| column.choice_label(&handle_kind));                    let normalised = super::text_of(&values, HANDLE_NORMALISED).unwrap_or_else(|| value.clone());                    let evidence = source.handle_activity(&handle_kind, &normalised);                    let channels = super::channels_for_handle(&handle_kind, &evidence, handles, kind, &tables);                    rows.push(ReachRow { id: row_id, label, value, channels });                }                if !rows.is_empty() {                    groups.push(GroupRead::Reach { table: handles.id.clone(), rows });                }            }        }    }    let mut headed = Vec::new();    for view in views.iter().filter(|view| view.id != OVERVIEW) {        if let Some(list) = headed_list(source, &tables, view, table, id, &words)? {            headed.push(list);        }    }    let (head_acts, tray_acts) = acts(&definition, &page);    let head_reach = groups.iter().find_map(|group| match group {        GroupRead::Reach { rows, .. } => rows.iter().find(|row| !row.channels.is_empty()).cloned(),        _ => None,    });    Ok(RecordPageRead {        opens,        thing,        dye: dye_of(&definition),        view: standing,        head_lines,        groups,        views: views.iter().map(|view| ViewRead { id: view.id.clone(), label: view.label.clone() }).collect(),        headed,        head_acts,        head_reach,        tray_acts,        page,    })}/// A link column's value said as the titles of the records it names.fn link_words(source: &mut dyn PageSource, column: &crate::definitions::Column, data: &Map<String, Value>, dates: &super::DateWords) -> Option<String> {    let target = link_target(column, data)?;    let ids = ids_of(data.get(&column.key));    if ids.is_empty() {        return None;    }    let linked = source.definition(&target)?;    let found = source.records(&target, &ids).ok()?;    let names: Vec<String> = found.into_iter().map(|(_, values)| record_name_in(&linked, &Value::Object(values), dates)).collect();    (!names.is_empty()).then(|| names.join(super::FACT_JOIN))}/// A view as a headed list: its count, and its newest `peek` records said/// by their own table's slip (a partitioned view's own slip where it/// declares one). A list with nothing still heads the page, at nought.fn headed_list(source: &mut dyn PageSource, tables: &[TableDefinition], view: &RecordView, host: &str, id: &str, words: &super::Words) -> Result<Option<HeadedList>, String> {    let zone = source.time_zone();    let now = source.now();    let peek = view.peek as usize;    let (table, slips, count, found, all) = if let Some(contributor) = &view.list {        let Some(other) = tables.iter().find(|table| table.id == contributor.table).cloned() else { return Ok(None) };        if let Some(through) = &contributor.through {            let mut filter = Map::new();            filter.insert(through.from.clone(), Value::from(id));            let (count, joins) = source.list(&through.table, &filter, peek)?;            let ids: Vec<String> = joins.iter().filter_map(|(_, values)| super::text_of(values, &through.to)).collect();            let found = if ids.is_empty() { Vec::new() } else { source.records(&other.id, &ids)? };            (other.id.clone(), other, count, found, PageListAll::Table { table: through.table.clone(), filter })        } else {            let Some(column) = &contributor.column else { return Ok(None) };            let mut filter = Map::new();            filter.insert(column.clone(), Value::from(id));            let (count, found) = source.list(&other.id, &filter, peek)?;            (other.id.clone(), other, count, found, PageListAll::Table { table: contributor.table.clone(), filter })        }    } else {        let Some((home, view_id)) = &view.tool_view else { return Ok(None) };        let Some(home) = tables.iter().find(|table| &table.id == home) else { return Ok(None) };        let Some(tool_view) = crate::definitions::record_page::partitioned_over(home, view_id, host, tables) else { return Ok(None) };        let Some(read) = tool_view.read.get("table").and_then(Value::as_str) else { return Ok(None) };        let Some(other) = tables.iter().find(|table| table.id == read) else { return Ok(None) };        let mut filter = tool_view.read.get("where").and_then(Value::as_object).cloned().unwrap_or_default();        filter.insert(tool_view.partition.clone().unwrap_or_default(), Value::from(id));        let (count, found) = source.list(read, &filter, peek)?;        (read.to_string(), tool_view.over(other), count, found, PageListAll::Table { table: read.to_string(), filter })    };    let dye = dye_of(&slips);    let peek = found        .into_iter()        .take(peek)        .map(|(row_id, values)| PeekSlip {            lines: resolve_slip_lines(&slips, &values, zone.as_deref(), now, false, words),            title: record_name_in(&slips, &Value::Object(values), &words.dates),            id: row_id,            dye: dye.clone(),        })        .collect();    Ok(Some(HeadedList { view: view.id.clone(), heading: view.label.clone(), table, count, peek, all }))}/// The tray: every act offered on the record, the main first, then the/// others, then what puts the record away, then what destroys it (Archive/// and Delete last). The head: the tray less those last two.fn acts(definition: &TableDefinition, page: &RecordPage) -> (Vec<PageAct>, Vec<PageAct>) {    let command = |act: &PageAct| definition.command(&act.id);    let rank = |act: &PageAct| match command(act) {        Some(command) if destroys(command) => 2,        Some(command) if command.does == Some(CommandDoes::PutsAway) => 1,        _ => 0,    };    let mut tray: Vec<PageAct> = page.acts.main.iter().chain(&page.acts.more).chain(&page.acts.away).cloned().collect();    tray.sort_by_key(|act| rank(act));    let head = tray.iter().filter(|act| rank(act) == 0).cloned().collect();    (head, tray)}fn destroys(command: &RecordCommand) -> bool {    command.kind == CommandKind::Delete || command.does == Some(CommandDoes::Destroys)}