//! What a record page opens on, how its facts are grouped into slips, and //! which views its ring turns: three add-only keys of `parts` //! (`parts.opens`, `parts.groups`, `parts.views`; architect, 21 Oct 2026 — //! `page` stays the array of sections). Each is DERIVED by column type when //! absent, so a definition that names none still gets a whole page, and no //! table or column name is written here. //! //! * opens: `thing` where a media column is the record (the slip plays it, //! or draws a picture the engine keeps, or a file the engine keeps); //! `body` where a long text is the title's body; else `facts`. //! * groups: the reach slip first where another table holds this record's //! handles; then the record's own columns in definition order, at most //! [`GROUP_COLUMNS`] to a slip; then every secondary long text as its own //! reading slip. //! * views: order and peek of the partitioned views other tools declare //! over this table and of the lists that link to it. use serde::{Deserialize, Deserializer, Serialize}; use serde::de::DeserializeOwned; use serde_json::Value; use super::contributors::Contributes; use super::{is_valid_id, ColumnType, DefinitionError, TableDefinition}; /// Most of the record's own columns one fact slip holds. pub const GROUP_COLUMNS: usize = 6; /// How many of a headed list's newest records the page shows when its view /// names no peek. pub const DEFAULT_PEEK: u32 = 2; /// The largest peek a view may ask (a page's list draws no more rows). pub const MAX_PEEK: u32 = crate::records::page::LIST_ROWS as u32; /// What a record opens on. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PageOpens { /// Its facts: the head, then its fact slips and lists. Facts, /// Its text, set for reading under the head. Body, /// The thing itself (a photo, a video, a document), full screen. Thing, } impl PageOpens { pub fn as_str(self) -> &'static str { match self { Self::Facts => "facts", Self::Body => "body", Self::Thing => "thing", } } } /// One fact slip of a record page. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum PageGroup { Columns(GroupColumns), Reads(GroupReads), Reach(GroupReach), } /// Some of the record's own columns, one line each; a column with nothing /// draws no line unless the group `invites` it, when its blank is drawn. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GroupColumns { pub columns: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub invites: Vec, } /// One long text set as a reading slip (`reads: true`); `folded: true` /// draws only its label behind a chevron until one tap unfolds it — for /// a reading kept one level down (the device page's every table). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GroupReads { pub column: String, pub reads: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub folded: bool, } /// The reach slip (`reach: true`): every handle that reaches the record, one /// row each. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GroupReach { pub reach: bool, } /// One of the record's views, by order and peek only: a partitioned view /// another tool declares (`view: "."`) or a list that links /// to this table (`list: ""`). Exactly one of the two. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PageViewRef { #[serde(default, skip_serializing_if = "Option::is_none")] pub view: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub list: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub peek: Option, } impl PageViewRef { /// The peek the page shows: the view's own, else [`DEFAULT_PEEK`]. pub fn peek(&self) -> u32 { self.peek.unwrap_or(DEFAULT_PEEK) } /// `(tool, view id)` of a `view` reference. pub fn tool_view(&self) -> Option<(&str, &str)> { self.view.as_deref()?.split_once('.') } } /// A list of objects read around: an entry this build cannot read (a newer /// build's form) is left out, the rest read as they came. Authoring refuses /// what was left out (`tolerant::refuse_unknown`). pub(crate) fn readable<'de, D: Deserializer<'de>, T: DeserializeOwned>(deserializer: D) -> Result>, D::Error> { let items = Option::>::deserialize(deserializer)?; Ok(items.map(|items| items.into_iter().filter_map(|item| serde_json::from_value(item).ok()).collect())) } const MEDIA: &[ColumnType] = &[ColumnType::Photo, ColumnType::File]; impl TableDefinition { /// What the record opens on: `parts.opens`, else derived by type. pub fn resolved_opens(&self) -> PageOpens { if let Some(opens) = self.parts.as_ref().and_then(|parts| parts.opens) { return opens; } if self.thing_column().is_some() { PageOpens::Thing } else if self.title_body().is_some() { PageOpens::Body } else { PageOpens::Facts } } /// The media column that IS the record: the one its slip plays, the /// picture its slip draws when the engine keeps it (a person's portrait /// is the person's to change, so it is never the thing), or a file the /// engine keeps. pub fn thing_column(&self) -> Option<&str> { let media = |key: &Option| { key.as_deref().and_then(|key| self.column(key)).filter(|column| MEDIA.contains(&column.column_type) && column.secret != Some(true)) }; if let Some(column) = media(&self.slip.player) { return Some(&column.key); } if let Some(column) = media(&self.slip.photo).filter(|column| column.readonly == Some(true)) { return Some(&column.key); } self.columns .iter() .find(|column| column.column_type == ColumnType::File && column.readonly == Some(true) && column.secret != Some(true)) .map(|column| column.key.as_str()) } /// The long text that is the title's body: the title column itself, or /// the long text an untitled record borrows its title from. pub fn title_body(&self) -> Option<&str> { let longtext = |key: &str| self.column(key).filter(|column| column.column_type == ColumnType::Longtext && column.secret != Some(true)); longtext(&self.title) .or_else(|| self.slip.title_fallback.as_deref().and_then(longtext)) .map(|column| column.key.as_str()) } /// The table among `tables` that holds this record's handles: one whose /// required link here lists nothing on the page (`contributes: false`) /// and whose every row says, by a required choice, what kind of handle /// its required title is. pub fn reach_table<'a>(&self, tables: &'a [TableDefinition]) -> Option<(&'a TableDefinition, &'a str, &'a str)> { tables.iter().find_map(|table| { if table.id == self.id { return None; } let link = table.columns.iter().find(|column| { column.column_type == ColumnType::Link && column.link_to.as_deref() == Some(self.id.as_str()) && column.required == Some(true) && column.contributes == Some(Contributes::Flag(false)) })?; let titled = table.column(&table.title).is_some_and(|column| column.column_type == ColumnType::Text && column.required == Some(true)); let kind = table.columns.iter().find(|column| column.column_type == ColumnType::Choice && column.required == Some(true) && column.multiple != Some(true))?; titled.then_some((table, link.key.as_str(), kind.key.as_str())) }) } /// The fact slips: `parts.groups`, else derived by type — the reach slip /// (where `tables` holds this record's handles), then the record's own /// columns in definition order, at most [`GROUP_COLUMNS`] to a slip, /// then each secondary long text as its own reading slip. Never the /// title, the body or the thing the page opens on, a picture or a file, /// a secret, or a stamp; where the page's sections draw columns, only /// the columns they draw. pub fn resolved_groups(&self, tables: &[TableDefinition]) -> Vec { if let Some(groups) = self.parts.as_ref().and_then(|parts| parts.groups.clone()) { return groups; } let opens = self.resolved_opens(); let body = (opens == PageOpens::Body).then(|| self.title_body()).flatten(); let drawn: Vec<&String> = self.page.iter().flat_map(|section| section.columns().iter()).collect(); let shown = |key: &String| drawn.is_empty() || drawn.contains(&key); let mut groups = Vec::new(); if self.reach_table(tables).is_some() { groups.push(PageGroup::Reach(GroupReach { reach: true })); } let own: Vec<&super::Column> = self .columns .iter() .filter(|column| column.key != self.title && Some(column.key.as_str()) != body) .filter(|column| !MEDIA.contains(&column.column_type) && column.secret != Some(true)) .filter(|column| !super::parts::STAMPS.contains(&column.key.as_str()) && shown(&column.key)) .collect(); let facts: Vec = own.iter().filter(|column| column.column_type != ColumnType::Longtext).map(|column| column.key.clone()).collect(); for chunk in facts.chunks(GROUP_COLUMNS) { groups.push(PageGroup::Columns(GroupColumns { columns: chunk.to_vec(), invites: Vec::new() })); } for column in own.iter().filter(|column| column.column_type == ColumnType::Longtext) { groups.push(PageGroup::Reads(GroupReads { column: column.key.clone(), reads: true, folded: false })); } groups } /// `parts.opens`, `parts.groups` and `parts.views` say only what this /// table can draw: a body only on a table with a long text, a thing only /// on one with a picture or a file; each group's columns this table's, /// each once across the page, invites among its own columns, a reading /// slip a long text, one reach slip; each view one of the two forms, /// named once, its peek between 1 and [`MAX_PEEK`]. That a view is a /// partitioned view over this table, and a list a table that links here, /// is checked where the other tables are known ([`Self::views_hold`]). pub(super) fn validate_record_page(&self) -> Result<(), DefinitionError> { if let Some(dye) = self.slip.dye.as_deref().filter(|dye| !super::theme::THEME_DYES.contains(dye)) { return Err(DefinitionError::BadSlot { slot: "slip.dye".into(), why: super::automations::said("is_not_one_of_the_theme_s_dyes", &[("dye", &format!("{dye:?}"))]) }); } let Some(parts) = &self.parts else { return Ok(()) }; let has = |types: &[ColumnType]| self.columns.iter().any(|column| types.contains(&column.column_type)); match parts.opens { Some(PageOpens::Body) if !has(&[ColumnType::Longtext]) => { return Err(DefinitionError::Requires { slot: "parts.opens".into(), needs: "a_long_text_column_to_open_on" }) } Some(PageOpens::Thing) if !has(MEDIA) => { return Err(DefinitionError::Requires { slot: "parts.opens".into(), needs: "a_photo_or_file_column_to_open" }) } _ => {} } let mut placed = std::collections::BTreeSet::new(); let mut reach = false; for group in parts.groups.iter().flatten() { match group { PageGroup::Columns(group) => { if group.columns.is_empty() { return Err(DefinitionError::Empty("parts.groups.columns")); } for key in &group.columns { self.named("parts.groups.columns", key, None)?; if !placed.insert(key.as_str()) { return Err(DefinitionError::Conflict { slot: "parts.groups.columns".into(), other: "the_same_column_in_another_group" }); } } if let Some(stray) = group.invites.iter().find(|key| !group.columns.contains(key)) { return Err(DefinitionError::UnknownColumn { slot: "parts.groups.invites".into(), column: stray.clone() }); } } PageGroup::Reads(group) => { if !group.reads { return Err(DefinitionError::Requires { slot: "parts.groups.reads".into(), needs: "true" }); } self.named("parts.groups.column", &group.column, Some((&[ColumnType::Longtext], "a long text")))?; if !placed.insert(group.column.as_str()) { return Err(DefinitionError::Conflict { slot: "parts.groups.column".into(), other: "the_same_column_in_another_group" }); } } PageGroup::Reach(group) => { if !group.reach || reach { return Err(DefinitionError::Requires { slot: "parts.groups.reach".into(), needs: "true, once" }); } reach = true; } } } let mut named = std::collections::BTreeSet::new(); for view in parts.views.iter().flatten() { let key = match (&view.view, &view.list) { (Some(_), None) => match view.tool_view() { Some((tool, id)) if is_valid_id(tool) && is_valid_id(id) => view.view.clone(), _ => return Err(DefinitionError::Requires { slot: "parts.views.view".into(), needs: "tool_view_id" }), }, (None, Some(list)) if is_valid_id(list) => Some(format!("list:{list}")), (None, Some(list)) => return Err(DefinitionError::BadId(list.clone())), _ => return Err(DefinitionError::Requires { slot: "parts.views".into(), needs: "a_view_or_a_list_not_both" }), }; if !named.insert(key) { return Err(DefinitionError::Conflict { slot: "parts.views".into(), other: "the_same_view_named_twice" }); } if view.peek.is_some_and(|peek| peek == 0 || peek > MAX_PEEK) { return Err(DefinitionError::Requires { slot: "parts.views.peek".into(), needs: "between_1_and_10" }); } } Ok(()) } /// `parts.views` against the tables beside this one: a `view` is a /// partitioned view of a tool among `tables` whose partition column /// links here; a `list` is a table among `tables` with a link here. A /// reference to a tool or a table not among `tables` is the install's to /// check, and passes here. pub fn views_hold(&self, tables: &[TableDefinition]) -> Result<(), DefinitionError> { let Some(views) = self.parts.as_ref().and_then(|parts| parts.views.as_ref()) else { return Ok(()) }; for view in views { if let Some((tool, id)) = view.tool_view() { let Some(home) = tables.iter().find(|table| table.tool.as_ref().is_some_and(|home| home.key.as_deref().unwrap_or(&table.id) == tool)) else { continue; }; if partitioned_over(home, id, &self.id, tables).is_none() { return Err(DefinitionError::Requires { slot: format!("parts.views.{tool}.{id}"), needs: "a_partitioned_view_over_this_table" }); } } if let Some(list) = &view.list { let Some(table) = tables.iter().find(|table| &table.id == list) else { continue }; if !links_to(table, &self.id) { return Err(DefinitionError::Requires { slot: format!("parts.views.{list}"), needs: "a_table_with_a_link_to_this" }); } } } Ok(()) } } /// The view `id` of `home`'s tool when it is partitioned over `host`: its /// read's table's partition column links to `host`. pub fn partitioned_over<'a>(home: &'a TableDefinition, id: &str, host: &str, tables: &[TableDefinition]) -> Option<&'a super::tool_views::ToolView> { let view = home.tool.as_ref()?.views.iter().find(|view| view.id == id)?; let column = view.partition.as_deref()?; let read = view.read.get("table").and_then(Value::as_str)?; let table = tables.iter().find(|table| table.id == read)?; table .column(column) .is_some_and(|column| column.column_type == ColumnType::Link && column.link_to.as_deref() == Some(host)) .then_some(view) } fn links_to(table: &TableDefinition, host: &str) -> bool { table.columns.iter().any(|column| column.column_type == ColumnType::Link && column.link_to.as_deref() == Some(host)) } /// The id of a record's first view, its own page. pub const OVERVIEW: &str = "overview"; /// One view the ring turns on a record: its own page (Overview), a /// partitioned view another tool declares over the record's table, or a /// list another table contributes to it. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct RecordView { /// `overview`, `.`, or `list:
` (`list:
:` /// where the same table contributes by several columns). pub id: String, pub label: String, #[serde(skip_serializing_if = "Option::is_none")] pub list: Option, /// The partitioned view's tool home table and view id. #[serde(skip_serializing_if = "Option::is_none")] pub tool_view: Option<(String, String)>, pub peek: u32, } impl RecordView { /// The table this view's slips are records of; none for Overview. pub fn table<'a>(&'a self, tables: &'a [TableDefinition]) -> Option<&'a str> { if let Some(list) = &self.list { return Some(&list.table); } let (home, id) = self.tool_view.as_ref()?; let home = tables.iter().find(|table| &table.id == home)?; home.tool.as_ref()?.views.iter().find(|view| &view.id == id)?.read.get("table")?.as_str() } } /// The views a record of `host` turns: Overview first, then those /// `parts.views` names in its order, then the rest by tool order. A view is /// a partitioned view over `host` ([`partitioned_over`]) or a list another /// table contributes ([`super::contributors::contributors`]); a contributed /// list a partitioned view already narrows by the same column is that view. /// A list is labelled with its tool's default view label where its tool has /// views, else as its link says or by the table's plural. pub fn record_views(tables: &[TableDefinition], host: &str) -> Vec { let Some(home) = tables.iter().find(|table| table.id == host) else { return Vec::new() }; let mut found: Vec = Vec::new(); let mut narrowed: Vec<(String, String)> = Vec::new(); for table in tables { let Some(tool) = &table.tool else { continue }; let name = tool.key.as_deref().unwrap_or(&table.id); for view in &tool.views { if partitioned_over(table, &view.id, host, tables).is_none() { continue; } if let (Some(read), Some(column)) = (view.read.get("table").and_then(Value::as_str), view.partition.as_deref()) { narrowed.push((read.to_string(), column.to_string())); } found.push(RecordView { id: format!("{name}.{}", view.id), label: view.label.clone(), list: None, tool_view: Some((table.id.clone(), view.id.clone())), peek: DEFAULT_PEEK, }); } } let contributed = super::contributors::contributors(tables, host); for contributor in contributed { if contributor.column.as_ref().is_some_and(|column| narrowed.contains(&(contributor.table.clone(), column.clone()))) { continue; } let said = contributor.column.as_ref().and_then(|key| { let table = tables.iter().find(|table| table.id == contributor.table)?; match &table.column(key)?.contributes { Some(Contributes::Said(said)) => said.label.clone(), _ => None, } }); let tool_label = tables .iter() .find(|table| table.id == contributor.table) .and_then(|table| table.tool.as_ref()) .and_then(|tool| tool.views.iter().find(|view| view.is_default)) .map(|view| view.label.clone()); let mut id = format!("list:{}", contributor.table); if found.iter().any(|view| view.id == id) { id = format!("{id}:{}", contributor.column.as_deref().or(contributor.through.as_ref().map(|through| through.table.as_str())).unwrap_or_default()); } found.push(RecordView { id, label: said.or(tool_label).unwrap_or_else(|| contributor.label.clone()), list: Some(contributor), tool_view: None, peek: DEFAULT_PEEK, }); } // The host names an order and peeks; what it does not name follows in // the order found (tool order). let named = home.parts.as_ref().and_then(|parts| parts.views.clone()).unwrap_or_default(); let mut ordered = vec![RecordView { id: OVERVIEW.into(), label: "Overview".into(), list: None, tool_view: None, peek: 0 }]; for reference in &named { let at = found.iter().position(|view| match (&reference.view, &reference.list) { (Some(named), _) => &view.id == named, (None, Some(list)) => view.list.as_ref().is_some_and(|contributor| &contributor.table == list), _ => false, }); if let Some(at) = at { let mut view = found.remove(at); view.peek = reference.peek(); ordered.push(view); } } ordered.extend(found); ordered }