//! What an owner may change on a built-in's row beyond how its records look: //! his own COLUMNS, its ACTS and its STACKS (architect STEP 2a, 12 Oct 2026). //! //! - **Columns.** On a shipped table a person may ADD columns of his own and //! change shipped columns' look. Made tables accept the same look edits, //! while their existing column keys and storage metadata stay fixed. //! A shipped column is never removed or //! retyped — its engine reads it — so every one of them is fixed: the row //! carries each exactly as the file ships it, the look his. An added //! column's key is in the owner's namespace ([`OWN_COLUMN_PREFIX`]), which //! no shipped file may use (a guard holds it), so it can never collide with //! a shipped or a future shipped key; its values are kept per database in //! `cotton_records` under [`own_values_table`] (cotton-tools //! `tables::own_values`). Added columns ride every upgrade; a hidden flag //! rides while its column still ships. //! - **Acts** are the lines of the list's menu the table offers — `links` //! (other lists, People's "Import contacts") and `menu` (app screens). An //! owner shows, hides and reorders them, and nothing else: every entry he //! keeps is one the shipped file offers, taken from the file as it stands, //! so an edit can never name a list, a filter or a screen the build does //! not (a link's `where` widens what a read selects). A page's acts are its //! `parts.acts`, already a look key, and name only the table's commands. //! - **Stacks** are `groups`: the face a group's pile above the list is drawn //! with, or none at all. Where the groups are kept is the //! shipped file's (`kept_in`: only the photo list's albums), never the //! row's — a stack cannot point at another table's records. //! //! One function says what a key's value is ON a shipped definition //! ([`on_shipped`]), in two ways: a WRITE is refused for anything the file //! does not offer, and an UPGRADE drops what the new file no longer offers — //! an act the new file does not have is dropped from the person's list, and a //! list none of whose acts is left falls back to the shipped one, so a stale //! edit is never kept broken. A stack names no column; the list's own //! grouping (`group`) does, and an edit naming a column the new file no //! longer has is dropped by validation in `with_edits`, as every look key is. use serde_json::Value; use super::automations::said; use super::{is_valid_id, refusal_words, Column, ColumnType, Groups, TableDefinition}; /// What every column a person adds to a shipped table is keyed under, and /// no shipped column ever is: `own_birth_city`. pub const OWN_COLUMN_PREFIX: &str = "own_"; /// What the `cotton_records` table id of an added column's values starts /// with — a code-owned id, like groups' `_group`, that no definition holds. pub const OWN_VALUES_TABLE_PREFIX: &str = "_own:"; /// The types an added column may be: values a record holds by itself. A /// link, a photo or a file names something that must exist, and is not one. pub const OWN_COLUMN_TYPES: &[ColumnType] = &[ ColumnType::AccountNumber, ColumnType::Text, ColumnType::Longtext, ColumnType::Date, ColumnType::Time, ColumnType::Number, ColumnType::Bytes, ColumnType::Amount, ColumnType::Choice, ColumnType::Bool, ColumnType::Url, ]; /// The keys an added column may say: its name, its type, a choice's choices /// (several or one), the word for nothing, and whether it is hidden. const OWN_COLUMN_KEYS: &[&str] = &["key", "name", "type", "choices", "multiple", "placeholder", "hidden"]; /// Appearance edits never change how a stored value is typed or written. pub const COLUMN_LOOK_KEYS: &[&str] = &["name", "readonly", "format", "units", "labels", "choice_names", "hidden", "placeholder"]; /// Whether `key` is a column a person added (his namespace). pub fn is_own_column(key: &str) -> bool { key.starts_with(OWN_COLUMN_PREFIX) } /// The key a tool's contributed column is kept under on the table it adds /// to: `own_birthdays__remind` — the owner's namespace, the tool's part of it. pub fn contributed_key(tool: &str, column: &str) -> String { format!("{OWN_COLUMN_PREFIX}{tool}__{column}") } /// A column `tool` contributes, as the table it adds to keeps it — at its /// contributed key, hidden in that table's own look — or why it cannot be: /// it holds values of its own, as any added column does. pub fn contributed_column(tool: &str, column: &Column) -> Result { if !is_valid_id(&column.key) || is_own_column(&column.key) || tool.contains("__") { return Err(said("a_contributed_column_is_keyed_in_plain", &[("key", &format!("{:?}", column.key)), ("prefix", &OWN_COLUMN_PREFIX)])); } let mut entry = serde_json::to_value(column).map_err(|error| error.to_string())?; entry["key"] = Value::from(contributed_key(tool, &column.key)); entry["hidden"] = Value::Bool(true); own_column(&entry) } /// The `cotton_records` table id the added columns' values of `table`'s /// records are kept under, one row per record at the record's own id. pub fn own_values_table(table: &str) -> String { format!("{OWN_VALUES_TABLE_PREFIX}{table}") } /// The keys of a definition that are its list's acts. pub const ACT_KEYS: &[&str] = &["links", "menu"]; /// The key of a definition that is its stacks. pub const STACKS_KEY: &str = "groups"; /// How [`on_shipped`] treats what the shipped file does not offer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Against { /// A person's write: refused, in words. Write, /// A revision bump (or a row read at this revision): dropped quietly. Upgrade, } /// `value`, a person's edit of `key`, as it stands on `shipped` — acts taken /// from the shipped file by identity in the person's order, a stack checked /// against the shipped file's `kept_in`; every other key unchanged. `Null` /// is the key removed (no acts, no stacks), except a shipped picture, which /// returns to the file's picture. pub fn on_shipped(shipped: &TableDefinition, key: &str, value: &Value, against: Against) -> Result { if key == "columns" { return columns_on_shipped(shipped, value, against); } if value.is_null() { // Clearing a shipped picture relinquishes the override; every other // nullable look key still means remove it. if key == "picture" && shipped.builtin { return serde_json::to_value(&shipped.picture).map_err(|error| error.to_string()); } return Ok(Value::Null); } match key { "links" | "menu" => acts_on_shipped(shipped, key, value, against), STACKS_KEY => stacks_on_shipped(shipped, value), _ => Ok(value.clone()), } } /// What makes an act the same act across files: a link's table, its route /// and its filter (its words may change); a menu line's route. fn act_identity(key: &str, entry: &Value) -> Value { match key { "links" => Value::Array(vec![ entry.get("table").cloned().unwrap_or(Value::Null), entry.get("path").cloned().unwrap_or(Value::Null), entry.get("where").cloned().unwrap_or(Value::Null), ]), _ => entry.get("path").cloned().unwrap_or(Value::Null), } } fn acts_on_shipped(shipped: &TableDefinition, key: &str, value: &Value, against: Against) -> Result { let Value::Array(wanted) = value else { return Err(said("is_a_list_of_the_acts_the_table_offers", &[("key", &key)])); }; let offered: Vec = match serde_json::to_value(shipped).ok().and_then(|all| all.get(key).cloned()) { Some(Value::Array(offered)) => offered, _ => Vec::new(), }; let mut kept: Vec = Vec::new(); for entry in wanted { let identity = act_identity(key, entry); let label = entry.get("label").and_then(Value::as_str).unwrap_or("an act"); let Some(found) = offered.iter().find(|offered| act_identity(key, offered) == identity) else { if against == Against::Write { return Err(said("is_not_an_act_the_table_offers", &[("key", &key), ("label", &format!("{label:?}")), ("table", &format!("{:?}", shipped.id))])); } continue; }; if kept.iter().any(|seen| act_identity(key, seen) == identity) { if against == Against::Write { return Err(said("act_is_named_twice", &[("key", &key), ("label", &format!("{label:?}"))])); } continue; } kept.push(found.clone()); } if against == Against::Upgrade && kept.is_empty() && !wanted.is_empty() { return Err(said("none_of_the_kept_is_offered_any_more", &[("key", &key)])); } Ok(Value::Array(kept)) } fn stacks_on_shipped(shipped: &TableDefinition, value: &Value) -> Result { let (groups, unnamed) = super::tolerant::reading(|| serde_json::from_value::(value.clone())); let groups = groups.map_err(|error| said("groups_do_not_read", &[("error", &error)]))?; if !unnamed.is_empty() { return Err(said("groups_name_which_this_build_does_not_draw", &[("names", &unnamed.join(", "))])); } let shipped_kept_in = shipped.groups.as_ref().and_then(|groups| groups.kept_in.as_ref()); if groups.kept_in.as_ref() != shipped_kept_in { return Err(said("where_groups_are_kept_is_its_own", &[("table", &format!("{:?}", shipped.id))])); } serde_json::to_value(groups).map_err(|error| error.to_string()) } /// The columns a person keeps on `shipped`: every shipped column as the file /// ships it — in its order, with the owner's look overlays — then the columns he /// added, in his order. A shipped column is named by its key (`{"key": /// "city", "hidden": true}`); name, format, units and display readonly are his. /// A WRITE is refused for a shipped column left out or changed in anything /// outside its look, a column outside his namespace the file /// does not ship, an added column that says more than [`OWN_COLUMN_KEYS`] or /// is of a type it cannot be, a key twice, or the title hidden; an UPGRADE /// keeps every added column that still reads and drops the look overlay of a /// column the new file no longer ships. fn columns_on_shipped(shipped: &TableDefinition, value: &Value, against: Against) -> Result { let Value::Array(wanted) = value else { return Err(refusal_words("columns_is_the_table_s_whole_list")); }; let mut overlays = std::collections::BTreeMap::new(); let mut own: Vec = Vec::new(); let mut seen: Vec = Vec::new(); for entry in wanted { let column_id = entry.get("key").and_then(Value::as_str).unwrap_or_default().to_string(); let refused = |reason: String| -> Result<(), String> { match against { Against::Write => Err(reason), Against::Upgrade => Ok(()), } }; if seen.contains(&column_id) { refused(said("column_is_named_twice", &[("key", &format!("{column_id:?}"))]))?; continue; } seen.push(column_id.clone()); if let Some(theirs) = shipped.columns.iter().find(|column| column.key == column_id) { // A partial look overlay keeps everything the engine shipped. // Storage and execution metadata outside the look remain fixed. let theirs_json = serde_json::to_value(theirs).map_err(|error| error.to_string())?; let hides = entry.get("hidden").and_then(Value::as_bool) == Some(true); let changed = entry.as_object().is_none_or(|said| { said.iter().any(|(name, value)| !COLUMN_LOOK_KEYS.contains(&name.as_str()) && theirs_json.get(name).unwrap_or(&Value::Null) != value) }); if changed { refused(said("is_a_column_never_removed_or_retyped", &[("key", &format!("{column_id:?}")), ("table", &format!("{:?}", shipped.id))]))?; continue; } if hides && column_id == shipped.title { refused(said("is_the_title_and_is_always_drawn", &[("key", &format!("{column_id:?}")), ("table", &format!("{:?}", shipped.plural))]))?; continue; } let mut overlay = theirs_json; for look in COLUMN_LOOK_KEYS { if let Some(value) = entry.get(*look) { if value.is_null() { overlay.as_object_mut().expect("a column is an object").remove(*look); } else { overlay[*look] = value.clone(); } } } // Decode here too: the upgrade path must never retain malformed // look data just because it came through an older stored row. if let Err(error) = serde_json::from_value::(overlay.clone()) { refused(said("column_does_not_read", &[("key", &format!("{column_id:?}")), ("error", &error)]))?; continue; } overlays.insert(column_id, overlay); continue; } if !shipped.builtin { refused(said("is_no_column_columns_cannot_be_added_here", &[("key", &format!("{column_id:?}")), ("table", &format!("{:?}", shipped.id))]))?; continue; } match own_column(entry) { Ok(column) => own.push(column), Err(reason) => refused(reason)?, } } if against == Against::Write { if let Some(gone) = shipped.columns.iter().find(|column| !seen.contains(&column.key)) { return Err(said("is_a_shipped_column_never_removed", &[("key", &format!("{:?}", gone.key)), ("table", &format!("{:?}", shipped.id))])); } } let mut kept: Vec = Vec::with_capacity(shipped.columns.len() + own.len()); for column in &shipped.columns { let column = overlays.remove(&column.key).unwrap_or(serde_json::to_value(column).map_err(|error| error.to_string())?); kept.push(column); } kept.extend(own); Ok(Value::Array(kept)) } /// One column a person added, as it is kept — or why it cannot be. fn own_column(entry: &Value) -> Result { let column_id = entry.get("key").and_then(Value::as_str).unwrap_or_default(); if !is_own_column(column_id) || !is_valid_id(column_id) { return Err(said("is_no_column_this_table_ships", &[("key", &format!("{column_id:?}")), ("prefix", &OWN_COLUMN_PREFIX)])); } if let Some(extra) = entry.as_object().and_then(|object| object.keys().find(|said| !OWN_COLUMN_KEYS.contains(&said.as_str()))) { return Err(said("an_added_column_says_its_name_type", &[("key", &format!("{column_id:?}")), ("extra", &format!("{extra:?}"))])); } let column: Column = serde_json::from_value(entry.clone()).map_err(|error| said("column_does_not_read", &[("key", &format!("{column_id:?}")), ("error", &error)]))?; if !OWN_COLUMN_TYPES.contains(&column.column_type) { return Err(said("an_added_column_holds_values_of_its", &[("key", &format!("{column_id:?}"))])); } let choices = column.choices.as_ref().is_some_and(|choices| !choices.is_empty()); if (column.column_type == ColumnType::Choice) != choices || (column.multiple.is_some() && column.column_type != ColumnType::Choice) { return Err(said("a_choice_column_names_its_choices", &[("key", &format!("{column_id:?}"))])); } serde_json::to_value(column).map_err(|error| error.to_string()) } #[cfg(test)] #[path = "owner_tests.rs"] mod tests;