//! The record page's five parts (Spec 11): `parts` on a definition, beside //! `page` (which stays the array of sections the app decodes). //! //! `parts` says which of the definition's columns and commands fill the //! page's head, links, body, lists and acts, and which of the two shapes the //! page takes. Absent, it is DERIVED from the rest of the definition by one //! rule for every table ([`TableDefinition::resolved_parts`]), never per kind: //! //! * shape: `desk` when the table has a long-text column, else `sheet`; //! * head: the first two short columns as facts (not the title, not a long //! text, not a link, picture or file, not secret, and drawn on the page); //! no state; //! * links: every link column; //! * body: the first long-text column; //! * lists: the page's sections that list another table's records by a link //! back to this one (a list over a read — rows that are no table's, a //! repository's commits — is named only in `parts`, see [`PartsRead`]; so //! is a list matched by value, see [`PartsMatch`]); //! * acts: no main act; the commands as the others (never the one the page //! runs on opening, which is no act); a delete command, when the //! definition has one, as the act that puts the record away; //! * cards: the columns its page draws, in order, as the sheet's slips — or //! all as a strip under the words where the body comes first. //! //! The record page as a sheet of slips (the owner's direction, 17 Oct 2026, //! replacing the one-size card grid): `cards` is the sheet — the record's //! fields as slips, each as tall as its words, two half slips sharing a row //! — and `strip` the slips under a page whose content comes first (a mail //! thread's from and due) or, beside a sheet, the fields after it. A card's //! width and the acts it fans when held are data: its own, or its kind's //! from the database's slips table ([`SlipsLayout`]), dealt into the drawn //! page by [`TableDefinition::deal_slips`]. A page with either is drawn by the //! card interpreter; a page with neither is drawn as before, so the two //! words ARE the per-tool switch, and no reader of an older build loses the //! definition (an unknown `shape` would). Each list's `face` says how what is //! tagged to the record is drawn below the hand. A card's `stock` sets its //! paper where its own colour would be another. use serde::{Deserialize, Serialize}; use super::{is_valid_id, not_blank, CardStock, Column, ColumnType, CommandKind, DefinitionError, OrderedMap, SectionWhen, TableDefinition, COMMAND_BINDINGS}; /// How a record page is drawn: a card of facts on its coloured paper, or a /// piece of writing on the desk. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PageShape { #[default] Sheet, Desk, } impl PageShape { /// The shape as a definition spells it. pub fn as_str(self) -> &'static str { match self { Self::Sheet => "sheet", Self::Desk => "desk", } } } /// Which columns fill a record page's parts, and which commands its acts. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PageParts { #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub shape: PageShape, pub head: PartsHead, /// Link columns, drawn as chips under the head. pub links: Vec, /// The long-text column drawn as the page's text. #[serde(default, skip_serializing_if = "Option::is_none")] pub body: Option, pub lists: Vec, pub acts: PartsActs, /// The hand: the record's fields as field cards, in order. #[serde(default, skip_serializing_if = "Option::is_none")] pub cards: Option>, /// The strip: small cards, five to a row, over a page whose content /// comes first — fields, and acts drawn as cards beside them — or under /// a hand, the fields the hand has no room for. #[serde(default, skip_serializing_if = "Option::is_none")] pub strip: Option>, /// What the record opens on; absent, derived by type /// ([`TableDefinition::resolved_opens`]). #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub opens: Option, /// The fact slips, in order; absent, derived by type /// ([`TableDefinition::resolved_groups`]). #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::record_page::readable")] pub groups: Option>, /// The ring's views after Overview, by order and peek only; the rest /// follow by tool order. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::record_page::readable")] pub views: Option>, } /// One card of the hand or the strip: a field (`column`) or, on the strip /// only, an act (`act`, a command id of this definition). Exactly one. #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct PartsCard { #[serde(default, skip_serializing_if = "Option::is_none")] pub column: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub act: Option, /// How much of the sheet's row the slip takes; absent, its kind's width /// from the database's slips table ([`SlipsLayout::widths`]), dealt by the /// core into the drawn page. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub width: Option, /// An older file's card that took its row to itself (`row: true`, the /// one-size grid's word): a stored copy keeps it as it came, and the /// core deals it as a full slip, so a kept copy or a person's edit that /// says it keeps its meaning. No shipped file writes it. #[serde(default, rename = "row", skip_serializing_if = "Option::is_none")] pub took_row: Option, /// The acts the slip fans when held, in order (ids of [`SLIP_ACTS`]); /// absent, its kind's acts, then every slip's, then an optional field's /// ([`SlipsLayout::acts`]), dealt by the core into the drawn page. #[serde(default, skip_serializing_if = "Option::is_none")] pub acts: Option>, /// A field card's object, where the column's own type would draw another /// (`bell` for a reminder, `ring` for a repeat rule): one of the objects /// the app draws; a name it does not draw falls back to the type's own. #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option, /// The card's paper, one of the six stocks, where its own colour (a /// field's, or an act's `does`) would be another. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub stock: Option, /// A field card's own short name, where the column's is longer than a /// card's two lines hold ("Gmail bin too"): a card never cuts its name. #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, /// A moment card's end: the date column that closes the span it opens /// (an event's `ends_at`), so the card reads "11:30 am – 12:30 pm" and no /// other line repeats the end. #[serde(default, skip_serializing_if = "Option::is_none")] pub until: Option, /// The form a field card says its column in (contract 6); absent, the /// column's type says it. #[serde(default, skip_serializing_if = "Option::is_none")] pub form: Option, /// The writable boolean fields this card presents as its switches. #[serde(default, skip_serializing_if = "Option::is_none")] pub switches: Option>, /// Literal caption words may contain only the `{on}` and `{total}` count /// tokens, such as `{on} of {total} on`. #[serde(default, skip_serializing_if = "Option::is_none")] pub caption: Option, /// The card appears only while this record holds this typed condition. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option, /// The other table a field card opens to explain or choose its values. #[serde(default, skip_serializing_if = "Option::is_none")] pub link_to: Option, /// The field card's command for clearing its choice back to none. #[serde(default, skip_serializing_if = "Option::is_none")] pub clear_command: Option, /// The field card's command for choosing a value through a native picker. #[serde(default, skip_serializing_if = "Option::is_none")] pub pick_command: Option, } /// The record's stamps: said on the facts line under the title, never a card. pub const STAMPS: &[&str] = &["created_at", "updated_at", "trashed_at"]; /// How much of a sheet's row a slip takes (recordslips, 17 Oct 2026): two /// half slips in a row share it and its height; a full slip, or a half one /// with no half after it, takes the row. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SlipWidth { Half, Full, } /// Every act a slip can offer: the app performs each one, and data picks /// which a slip offers (`slips.acts`, a card's `acts`). Clearing a link is /// unlinking it: one act, whose word a kind may name for itself (`slips.words` /// `clear.link`, "Unlink"). pub const SLIP_ACTS: &[&str] = &["edit", "copy", "call", "message", "video_call", "email", "open", "share", "open_day", "clear", "replace"]; /// The act that takes the field away: listed last, by meaning, and offered /// only where the record may leave the field empty. pub const SLIP_DESTROYS: &str = "clear"; /// The `slips.acts` key for a kind the table does not name. pub const SLIP_OTHER: &str = "other"; /// The `slips.words` line under a list's first rows: `{n}` is how many more. pub const SLIP_MORE: &str = "more"; /// The record page's slips table (recordslips, 17 Oct 2026), carried by the /// database definition and edited in place per database like any of its /// keys: each kind's width and its whole list of acts — a kind is a column's /// reach (`phone`, `email`, `instagram`) or else its type; a kind with one /// act does it on a tap, a kind with more lifts its list — and the word and /// the object each act's row says, and the "and N more" line. The core deals widths and acts into every drawn /// page ([`TableDefinition::deal_slips`]); the app names none of them. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipsLayout { pub widths: OrderedMap, pub acts: OrderedMap>, pub words: OrderedMap, /// The object each act's row stands beside its word (a `CardEnamel` /// name); a kind may name its own (`clear.link`, the unlink). #[serde(default)] pub objects: OrderedMap, /// How many of a list's rows a record page draws as slips before the /// one slip that says how many more and opens the list; absent, every /// row it reads. #[serde(default, skip_serializing_if = "Option::is_none")] pub list_rows: Option, } impl SlipsLayout { /// Every act a kind names is one a slip performs, has a word and an /// object, and the act that takes the field away comes last; the "and N /// more" line counts. pub(super) fn validate(&self) -> Result<(), DefinitionError> { for (kind, acts) in self.acts.iter() { if acts.iter().position(|act| act == SLIP_DESTROYS).is_some_and(|at| at + 1 != acts.len()) { return Err(DefinitionError::Requires { slot: format!("slips.acts.{kind}"), needs: "the_act_that_takes_the_field_away" }); } for act in acts { if !SLIP_ACTS.contains(&act.as_str()) { return Err(DefinitionError::Requires { slot: format!("slips.acts.{kind}"), needs: "acts_a_slip_fans_slip_acts" }); } if self.words.get(act).is_none_or(|word| word.trim().is_empty()) { return Err(DefinitionError::Requires { slot: format!("slips.words.{act}"), needs: "the_act_s_word" }); } if self.objects.get(act).is_none_or(|object| object.trim().is_empty()) { return Err(DefinitionError::Requires { slot: format!("slips.objects.{act}"), needs: "the_act_s_object" }); } } } if self.list_rows == Some(0) { return Err(DefinitionError::Requires { slot: "slips.list_rows".into(), needs: "at_least_one_row" }); } if !self.words.get(SLIP_MORE).is_some_and(|line| line.contains("{n}")) { return Err(DefinitionError::Requires { slot: format!("slips.words.{SLIP_MORE}"), needs: "a_line_counting_n" }); } Ok(()) } } /// How a list below the hand draws what is tagged to the record. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ListFace { /// Slips, as every list in the app (the default). Slips, /// Notes as paper, their words shown. Notes, /// Pictures as polaroids, three to a row. Photos, } /// The head: the facts said in one line under the title, and the column /// whose value is the record's one state tag. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PartsHead { pub facts: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option, } /// What belongs to the record: `table`'s records whose `relation` (a link /// column on THAT table) names this one, or whose column holds this record's /// value ([`PartsMatch`], in place of `relation`) — or, for rows no table /// holds, the rows a [`PartsRead`] answers. Exactly one of the three. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PartsList { #[serde(default, skip_serializing_if = "Option::is_none")] pub table: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub relation: Option, /// `table`'s records matched by value, in place of `relation`. #[serde(default, rename = "match", skip_serializing_if = "Option::is_none")] pub matching: Option, /// The read whose rows the list draws, in place of `table`. #[serde(default, skip_serializing_if = "Option::is_none")] pub read: Option, /// The list's heading; absent, the other table's plural. #[serde(default, skip_serializing_if = "Option::is_none")] pub heading: Option, /// A command of the OTHER table offered at each row's right. #[serde(default, skip_serializing_if = "Option::is_none")] pub main_act: Option, /// How the list is drawn; absent, as slips. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub face: Option, /// THIS table's columns whose values the list's rows keep (a person's /// phones, emails and Instagram are their handles): a slip of one is /// edited where it is kept, so its Edit opens this list. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub keeps: Vec, } /// A table list's records matched by value rather than by a link: those /// whose `column` (on the OTHER table) equals this record's `parent` column /// (a repository's `host` and a code-host connection's `reaches`). This /// record's value empty, the list is absent. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PartsMatch { pub column: String, pub parent: String, } impl PartsList { /// The list holds against `other`, the table it lists: a match names one /// of `other`'s columns. A list that does not is drawn nowhere. pub fn holds_against(&self, other: &TableDefinition) -> Result<(), DefinitionError> { if let Some(relation) = &self.relation { other.named("parts.lists.relation", relation, None)?; } match &self.matching { Some(by) => other.named("parts.lists.match.column", &by.column, None).map(|_| ()), None => Ok(()), } } } /// A list over an existing screen read (`read.`, one of [`PAGE_READS`]): /// its arguments bound from this record, the answer's array of rows, and /// which field of a row is its id, its title (said as its first line) and /// its trailing words. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PartsRead { pub name: String, /// Argument → `$id` or a column of this table, as a command binds them. pub bindings: OrderedMap, /// The key of the answer's array of rows. pub rows: String, pub id: String, pub title: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub trailing: Option, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub trailing_format: Option, /// Native words under the title, joined in order; missing fields add nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option>, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ReadLine { pub field: String, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub format: Option, } /// How a read row's field is said. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReadFormat { /// A commit hash, said as its first [`SHORT_HASH`] letters. ShortHash, /// The shared page's date words, in the reader's zone when available. Date, } /// How many letters of a hash a short hash keeps. pub const SHORT_HASH: usize = 7; /// The screen reads a page's list may name: each answers its whole set (or /// a bounded window) for one record, and nothing else is ever called. pub const PAGE_READS: &[&str] = &["repoCommits"]; /// The acts on the whole record, each a command id of this definition: the /// one main act (the ink pill), the others, and the one that puts the record /// away, last. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PartsActs { #[serde(default, skip_serializing_if = "Option::is_none")] pub main: Option, pub more: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub away: Option, } /// Column types a fact is said from; a long text is a body, a link a chip, /// a picture or a file is drawn, never said. pub const FACT_TYPES: &[ColumnType] = &[ ColumnType::AccountNumber, ColumnType::Text, ColumnType::Date, ColumnType::Time, ColumnType::Number, ColumnType::Bytes, ColumnType::Amount, ColumnType::Choice, ColumnType::Bool, ColumnType::Url, ColumnType::Place, ]; /// Column types a state tag is read from: one word, a choice or a text. pub const STATE_TYPES: &[ColumnType] = &[ColumnType::Choice, ColumnType::Text]; /// One part of a record's page, from the fixed vocabulary the app draws /// (architect, 13 Oct 2026): a definition's `page_parts` names its parts in /// order, and a new layout is a new part kind, built once and named from data. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PagePart { /// The record's title. Title, /// The facts line under it. Facts, /// The grid: its fields, then its acts. Grid, /// The record's text, a column to read. Content, /// A conversation over a child table (`conversation`), with its composer /// when the table can send. Messages, /// A story's scenes, set as a script. Script, /// Named child lists, as slips. Sections, /// The strip of small cards. Strip, } /// The parts of a page whose definition names none. pub const PLAIN_PAGE: [PagePart; 5] = [PagePart::Title, PagePart::Facts, PagePart::Grid, PagePart::Content, PagePart::Sections]; /// The plain page whose content comes first (small cards in a strip, no /// hand): its words, then the strip. pub const CONTENT_FIRST_PAGE: [PagePart; 5] = [PagePart::Title, PagePart::Facts, PagePart::Content, PagePart::Grid, PagePart::Sections]; impl TableDefinition { /// The page's part list: the definition's own `page_parts`, else the /// plain page's — derived here as the hand is, so every page has an /// explicit list by the time the app reads it. pub fn resolved_page_parts(&self) -> Vec { self.page_parts.clone().unwrap_or_else(|| { if self.content_first() { CONTENT_FIRST_PAGE.to_vec() } else { PLAIN_PAGE.to_vec() } }) } /// Whether the page's content comes first: small cards in a strip, no hand. pub fn content_first(&self) -> bool { self.parts.as_ref().is_some_and(|parts| parts.strip.is_some() && parts.cards.is_none()) } /// The page's parts: the definition's own `parts`, else the one default /// every table gets (see the module's header). pub fn resolved_parts(&self) -> PageParts { if let Some(parts) = &self.parts { let mut parts = parts.clone(); for act in self.acts.iter().flatten() { if parts.acts.main.as_ref() != Some(&act.id) && parts.acts.away.as_ref() != Some(&act.id) && !parts.acts.more.contains(&act.id) { parts.acts.more.push(act.id.clone()); } } return parts; } let drawn = |key: &str| self.page.iter().any(|section| section.columns().iter().any(|column| column == key)); let facts = self .columns .iter() .filter(|column| column.key != self.title && FACT_TYPES.contains(&column.column_type)) .filter(|column| column.secret != Some(true) && drawn(&column.key)) .take(2) .map(|column| column.key.clone()) .collect(); let body = self .columns .iter() .find(|column| column.column_type == ColumnType::Longtext) .map(|column| column.key.clone()); let lists = self .page .iter() .filter_map(|section| { let list = section.list.as_ref()?; Some(PartsList { table: Some(list.table.clone()), relation: Some(list.link.clone()?), matching: None, read: None, heading: section.heading.clone(), main_act: None, face: None, keeps: Vec::new(), }) }) .collect(); // A tool that names no parts is dealt cards as a built-in is (owner, // 12 Oct 2026: shipped and imported tools are the same kind): the // columns its page draws, in order, as a hand — or a strip where its // body comes first. let mut seen = std::collections::BTreeSet::new(); let dealt_cards: Vec = self .page .iter() .flat_map(|section| section.columns().iter()) .filter(|key| **key != self.title && Some(*key) != body.as_ref()) // The stamps are the facts line's, never a card. .filter(|key| !STAMPS.contains(&key.as_str())) .filter(|key| self.columns.iter().any(|column| column.key == **key && column.secret != Some(true))) .filter(|key| seen.insert(key.as_str())) .map(|key| PartsCard { column: Some(key.clone()), ..PartsCard::default() }) .collect(); // Content first, every slip is the strip's, under the words; else // every slip is the sheet's, in the page's order. let (hand, under) = match &body { Some(_) => (None, Some(dealt_cards)), None => (Some(dealt_cards), None), }; // The command the page runs on opening is no act (rule 8: no act // duplicates what opening does). let commands = self.all_commands().filter(|command| !command.edits_field(self) && self.on_open.as_deref() != Some(command.id.as_str())); let away = commands .clone() .find(|command| command.kind == CommandKind::Delete) .or_else(|| commands.clone().find(|command| command.is_away_act())) .map(|command| command.id.clone()); PageParts { shape: if body.is_some() { PageShape::Desk } else { PageShape::Sheet }, head: PartsHead { facts, state: None }, links: self .columns .iter() .filter(|column| column.column_type == ColumnType::Link) .map(|column| column.key.clone()) .collect(), body, lists, acts: PartsActs { main: None, more: commands .filter(|command| !command.is_away_act()) .map(|command| command.id.clone()) .collect(), away, }, cards: hand, strip: under, opens: None, groups: None, views: None, } } /// The drawn page's slips: every field card given its width and its acts /// from `slips` where the definition names none — its kind's list, else /// the list for a kind the table leaves out (whose width is full), less /// the act that takes the field away where the record must keep it. Run /// on the page the app draws. pub fn deal_slips(&self, parts: &mut PageParts, slips: &SlipsLayout) { for card in parts.cards.iter_mut().flatten().chain(parts.strip.iter_mut().flatten()) { let Some(column) = card.column.as_deref().and_then(|key| self.column(key)) else { continue }; let kind = slip_kind(column); if card.width.is_none() { let whole = card.took_row == Some(true); card.width = Some(if whole { SlipWidth::Full } else { slips.widths.get(&kind).copied().unwrap_or(SlipWidth::Full) }); } card.took_row = None; if card.acts.is_none() { let kept = column.required == Some(true); let acts = slips.acts.get(&kind).or_else(|| slips.acts.get(SLIP_OTHER)).cloned().unwrap_or_default(); card.acts = Some(acts.into_iter().filter(|act| !(kept && act == SLIP_DESTROYS)).collect()); } } } /// `parts` names only this table's columns, each of the type its part /// draws, and only its commands, each act once. A list's table and /// relation are another definition's, checked where both are known. pub(super) fn validate_parts(&self) -> Result<(), DefinitionError> { let Some(parts) = &self.parts else { return self.validate_record_page() }; for fact in &parts.head.facts { self.named("parts.head.facts", fact, Some((FACT_TYPES, "a_short_column")))?; } if let Some(state) = &parts.head.state { self.named("parts.head.state", state, Some((STATE_TYPES, "a_choice_or_a_text")))?; // A state is one tag; never also a fact. if parts.head.facts.contains(state) { return Err(DefinitionError::Conflict { slot: "parts.head.state".into(), other: "the_same_column_among_the_facts", }); } } for link in &parts.links { self.named("parts.links", link, Some((&[ColumnType::Link], "a link")))?; } if let Some(body) = &parts.body { self.named("parts.body", body, Some((&[ColumnType::Longtext], "a long text")))?; } for list in &parts.lists { match (&list.table, &list.relation, &list.read, &list.matching) { (Some(_), Some(_), None, None) => {} (Some(_), None, None, Some(by)) => self.validate_match(by)?, (None, None, Some(read), None) => self.validate_read(read)?, (_, Some(_), _, Some(_)) => { return Err(DefinitionError::Conflict { slot: "parts.lists.match".into(), other: "a relation" }) } (_, _, Some(_), Some(_)) => { return Err(DefinitionError::Conflict { slot: "parts.lists.match".into(), other: "a read" }) } (_, _, Some(_), None) => { return Err(DefinitionError::Conflict { slot: "parts.lists.read".into(), other: "a_table_and_relation" }) } _ => { return Err(DefinitionError::Requires { slot: "parts.lists".into(), needs: "a_table_and_relation_a_table_and", }) } } // A row act is a command of the other TABLE; a read's rows have none. if list.read.is_some() && list.main_act.is_some() { return Err(DefinitionError::Conflict { slot: "parts.lists.main_act".into(), other: "a read" }); } let matched = list.matching.iter().map(|by| &by.column); for id in list.table.iter().chain(&list.relation).chain(matched).chain(&list.main_act) { if !is_valid_id(id) { return Err(DefinitionError::BadId(id.clone())); } } if let Some(heading) = &list.heading { not_blank(heading, "parts.lists.heading")?; } for kept in &list.keeps { self.named("parts.lists.keeps", kept, None)?; } } let mut acted = std::collections::BTreeSet::new(); let acts = parts.acts.main.iter().map(|id| ("parts.acts.main", id)); let acts = acts .chain(parts.acts.more.iter().map(|id| ("parts.acts.more", id))) .chain(parts.acts.away.iter().map(|id| ("parts.acts.away", id))); for (slot, id) in acts { if let Some(command) = self.command(id) { if command.edits_field(self) { return Err(DefinitionError::Requires { slot: slot.into(), needs: "a_whole_record_act" }); } if slot != "parts.acts.away" && command.is_away_act() { return Err(DefinitionError::Requires { slot: slot.into(), needs: "a_non_destructive_main_act" }); } } if self.command(id).is_none() && !self.is_unavailable(id) && !self.actions.iter().flatten().any(|action| { let scheme = serde_json::to_value(action.scheme).unwrap(); format!("{}:{}", scheme.as_str().unwrap(), action.column) == *id }) { return Err(DefinitionError::UnknownCommand { slot: slot.into(), id: id.clone() }); } if !acted.insert(id.as_str()) { return Err(DefinitionError::Conflict { slot: slot.into(), other: "the_same_command_in_another_act" }); } } self.validate_cards(parts, &mut acted)?; self.validate_record_page() } /// The hand and the strip: each card a column of this table or (on the /// strip) one of its commands, every field and every act drawn once /// across the page, the title never a card (it heads the page), and a /// whole row only for a card of the hand. A strip beside a hand is the /// fields under it, never an act. fn validate_cards<'a>(&self, parts: &'a PageParts, acted: &mut std::collections::BTreeSet<&'a str>) -> Result<(), DefinitionError> { if parts.cards.is_some() && parts.strip.iter().flatten().any(|card| card.act.is_some()) { return Err(DefinitionError::Conflict { slot: "parts.strip".into(), other: "a_hand_whose_acts_are_the_tray" }); } // A chat comes first and takes a strip; mail that folds is laid out as // every record page — title, facts, the grid, then the mail (architect, r7). if parts.cards.is_some() && self.conversation.as_ref().is_some_and(|layout| layout.folds != Some(true)) { return Err(DefinitionError::Conflict { slot: "parts.cards".into(), other: "a_chat_which_comes_first_and_takes" }); } let mut drawn = std::collections::BTreeSet::new(); let placed = parts.cards.iter().flatten().map(|card| ("parts.cards", card)); for (slot, card) in placed.chain(parts.strip.iter().flatten().map(|card| ("parts.strip", card))) { match (&card.column, &card.act) { (Some(column), None) => { // The stamp is not a card (architect, r6): when a record was // made, written or binned is said on the facts line. if STAMPS.contains(&column.as_str()) { return Err(DefinitionError::Conflict { slot: slot.into(), other: "the_facts_line_which_says_when_the" }); } self.named(slot, column, None)?; if *column == self.title { return Err(DefinitionError::Conflict { slot: slot.into(), other: "the_title_which_heads_the_page" }); } if !drawn.insert(column.as_str()) { return Err(DefinitionError::Conflict { slot: slot.into(), other: "the_same_column_on_another_card" }); } } (None, Some(act)) if slot == "parts.strip" => { if self.command(act).is_none() && !self.is_unavailable(act) { return Err(DefinitionError::UnknownCommand { slot: slot.into(), id: act.clone() }); } if !acted.insert(act.as_str()) { return Err(DefinitionError::Conflict { slot: slot.into(), other: "the_same_command_in_another_act" }); } } (None, Some(_)) => { return Err(DefinitionError::Requires { slot: slot.into(), needs: "a_column_acts_are_the_tray_s" }) } _ => return Err(DefinitionError::Requires { slot: slot.into(), needs: "a_column_or_an_act_one_of" }), } if let Some(object) = &card.object { if card.column.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.object"), needs: "a_field_card" }); } if !is_valid_id(object) { return Err(DefinitionError::BadId(object.clone())); } } if let Some(form) = card.form { let column = card.column.as_deref().and_then(|key| self.column(key)); let Some(column) = column else { return Err(DefinitionError::Requires { slot: format!("{slot}.form"), needs: "a_field_card" }); }; form.fits(column).map_err(|needs| DefinitionError::Requires { slot: format!("{slot}.form"), needs })?; } if let Some(until) = &card.until { self.named(&format!("{slot}.until"), until, None)?; let dated = |key: &str| self.column(key).is_some_and(|column| column.column_type == ColumnType::Date); if !card.column.as_deref().is_some_and(dated) || !dated(until) { return Err(DefinitionError::Requires { slot: format!("{slot}.until"), needs: "a_date_card_closed_by_a_date" }); } } for act in card.acts.iter().flatten() { if card.column.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.acts"), needs: "a_field_card" }); } if !SLIP_ACTS.contains(&act.as_str()) { return Err(DefinitionError::Requires { slot: format!("{slot}.acts"), needs: "acts_a_slip_fans_slip_acts" }); } } if let Some(when) = &card.when { self.validate_when(&format!("{slot}.when"), when)?; } if let Some(switches) = &card.switches { if switches.is_empty() { return Err(DefinitionError::EmptyAt(format!("{slot}.switches"))); } let mut distinct = std::collections::BTreeSet::new(); for key in switches { let column = self.named(&format!("{slot}.switches"), key, Some((&[ColumnType::Bool], "a_writable_boolean")))?; if column.readonly == Some(true) { return Err(DefinitionError::Requires { slot: format!("{slot}.switches"), needs: "a_writable_boolean" }); } if !distinct.insert(key.as_str()) { return Err(DefinitionError::Conflict { slot: format!("{slot}.switches"), other: "each_switch_once" }); } } } if let Some(caption) = &card.caption { if card.switches.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.caption"), needs: "switches" }); } if !Self::switch_caption(caption) { return Err(DefinitionError::Requires { slot: format!("{slot}.caption"), needs: "literal_words_with_on_or_total" }); } } if let Some(link_to) = &card.link_to { if card.column.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.link_to"), needs: "a_field_card" }); } if !is_valid_id(link_to) { return Err(DefinitionError::BadId(link_to.clone())); } } if let Some(command) = &card.clear_command { if card.column.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.clear_command"), needs: "a_field_card" }); } if self.command(command).is_none() && !self.is_unavailable(command) { return Err(DefinitionError::UnknownCommand { slot: format!("{slot}.clear_command"), id: command.clone() }); } } if let Some(command) = &card.pick_command { if card.column.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.pick_command"), needs: "a_field_card" }); } if self.command(command).is_none() && !self.is_unavailable(command) { return Err(DefinitionError::UnknownCommand { slot: format!("{slot}.pick_command"), id: command.clone() }); } } } Ok(()) } fn switch_caption(caption: &str) -> bool { let mut rest = caption; let mut token = false; while let Some(open) = rest.find('{') { let (literal, after_open) = rest.split_at(open); if literal.contains('}') { return false; } let Some(close) = after_open.find('}') else { return false; }; match &after_open[..=close] { "{on}" | "{total}" => token = true, _ => return false, } rest = &after_open[close + 1..]; } !rest.contains('}') && token } /// A match names one of this table's columns as the parent; its other /// column is checked against the listed table ([`PartsList::holds_against`]). fn validate_match(&self, by: &PartsMatch) -> Result<(), DefinitionError> { not_blank(&by.column, "parts.lists.match.column")?; self.named("parts.lists.match.parent", &by.parent, None).map(|_| ()) } /// A list's read names a read on [`PAGE_READS`], binds each argument to /// `$id` or one of this table's columns, and names its row fields. fn validate_read(&self, read: &PartsRead) -> Result<(), DefinitionError> { if !PAGE_READS.contains(&read.name.as_str()) { return Err(DefinitionError::Requires { slot: "parts.lists.read.name".into(), needs: "a_read_on_the_allowlist" }); } if read.bindings.iter().next().is_none() { return Err(DefinitionError::Requires { slot: "parts.lists.read.bindings".into(), needs: "this_record_bound_to_an_argument" }); } for (argument, column) in read.bindings.iter() { not_blank(argument, "parts.lists.read.bindings")?; if column != COMMAND_BINDINGS[0] { self.named("parts.lists.read.bindings", column, None)?; } } let fields = [("parts.lists.read.rows", &read.rows), ("parts.lists.read.id", &read.id), ("parts.lists.read.title", &read.title)]; for (slot, key) in fields.into_iter().chain(read.trailing.as_ref().map(|key| ("parts.lists.read.trailing", key))) { not_blank(key, slot)?; } if read.trailing_format.is_some() && read.trailing.is_none() { return Err(DefinitionError::Requires { slot: "parts.lists.read.trailing_format".into(), needs: "a_trailing_field" }); } for field in read.line.iter().flatten() { not_blank(&field.field, "parts.lists.read.line.field")?; } Ok(()) } } /// A column's slip kind: how it reaches someone (`phone`, `email`, /// `instagram`), else its type as a definition spells it. pub fn slip_kind(column: &Column) -> String { let spelled = match &column.reach { Some(reach) => serde_json::to_value(reach.kind()), None => serde_json::to_value(column.column_type), }; spelled.ok().and_then(|value| value.as_str().map(str::to_owned)).unwrap_or_default() } #[cfg(test)] #[path = "parts_tests.rs"] mod tests;