Cotton code
312 lines · 12.5 KB · RustRaw
//! A database's tools and its Home — what the person keeps, never an order.//!//! Two things, and no third (owner's ruling, 12 Oct 2026): a tool is IN a//! database or it is not, and Home is a set of VIEW ids — a tool's list//! (`tool/<key>`), a shipped view (`ready/everything`) or a group//! (`<table>/<groupId>`). Nothing is//! "put away": a tile is on Home or it is not, and a tile with nothing to show//! is drawn faint in its place ([`mark_empty`]).//!//! The fan's order is ALPHABETICAL in every database, always (owner, 17 Oct//! 2026: "that is how he finds tools"). There is no kept or per-database card//! order: the stored arrays are read as membership and every answer here is//! sorted by name ([`crate::js_text::sort_by_name`]), whatever order the row//! holds them in. Me is not special; it sits under M.//!//! The projects band keeps the merge rules ([`merge_order`])://!//!   1. nothing stored ⇒ the default order, verbatim;//!   2. a stored entry counts only if the default set still holds it, and only//!      the first time it appears;//!   3. everything the default set holds that the stored list did not name is//!      APPENDED, in default order;//!   4. the answer is a permutation of the default set.//!//! No clock, no database, no `Ctx` — the whole module is a function of its//! arguments, which is what lets `home_arrangement_tests.rs` state the rules//! as arithmetic. The file-side reads are `cotton_tools::home_arrangement`.use std::collections::BTreeSet;/// Everything: a shipped view over every table, not a tool (owner's ruling,/// 12 Oct 2026). A tile on the personal database's Home by default, removable/// like any tile; it has something to show when any tool of the database does.pub const EVERYTHING_VIEW: &str = "ready/everything";const TOOL_VIEW: &str = "tool/";/// A tool's own view — its list — by the id Home and the Shows list name it.pub fn tool_view(key: &str) -> String {    format!("{TOOL_VIEW}{key}")}/// The tool whose list this view is, or `None` for any other view.pub fn view_tool(view: &str) -> Option<&str> {    view.strip_prefix(TOOL_VIEW).filter(|key| !key.is_empty())}/// One `cotton_home_arrangement` row, as the engine reads it.////// Three lists and nothing else. `tools` is the database's tools as they were/// when the row was last written — the set Home has been shown, which is how a/// tool that joined since (a new built-in in the personal database) is told/// from a tile the person took off ([`home_views`]). `view_ids` is Home./// `tools` and `view_ids` are SETS: their order is never read (the fan is/// alphabetical, always).#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct HomeArrangement {    /// Active project slugs, in the person's order (the projects band).    pub project_slugs: Vec<String>,    /// The database's tool keys — membership only.    pub tools: Vec<String>,    /// Home's tiles: view ids — membership only.    pub view_ids: Vec<String>,}/// THE merge — rules 1 to 4 above, over any default set. The projects band's/// alone: the fan has no stored order to merge.////// `default_order` is what the screen would draw with no record at all;/// `manual` is what the person stored. The answer is a permutation of/// `default_order`, whatever `manual` says.pub fn merge_order(default_order: &[&str], manual: &[String]) -> Vec<String> {    let mut kept: Vec<String> = Vec::with_capacity(default_order.len());    if !manual.is_empty() {        let known: BTreeSet<&str> = default_order.iter().copied().collect();        for entry in manual {            if known.contains(entry.as_str()) && !kept.iter().any(|already| already == entry) {                kept.push(entry.clone());            }        }    }    for entry in default_order {        if !kept.iter().any(|already| already == entry) {            kept.push((*entry).to_string());        }    }    kept}/// A database's tools: exactly the tools it holds by a row of its own/// (`cotton_tool_definitions`), sorted by their names. No tool is built in/// (72nd amendment, 21 Oct 2026: tools are records only).pub fn installed_tools(installed: &[String], name: impl Fn(&str) -> String) -> Vec<String> {    let mut tools = installed.to_vec();    crate::js_text::sort_by_name(&mut tools, |key| name(key), String::clone);    tools}/// Home's tiles, alphabetical by `name` (the name its tile is drawn with).////// No row: every tool's list and Everything in the personal database. A row:/// its views, each once, while it still names/// something here — a tool's list while the tool is one of `tools`,/// Everything, or a view `admits` knows (a group that still exists) — then the/// list of every tool the row was never shown (`tools` it does not name), so a/// tool that joins the database arrives on Home and a tile the person took off/// stays off.////// `arriving` are the views that come to Home on their own — a project's/// sections that hold something (`project_page::section_view`). They arrive/// after the tools' lists, once: the row's `tools` is the set Home has been/// shown, so it names each one it has shown, and one the person took off stays/// off.pub fn home_views(    manual: Option<&HomeArrangement>,    tools: &[String],    personal: bool,    arriving: &[String],    admits: impl FnMut(&str) -> bool,    name: impl Fn(&str) -> String,) -> Vec<String> {    let mut out = home_members(manual, tools, personal, arriving, admits);    crate::js_text::sort_by_name(&mut out, |view| name(view), String::clone);    out}/// Home's membership, in no order that means anything ([`home_views`] sorts it).fn home_members(    manual: Option<&HomeArrangement>,    tools: &[String],    personal: bool,    arriving: &[String],    mut admits: impl FnMut(&str) -> bool,) -> Vec<String> {    let mut out: Vec<String> = Vec::new();    let Some(row) = manual else {        out.extend(tools.iter().map(|key| tool_view(key)));        out.extend(arriving.iter().filter(|view| admits(view)).cloned());        if personal {            out.push(EVERYTHING_VIEW.to_string());        }        return out;    };    for view in &row.view_ids {        let here = match view_tool(view) {            Some(key) => tools.iter().any(|tool| tool == key),            None => view == EVERYTHING_VIEW || admits(view),        };        if here && !out.contains(view) {            out.push(view.clone());        }    }    for key in tools.iter().filter(|key| !row.tools.contains(key)) {        let view = tool_view(key);        if !out.contains(&view) {            out.push(view);        }    }    for view in arriving.iter().filter(|view| !row.tools.contains(view)) {        if !out.contains(view) && admits(view) {            out.push(view.clone());        }    }    out}/// One tile on Home: the view it draws and whether it has nothing to show.#[derive(Debug, Clone, PartialEq, Eq)]pub struct HomeTile {    pub id: String,    /// Nothing to show yet: drawn faint, in its alphabetical place.    pub empty: bool,}/// The faint rule (owner's ruling, 12 Oct 2026), without the move (owner,/// 17 Oct 2026: alphabetical always): each tile says whether it has nothing/// to show, and stays where the alphabet put it.pub fn mark_empty(views: Vec<String>, mut has_something: impl FnMut(&str) -> bool) -> Vec<HomeTile> {    views        .into_iter()        .map(|id| {            let empty = !has_something(&id);            HomeTile { id, empty }        })        .collect()}/// What [`arrange_projects`] needs of a project row: the slug the arrangement/// names it by.////// The SLUG rather than the id, deliberately — it is what the cap colours/// and the deep links already carry, so an arrangement written on the phone/// reads the same on the Mac.pub trait ArrangedProject {    fn slug(&self) -> &str;}impl<T: ArrangedProject + ?Sized> ArrangedProject for &T {    fn slug(&self) -> &str {        (**self).slug()    }}/// The projects band, arranged — the same rules, over whatever order the/// caller already put the rows in.////// Totality is the point: every row handed in comes back out exactly once,/// however stale the stored list is. A slug the stored list names twice, or one/// two rows somehow share, cannot drop a row — anything the walk did not seat/// is appended in the order it arrived.pub fn arrange_projects<T: ArrangedProject>(    in_default_order: Vec<T>,    manual: Option<&HomeArrangement>,) -> Vec<T> {    let Some(manual) = manual else {        return in_default_order;    };    if manual.project_slugs.is_empty() {        return in_default_order;    }    let mut seats: Vec<(String, T)> = in_default_order        .into_iter()        .map(|project| (project.slug().to_string(), project))        .collect();    let order = {        let defaults: Vec<&str> = seats.iter().map(|(slug, _)| slug.as_str()).collect();        merge_order(&defaults, &manual.project_slugs)    };    let mut out: Vec<T> = Vec::with_capacity(seats.len());    for slug in &order {        if let Some(at) = seats.iter().position(|(seated, _)| seated == slug) {            out.push(seats.remove(at).1);        }    }    out.extend(seats.into_iter().map(|(_, project)| project));    out}/// The tool a store table's rows belong to, by the name on its tile/// ("Email" for `cotton_emails`, `cotton_email_threads` and their/// `cotton_email_participants`) — what a count of rows by table is said in/// to a person ("Email · 41,000 of 58,900" while a device catches up)./// `None` for a table no tool's tile stands for: plumbing, and anything this/// build does not know.////// A tool's tables are the ones its home names, then every table of its/// engine (where two tools share an/// engine, each home's own table is its own and the rest go to the tool/// named for the engine, else to the first)./// A table with no definition of its own — a child kept for a tool, like a/// thread's participants — goes with the tool whose tables share its first/// word (`cotton_email_…`).pub fn tool_of_store_table(table: &str) -> Option<&'static str> {    static TOOLS: std::sync::OnceLock<Vec<(&'static str, String)>> = std::sync::OnceLock::new();    let tools = TOOLS.get_or_init(|| {        use crate::definitions::{builtin_store_table, builtin_table_definitions};        let shipped = builtin_table_definitions();        let mut found: Vec<(&'static str, String)> = Vec::new();        let name = |found: &mut Vec<(&'static str, String)>, id: &str, tool: &str| {            if let Some(table) = builtin_store_table(id) {                if !found.iter().any(|(known, _)| *known == table) {                    found.push((table, tool.to_string()));                }            }        };        // Every home's own table first, so no other tool's sweep takes it.        for home in shipped.iter().filter(|definition| definition.tool.is_some()) {            if let Some(tool) = &home.tool {                name(&mut found, &home.id, &tool.name);            }        }        // Where two tools share an engine, the one named for it sweeps        // first: `media` is Photos, and takes `photo` before Videos could.        let named_for_engine =            |home: &&crate::definitions::TableDefinition| home.engine.as_deref() == Some(home.id.as_str());        let homes = shipped            .iter()            .filter(named_for_engine)            .chain(shipped.iter().filter(|home| !named_for_engine(home)));        for home in homes {            let Some(tool) = &home.tool else { continue };            for id in &tool.tables {                name(&mut found, id, &tool.name);            }            for definition in shipped {                if definition.engine.is_some() && definition.engine == home.engine {                    name(&mut found, &definition.id, &tool.name);                }            }        }        found    });    if let Some((_, tool)) = tools.iter().find(|(known, _)| *known == table) {        return Some(tool.as_str());    }    // A child table: the tool whose tables share its first word.    let word = table.strip_prefix("cotton_")?.split('_').next().filter(|word| word.len() >= 3)?;    tools        .iter()        .find(|(known, _)| {            known.strip_prefix("cotton_").is_some_and(|rest| {                rest.strip_prefix(word).is_some_and(|after| {                    after.is_empty() || after.starts_with('_') || after == "s" || after.starts_with("s_")                })            })        })        .map(|(_, tool)| tool.as_str())}#[cfg(test)]#[path = "home_arrangement_tests.rs"]mod tests;