Cotton code
584 lines · 34.0 KB · RustRaw
//! `shell.fan {chosen?, tool?, every?, today?, timezone?}` — everything the fan draws,//! and nothing about how (boundary review move 1, 5 Nov 2026: the core//! answers what to show, a platform shell only draws).//!//! The answer is the fan of the database shown, for the app this core was//! opened as (the manifest's `fan`, [`FanCards`])://!//! - `tiles`: the fan's cards in its order — every tool Home holds by name,//!   Home and Tools among them where the app keeps them, a Settings card//!   last where it names one, then the tools the object says hold no rows//!   (the home board's `tools` part, `empty`), Home last of all where the//!   app opens on a tool and keeps it. Each says what it is (`kind`: home,//!   tools, settings, tool, view), its name, its picture and paper, whether//!   its page is a list its views ring (`ringed`), whether it has no page//!   the fan draws (`poster`), the table its views list (`views_table`),//!   its views in the ring's order (the default first) and the one it//!   stands on (`current`, the `chosen` while it is still one), and the view//!   holding every record of its table (`whole`), where it has one.//! - `opens`: where the fan opens — a fan of one tool whose page its views//!   ring opens on that tool's views (Cotton Books), any other on its tools//!   at the app's named tool, else Home, else its first card.//! - `root`: the fan's first tier as the shell keeps it: its id, its cards//!   by id and the card raised.//! - `every: true` deals every tool of the database instead, in the person's//!   order and with none of the app's own cards, for the Tools board: a tile//!   Home holds none of says `hidden: true`.//!//! One call per fan state: the views of ONE tile are counted — `tool`, the//! tile the fan stands on (else the one it opens on) — with their heads and//! the tool's lists; every other ringed tile carries its views as declared,//! uncounted (`counted: false`), so a tier stands at once while its counts//! are asked. The Settings card's views are its rows, read only when it is//! the tile counted.use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::definitions::fan_tile::FanTile;use cotton_core::definitions::{ToolDefinition, ToolPicture, TableDefinition};use cotton_core::flavor::FanCards;use serde_json::{json, Map, Value};/// The Home card: the person, the fan's centre in Cotton.pub const HOME: &str = "home";/// The Tools card: every tool of the database, on two views.pub const TOOLS: &str = "tools";/// The Settings card: the settings rows, last on the dial where the app names it.pub const SETTINGS: &str = "settings";/// The settings rows' table, whose rows are the Settings card's views.const SETTINGS_TABLE: &str = "settings";/// The tools tier's id; a views tier is `views-<tool>`.pub const TOOLS_TIER: &str = "tools";pub fn call(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {    read_with(&handle.client(), handle.fan(), request, &|args| {        crate::methods::dispatch(handle, "records.list", &crate::phone::records::in_named_database(args.clone()))    })}#[cfg(test)]pub fn read(client: &ClientController, fan: &FanCards, request: &Value) -> Result<Value, MethodError> {    read_with(client, fan, request, &|args| crate::phone::records::call(client, "records.list", args))}/// One tile as the fan is dealt, before its views are read.struct Tile {    key: String,    name: String,    kind: &'static str,    tool: Option<String>,    view: Option<Value>,    picture: Option<Value>,    stock: Option<Value>,    /// The tool's fan tile (`FanTile`), which its views and every tier under it are drawn as.    tile: Option<FanTile>,    ringed: bool,    poster: bool,    views_table: Option<String>,    views: Vec<Value>,    /// The tables the tool owns, where it names a tile: a whole's parts under    /// it (a series' seasons, a season's episodes) are drawn on its tile too;    /// a table other tools list as well (`vault_key`) is not.    owns: Vec<String>,    /// `every` asked: Home holds no tile of this tool.    hidden: bool,}pub(super) fn read_with(    client: &ClientController,    fan: &FanCards,    request: &Value,    native: &dyn Fn(&Value) -> Result<Value, MethodError>,) -> Result<Value, MethodError> {    let asked_chosen = match request.get("chosen") {        None | Some(Value::Null) => Map::new(),        Some(Value::Object(chosen)) if chosen.values().all(Value::is_string) => chosen.clone(),        Some(_) => return Err(MethodError::new("bad_request", "chosen is {tool: view}, each a view's id")),    };    // RULE (owner on Cotton Cinemas 1.0 (4), 7 Nov 2026): the view a person    // last stood on is kept beside the copy, as shell.player keeps its song, so    // a relaunch opens there; the shell's choices since stand over the kept.    let kept = Kept::read(client);    let mut chosen = kept.chosen.clone();    chosen.extend(asked_chosen.clone());    let asked = match request.get("tool") {        None | Some(Value::Null) => None,        Some(Value::String(tool)) => Some(tool.clone()),        Some(_) => return Err(MethodError::new("bad_request", "tool is the id of the fan's tile it stands on")),    };    let personal = crate::phone::reads::personal_database(client).map_err(|reason| MethodError::new("unreadable", reason))?;    let every = request["every"] == true;    let mut tiles = deal(client, fan, personal.as_deref(), every)?;    // Where it opens, and so which tile is counted when none is asked.    let opens_at = fan.opens.as_deref().and_then(|tool| tiles.iter().position(|tile| tile.key == tool))        .or_else(|| tiles.iter().position(|tile| tile.key == HOME))        .unwrap_or(0);    let counted = asked.or_else(|| tiles.get(opens_at).map(|tile| tile.key.clone()));    if let Some(key) = &counted {        if let Some(tile) = tiles.iter_mut().find(|tile| &tile.key == key && tile.ringed) {            tile.views = match tile.kind {                "settings" => settings_views(native)?,                "tool" => {                    let mut read = json!({"tool": key});                    for field in ["today", "timezone"] {                        if let Some(value) = request.get(field).filter(|value| !value.is_null()) { read[field] = value.clone(); }                    }                    let answer = crate::phone::tool_views::read_with(client, &read, native)?;                    answer["views"].as_array().cloned().unwrap_or_default().into_iter().map(named_default).collect()                }                _ => std::mem::take(&mut tile.views),            };        }    }    // RULE (owner on Cotton Story build 4, 18 Nov 2026): a kit whose fan is its    // records holds Account, one card a screenplay and the card that starts a    // new one, none of its tool's views; it stands on the tile just picked,    // else on the current screenplay.    // The kit this build ships says so: the copy saved beside the database may    // be an older build's.    let fan_of = crate::phone::tool_acts::app_kit(client)?.and_then(|kit| cotton_core::kit::AppKit::named(&kit.id)).and_then(|kit| kit.fan_of);    if let Some(tile) = tiles.iter_mut().find(|tile| !every && fan_of.as_deref() == Some(crate::phone::story::STORY) && tile.kind == "tool") {        let (cards, standing) = crate::phone::story::fan_cards(client)?;        let picked = asked_chosen.get(&tile.key).and_then(Value::as_str).filter(|id| cards.iter().any(|card| card["id"].as_str() == Some(*id))).map(str::to_string);        tile.ringed = true;        tile.views = cards;        match picked.or(standing) {            Some(card) => { chosen.insert(tile.key.clone(), json!(card)); }            None => { chosen.remove(&tile.key); }        }    }    // RULE (owner, Cotton Notes as a writing app, 19 Nov 2026): the notebook's    // fan is Notes, Untagged, Archive, Bin and a card per tag, most used first,    // a nested tag folding under its parent (`phone::notes::fan`).    if let Some(tile) = tiles.iter_mut().find(|tile| !every && fan_of.as_deref() == Some(crate::phone::notes::NOTE) && tile.kind == "tool") {        let (mut cards, standing) = crate::phone::notes::fan_cards(client)?;        // A list the person made by hand (a group not named `#tag`, which is a        // tag card above) stays on the fan after Notes' cards and opens as its        // deck, as in every app with lists (owner, 6 Nov 2026).        cards.extend(std::mem::take(&mut tile.views).into_iter().filter(|view| {            view["id"].as_str().is_some_and(|id| id.starts_with("group:")) && !view["label"].as_str().is_some_and(|name| name.starts_with('#'))        }));        let picked = asked_chosen.get(&tile.key).and_then(Value::as_str).filter(|id| cards.iter().any(|card| card["id"].as_str() == Some(*id))).map(str::to_string);        tile.ringed = true;        tile.views = cards;        match picked.or_else(|| kept.chosen.get(&tile.key).and_then(Value::as_str).map(str::to_string).filter(|id| tile.views.iter().any(|card| card["id"].as_str() == Some(id.as_str())))).or(standing) {            Some(card) => { chosen.insert(tile.key.clone(), json!(card)); }            None => { chosen.remove(&tile.key); }        }    }    // A view the counted tool no longer holds (a list since deleted) leaves    // the kept file: it falls back to the tool's first view, here and at launch.    if let Some(tile) = counted.as_deref().and_then(|key| tiles.iter().find(|tile| tile.key == key && tile.ringed)) {        let held = chosen.get(&tile.key).and_then(Value::as_str)            .is_some_and(|view| tile.views.iter().any(|known| known["id"].as_str() == Some(view)));        if !held { chosen.remove(&tile.key); }    }    if chosen != kept.chosen { Kept { chosen: chosen.clone() }.write(client)?; }    let mut answered: Vec<Value> = tiles.iter().map(|tile| {        let mut views = ringed_order(&tile.views);        if let Some(look) = &tile.tile {            for view in &mut views {                if let Some(photo) = pictogram(look, view) { view["pictogram"] = json!(photo); }            }        }        let current = current(&views, chosen.get(&tile.key).and_then(Value::as_str));        let mut answer = json!({            "key": tile.key, "name": tile.name, "kind": tile.kind, "tool": tile.tool, "view": tile.view,            "picture": tile.picture, "stock": tile.stock, "ringed": tile.ringed, "poster": tile.poster,            "views_table": tile.views_table, "counted": counted.as_deref() == Some(tile.key.as_str()) && tile.ringed,            "current": current, "views": views,        });        // The view holding every record of its table, where it has one: what a        // shell turns to when many records land at once.        if let Some(whole) = whole_of(&views, tile.views_table.as_deref()) { answer["whole"] = whole; }        // Only a tool naming a tile says one: every other tile's answer stands as it was.        if let Some(look) = &tile.tile {            answer["tile"] = look.look();            answer["tile"]["tables"] = json!(tile.owns);        }        if tile.hidden { answer["hidden"] = json!(true); }        answer    }).collect();    // RULE (owner on Cotton Books 1.0.0 (1), 5 Nov 2026): a fan of one tool    // whose page its views ring opens on that tool's views — a tools tier of    // one tile is a step that buys nothing; any other opens on its tools.    let stands_alone = answered.len() == 1 && answered[0]["ringed"] == true && answered[0]["views"].as_array().is_some_and(|views| !views.is_empty());    // RULE (owner, 11 Nov 2026): the fan opens on its first card in the    // centre, and the cards a person reaches for less often stand to its    // LEFT, as the app's kit names them (`AppKit::aside`): Account first,    // this phone's sign-in and sync, its tile saying how they stand at a    // glance. Dealt before the first view and never raised, so the fan    // still opens where it did; it reads no table, so no deck is asked.    // An app of several tools opens on its tools; the card stands left of    // the first view of its first tool, the one the app opens on.    let home = if every { None } else { super::shell_account::home(client) };    if let Some(tile) = home.and_then(|home| answered.iter_mut().find(|tile| tile["key"] == json!(home) && tile["ringed"] == true)) {        let card = json!({            "id": cotton_core::kit::ACCOUNT_CARD, "label": super::shell_account::name(), "default": false, "count": null,            "read": {"table": ""}, "aside": true, "line": super::shell_account::tile_line(client),        });        if let Some(views) = tile["views"].as_array_mut().filter(|views| !views.is_empty()) {            views.insert(0, card);            // RULE (Send, 13 Nov 2026): an app with no chat tool shows what was sent to its person on a            // card of its own beside Account, only while this phone holds something sent.            if let Some(sent) = crate::phone::cotton_send::sent_card(client) {                views.insert(1, sent);            }        }    }    let sole = stands_alone.then(|| &answered[0]);    let (opens, root) = match sole {        Some(tile) => {            let ids: Vec<Value> = tile["views"].as_array().into_iter().flatten().map(|view| view["id"].clone()).collect();            (json!({"tier": "views", "tool": tile["key"], "view": tile["current"]}),             json!({"id": format!("views-{}", tile["key"].as_str().unwrap_or_default()), "cards": ids, "raised": tile["current"]}))        }        None => {            let at = answered.get(opens_at).map(|tile| tile["key"].clone()).unwrap_or(Value::Null);            let ids: Vec<Value> = answered.iter().map(|tile| tile["key"].clone()).collect();            (json!({"tier": "tools", "tool": at}), json!({"id": TOOLS_TIER, "cards": ids, "raised": at}))        }    };    let mut answer = json!({"opens": opens, "tiles": answered, "root": root});    // RULE (owner, 14 Nov 2026): an app whose flavour says its face is one    // stream of chats (`fan.stream`, Cotton Messages) draws no fan and no    // hub: the shell pages the conversations of the tool it opens on    // (`shell.stream`), its table said here. Every other app says nothing.    if fan.stream {        let tool = answer["opens"]["tool"].as_str().unwrap_or_default().to_string();        let table = answer["tiles"].as_array().into_iter().flatten().find(|tile| tile["key"] == json!(tool))            .and_then(|tile| tile["views"].as_array()).into_iter().flatten()            .find(|view| view["default"] == true).and_then(|view| view["read"]["table"].as_str())            .filter(|table| !table.is_empty()).map(str::to_string);        if let Some(table) = table { answer["stream"] = json!({"tool": tool, "table": table}); }    }    Ok(answer)}/// The file the views last stood on are kept in, in this client's folder.pub const KEPT_FILE: &str = "fan.json";/// The view each tool last stood on, of the database shown (the household's/// own under ""), kept beside the copy across a relaunch.#[derive(Default)]struct Kept { chosen: Map<String, Value> }/// The view each tool last stood on, as kept beside the copy.pub(super) fn kept_chosen(client: &ClientController) -> Map<String, Value> {    Kept::read(client).chosen}impl Kept {    fn shown() -> String { crate::shell::client::named_database().unwrap_or_default() }    fn read(client: &ClientController) -> Kept {        let path = client.layout().client_dir().join(KEPT_FILE);        let file: Map<String, Value> = std::fs::read(path).ok()            .and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default();        let chosen = match file.get(&Self::shown()) {            Some(Value::Object(chosen)) => chosen.iter().filter(|(_, view)| view.is_string()).map(|(tool, view)| (tool.clone(), view.clone())).collect(),            _ => Map::new(),        };        Kept { chosen }    }    /// One read-and-write at a time, replaced whole ([`cotton_client::whole_file`]): two fans asked at once (the    /// shell's refresh and its home after a sign-out, launch-story walk, 22 Nov 2026) both wrote `fan.json.new` and    /// renamed it; the second rename found the file gone and the person read "That didn't work. Try again.".    fn write(&self, client: &ClientController) -> Result<(), MethodError> {        static WRITING: std::sync::Mutex<()> = std::sync::Mutex::new(());        let _one = WRITING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);        let dir = client.layout().client_dir();        let mut file: Map<String, Value> = std::fs::read(dir.join(KEPT_FILE)).ok()            .and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default();        file.insert(Self::shown(), Value::Object(self.chosen.clone()));        let bytes = serde_json::to_vec(&file).map_err(|why| MethodError::new("unwritable", why.to_string()))?;        // not a copy: the fan's kept list, a file of its own.        cotton_client::whole_file::replace(&dir.join(KEPT_FILE), &bytes)            .map_err(|why| MethodError::new("unwritable", format!("the view stood on could not be kept: {why}")))    }}/// The fan's tiles in its order, each with its views as declared.fn deal(client: &ClientController, fan: &FanCards, personal: Option<&str>, every: bool) -> Result<Vec<Tile>, MethodError> {    let mut held: Vec<Tile> = Vec::new();    let mut empty: Vec<String> = Vec::new();    let kit = crate::phone::tool_acts::app_kit(client)?;    client.read_rows("shell.fan", &mut |ctx| {        let db = ctx.read.driver();        let workspace = ctx.workspace_id;        let mut tables = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?.definitions;        let mut tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|e| e.to_string())?.definitions;        // The tools the app's kit folds are drawn as its one tool's views.        if let Some(kit) = &kit { kit.fold(&mut tables, &mut tools); }        let lines = cotton_tools::presentation::line_rows(db, workspace);        let said = |set: &str, line: &str| cotton_core::rules::shell_lines::resolve(set, line, &lines, &[])            .ok_or_else(|| format!("the {set} set says no line {line}"));        let stored = cotton_tools::home_arrangement::stored(db, workspace)?;        let home = cotton_tools::home_arrangement::home(db, workspace, stored.as_ref(), personal == Some(workspace))?;        // The tools the object says hold no rows yet, in the kit's order: the home board's `tools` part.        empty = cotton_tools::presentation::board(db, workspace, HOME)?            .and_then(|board| board.definition["parts"].as_array().cloned())            .into_iter().flatten()            .find(|part| part["kind"] == "tools")            .and_then(|part| part["empty"].as_array().cloned())            .into_iter().flatten()            .filter_map(|key| key.as_str().map(str::to_string))            .collect();        // Every tool Home holds a tile of, as the tool's own tile (BoardPage).        let worn: Vec<&ToolDefinition> = tools.iter().filter(|tool| board_home(tool, &tables).is_some()).collect();        let tool_tile = |tool: &ToolDefinition| -> Result<Tile, String> {            let table = board_home(tool, &tables).expect("a laid tool has a home table");            let picture = owners_picture(table).or_else(|| tool.picture.as_ref().and_then(picture)).or_else(|| table.picture.as_ref().and_then(picture));            let declared = declared_views(&tool.id, &tables, &tools);            let route = declared_route(tool, &tables, &tools);            let direct = direct_table(tool, &tables, &tools);            let ringed = route.is_some() || direct.is_some();            Ok(Tile {                key: tool.id.clone(), name: tool.name.clone(), kind: "tool", tool: Some(tool.id.clone()), view: None,                picture, stock: tool.card_stock.as_ref().map(|stock| serde_json::to_value(stock).unwrap_or(Value::Null)),                tile: tool.fan_tile.clone(),                ringed,                poster: route.is_some_and(|route| !draws_in_place(route)),                views_table: if route.is_none() && ringed { direct.map(|table| table.id.clone()) } else { None },                views: if ringed {                    declared.iter().filter(|view| view.partition.is_none())                        .filter(|view| kit.as_ref().is_none_or(|kit| kit.deals_view(view.read.get("table").and_then(Value::as_str))))                        .map(|view| declared_view(view, &tool.name)).collect()                } else { Vec::new() },                owns: if tool.fan_tile.is_some() {                    tables.iter()                        .filter(|table| crate::phone::tool_views::owns(&tool.id, table, &tools))                        // A table several tools list (the vault's device keys) is none of theirs to draw.                        .filter(|table| tools.iter().filter(|other| other.tables.contains(&table.id)).count() <= 1)                        .map(|table| table.id.clone()).collect()                } else { Vec::new() },                hidden: false,            })        };        // The Tools board's `tools` part: every tool of the database in the        // person's order, each saying whether Home holds it.        if every {            let on_home: std::collections::HashSet<String> = home.tiles.iter().flat_map(|tile| {                let view = home.view(&tile.id).and_then(|view| view.tool.clone());                cotton_core::rules::home_arrangement::view_tool(&tile.id).map(str::to_string).into_iter().chain(view)            }).collect();            for key in &home.tools {                if let Some(tool) = worn.iter().find(|tool| &tool.id == key) {                    let mut tile = tool_tile(tool)?;                    tile.hidden = !on_home.contains(key);                    held.push(tile);                }            }            return Ok(Value::Null);        }        let mut dealt: Vec<Tile> = Vec::new();        for tile in &home.tiles {            let view = home.view(&tile.id);            let wears = if tile.id == cotton_core::rules::home_arrangement::EVERYTHING_VIEW { Some(EVERYTHING.to_string()) } else { view.and_then(|view| view.tool.clone()) };            let Some(wears) = wears else { continue };            let key = cotton_core::rules::home_arrangement::view_tool(&tile.id).map(str::to_string)                .unwrap_or_else(|| if tile.id == cotton_core::rules::home_arrangement::EVERYTHING_VIEW { EVERYTHING.to_string() } else { tile.id.clone() });            let named = view.and_then(|view| view.name.clone());            let shown = json!({"id": tile.id, "name": named, "opens": view.and_then(|view| view.opens.clone()), "table": view.and_then(|view| view.table.clone())});            match worn.iter().find(|tool| tool.id == wears) {                Some(tool) if key == tool.id => dealt.push(tool_tile(tool)?),                Some(tool) => {                    let own = tool_tile(tool)?;                    dealt.push(Tile { key, name: named.unwrap_or_else(|| tool.name.clone()), kind: "view", tool: Some(tool.id.clone()), view: Some(shown),                        picture: own.picture, stock: own.stock, tile: None, ringed: false, poster: false, views_table: None, views: Vec::new(), owns: Vec::new(), hidden: false });                }                // A project's section wears a shipped tool's picture, a tool                // this database need not hold.                None if cotton_core::rules::project_page::view_section(&tile.id).is_some() => {                    dealt.push(Tile { key, name: named.unwrap_or_else(|| wears.clone()), kind: "view", tool: Some(wears.clone()), view: Some(shown),                        picture: None, stock: None, tile: None, ringed: false, poster: false, views_table: None, views: Vec::new(), owns: Vec::new(), hidden: false });                }                None => {}            }        }        dealt.retain(|tile| tile.key != HOME && tile.key != TOOLS && tile.key != SETTINGS);        if fan.home {            dealt.push(Tile { key: HOME.into(), name: said("board", "dial.home")?, kind: "home", tool: None, view: None, picture: None, stock: None, tile: None,                ringed: false, poster: false, views_table: None, views: Vec::new(), owns: Vec::new(), hidden: false });        }        if fan.tools {            let views = vec![                json!({"id": "shown", "label": said("board", "tools.shown")?, "default": true, "count": null, "read": {"table": ""}}),                json!({"id": "hidden", "label": said("board", "tools.hidden")?, "default": false, "count": null, "read": {"table": ""}}),            ];            dealt.push(Tile { key: TOOLS.into(), name: said("board", "dial.tools")?, kind: "tools", tool: None, view: None, picture: None, stock: None, tile: None,                ringed: true, poster: false, views_table: None, views, owns: Vec::new(), hidden: false });        }        // RULE (owner, 17 Oct 2026): the fan is alphabetical in every database, always.        cotton_core::js_text::sort_by_name(&mut dealt, |tile| tile.name.clone(), |_| String::new());        let settings = fan.settings.then(|| -> Result<Tile, String> {            Ok(Tile { key: SETTINGS.into(), name: said("board", "dial.settings")?, kind: "settings", tool: None, view: None, picture: None, stock: None, tile: None,                ringed: true, poster: false, views_table: None, views: Vec::new(), owns: Vec::new(), hidden: false })        }).transpose()?;        held = order(dealt, fan, &empty, settings);        Ok(Value::Null)    }).map_err(|reason| MethodError::new("unreadable", reason))?;    Ok(held)}/// Everything's key: a shipped view over every table, drawn under a tool so keyed.const EVERYTHING: &str = "everything";/// RULE: the flavour's `fan` says which of Cotton's own cards the dial holds — absent, Home and Tools; Rigby holds neither and ends in a Settings card, last, in place of Tools (owner and architect, 22 Oct 2026); Cotton keeps both and ends in the same Settings card (the owner, 23 Oct 2026)./// RULE: a tool whose tables hold no rows sits after Settings, in the order the object names them (`empty`, the kit's); a tool with rows keeps its place (owner, 26 Oct 2026)./// RULE: a flavour that opens on a tool and keeps Home deals Home — the sync card — last of all (Cotton Music, 4 Nov 2026).fn order(dealt: Vec<Tile>, fan: &FanCards, empty: &[String], settings: Option<Tile>) -> Vec<Tile> {    let (mut resting, mut cards): (Vec<Tile>, Vec<Tile>) = dealt.into_iter().partition(|tile| empty.contains(&tile.key));    let home_last = fan.home && fan.opens.is_some();    let home = home_last.then(|| cards.iter().position(|tile| tile.key == HOME)).flatten().map(|at| cards.remove(at));    cards.extend(settings);    for key in empty {        if let Some(at) = resting.iter().position(|tile| &tile.key == key) { cards.push(resting.remove(at)); }    }    cards.extend(home);    cards}/// The table a tool's tile and route are drawn from: its first table, else —/// a tool of views alone, which owns no table (Birthdays over People's/// person) — the table its default view reads.fn board_home<'a>(tool: &ToolDefinition, tables: &'a [TableDefinition]) -> Option<&'a TableDefinition> {    if let Some(first) = tool.tables.first().and_then(|first| tables.iter().find(|table| &table.id == first)) {        return Some(first);    }    let views: Vec<_> = tool.views.iter().filter(|view| view.partition.is_none()).collect();    let view = views.iter().find(|view| view.is_default).or(views.first())?;    tables.iter().find(|table| Some(table.id.as_str()) == view.read.get("table").and_then(Value::as_str))}/// A tool's views as declared, as the tile counted reads them: its keyed home/// table's, else the tool definition's own.fn declared_views<'a>(tool: &str, tables: &'a [TableDefinition], tools: &'a [ToolDefinition]) -> &'a [cotton_core::definitions::tool_views::ToolView] {    let own = tables.iter().find(|table| table.tool.as_ref().is_some_and(|home| home.key.as_deref().unwrap_or(&table.id) == tool))        .and_then(|table| table.tool.as_ref()).map(|home| home.views.as_slice()).unwrap_or_default();    if !own.iter().any(|view| view.partition.is_none()) {        if let Some(installed) = tools.iter().find(|definition| definition.id == tool) { return &installed.views; }    }    own}/// Whether the tool owns its board home (`tool_views::owns`); a tool with no/// home table owns nothing to give away.fn owns_home(tool: &ToolDefinition, tables: &[TableDefinition], tools: &[ToolDefinition]) -> bool {    board_home(tool, tables).is_none_or(|home| crate::phone::tool_views::owns(&tool.id, home, tools))}/// The screen a tool's home table names (`tool.route`), where the tool owns it.fn declared_route<'a>(tool: &ToolDefinition, tables: &'a [TableDefinition], tools: &[ToolDefinition]) -> Option<&'a str> {    if !owns_home(tool, tables, tools) { return None }    board_home(tool, tables)?.tool.as_ref()?.route.as_deref()}/// Where a tool's page is its home table's list, its views ringing it: a tool/// that declares views, or one whose other tables are each a `list` section/// of its home table's page (Quotas' readings on each account's page).fn direct_table<'a>(tool: &ToolDefinition, tables: &'a [TableDefinition], tools: &[ToolDefinition]) -> Option<&'a TableDefinition> {    let home = board_home(tool, tables)?;    if declared_views(&tool.id, tables, tools).iter().any(|view| view.partition.is_none()) { return Some(home) }    let listed: std::collections::BTreeSet<&str> = home.page.iter().filter_map(|section| section.list.as_ref().map(|list| list.table.as_str())).collect();    tool.tables.iter().skip(1).all(|table| listed.contains(table.as_str())).then_some(home)}/// RULE: a tile's page stands in the fan when its route is a screen — a list or a page; an instruction (capture, a take) or the root is no page, and its tile is a poster.fn draws_in_place(route: &str) -> bool {    let path = route.split('?').next().unwrap_or(route);    !matches!(path, "" | "/" | "/home" | "/capture" | "/take" | "/keyboard-take")}/// A picture as a card draws it: the object it names and the photo record,/// either; a picture that only says how a link is drawn is none.fn picture(picture: &ToolPicture) -> Option<Value> {    match picture {        ToolPicture::Asset(object) => Some(json!({"object": object})),        ToolPicture::Photo(photo) => Some(json!({"photo": photo.photo, "object": photo.object})),        ToolPicture::Link(_) => None,    }}/// The photo the owner set on a table (`update_definition`, said in its/// `edited`): it wins over the tool's own picture.fn owners_picture(table: &TableDefinition) -> Option<Value> {    let edited = table.edited.iter().any(|key| key == "picture" || key.starts_with("picture."));    match &table.picture {        Some(ToolPicture::Photo(photo)) if edited => Some(json!({"photo": photo.photo})),        _ => None,    }}/// The pictogram at the head of a view's tile, by reference: the view's own/// where the tool's tile names one; a list's (`group:`), the tile's `list`/// role, which the shell draws where the list has no picture and no/// members' covers of its own.fn pictogram<'a>(tile: &'a FanTile, view: &Value) -> Option<&'a str> {    let id = view["id"].as_str().unwrap_or_default();    if id.starts_with("group:") { tile.role("list") } else { tile.view(id) }}/// A view as declared, before it is counted.fn declared_view(view: &cotton_core::definitions::tool_views::ToolView, tool: &str) -> Value {    json!({"id": view.id, "label": view.label, "visibility": view.visibility, "count": null, "default": view.is_default,        "face": view.face, "sort": view.sort, "slip": view.slip, "tile": view.tile, "title": tool, "head": null,        "picture": view.picture, "read": view.read})}/// A counted view as `tool_views` answers it, its default said `default`.pub(super) fn named_default(mut view: Value) -> Value {    if let Some(fields) = view.as_object_mut() {        let default = fields.remove("is_default").unwrap_or(Value::Bool(false));        fields.insert("default".into(), default);    }    view}/// The Settings card's views: its rows in the engine's order, each said by/// its name and opening its route, the first the one the card opens on.fn settings_views(native: &dyn Fn(&Value) -> Result<Value, MethodError>) -> Result<Vec<Value>, MethodError> {    let rows = native(&json!({"table": SETTINGS_TABLE, "limit": 200}))?;    Ok(rows["records"].as_array().into_iter().flatten().enumerate().map(|(at, row)| {        let address = row["data"]["route"].as_str().map(str::trim).filter(|route| !route.is_empty());        json!({"id": row["id"], "label": row["data"]["name"], "default": at == 0, "count": null, "address": address, "read": {"table": SETTINGS_TABLE}})    }).collect())}/// RULE: a views tier deals the default view first, then the rest in the ring's order.fn ringed_order(views: &[Value]) -> Vec<Value> {    let (default, rest): (Vec<&Value>, Vec<&Value>) = views.iter().partition(|view| view["default"] == true);    default.into_iter().chain(rest).cloned().collect()}/// RULE: a tool shows exactly one of its views, never none and never a mix: the one chosen while it is still the tool's, else the tool's default, else its first — a chosen list that was deleted falls back to the default rather than to an empty page./// The view that reads `table` whole: no columns, no section, no list.fn whole_of(views: &[Value], table: Option<&str>) -> Option<Value> {    let table = table?;    views.iter().find(|view| {        let read = &view["read"];        read["table"].as_str() == Some(table) && read["section"].is_null()            && read["where"].as_object().is_none_or(Map::is_empty)            // A view narrowed once its rows open (Health's Sleep) is no whole read.            && view["opened"]["where"].as_object().is_none_or(Map::is_empty)            && !view["id"].as_str().is_some_and(|id| id.starts_with("group:"))    }).map(|view| view["id"].clone())}fn current(views: &[Value], chosen: Option<&str>) -> Option<Value> {    views.iter().find(|view| chosen.is_some() && view["id"].as_str() == chosen)        .or_else(|| views.iter().find(|view| view["default"] == true))        .or(views.first())        .map(|view| view["id"].clone())}#[cfg(test)]#[path = "shell_fan_tests.rs"]mod tests;