//! 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;usesuper::contributors::Contributes;usesuper::{is_valid_id, ColumnType, DefinitionError, TableDefinition};/// Most of the record's own columns one fact slip holds.pubconst GROUP_COLUMNS: usize = 6;/// How many of a headed list's newest records the page shows when its view/// names no peek.pubconst DEFAULT_PEEK: u32 = 2;/// The largest peek a view may ask (a page's list draws no more rows).pubconst 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")]pubenumPageOpens {/// 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,}implPageOpens {pubfn as_str(self) -> &'static str {matchself {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)]pubenumPageGroup {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)]pubstructGroupColumns {pub columns: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")]pub invites: Vec<String>,}/// 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)]pubstructGroupReads {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)]pubstructGroupReach {pub reach: bool,}/// One of the record's views, by order and peek only: a partitioned view/// another tool declares (`view: "<tool>.<view id>"`) or a list that links/// to this table (`list: "<table>"`). Exactly one of the two.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pubstructPageViewRef { #[serde(default, skip_serializing_if = "Option::is_none")]pub view: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub list: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub peek: Option<u32>,}implPageViewRef {/// The peek the page shows: the view's own, else [`DEFAULT_PEEK`].pubfn peek(&self) -> u32 {self.peek.unwrap_or(DEFAULT_PEEK) }/// `(tool, view id)` of a `view` reference.pubfn 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<Option<Vec<T>>, D::Error> {let items = Option::<Vec<Value>>::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];implTableDefinition {/// What the record opens on: `parts.opens`, else derived by type.pubfn resolved_opens(&self) -> PageOpens {ifletSome(opens) = self.parts.as_ref().and_then(|parts| parts.opens) {return opens; }ifself.thing_column().is_some() {PageOpens::Thing } elseifself.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.pubfn thing_column(&self) -> Option<&str> {let media = |key: &Option<String>| { key.as_deref().and_then(|key| self.column(key)).filter(|column| MEDIA.contains(&column.column_type) && column.secret != Some(true)) };ifletSome(column) = media(&self.slip.player) {returnSome(&column.key); }ifletSome(column) = media(&self.slip.photo).filter(|column| column.readonly == Some(true)) {returnSome(&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.pubfn 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.pubfn reach_table<'a>(&self, tables: &'a [TableDefinition]) -> Option<(&'a TableDefinition, &'a str, &'a str)> { tables.iter().find_map(|table| {if table.id == self.id {returnNone; }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.pubfn resolved_groups(&self, tables: &[TableDefinition]) -> Vec<PageGroup> {ifletSome(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);letmut groups = Vec::new();ifself.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<String> = 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> {ifletSome(dye) = self.slip.dye.as_deref().filter(|dye| !super::theme::THEME_DYES.contains(dye)) {returnErr(DefinitionError::BadSlot { slot: "slip.dye".into(), why: super::automations::said("is_not_one_of_the_theme_s_dyes", &[("dye", &format!("{dye:?}"))]) }); }letSome(parts) = &self.parts else { returnOk(()) };let has = |types: &[ColumnType]| self.columns.iter().any(|column| types.contains(&column.column_type));match parts.opens {Some(PageOpens::Body) if !has(&[ColumnType::Longtext]) => {returnErr(DefinitionError::Requires { slot: "parts.opens".into(), needs: "a_long_text_column_to_open_on" }) }Some(PageOpens::Thing) if !has(MEDIA) => {returnErr(DefinitionError::Requires { slot: "parts.opens".into(), needs: "a_photo_or_file_column_to_open" }) } _ => {} }letmut placed = std::collections::BTreeSet::new();letmut reach = false;for group in parts.groups.iter().flatten() {match group {PageGroup::Columns(group) => {if group.columns.is_empty() {returnErr(DefinitionError::Empty("parts.groups.columns")); }for key in &group.columns {self.named("parts.groups.columns", key, None)?;if !placed.insert(key.as_str()) {returnErr(DefinitionError::Conflict { slot: "parts.groups.columns".into(), other: "the_same_column_in_another_group" }); } }ifletSome(stray) = group.invites.iter().find(|key| !group.columns.contains(key)) {returnErr(DefinitionError::UnknownColumn { slot: "parts.groups.invites".into(), column: stray.clone() }); } }PageGroup::Reads(group) => {if !group.reads {returnErr(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()) {returnErr(DefinitionError::Conflict { slot: "parts.groups.column".into(), other: "the_same_column_in_another_group" }); } }PageGroup::Reach(group) => {if !group.reach || reach {returnErr(DefinitionError::Requires { slot: "parts.groups.reach".into(), needs: "true, once" }); } reach = true; } } }letmut 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(), _ => returnErr(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)) => returnErr(DefinitionError::BadId(list.clone())), _ => returnErr(DefinitionError::Requires { slot: "parts.views".into(), needs: "a_view_or_a_list_not_both" }), };if !named.insert(key) {returnErr(DefinitionError::Conflict { slot: "parts.views".into(), other: "the_same_view_named_twice" }); }if view.peek.is_some_and(|peek| peek == 0 || peek > MAX_PEEK) {returnErr(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.pubfn views_hold(&self, tables: &[TableDefinition]) -> Result<(), DefinitionError> {letSome(views) = self.parts.as_ref().and_then(|parts| parts.views.as_ref()) else { returnOk(()) };for view in views {ifletSome((tool, id)) = view.tool_view() {letSome(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() {returnErr(DefinitionError::Requires { slot: format!("parts.views.{tool}.{id}"), needs: "a_partitioned_view_over_this_table" }); } }ifletSome(list) = &view.list {letSome(table) = tables.iter().find(|table| &table.id == list) else { continue };if !links_to(table, &self.id) {returnErr(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`.pubfn 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.pubconst 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)]pubstructRecordView {/// `overview`, `<tool>.<view id>`, or `list:<table>` (`list:<table>:<column>`/// where the same table contributes by several columns).pub id: String,pub label: String, #[serde(skip_serializing_if = "Option::is_none")]pub list: Option<super::contributors::Contributor>,/// 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,}implRecordView {/// The table this view's slips are records of; none for Overview.pubfn table<'a>(&'a self, tables: &'a [TableDefinition]) -> Option<&'a str> {ifletSome(list) = &self.list {returnSome(&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.pubfn record_views(tables: &[TableDefinition], host: &str) -> Vec<RecordView> {letSome(home) = tables.iter().find(|table| table.id == host) else { returnVec::new() };letmut found: Vec<RecordView> = Vec::new();letmut narrowed: Vec<(String, String)> = Vec::new();for table in tables {letSome(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; }iflet (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());letmut 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();letmut 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, });ifletSome(at) = at {letmut view = found.remove(at); view.peek = reference.peek(); ordered.push(view); } } ordered.extend(found); ordered}