//! A CARD: one record drawn alone above the strip and the fan (programme //! cardtrial, 22 Oct 2026, a trial beside today's faces). A table or a view //! may carry a `card` block; while the phone's "Try cards" switch is on, a //! view of such a table is drawn as a deck of these, one in front. //! //! Everything a card shows is named here as data: which face draws it, //! which column fills each of the face's places, which facts may stand in its //! top corner ("why it is here now"), and whether it carries the pace art. //! The core resolves a record's card at read (`records::card`); the app draws //! what it is handed and composes no words of its own. //! //! ```json //! "card": { //! "face": "todo.card", //! "fields": [{"slot": "check", "column": "status"}, //! {"slot": "title", "column": "title"}, //! {"slot": "body", "column": "notes"}, //! {"slot": "date", "column": "due_at", "form": "weekday_date"}], //! "corner": [{"column": "due_at", "form": "late", "within": 1}], //! "art": "pace", //! "pace": {"date": "due_at", "done": {"column": "status", "values": ["done", "dropped", "missed"]}, //! "repeat": "recurrence_id"} //! } //! ``` //! //! A MARK drawn over the card at rest acts on its record (owner, 3 Nov //! 2026: "marking a todo as done is just having a check mark"): the table //! binds each mark the ink reads ([`MARKS`]) to one of its commands, as data //! — `"marks": {"check": "done"}` — and the deck runs that command on the //! card's record as its acts would. Letters search, marks act. use serde::{Deserialize, Serialize}; use super::{ColumnType, CommandKind, DefinitionError, Form, TableDefinition, ValueMatch}; /// The marks the ink reads that a table may bind to a command /// (`TableDefinition::marks`). pub const MARKS: &[&str] = &["check"]; impl TableDefinition { /// Each mark is one the ink reads, bound to one of the table's commands /// that runs on the record at once: an update that neither asks first /// nor picks, never a list's act. pub(super) fn validate_marks(&self) -> Result<(), DefinitionError> { for (mark, id) in self.marks.iter().flatten() { if !MARKS.contains(&mark.as_str()) { return Err(DefinitionError::UnknownChoice { slot: "marks".into(), column: "marks".into(), value: mark.clone() }); } let slot = format!("marks.{mark}"); if self.is_unavailable(id) { continue; } let Some(command) = self.command(id) else { return Err(DefinitionError::UnknownCommand { slot, id: id.clone() }); }; let runs_at_once = command.kind == CommandKind::Update && !command.asks_first() && command.list.is_none() && command.pick.is_none() && command.picks.is_none() && command.pick_table.is_none() && command.sheet.is_none(); if !runs_at_once { return Err(DefinitionError::Requires { slot, needs: "an_update_command_that_does_not_ask" }); } } Ok(()) } } /// A table's or a view's card. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CardFace { /// The face that draws it, by its open id. pub face: FaceId, /// Ordered faces the person may wear; absent, only `face`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub offers: Vec, /// Faces tried in order; the first matching choice wears its face. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub faces: Vec, /// The face's places, each filled from one column, in the order drawn. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub fields: Vec, /// The facts the top corner may say, tried in order; the first that /// holds is said, and none is said when none holds. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub corner: Vec, /// The art the card carries; absent, none. #[serde(default, skip_serializing_if = "Option::is_none")] pub art: Option, /// What the pace is read from; present exactly when `art` is `pace`. #[serde(default, skip_serializing_if = "Option::is_none")] pub pace: Option, /// The text columns the card turns to after its face, in order, each /// cut into the pages it fills (a meeting's summary, its decisions, its /// transcript). Absent, the body place's column is the one page after. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pages: Vec, /// The parts a record opens into, when it is a whole made of them: an /// album its tracks, a series its seasons, a season its episodes, a /// story its scenes. The deck turns the fan into these. Absent, the /// record is no whole. #[serde(default, skip_serializing_if = "Option::is_none")] pub opens: Option, } /// A face worn while a choice column holds one of the named values. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FaceByValue { pub when: ValueMatch, pub face: FaceId, } /// The parts table a whole opens into: its records whose `by` link names the /// whole, in `order`; with `through`, each part stands for the record its /// link column names (a playlist's entries are its tracks). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CardOpens { /// The parts' table. pub table: String, /// The parts' link column naming the whole. pub by: String, /// The parts' columns they are dealt in, first to last. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub order: Vec, /// A link column of the parts' naming the record each part stands for. #[serde(default, skip_serializing_if = "Option::is_none")] pub through: Option, /// The records that are wholes, when not every one is: those whose /// choice column holds one of these values (a film opens into its /// seasons only while its kind is series). Absent, every record opens. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option, } /// Every whole among `tables` opens into parts that are there and read back /// to it: the parts table is one of `tables`, its `by` column links to the /// whole's table, each `order` column is the parts', and `through` is a link; /// `when` reads a choice column of the whole's own and names only its /// choices. A package's tables are checked together, as a whole and its /// parts arrive together. pub fn validate_openings(tables: &[TableDefinition]) -> Result<(), DefinitionError> { for whole in tables { let Some(opens) = whole.card.as_ref().and_then(|card| card.opens.as_ref()) else { continue }; let bad = |why: String| DefinitionError::BadSlot { slot: "card.opens".into(), why }; let parts = tables .iter() .find(|table| table.id == opens.table) .ok_or_else(|| bad(refusal("card.opens_parts", &[("whole", &whole.id), ("parts", &opens.table)])))?; let link = |key: &str| parts.column(key).filter(|column| column.column_type == ColumnType::Link); if link(&opens.by).and_then(|column| column.link_to.as_deref()) != Some(whole.id.as_str()) || opens.order.iter().any(|key| parts.column(key).is_none()) || opens.through.as_deref().is_some_and(|key| link(key).and_then(|column| column.link_to.as_deref()).is_none()) { return Err(bad(refusal("card.opens_parts", &[("whole", &whole.id), ("parts", &opens.table)]))); } if let Some(when) = &opens.when { let choices = whole .column(&when.column) .filter(|column| column.column_type == ColumnType::Choice) .and_then(|column| column.choices.as_deref()); if when.values.is_empty() || !choices.is_some_and(|choices| when.values.iter().all(|value| choices.contains(value))) { return Err(bad(refusal("card.opens_when", &[("whole", &whole.id)]))); } } } Ok(()) } /// A face's open id: the name a kit gives the face that draws a card /// (`"face": "todo.card"`). The app holds its faces in Loom's registry /// (`apps/loom/faces.json`) and, until each moves there, in CottonUI /// (`apps/loom/faces-pending.json`); `pnpm gen:faces` writes the two together /// into `face_ids.json` beside this file, which the build compiles in. An id /// is lowercase words of letters, digits and `_`, each a letter first, joined /// by `.` (`todo`, `kitchen.dish`). /// /// Only a face the app draws is a `FaceId`: an authored definition naming any /// other is refused with the id named, and a device reads a card naming one /// a newer build drew as no card (`face_or_absent`). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct FaceId(&'static str); mod known { include!(concat!(env!("OUT_DIR"), "/face_ids.rs")); } impl FaceId { /// The group face (`records::card::deal_groups`): the core deals one card /// per record its people place names. pub const GROUP: FaceId = FaceId("group"); /// The face the app draws by `id`, or `None` when it draws none. pub fn known(id: &str) -> Option { known::KNOWN_FACES.binary_search(&id).ok().map(|at| FaceId(known::KNOWN_FACES[at])) } /// Every face the app draws, by id. pub fn all() -> impl Iterator { known::KNOWN_FACES.iter().map(|id| FaceId(id)) } pub fn as_str(self) -> &'static str { self.0 } } impl std::fmt::Display for FaceId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.0) } } impl PartialEq<&str> for FaceId { fn eq(&self, other: &&str) -> bool { self.0 == *other } } impl Serialize for FaceId { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.0) } } impl<'de> Deserialize<'de> for FaceId { fn deserialize>(deserializer: D) -> Result { let id = std::borrow::Cow::<'de, str>::deserialize(deserializer)?; FaceId::known(&id).ok_or_else(|| serde::de::Error::custom(unknown_face(&id))) } } /// Why a card naming `id` is refused: the app draws no face by that id. pub fn unknown_face(id: &str) -> String { refusal("card.unknown_face", &[("id", &format!("{id:?}"))]) } /// One place on a face and the column that fills it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CardField { pub slot: CardSlot, /// The column that fills the place. Absent exactly on the group place, /// which reads the record's own group. #[serde(default, skip_serializing_if = "Option::is_none")] pub column: Option, /// On the state place: the values of its choice column whose label is /// said; any other value says nothing. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub only: Vec, /// How the value in this place is said (contract 6, T1's [`Form`]), /// checked against the column's type. Absent on a date, the weekday date. #[serde(default, skip_serializing_if = "Option::is_none")] pub form: Option
, /// More columns said in the same place after the first, each as its own /// words, joined by the `cards` set's `join` line ("Architect · Studio /// Iyer · Bengaluru"); an empty one is left out. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub also: Vec, /// A line of the `cards` set (under `field.`) the place is said inside: /// `{said}` is the first column's words and each `also` column fills the /// placeholder named by its key ("Last spoke {said} on {thread_channel}"). /// The place is left empty when a placeholder has no value. #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option, /// On the people place: how many it names at most; the rest are said as /// a count (the `cards` set's `people.more`, "+2"). #[serde(default, skip_serializing_if = "Option::is_none")] pub max: Option, /// A line of the `cards` set (under `label.`) said as this place's label /// on this card, over the face's own (Money's Future says its date /// "Due"); it reaches the face under `fields.labels`, keyed by place. #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, /// On the amount, expires and holder places: the key of the column's /// object the value is kept under (a document's facts: `total_minor`, /// its currency under `currency`; `expires_on`). #[serde(default, skip_serializing_if = "Option::is_none")] pub at: Option, /// On the photo place: a choice column of the record a tap on the /// picture chooses, on the shell's fan of that column's choices, in the /// viewer's place (an event's picture chooses its kind). #[serde(default, skip_serializing_if = "Option::is_none")] pub chooses: Option, /// On the body place: its words are Markdown, set as such wherever the /// record is read (a note's page, its search snippet). The card's word, /// not the column's: the card is the build's on every table, so it /// reaches a database whose column was defined before the flag. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub markdown: bool, } /// The places a face draws. A face draws the places it knows and passes over /// the rest, so a definition may name a place another face reads. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CardSlot { /// The record's done state, drawn as a checkbox (a choice column). Check, Title, Subtitle, /// The longer words under the title. Body, /// The date at the foot. Date, Place, /// The city named by a person’s existing card definition. City, Photo, /// Who the record came from, said in its own words (a document's /// issuer: "From Studio Iyer"). A card never shows a record number /// (owner's ruling, 22 Oct 2026). Source, /// When the record was last in touch, said around its form (a person's /// "Last spoke 3 months ago on WhatsApp"). Reached, /// A recording's or a film's length ("0:42"). Length, /// The people a record is with (an event's guests): a link column, each /// linked record said as its name and the key of its picture, read once /// per answer by the caller (a read carries no link expansion). People, /// The name of the group the record stands in, when it stands in one; /// read from the record's own membership, never a column. Group, /// A choice column's label, said only for the values the field names in /// `only` (a todo's "Dropped"): the state a person should see beside the /// date, and nothing while the record is simply open. A yes/no column /// in `also` that is set stands there first, said by its own name (a /// film "Converting on your Mac"). State, /// A sum of money, said in its currency ("₹1,250.00"; an amount column, /// the money form unless the field names another). Amount, /// The account money moved through: a link column, said as the linked /// record's name, read once per answer by the caller like the people. Account, /// A number kept masked as stored ("•• 4242"), said as it is. Mask, /// How many the record holds (an email thread's emails), said as a count. Count, /// Whether the record waits to be read, drawn as a dot: a yes/no column, /// or a choice column with its unread values named in `only`. Unread, /// The gauge's filled part (a number column): of `limit` when the card /// has one, else out of a hundred. Used, /// The gauge's empty part (a number column), of `limit`: a card names /// `used` or `free`, never both. Free, /// The gauge's whole (a number column). Limit, /// The period a figure is for or runs out with ("Monthly", "resets in /// 2d 23h"), said in words; a choice column says its label. Period, /// What a recurring payment costs each period (an amount column). Price, /// When a recurring payment is next taken (a date column), said as the /// date place is. NextCharge, /// The age a yearly date comes round to next ("turns 35"): a yearly date /// column kept with its year; a day kept without one says nothing. Turns, /// Whether wishes go out on the day: a yes/no column, drawn as a switch. Wishes, /// When the person was last wished (a date column), said against today /// unless the field names another form. LastWished, /// The days a record spans (an album's trip): its first day's date column /// and, in `also`, its last day's — "Sat 3 Oct – Fri 9 Oct", or the one /// day where they are the same or the last is not kept. Span, /// The file a card plays (a track's recording): a file column, said as /// the file's key, never words. Play, /// A few facts, each said under its column's label as the record page /// said it: the field's column, then each of `also`, in order; one with /// no value is left out. A link or a secret is never a fact. Facts, /// The record's number in its order (a scene's 12): a number column, /// said as the figure alone. Number, /// A line quoted from the work (a book's favourite quote), said as kept. Quote, /// A short note in the owner's own words, said as kept. Note, /// The choice a face draws in (a highlight's pencil colour): a choice /// column, said as its stored value and never its label, since the face /// picks its ink by the value and the label is copy. Ink, /// Who directed a film, said as kept. Director, /// Who recommended the record: a link to a person, said as their name, /// read once per answer by the caller like the people; or, where the /// link is empty, the name kept in `also`'s text column. RecommendedBy, /// Whom the owner watched or did it with, said as kept. WatchedWith, /// A machine's memory dial: the used part (a number column) of the whole /// in `also`, said as the two numbers `{used, total}` the face draws. MemoryDial, /// A machine's disk dial, as the memory dial: `{used, total}`. DiskDial, /// A machine's load dial: its load (a number column) of its cores in /// `also`, as `{used, total}`. LoadDial, /// The whole hours until a date column's instant, on the reader's clock /// ("38 hours left", "Under an hour left", "Has reset"). HoursLeft, /// The weekday a date column's instant falls on, in the reader's zone /// ("resets Sunday"); nothing once it has passed. ResetsOn, /// The last few readings for a trend line: a text column holding a list /// of numbers, said as the numbers, oldest first. Trend, /// A share in words ("62 percent used"): a number column said through /// the field's line. Share, /// What the machine is ("Mac mini", "MacBook Pro"), said as kept: the /// face draws its picture by it. Model, /// When the record was begun (a book's first day of reading): a date /// column, said as the date place is. Started, /// When the record was last read (a book's page last turned): a date /// column, said as the date place is. LastRead, /// How many pages the record has (a book's): a number column, handed /// to the face as the number it reckons a place in pages with, never /// words. Pages, /// The year the record is of (an album's), said as kept; a date column /// says its year alone. Year, /// The whole the record sits in (a scene's story), said as its /// title, for the crumb over the card. Crumb, /// How the person was last wished (a choice column: a call, WhatsApp), /// said in its choice's label. WishedVia, /// A number to call the person on: a phone column, its first number /// said as kept. Phone, /// The album the record is in: a link column, said as the first linked /// album's name, read once per answer by the caller like the people. Album, /// The word the record is filed under (a transaction's category), said /// as kept; a choice says its label. Tag, /// When the record runs out (a document's expiry): a date column, or a /// day kept under `at` in a column's object, said as the date place is. Expires, /// Whose the record is (a document's holder): a text column, or a name /// kept under `at` in a column's object, said as kept. Holder, /// When the record ends (an event's end): a date column, with its start's /// in `also`; said as its clock alone on the day it starts ("8:00 pm"), /// else as its weekday date, with its clock when it keeps one. Ends, /// How the record repeats (an event's rule), said in words as its page /// says it ("Every week on Tuesday"). Repeats, /// Who keeps the record in step: the column the table's `kept_by` reads, /// said in that block's own words ("Kept by your assistant") while it /// holds a value, never the value itself. KeptBy, /// The mood a page is sealed with (a diary's wax seal): a choice column, /// said as its stored value, since the face picks the wax by the value /// and the label is copy; no value leaves the seal unpressed. Seal, /// The day's weather drawn as a small glyph: a choice column, said as /// its stored value, the face drawing the glyph by it. Weather, /// Whether the record is starred (a diary's ribbon pulled out): a yes/no /// column, said as yes or no, never words. Star, } /// One fact the corner may say: a date column said in a [`Form`], while /// the fact calls for attention — the date at most `within` days ahead (a day /// behind always calls), or at least `behind` days back. `line` names a line /// of the `cards` set the form's words are said inside (`{said}`): "Not /// reached in {said}". #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CornerFact { pub column: String, pub form: Form, #[serde(default, skip_serializing_if = "Option::is_none")] pub within: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub behind: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option, /// Said only once the record is finished (a todo's "Done yesterday"): /// a finished record says its done facts and no other, an open record /// says no done fact. A done fact needs the card's pace, which says /// when the record is finished. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub done: bool, /// Said only while the date is today or ahead (an event's "in 6 days"): /// a date gone says nothing, where a window otherwise lets a day behind /// always call. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub ahead: bool, } /// The art a card may carry. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum CardArt { /// The pace animal on a band's paper (`transforms::pace`). Pace, } /// What a record's pace is read from: the date it is owed by, the values of /// a column that say it is finished, and the column that says it repeats. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PaceInputs { pub date: String, pub done: ValueMatch, #[serde(default, skip_serializing_if = "Option::is_none")] pub repeat: Option, } /// A card as a device on this build reads it (`tolerant`): a face this /// build cannot draw reads as no card, so the table falls back to its page, /// and a place it does not name is left off the face; the rest reads as it /// came. pub fn face_or_absent<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { use serde::de::Error as _; use serde_json::Value; let mut value = Value::deserialize(deserializer)?; if value.is_null() { return Ok(None); } let faces = value.get("faces").and_then(Value::as_array).into_iter().flatten().filter_map(|rule| rule.get("face")); if let Some(face) = value.get("face").into_iter().chain(faces).find(|face| face.as_str().is_some_and(|id| FaceId::known(id).is_none())) { super::tolerant::fell_back(face); return Ok(None); } if let Some(Value::Array(fields)) = value.get_mut("fields") { fields.retain(|field| match field.get("slot") { Some(slot) if super::tolerant::unnamed::(slot) => { super::tolerant::fell_back(slot); false } _ => true, }); } serde_json::from_value(value).map(Some).map_err(D::Error::custom) } /// A card refusal said in the refusal set's `card` words, its pieces filled. fn refusal(line: &str, fills: &[(&str, &str)]) -> String { crate::rules::shell_lines::LineSet::shipped("refusal").and_then(|set| set.say(line, fills)).unwrap_or_else(|| line.to_string()) } impl CardFace { /// The card checked against the table it draws: every column it names /// exists, and each is of the type its place or fact reads. pub fn validate(&self, table: &TableDefinition, slot: &str) -> Result<(), DefinitionError> { let bad = |why: String| DefinitionError::BadSlot { slot: slot.into(), why }; let column = |name: &str| table.column(name).ok_or_else(|| bad(format!("names {name:?}, which {} does not have", table.id))); let date = |name: &str, yearly: bool| -> Result<(), DefinitionError> { let held = column(name)?; if held.column_type != ColumnType::Date || held.yearly.unwrap_or(false) != yearly { let want = if yearly { "a yearly date" } else { "a date" }; return Err(bad(format!("reads {name:?} as {want}"))); } Ok(()) }; if !self.offers.is_empty() { if !self.offers.contains(&self.face) { return Err(bad(refusal("card.offers_include_face", &[]))); } let unique: std::collections::BTreeSet<_> = self.offers.iter().collect(); if unique.len() != self.offers.len() { return Err(bad(refusal("card.offers_unique", &[]))); } } for rule in &self.faces { let held = column(&rule.when.column)?; let choices = held.choices.as_deref().unwrap_or_default(); if held.column_type != ColumnType::Choice || rule.when.values.is_empty() || rule.when.values.iter().any(|value| !choices.contains(value)) { return Err(bad(refusal("card.faces_choice", &[]))); } } for name in &self.pages { if !matches!(column(name)?.column_type, ColumnType::Text | ColumnType::Longtext) { return Err(bad(refusal("card.pages_text", &[("column", &format!("{name:?}"))]))); } } let mut seen = std::collections::BTreeSet::new(); for field in &self.fields { if !seen.insert(field.slot) { return Err(bad(format!("fills {:?} once", field.slot))); } let Some(name) = &field.column else { if field.slot == CardSlot::Group && field.form.is_none() && field.also.is_empty() && field.line.is_none() && field.only.is_empty() && field.max.is_none() { continue; } return Err(bad(refusal("card.field_column", &[("slot", &format!("{:?}", field.slot))]))); }; if field.slot == CardSlot::Group { return Err(bad(refusal("card.group_column", &[]))); } let held = column(name)?; if field.slot == CardSlot::State { let choices = held.choices.as_deref().unwrap_or_default(); if held.column_type != ColumnType::Choice || field.only.is_empty() || field.only.iter().any(|value| !choices.contains(value)) { return Err(bad(refusal("card.state_only", &[]))); } if field.also.iter().any(|flag| column(flag).map_or(true, |flag| flag.column_type != ColumnType::Bool)) { return Err(bad(refusal("card.state_flags", &[]))); } } else if field.slot == CardSlot::Unread { let choices = held.choices.as_deref().unwrap_or_default(); let reads = match held.column_type { ColumnType::Bool => field.only.is_empty(), ColumnType::Choice => !field.only.is_empty() && field.only.iter().all(|value| choices.contains(value)), _ => false, }; if !reads || field.form.is_some() { return Err(bad(refusal("card.unread_column", &[]))); } } else if !field.only.is_empty() { return Err(bad(refusal("card.only_on_state", &[]))); } let plain = field.form.is_none() && field.also.is_empty() && field.line.is_none(); if field.markdown && (field.slot != CardSlot::Body || !plain || !matches!(held.column_type, ColumnType::Text | ColumnType::Longtext)) { return Err(bad(refusal("card.markdown_body", &[]))); } if field.at.is_some() { let kept = matches!(field.slot, CardSlot::Amount | CardSlot::Expires | CardSlot::Holder); if !kept || !plain || !matches!(held.column_type, ColumnType::Text | ColumnType::Longtext) { return Err(bad(refusal("card.at_object", &[]))); } } if let Some(label) = &field.label { let said = crate::rules::shell_lines::LineSet::shipped("cards").and_then(|cards| cards.say(label, &[])); if !label.starts_with("label.") || said.is_none() { return Err(bad(refusal("card.field_label", &[("line", &format!("{label:?}"))]))); } } match field.slot { CardSlot::Account if held.column_type != ColumnType::Link || held.link_to.is_none() || !plain => { return Err(bad(refusal("card.account_link", &[]))) } CardSlot::Album if held.column_type != ColumnType::Link || held.link_to.is_none() || !plain => { return Err(bad(refusal("card.album_link", &[]))) } CardSlot::WishedVia if held.column_type != ColumnType::Choice || !plain => { return Err(bad(refusal("card.wished_via_choice", &[]))) } CardSlot::Ink if held.column_type != ColumnType::Choice || !plain => { return Err(bad(refusal("card.ink_choice", &[]))) } CardSlot::Seal | CardSlot::Weather if held.column_type != ColumnType::Choice || !plain => { return Err(bad(refusal("card.drawn_choice", &[("slot", &format!("{:?}", field.slot))]))) } CardSlot::Star if held.column_type != ColumnType::Bool || !plain => { return Err(bad(refusal("card.star_switch", &[]))) } CardSlot::Phone if held.column_type != ColumnType::Text || !plain => { return Err(bad(refusal("card.phone_text", &[]))) } CardSlot::Ends if held.column_type != ColumnType::Date || field.form.is_some() || field.line.is_some() || field.also.len() != 1 || field.also.iter().any(|start| column(start).map_or(true, |start| start.column_type != ColumnType::Date)) => { return Err(bad(refusal("card.ends_dates", &[]))) } CardSlot::Repeats if held.format != Some(super::ColumnFormat::RepeatRule) || !plain => { return Err(bad(refusal("card.repeats_rule", &[]))) } CardSlot::KeptBy if table.kept_by.as_ref().is_none_or(|kept| &kept.when != name) || !plain => { return Err(bad(refusal("card.kept_by_column", &[]))) } CardSlot::Expires if held.column_type != ColumnType::Date && field.at.is_none() => { return Err(bad(refusal("card.date_place", &[("column", &format!("{name:?}"))]))) } CardSlot::Holder if held.column_type != ColumnType::Text && field.at.is_none() => { return Err(bad(refusal("card.at_object", &[]))) } CardSlot::Used | CardSlot::Free | CardSlot::Limit | CardSlot::Pages if held.column_type != ColumnType::Number || !plain => { return Err(bad(refusal("card.gauge_number", &[("slot", &format!("{:?}", field.slot))]))) } CardSlot::Amount | CardSlot::Price if held.column_type != ColumnType::Amount && field.at.is_none() => { return Err(bad(refusal("card.amount_place", &[("slot", &format!("{:?}", field.slot))]))) } CardSlot::Count if held.column_type != ColumnType::Number => { return Err(bad(refusal("card.count_number", &[]))) } CardSlot::NextCharge | CardSlot::LastWished | CardSlot::Started | CardSlot::LastRead if held.column_type != ColumnType::Date => { return Err(bad(refusal("card.date_place", &[("column", &format!("{name:?}"))]))) } CardSlot::Turns if held.column_type != ColumnType::Date || held.yearly != Some(true) || !plain => { return Err(bad(refusal("card.turns_yearly", &[]))) } CardSlot::Wishes if held.column_type != ColumnType::Bool || !plain => { return Err(bad(refusal("card.wishes_switch", &[]))) } CardSlot::Span if held.column_type != ColumnType::Date || field.form.is_some() || field.line.is_some() || field.also.len() > 1 => { return Err(bad(refusal("card.span_dates", &[]))) } CardSlot::Play if held.column_type != ColumnType::File || !plain => { return Err(bad(refusal("card.play_file", &[]))) } CardSlot::MemoryDial | CardSlot::DiskDial | CardSlot::LoadDial if held.column_type != ColumnType::Number || field.form.is_some() || field.line.is_some() || field.also.len() != 1 || field.also.iter().any(|whole| column(whole).map_or(true, |whole| whole.column_type != ColumnType::Number)) => { return Err(bad(refusal("card.dial_numbers", &[("slot", &format!("{:?}", field.slot))]))) } CardSlot::HoursLeft | CardSlot::ResetsOn if held.column_type != ColumnType::Date || !plain => { return Err(bad(refusal("card.quota_places", &[("slot", &format!("{:?}", field.slot)), ("wanted", &"date")]))) } CardSlot::Trend if !matches!(held.column_type, ColumnType::Text | ColumnType::Longtext) || !plain => { return Err(bad(refusal("card.quota_places", &[("slot", &format!("{:?}", field.slot)), ("wanted", &"text")]))) } CardSlot::RecommendedBy if !(held.column_type == ColumnType::Text || held.column_type == ColumnType::Link && held.link_to.is_some()) || field.form.is_some() || field.line.is_some() || field.also.len() > 1 || field.also.iter().any(|key| column(key).map_or(true, |also| also.column_type != ColumnType::Text)) => { return Err(bad(refusal("card.recommended_by", &[]))) } CardSlot::Facts if field.form.is_some() || field.line.is_some() => { return Err(bad(refusal("card.facts_plain", &[]))) } _ => {} } if field.slot == CardSlot::People { let linked = held.column_type == ColumnType::Link && held.link_to.is_some(); if !linked || field.form.is_some() || !field.also.is_empty() || field.line.is_some() || field.max == Some(0) { return Err(bad(refusal("card.people_link", &[]))); } } else if field.max.is_some() { return Err(bad(refusal("card.max_on_people", &[]))); } if let Some(chosen) = &field.chooses { let held = column(chosen)?; let written = held.column_type == ColumnType::Choice && held.multiple != Some(true) && held.readonly != Some(true) && held.computed.is_none() && held.choices.as_ref().is_some_and(|choices| !choices.is_empty()); if field.slot != CardSlot::Photo || !written { return Err(bad(refusal("card.chooses_choice", &[]))); } } match field.slot { CardSlot::Check if held.column_type != ColumnType::Choice => { return Err(bad("the check reads a choice column".into())) } CardSlot::Check if field.form.is_some() => return Err(bad("the check names no form".into())), CardSlot::Date if held.column_type != ColumnType::Date => { return Err(bad(refusal("card.date_place", &[("column", &format!("{name:?}"))]))) } _ => {} } if let Some(form) = field.form { form.fits(held).map_err(|needs| { bad(refusal( "card.form_needs", &[("form", &format!("{form:?}")), ("column", &format!("{name:?}")), ("needs", &super::refusal_words(needs))], )) })?; } for also in &field.also { let joined = column(also)?; if field.slot == CardSlot::Span && joined.column_type != ColumnType::Date { return Err(bad(refusal("card.span_dates", &[]))); } } if field.slot == CardSlot::Facts { for fact in std::iter::once(name).chain(&field.also) { let fact = column(fact)?; if fact.column_type == ColumnType::Link || fact.secret == Some(true) { return Err(bad(refusal("card.facts_plain", &[]))); } } } if let Some(line) = &field.line { // A line with plural forms is picked by the column's count (`{n}`). let said = crate::rules::shell_lines::LineSet::shipped("cards").and_then(|cards| cards.say(line, &[("said", ""), ("n", "1")])); if !line.starts_with("field.") || said.is_none() { return Err(bad(refusal("card.field_line", &[("line", &format!("{line:?}"))]))); } } } let fills = |slot: CardSlot| self.fields.iter().any(|field| field.slot == slot); if fills(CardSlot::Used) && fills(CardSlot::Free) { return Err(bad(refusal("card.used_or_free", &[]))); } if fills(CardSlot::Free) && !fills(CardSlot::Limit) { return Err(bad(refusal("card.free_of_limit", &[]))); } if self.fields.iter().any(|field| field.slot == CardSlot::Check) && self.pace.is_none() { return Err(bad("a check says the pace's done state, so the card names its pace".into())); } for fact in &self.corner { let held = column(&fact.column)?; if held.column_type != ColumnType::Date { return Err(bad(format!("the corner reads {:?} as a date", fact.column))); } fact.form.fits(held).map_err(|needs| { bad(refusal( "card.form_needs", &[("form", &format!("{:?}", fact.form)), ("column", &format!("{:?}", fact.column)), ("needs", &super::refusal_words(needs))], )) })?; if fact.done && self.pace.is_none() { return Err(bad(refusal("card.done_fact_pace", &[]))); } if fact.within.is_some() == fact.behind.is_some() { return Err(bad("a corner fact names one window: within or behind".into())); } if let Some(line) = &fact.line { let said = crate::rules::shell_lines::LineSet::shipped("cards") .and_then(|cards| cards.say(line, &[("said", "")])); if !line.starts_with("corner.") || said.is_none() { return Err(bad(format!("{line:?} is no corner line of the cards set"))); } } } // A group card is dealt per record its people place names. if self.face == FaceId::GROUP && !self.fields.iter().any(|field| field.slot == CardSlot::People) { return Err(bad(refusal("card.group_by", &[]))); } match (&self.art, &self.pace) { (Some(CardArt::Pace), None) => return Err(bad("the pace art needs pace".into())), _ => {} } if let Some(pace) = &self.pace { date(&pace.date, false)?; let done = column(&pace.done.column)?; let choices = done.choices.as_deref().unwrap_or_default(); if done.column_type != ColumnType::Choice || pace.done.values.is_empty() || pace.done.values.iter().any(|value| !choices.contains(value)) { return Err(bad("pace.done names values of a choice column".into())); } if let Some(repeat) = &pace.repeat { column(repeat)?; } } Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::definitions::builtin_table_definitions; use serde_json::json; fn todo() -> TableDefinition { builtin_table_definitions().iter().find(|table| table.id == "todo").unwrap().clone() } fn card(value: serde_json::Value) -> CardFace { serde_json::from_value(value).unwrap() } // RULE: a card names columns its table has, each of the type its place // reads — the app draws a card's places without checking them, so a // wrong column is refused at save, never drawn as nothing. #[test] fn a_card_reads_columns_of_the_right_type() { let table = todo(); let pace = json!({"date": "due_at", "done": {"column": "status", "values": ["done"]}}); for (bad, why) in [ (json!({"face": "todo.card", "fields": [{"slot": "title", "column": "nope"}]}), "missing column"), (json!({"face": "todo.card", "fields": [{"slot": "date", "column": "title"}]}), "date place on text"), (json!({"face": "todo.card", "fields": [{"slot": "check", "column": "title"}], "pace": pace}), "check on text"), (json!({"face": "todo.card", "fields": [{"slot": "title", "column": "title", "form": "relative"}]}), "date form on text"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "next_occurrence", "within": 7}]}), "yearly form on a plain date"), (json!({"face": "todo.card", "corner": [{"column": "title", "form": "late", "within": 1}]}), "corner on text"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "money", "within": 1}]}), "money on a date"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "late"}]}), "no window"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "late", "within": 1, "behind": 3}]}), "two windows"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "late", "within": 1, "line": "deck.search"}]}), "not a corner line"), (json!({"face": "todo.card", "art": "pace"}), "art without pace"), (json!({"face": "todo.card", "art": "pace", "pace": {"date": "due_at", "done": {"column": "status", "values": ["finished"]}}}), "done value not a choice"), ] { assert!(card(bad).validate(&table, "card").is_err(), "{why}"); } card(json!({"face": "todo.card", "art": "pace", "pace": pace, "fields": [{"slot": "check", "column": "status"}, {"slot": "date", "column": "due_at", "form": "relative"}], "corner": [{"column": "due_at", "form": "late", "within": 1}]})) .validate(&table, "card") .unwrap(); } // RULE (owner, 29 Oct 2026): only the photo place chooses, and it // chooses one choice column a person writes — the shell turns the fan // into that column's values on a tap of the picture, so a column it could // not write, or a place that is no picture, is refused at save; the // event's card chooses its kind. #[test] fn only_the_picture_chooses_and_it_chooses_a_choice_a_person_writes() { let find = |id: &str| builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone(); let event = find("event"); let photo = event.card.as_ref().unwrap().fields.iter().find(|field| field.slot == CardSlot::Photo).unwrap(); assert_eq!(photo.chooses.as_deref(), Some("kind"), "the event's picture chooses its kind"); let table = event.clone(); let refused = |value: serde_json::Value, why: &str| { let error = card(value).validate(&table, "card").unwrap_err().to_string(); assert!(error.contains("only the photo place chooses"), "{why}: {error}"); }; refused(json!({"face": "event.rolodex", "fields": [{"slot": "title", "column": "title", "chooses": "kind"}]}), "a title"); refused(json!({"face": "event.rolodex", "fields": [{"slot": "photo", "column": "picture", "chooses": "title"}]}), "a text"); refused(json!({"face": "event.rolodex", "fields": [{"slot": "photo", "column": "picture", "chooses": "invited"}]}), "a read-only choice"); card(json!({"face": "event.rolodex", "fields": [{"slot": "photo", "column": "picture", "chooses": "kind"}]})) .validate(&table, "card") .unwrap(); } // RULE: a card says its body is Markdown (a note's page), only on the // body place of a text column read plain; the note kit says so, rather // than the app guessing it from the face's name. #[test] fn only_the_body_place_is_markdown_and_the_note_says_so() { let find = |id: &str| builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone(); let note = find("note"); let body = note.card.as_ref().unwrap().fields.iter().find(|field| field.slot == CardSlot::Body).unwrap(); assert!(body.markdown, "the note's body is Markdown"); let refused = |value: serde_json::Value, why: &str| { let error = card(value).validate(¬e, "card").unwrap_err().to_string(); assert!(error.contains("only the body place is Markdown"), "{why}: {error}"); }; refused(json!({"face": "note.page", "fields": [{"slot": "title", "column": "title", "markdown": true}]}), "a title"); refused(json!({"face": "note.page", "fields": [{"slot": "body", "column": "updated_at", "markdown": true}]}), "a date"); card(json!({"face": "note.page", "fields": [{"slot": "body", "column": "body", "markdown": true}]})) .validate(¬e, "card") .unwrap(); } // RULE: a card names its face by an open id, and only a face the app // draws reads: one it does not is refused with the id named, never drawn // as nothing (Loom step 5). #[test] fn a_card_names_a_face_the_app_draws() { assert_eq!(card(json!({"face": "todo.card"})).face, "todo.card"); let refused = serde_json::from_value::(json!({"face": "hologram"})).unwrap_err().to_string(); assert!(refused.contains("\"hologram\" is no face the app draws"), "{refused}"); assert!(FaceId::known("Todo").is_none() && FaceId::known("").is_none()); assert_eq!(FaceId::known("group"), Some(FaceId::GROUP), "the core deals the group face"); assert_eq!(serde_json::to_value(FaceId::GROUP).unwrap(), json!("group")); } // RULE: the ids a card may name are face_ids.json's — Loom's registry // (apps/loom/faces.json) and the faces CottonUI still draws // (faces-pending.json), as `pnpm gen:faces` writes them, which the guard // faces-registry holds fresh — each a well-formed id, the group face // among them. #[test] fn the_known_faces_are_well_formed_ids() { let known: Vec<&str> = FaceId::all().map(FaceId::as_str).collect(); assert!(known.contains(&FaceId::GROUP.as_str()), "the core deals the group face"); for id in known { let word = |word: &str| word.starts_with(|c: char| c.is_ascii_lowercase()) && word.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'); assert!(id.split('.').all(word), "{id:?} is lowercase words of letters, digits and _, joined by ."); } } // RULE: a device reads a card naming a face a newer build draws as no // card, and the row says the word it fell back on; an authored one is // refused. #[test] fn a_face_this_build_does_not_draw_reads_as_no_card() { #[derive(Deserialize)] struct Held { #[serde(deserialize_with = "face_or_absent")] card: Option, } let (held, words) = crate::definitions::tolerant::reading(|| serde_json::from_value::(json!({"card": {"face": "hologram"}}))); assert!(held.unwrap().card.is_none()); assert_eq!(words, ["hologram"]); } #[test] fn faces_by_value_read_only_choices_and_known_faces() { let table = todo(); for (column, values) in [("status", json!([])), ("status", json!(["invented"])), ("title", json!(["done"])), ("missing", json!(["done"]))] { let card = card(json!({"face": "todo.card", "faces": [{"when": {"column": column, "values": values}, "face": "plain"}]})); assert!(card.validate(&table, "card").is_err(), "{column}: {values}"); } let held = card(json!({"face": "todo.card", "faces": [{"when": {"column": "status", "values": ["done"]}, "face": "plain"}]})); held.validate(&table, "card").unwrap(); assert_eq!(card(serde_json::to_value(&held).unwrap()), held); for face in [json!("hologram"), json!("Todo.card"), json!(7)] { assert!(serde_json::from_value::(json!({"face": "todo.card", "faces": [{"when": {"column": "status", "values": ["done"]}, "face": face}]})).is_err()); } assert!(serde_json::to_value(card(json!({"face": "todo.card"}))).unwrap().get("faces").is_none()); } #[test] fn offers_are_ordered_known_distinct_faces_including_the_base() { let table = todo(); let offered = card(json!({"face":"todo.card", "offers":["todo.card", "plain"]})); offered.validate(&table, "card").unwrap(); assert_eq!(card(serde_json::to_value(&offered).unwrap()), offered); for offers in [json!(["plain"]), json!(["todo.card", "todo.card"])] { assert!(card(json!({"face":"todo.card", "offers":offers})).validate(&table, "card").is_err()); } assert!(serde_json::from_value::(json!({"face":"todo.card", "offers":["invented"]})).is_err()); assert!(serde_json::to_value(card(json!({"face":"todo.card"}))).unwrap().get("offers").is_none()); } #[test] fn a_row_key_names_a_required_writable_text_column() { let mut table: TableDefinition = serde_json::from_str(include_str!("../../kits/personal/tables/face_settings.json")).unwrap(); table.validate().unwrap(); for key in ["missing", "chosen_at"] { table.row_key = Some(key.into()); assert!(table.validate().is_err()); } table.row_key = Some("table".into()); table.columns.iter_mut().find(|c| c.key == "table").unwrap().required = Some(false); assert!(table.validate().is_err()); } // RULE: every shipped card block passes its own table's check. #[test] fn every_shipped_card_is_valid() { let mut seen = 0; for table in builtin_table_definitions() { if let Some(card) = &table.card { card.validate(table, "card").unwrap(); seen += 1; } } assert!(seen > 0, "the kit ships at least the todo card"); } // RULE: a whole opens only into parts that come with it and link back to // it — the deck turns the fan into a whole's parts by this block alone, // so a parts table that is not there, or a link that names another // table, is refused when the package is read, never dealt as nothing. #[test] fn a_whole_opens_into_parts_that_link_back_to_it() { let find = |id: &str| builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone(); let (mut album, item) = (find("album"), find("album_item")); let opens = |by: &str, through: Option<&str>| -> CardOpens { serde_json::from_value(json!({"table": "album_item", "by": by, "order": ["taken_at"], "through": through})).unwrap() }; album.card.as_mut().unwrap().opens = Some(opens("album_id", None)); validate_openings(&[album.clone(), item.clone()]).unwrap(); let read: CardFace = serde_json::from_value(serde_json::to_value(album.card.as_ref().unwrap()).unwrap()).unwrap(); assert_eq!(read.opens, Some(opens("album_id", None)), "the block reads back as written"); assert!(validate_openings(&[album.clone()]).is_err(), "the parts must come with the whole"); album.card.as_mut().unwrap().opens = Some(opens("record_id", None)); assert!(validate_openings(&[album.clone(), item.clone()]).is_err(), "the by column is a link to the whole"); album.card.as_mut().unwrap().opens = Some(opens("album_id", Some("caption"))); assert!(validate_openings(&[album.clone(), item.clone()]).is_err(), "through names a link"); // Only some records may be wholes: those whose choice holds a value. let when = |column: &str, values: &[&str]| -> CardOpens { let mut opens = opens("album_id", None); opens.when = Some(ValueMatch { column: column.into(), values: values.iter().map(|value| value.to_string()).collect() }); opens }; album.card.as_mut().unwrap().opens = Some(when("kind", &["trip"])); validate_openings(&[album.clone(), item.clone()]).unwrap(); for (bad, why) in [(when("kind", &["holiday"]), "a value that is no choice"), (when("kind", &[]), "no value"), (when("title", &["trip"]), "a column that is no choice"), (when("nope", &["trip"]), "a column the whole has not")] { album.card.as_mut().unwrap().opens = Some(bad); let refused = validate_openings(&[album.clone(), item.clone()]).unwrap_err().to_string(); assert!(refused.contains("opens only while"), "{why}: {refused}"); } } }