279 lines · 15.3 KB · RustRaw
//! The record page's two guards (the record-page proposal's guards 2 and 6)://! what a record opens on and how its facts are grouped, derived by column//! type alone; and the one page read answering everything a page shows.//! Every table, column and value here is invented.use std::collections::BTreeMap;use serde_json::{json, Map, Value};use super::*;use crate::definitions::{ColumnType, GroupColumns, GroupReach, GroupReads, PageGroup, PageOpens, TableDefinition};/// A user table of the columns given, its page drawing every one of them.fn table(id: &str, columns: Value, extra: Value) -> TableDefinition { let title = columns[0]["key"].clone(); let every: Vec<Value> = columns.as_array().unwrap().iter().map(|column| column["key"].clone()).collect(); let mut value = json!({ "id": id, "name": id, "plural": format!("{id}s"), "picture": null, "builtin": false, "engine": null, "columns": columns, "title": title, "date": null, "project": null, "order": null, "slip": { "title": title, "subtitle": null, "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [{ "heading": null, "columns": every }], "instructions": "A fixture." }); for (key, held) in extra.as_object().unwrap() { if key == "slip" { for (slot, said) in held.as_object().unwrap() { value["slip"][slot] = said.clone(); } } else { value[key] = held.clone(); } } serde_json::from_value(value).expect("parses")}/// One column of every type, keyed by its type, after a text title.fn every_type() -> Value { let mut columns = vec![json!({ "key": "name", "type": "text" })]; for column_type in ColumnType::ALL { let spelled = serde_json::to_value(column_type).unwrap(); let key = spelled.as_str().unwrap().to_string(); let mut column = json!({ "key": key, "type": spelled }); match column_type { ColumnType::Choice => column["choices"] = json!(["one", "two"]), ColumnType::Link => column["link_to"] = json!("elsewhere"), _ => {} } columns.push(column); } Value::Array(columns)}fn facts(columns: &[&str]) -> PageGroup { PageGroup::Columns(GroupColumns { columns: columns.iter().map(|key| key.to_string()).collect(), invites: Vec::new() })}/// RULE: A record opens on what it is for and its facts are grouped by column TYPE alone, never by a table or column name: a media column the record IS (played by its slip, or a picture or file the engine keeps) opens it as the thing; the long text its title is borrowed from opens it on the body; else its facts. The groups are the reach slip where another table holds the record's handles, the own columns in definition order six to a slip (never the title, the body, a picture, a file or a secret), then each other long text as its own reading slip; an authored `parts` wins over every derivation. The Swift face draws these and names no column, so a wrong derivation is a wrong page for every tool that names none.#[test]fn the_opening_and_the_groups_are_derived_by_column_type() { let plain = table("specimen", every_type(), json!({})); assert_eq!(plain.resolved_opens(), PageOpens::Facts, "a picture the person sets is no thing"); let own = ["text", "account_number", "date", "time", "number", "bytes", "amount", "choice", "link", "bool", "url", "place"]; assert_eq!( plain.resolved_groups(&[plain.clone()]), vec![facts(&own[..6]), facts(&own[6..]), PageGroup::Reads(GroupReads { column: "longtext".into(), reads: true, folded: false })], ); let played = table("specimen", every_type(), json!({ "slip": { "player": "file" } })); assert_eq!(played.resolved_opens(), PageOpens::Thing); assert_eq!(played.thing_column(), Some("file")); let mut kept = every_type(); kept[ColumnType::ALL.iter().position(|t| *t == ColumnType::Photo).unwrap() + 1]["readonly"] = json!(true); let pictured = table("specimen", kept, json!({ "slip": { "photo": "photo" } })); assert_eq!(pictured.resolved_opens(), PageOpens::Thing, "a picture the engine keeps and the slip draws is the record"); let written = table("specimen", every_type(), json!({ "slip": { "title_fallback": "longtext" } })); assert_eq!(written.resolved_opens(), PageOpens::Body); let groups = written.resolved_groups(&[written.clone()]); assert!(!groups.iter().any(|group| matches!(group, PageGroup::Reads(_))), "the body is the page, never a slip under it"); let mut secret = every_type(); secret[1]["secret"] = json!(true); let sealed = table("specimen", secret, json!({})); assert!(!sealed.resolved_groups(&[]).iter().any(|group| matches!(group, PageGroup::Columns(g) if g.columns.contains(&"text".to_string())))); let ways = table( "way_in", json!([ { "key": "value", "type": "text", "required": true }, { "key": "kind", "type": "choice", "choices": ["phone", "email"], "required": true }, { "key": "owner", "type": "link", "link_to": "specimen", "required": true, "contributes": false } ]), json!({}), ); let groups = plain.resolved_groups(&[plain.clone(), ways]); assert_eq!(groups.first(), Some(&PageGroup::Reach(GroupReach { reach: true })), "the reach slip leads"); let mut authored = plain.clone(); let mut parts = authored.resolved_parts(); parts.opens = Some(PageOpens::Body); parts.groups = Some(vec![facts(&["date"])]); authored.parts = Some(parts); assert_eq!(authored.resolved_opens(), PageOpens::Body); assert_eq!(authored.resolved_groups(&[]), vec![facts(&["date"])]);}/// A household of rows, read as the generic verbs answer them, counting/// each read.struct Household { tables: Vec<TableDefinition>, rows: BTreeMap<String, Vec<(String, Map<String, Value>)>>, asked: BTreeMap<&'static str, usize>,}impl Household { fn ask(&mut self, what: &'static str) { *self.asked.entry(what).or_default() += 1; }}impl PageSource for Household { fn line_rows(&mut self) -> Vec<crate::rules::shell_lines::LineRow> { Vec::new() } fn definition(&mut self, table: &str) -> Option<TableDefinition> { self.tables.iter().find(|definition| definition.id == table).cloned() } fn record(&mut self, table: &str, id: &str) -> Result<Map<String, Value>, String> { self.ask("record"); self.rows.get(table).and_then(|rows| rows.iter().find(|(row, _)| row == id)).map(|(_, data)| data.clone()).ok_or_else(|| "gone".into()) } fn records(&mut self, table: &str, ids: &[String]) -> Result<Vec<(String, Map<String, Value>)>, String> { Ok(self.rows.get(table).into_iter().flatten().filter(|(id, _)| ids.contains(id)).cloned().collect()) } fn list(&mut self, table: &str, filter: &Map<String, Value>, limit: usize) -> Result<(u64, Vec<(String, Map<String, Value>)>), String> { let found: Vec<_> = self .rows .get(table) .into_iter() .flatten() .filter(|(_, data)| filter.iter().all(|(key, value)| data.get(key) == Some(value))) .cloned() .collect(); Ok((found.len() as u64, found.into_iter().take(limit).collect())) } fn active_project_slugs(&mut self) -> Vec<String> { Vec::new() } fn read(&mut self, name: &str, _args: &Map<String, Value>) -> Result<Value, String> { Err(format!("no read.{name}")) } fn definitions(&mut self) -> Vec<TableDefinition> { self.ask("definitions"); self.tables.clone() }}fn row(id: &str, data: Value) -> (String, Map<String, Value>) { (id.to_string(), data.as_object().unwrap().clone())}/// RULE: One page read answers everything a record page shows — the opening, the head's lines (with the standing view's head line), the fact slips with their invited blanks, the reach rows, every view's id in order, and each headed list's count and newest few said by the CONTRIBUTING table's slip in that table's dye — reading the record once and the installed tables once. The phone's `records.page` is this read: a page that needed a second read would reflow after paint, and a list said by the host's slip would wear the wrong words and colour.#[test]fn one_page_read_answers_head_groups_peeks_views_and_counts() { let host = table( "friend", json!([ { "key": "name", "type": "text" }, { "key": "tier", "type": "choice", "choices": ["close", "far"], "labels": { "close": "Close", "far": "Far" } }, { "key": "birthday", "type": "date" }, { "key": "summary", "type": "longtext" } ]), json!({ "parts": { "shape": "sheet", "head": { "facts": [] }, "links": [], "lists": [], "acts": { "main": null, "more": [], "away": null }, "groups": [{ "reach": true }, { "columns": ["tier", "birthday"], "invites": ["birthday"] }, { "column": "summary", "reads": true }], "views": [{ "view": "payments.between_us", "peek": 2 }, { "list": "chore", "peek": 1 }] } }), ); let ways = table( "way_in", json!([ { "key": "value", "type": "text", "required": true }, { "key": "kind", "type": "choice", "choices": ["phone", "email"], "labels": { "phone": "Phone", "email": "Email" }, "required": true }, { "key": "owner", "type": "link", "link_to": "friend", "required": true, "contributes": false } ]), json!({}), ); let chore = table( "chore", json!([{ "key": "title", "type": "text" }, { "key": "for_whom", "type": "link", "link_to": "friend" }]), json!({ "slip": { "dye": "pink" }, "tool": { "name": "Chores", "views": [{ "id": "all", "label": "Things to do", "is_default": true, "read": { "table": "chore" } }] } }), ); let payment = table( "payment", json!([{ "key": "what", "type": "text" }, { "key": "friend", "type": "link", "link_to": "friend" }]), json!({ "slip": { "dye": "buff" }, "tool": { "name": "Payments", "key": "payments", "views": [ { "id": "all", "label": "Payments", "is_default": true, "read": { "table": "payment" } }, { "id": "between_us", "label": "Between us", "read": { "table": "payment" }, "partition": "friend", "head_line": { "columns": ["tier"] } } ] } }), ); for definition in [&host, &ways, &chore, &payment] { definition.validate().unwrap_or_else(|why| panic!("{}: {why}", definition.id)); } host.views_hold(&[host.clone(), ways.clone(), chore.clone(), payment.clone()]).expect("its views are over it"); let mut rows = BTreeMap::new(); rows.insert("friend".to_string(), vec![row("f1", json!({ "name": "Wren Alder", "tier": "close", "summary": "Met at the harbour." }))]); rows.insert("way_in".to_string(), vec![row("w1", json!({ "value": "+00 5550 0101", "kind": "phone", "owner": "f1" }))]); rows.insert("chore".to_string(), vec![row("c1", json!({ "title": "Return the ladder", "for_whom": "f1" }))]); rows.insert( "payment".to_string(), (1..=3).map(|n| row(&format!("p{n}"), json!({ "what": format!("Ferry ticket {n}"), "friend": "f1" }))).collect(), ); let mut household = Household { tables: vec![host, ways, chore, payment], rows, asked: BTreeMap::new() }; let page = record_page_read(&mut household, "friend", "f1", Some("payments.between_us")).expect("a page"); assert_eq!(household.asked.get("record"), Some(&1), "the record is read once"); assert_eq!(household.asked.get("definitions"), Some(&1), "the installed tables are read once"); assert_eq!(page.opens, PageOpens::Facts); assert_eq!(page.page.head.title, "Wren Alder"); assert_eq!(page.view, "payments.between_us"); assert_eq!(page.head_lines.caption.as_deref(), Some("Close"), "the standing view's head line"); assert_eq!( page.views.iter().map(|view| view.id.as_str()).collect::<Vec<_>>(), ["overview", "payments.between_us", "list:chore"], "Overview, then the named order; the list a partitioned view narrows is that view", ); let GroupRead::Reach { rows, .. } = &page.groups[0] else { panic!("the reach slip leads: {:?}", page.groups) }; assert_eq!((rows[0].label.as_str(), rows[0].value.as_str(), rows[0].channels[0].label.as_str()), ("Phone", "+00 5550 0101", "Phone")); let GroupRead::Facts { lines } = &page.groups[1] else { panic!("{:?}", page.groups) }; assert_eq!(lines[0].value.as_deref(), Some("Close")); assert!(lines[1].invited && lines[1].value.is_none(), "an invited blank is drawn"); assert!(matches!(&page.groups[2], GroupRead::Reads { text, .. } if text == "Met at the harbour.")); let between = &page.headed[0]; assert_eq!((between.heading.as_str(), between.count, between.peek.len()), ("Between us", 3, 2)); assert!(between.peek.iter().all(|slip| slip.dye == "buff" && slip.title.starts_with("Ferry ticket"))); let chores = &page.headed[1]; assert_eq!((chores.heading.as_str(), chores.count), ("Things to do", 1), "labelled by its tool's view"); assert_eq!((chores.peek[0].title.as_str(), chores.peek[0].dye.as_str()), ("Return the ladder", "pink"));}/// RULE: A page's fact line says its label once: its value never repeats the label (a switch says on or off, a bare number its figure), and no two lines on one page share a label.////// WHY: 22 Oct 2026, Rigby build 3's walk — This Device drew "Events //// Events", "Alarms / Alarms" for switches that were on, and "Sessions //// 3 sessions" beside "Sessions / Sessions 0": the facts were worded for a/// slip's sentence, where the name is part of the value, then drawn under/// their label.#[test]fn a_fact_line_says_its_label_once() { let raw = crate::definitions::BUILTIN_DEFINITION_FILES.iter().find(|(id, _)| *id == "device").expect("the kit ships device").1; let device = TableDefinition::from_json(raw).expect("device parses"); let mut rows = BTreeMap::new(); rows.insert("device".to_string(), vec![row("d1", json!({ "name": "An invented phone", "status": "this device", "kind": "iPhone", "notify": true, "notify_reminders": true, "notify_events": false, "notify_birthdays": true, "notify_alarms": false, "sessions_cap": 3, "sessions_running": 0, }))]); let mut household = Household { tables: vec![device], rows, asked: BTreeMap::new() }; let page = record_page_read(&mut household, "device", "d1", None).expect("a page"); let mut labels = BTreeMap::new(); let mut said = BTreeMap::new(); for group in &page.groups { let GroupRead::Facts { lines } = group else { continue }; for line in lines.iter().filter(|line| line.value.is_some()) { let value = line.value.as_deref().unwrap_or_default(); assert!(!value.starts_with(line.label.as_str()), "{}: {:?} repeats its label {:?}", line.column, value, line.label); if let Some(other) = labels.insert(line.label.clone(), line.column.clone()) { panic!("{} and {other} are both labelled {:?}", line.column, line.label); } said.insert(line.column.clone(), value.to_string()); } } for switch in ["notify", "notify_reminders", "notify_events", "notify_birthdays", "notify_alarms"] { assert!(said.contains_key(switch), "{switch} says on or off: {said:?}"); } assert_ne!(said["notify"], said["notify_events"], "on and off are said differently");}