Cotton code
2205 lines · 121.4 KB · RustRaw
//! `shell.list {table, view?, where?, query?, project?, archived?, section?,//! pick?, cursor?, limit?, timezone?, today?, rows?, bin_shown?, deleting?,//! failed?}` — A PAGE OF A SCROLLING LIST,//! ANSWERED WHOLE (the shell boundary, 5 Nov 2026: the core answers what to//! show, a platform shell only draws). Every list that is not a deck — a//! pick, Select, the archived, a route's narrowed list, a view whose face is//! a list, a table with no card, its group pages — is this answer drawn.//!//! ```json//! { "table", "title", "head": { "lines" },//!   "sections": [{ "id", "heading", "count"?, "open", "folds", "note"?, "lines",//!                  "leaf"?: { "day", "month" },//!                  "rows": [{ "id", "slip", "toggled"?, "toggle"?, "dimmed",//!                            "stamp"?, "held"?, "deletes", "acts": [id],//!                            "press": [act], "tap", "opens"?, "place"? }] }],//!   "acts": { id: { "label", "kind", "red", "primary"?, "icon"? } },//!   "menu": [{ "id", "label", "red", "asks"?, "opens"?, "object"? }],//!   "links": [{ "id", "label", "words", "count", "lead", "above", "opens" }],//!   "groups": [{ "id", "name", "count", "top", "opens" }] | null, "offers_new_group",//!   "index": [{ "letter", "row", "at" }] | null,//!   "filter": { "column", "all", "tabs", "values", "review"? } | null,//!   "empty": { "title", "message", "picture"? } | null,//!   "clear": { "label", "note"?, "question", "message", "confirm", "done"? } | null,//!   "select": { "deletes", "adds_to_group", "word" }, "reorders", "polls", "across",//!   "search", "section_words": { "new", "create", "select", "reorder", "all" },//!   "plus", "count", "next" }//! ```//!//! - `sections`: the list's rows in the order and under the headings the//!   definition says — a day plan's Today, its Late, each day ahead, Later,//!   No date and its finished groups (`day_plan`, counted over the whole//!   table); a calendar's days; a `group`'s sections, runs or due parts; days//!   (`by_day`), months (`by_month`, `months`); one unheaded section else.//!   A section that `folds` opens shut with its `count` in words; asked with//!   `section` (its id) it is answered alone, open, paged by `cursor`.//!   The `today` section carries `leaf`, the calendar's month leaf drawn//!   beside its name: `day` the day of the month (a number) and `month` its//!   short name in the kit's day words (`dates` › `months.*`), both of the//!   list's today on its `timezone`.//! - Rows: `slip` the words the slip draws (title, subtitle, caption, foot,//!   day foot, stub, byline, badge, unread) and `record`, the row itself,//!   which the slip face and the shell's routes still take; `toggle` what a//!   tap on its check writes; `acts` the ids of the acts its long press//!   offers — `shell.opened`'s own rule (`card_actions::opened`) — each named//!   once in `acts`; `press` the acts the row's long press runs, each whole//!   as `shell.opened` answers it (its address, its tool's words), those that//!   open a step left to the card's fan, Bring back on the archived, and a//!   command that asks first with its `question`; `tap` what a tap does//!   (`open.<opening>`, or `pick`); `opens` where the record opens — its//!   route and the kind of screen (`routes::opens`), on every row but a pick's.//! - `place`: on a table whose slip numbers its records (`ordinal`), the//!   row's place on the list, counted from 1 past the cursor, the archived//!   not counted; a row with no title of its own is titled by it.//! - A group's page's `menu`: its picks first (Add, Remove: `picks`, each a//!   list act, `tools.act` `list_add` / `list_take_out` over the records//!   picked), then the list's own acts (`tool_acts::list_acts`), Remove list//!   with its `question` in the list's words.//! - `opens: true` answers only what a route's list opens on, `{deck}`: the//!   face its card wears where it is a deck, null where it is these slips.//! - `menu`'s lines each carry the `object` their card stands and what they//!   `does`, which the tray colours them by.//! - `tile: true` answers what a fan tile of slips shows, `{table, records,//!   count}`: the records whole, each carrying its `@said`, in the list's own//!   order, less every section it keeps shut (open work aside: Late, Later//!   and No date are what the tile is for) and less the finished.//! - `deleting: [id]` answers Select's Delete alone — `{table, deleting://!   {ids, asks, word, question, done, undone, outcome}}`: the records picked//!   it takes, its question in the table's words, the receipt over them; with//!   `failed: [id]` the outcome says how many could not go. `bin_shown` says//!   the Bin stands on Home, which the words of where a record goes follow.//! - `next`: the cursor of the page after, or null at the end. The shell//!   asks for it near the end of the list, and again from 0 on a data event,//!   a definitions change or a receipt — never per frame. A later page's rows//!   stand under the section of the same id on the page before.//! - Writes keep their verbs (`records.update/command/delete/reorder`,//!   `groups.*`, `tools.act`); the shell asks again after each.//! - `rows`: a table whose rows a shell's own source still answers (a//!   Settings source not yet in the core) hands them, in their order, read//!   whole and already narrowed; the core words, sections and pages them as//!   it would its own read — never as a day plan, never with an archive.use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::definitions::TableDefinition;use cotton_core::rules::card_actions::{self, CardAction};use cotton_core::rules::shell_lines::{self, LineRow};use serde_json::{json, Map, Value};use super::shell_slip::{self, deletes, Reading};const METHOD: &str = "shell.list";/// A page of the list.pub const PAGE: usize = 50;/// How often an open list of a polled table asks again, in seconds.const POLL_SECONDS: u64 = 5;/// How many records a list holds before month headings earn their place.const MONTHS_OVER: usize = 12;/// The one section of a list read flat.const ALL: &str = "all";/// The where key naming a group (`groups::WHERE_KEY`).const GROUP_KEY: &str = "group";/// The index rail, top to bottom; `#` holds every name that starts with no letter.const OTHER_LETTER: &str = "#";/// A row's place in the store's order, on a kept cut.const AT: &str = "@at";/// `records.list`'s light read: the stored columns, no slip or card said.const LIGHT: &str = "light";/// The columns a light read reads (`records.list`'s `columns`).const COLUMNS: &str = "columns";/// `records.list`'s narrow cut: each row `[id, …columns]`, never a record.const CUT: &str = "cut";/// `records.list` without its group heads (the cut keeps the first read's).const HEADS: &str = "heads";/// How many runs of the store's order a page reads as pages before it/// reads its rows by id instead.const MOST_RUNS: usize = 4;type Native<'a> = &'a dyn Fn(&str, &Value) -> Result<Value, MethodError>;pub fn call(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {    let asked = request;    let mut request = request.clone();    // Rows a shell's source handed are worded as the core's own read words them.    if let Some(rows) = handed(&request)? {        let mut answer = json!({"table": request["table"], "records": rows, "total": rows.len(), "next_page": null});        crate::phone::records::resolve_slips_on(handle, "records.list", &json!({"table": request["table"]}), &mut answer)?;        request["rows"] = answer["records"].take();    }    // Asked again while nothing it reads has moved, the kept answer.    let client = handle.client();    if request["opens"] == true {        return opens(&client, &request, &|method, args| {            crate::methods::dispatch(handle, method, &crate::phone::records::in_named_database(args.clone()))        });    }    if request["tile"] == true {        return tile(&client, &request, &|method, args| {            crate::methods::dispatch(handle, method, &crate::phone::records::in_named_database(args.clone()))        });    }    let at = client.moved();    if let Some(answer) = crate::methods::shell_kept::answer(&client, METHOD, asked) { return Ok((*answer).clone()); }    let (answer, aside) = read_answer(&client, &request, &|method, args| {        crate::methods::dispatch(handle, method, &crate::phone::records::in_named_database(args.clone()))    })?;    if let Some(aside) = aside { crate::methods::shell_kept::keep(&client, METHOD, asked, at, aside, &answer); }    Ok(answer)}/// The words of the rows under this table's section on another's page.fn section_words(held: &Held) -> Value {    let definition = &held.definition;    let (kind, plural) = (definition.name.to_lowercase(), definition.plural.to_lowercase());    let new = line("lists", "new_kind", &held.lines, &[("kind", &kind)]);    json!({        "create": definition.create.as_ref().map_or_else(|| new.clone(), |create| create.label.clone()),        "new": new,        "select": line("lists", "select_plural", &held.lines, &[("plural", &plural)]),        "reorder": line("lists", "reorder_plural", &held.lines, &[("plural", &plural)]),        "all": line("lists", "all_plural", &held.lines, &[("plural", &plural)]),    })}/// What a fan tile of slips shows (`tile`).fn tile(client: &ClientController, request: &Value, native: Native) -> Result<Value, MethodError> {    use cotton_core::definitions::ToggleStyle;    let mut plain = request.clone();    if let Some(asked) = plain.as_object_mut() { asked.remove("tile"); }    let (list, _) = read_answer(client, &plain, native)?;    let held = read_held(client, &asked(client, &plain)?)?;    let upcoming = held.definition.upcoming.as_ref();    let open_work: Vec<&str> = [upcoming.and_then(|up| up.late.as_deref()), upcoming.and_then(|up| up.later.as_deref()), upcoming.and_then(|up| up.undated.as_deref())].into_iter().flatten().collect();    let strikes = held.definition.slip.toggle_style != Some(ToggleStyle::Switch);    let mut records = Vec::new();    for section in list["sections"].as_array().into_iter().flatten() {        let folded = section["folds"] == true;        if folded && !section["heading"].as_str().is_some_and(|heading| open_work.contains(&heading)) { continue; }        let opened = if folded {            let mut ask = plain.clone();            ask["section"] = section["id"].clone();            Some(read_answer(client, &ask, native)?.0)        } else { None };        let rows = match &opened {            Some(opened) => opened["sections"].as_array().into_iter().flatten().flat_map(|section| section["rows"].as_array().into_iter().flatten()).collect::<Vec<_>>(),            None => section["rows"].as_array().into_iter().flatten().collect(),        };        records.extend(rows.into_iter().filter(|row| !(strikes && row["toggled"] == true)).map(|row| row["slip"]["record"].clone()));    }    Ok(json!({"table": request["table"], "records": records, "count": list["count"]}))}/// The rows a shell's own source handed, each `{id, data}`; None where the core reads its own.fn handed(request: &Value) -> Result<Option<Vec<Value>>, MethodError> {    match request.get("rows") {        None | Some(Value::Null) => Ok(None),        Some(Value::Array(rows)) if rows.iter().all(|row| row["id"].is_string() && row["data"].is_object()) => Ok(Some(rows.clone())),        Some(_) => Err(bad("rows are the source's records, each {id, data}")),    }}/// `records.list` over the handed rows, as the store would answer it: by/// ids, counted, or a page of them. Handed for a live list, they hold nothing/// archived; handed for the archived list, they are the archived.fn read_handed(rows: &[Value], args: &Value, archived: bool) -> Value {    let table = &args["table"];    if let Some(ids) = args["ids"].as_array() {        let records: Vec<&Value> = rows.iter().filter(|row| ids.contains(&row["id"])).collect();        return json!({"table": table, "records": records, "total": records.len(), "next_page": null});    }    if args["archived"] == true && !archived {        return json!({"table": table, "records": [], "total": 0, "next_page": null});    }    if args["count_only"] == true || args["limit"] == 0 {        return json!({"table": table, "records": [], "total": rows.len(), "next_page": null});    }    let limit = args["limit"].as_u64().map(|limit| limit as usize).unwrap_or(PAGE).max(1);    let page = args["page"].as_u64().unwrap_or(0) as usize;    let from = (page * limit).min(rows.len());    let to = (from + limit).min(rows.len());    json!({"table": table, "records": &rows[from..to], "total": rows.len(), "next_page": (to < rows.len()).then_some(page + 1)})}/// What the list was asked.struct Asked {    table: String,    view: Option<String>,    filter: Map<String, Value>,    query: Option<String>,    /// The project a table filed under projects is narrowed to.    project: Option<String>,    archived: bool,    section: Option<String>,    pick: Option<Pick>,    cursor: usize,    limit: usize,    zone: String,    today: Option<Value>,    /// The rows are a shell's source's, handed whole (`rows`).    handed: bool,    /// The Bin stands on Home, so what goes there is said to go to it (`bin_shown`).    bin_shown: bool,}struct Pick {    held: Vec<String>,}/// What the list reads beside its rows, once per page.struct Held {    definition: TableDefinition,    /// Every table's definition, the catalogue's own shared copy.    tables: std::sync::Arc<cotton_tools::definitions::Definitions<TableDefinition>>,    lines: Vec<LineRow>,    tools: Vec<CardAction>,    words: cotton_core::records::page::Words,    now: chrono::DateTime<chrono::Utc>,    /// The file's bus and how often it has moved on, at this ask.    moved: (u64, u64),    bus: std::sync::Arc<crate::events::EventBus>,    /// The store tables this list leaves aside (`shell_kept::aside`).    aside: std::sync::Arc<std::collections::HashSet<String>>,}impl Held {    /// Where this ask began, for what `shell_list_kept` keeps.    fn at(&self) -> kept::At<'_> {        kept::At { bus: &self.bus, moved: self.moved, aside: &self.aside }    }}/// One section as answered, before its rows are made: its rows records/// (`Value`), or a kept cut's ids and places (`Cut`).#[derive(Clone)]struct Section<R = Value> {    id: String,    heading: Option<String>,    rows: Vec<R>,    folds: bool,    open: bool,    /// The whole section's count where it holds more than its rows (a plan's).    count: Option<u64>,    note: Option<String>,    /// The section's head lines, shared by every run of one group's value.    lines: std::sync::Arc<Vec<Value>>,    /// The group's value whose head lines the section says, where it says one.    head: Option<Value>,}impl<R> Section<R> {    fn new(id: impl Into<String>, heading: Option<String>, rows: Vec<R>) -> Section<R> {        Section { id: id.into(), heading, rows, folds: false, open: true, count: None, note: None, lines: Default::default(), head: None }    }    /// The section's rows, and the section holding none.    fn into_parts(mut self) -> (Vec<R>, Section<()>) {        let rows = std::mem::take(&mut self.rows);        (rows, Section { id: self.id, heading: self.heading, rows: Vec::new(), folds: self.folds, open: self.open, count: self.count, note: self.note, lines: self.lines, head: self.head })    }    /// The same section over other rows.    fn with_rows<T>(&self, rows: Vec<T>) -> Section<T> {        Section { id: self.id.clone(), heading: self.heading.clone(), rows, folds: self.folds, open: self.open, count: self.count,                  note: self.note.clone(), lines: std::sync::Arc::clone(&self.lines), head: self.head.clone() }    }}impl Section<()> {    /// This section, moved, over `rows`.    fn with_moved_rows<T>(self, rows: Vec<T>) -> Section<T> {        Section { id: self.id, heading: self.heading, rows, folds: self.folds, open: self.open, count: self.count, note: self.note, lines: self.lines, head: self.head }    }}/// Drops `spent` on a thread of its own: freeing a whole book's values is/// no part of an answer.pub(super) fn let_go<T: Send + 'static>(spent: T) {    // With no thread to be had, the refused closure drops it here.    let _ = std::thread::Builder::new().name("shell.list let go".into()).spawn(move || drop(spent));}/// A kept cut's row: its id and its place in the store's order.struct Cut {    id: Value,    at: usize,}/// The list's answer, and what it leaves aside where it may be kept/// (`shell_kept`): None for an ask that is never kept./// What a route's list opens on (`shell.list {…, opens: true}`): `deck`, the/// face its card wears, where it is a tool's plain list (not archived, not/// searched, not one section) of a table or view with a card and no list or/// grid face of its own; null where it is the slips. Whether this build draws/// that face is the shell's.fn opens(client: &ClientController, request: &Value, native: Native) -> Result<Value, MethodError> {    let asked = asked(client, request)?;    let held = read_held(client, &asked)?;    let view = match &asked.view {        Some(name) => Some(crate::methods::shell_deck::read_view(client, request, name, &asked.zone, &|args| native("records.list", args))?),        None => None,    };    let plain = !asked.archived && asked.query.is_none() && asked.section.is_none();    let listed = view.as_ref().is_some_and(|view| matches!(view["face"].as_str(), Some("list" | "grid")));    let viewed = view.as_ref().and_then(|view| view["card"]["face"].as_str().map(str::to_string));    let face = viewed.or_else(|| held.definition.card.as_ref().and_then(|card| serde_json::to_value(card.face).ok()).and_then(|face| face.as_str().map(str::to_string)));    Ok(json!({"deck": face.filter(|_| plain && !listed)}))}fn read_answer(client: &ClientController, request: &Value, native: Native) -> Result<(Value, Option<std::collections::HashSet<String>>), MethodError> {    let rows = handed(request)?;    let table = request["table"].clone();    let archived = request["archived"] == true;    let own = |method: &str, args: &Value| -> Result<Value, MethodError> {        match &rows {            Some(rows) if method == "records.list" && args["table"] == table => Ok(read_handed(rows, args, archived)),            _ => native(method, args),        }    };    let native: Native = &own;    let asked = asked(client, request)?;    let held = read_held(client, &asked)?;    tests::phase("held");    let definition = &held.definition;    if let Some(picked) = request.get("deleting").filter(|picked| !picked.is_null()) {        return deleting(&held, request, picked, native).map(|answer| (answer, None));    }    // The rows, sectioned and paged.    let read = Read { asked: &asked, held: &held, native };    let (sections, count, next, planned) = read.sections()?;    // Everything else the list says.    let narrowed = asked.query.is_some() || !asked.filter.is_empty() || asked.view.is_some() || asked.project.is_some();    let group_page = asked.filter.get(GROUP_KEY).and_then(Value::as_str).map(str::to_string);    let keeps_groups = definition.groups.is_some();    let shows_groups = keeps_groups && asked.pick.is_none() && asked.filter.is_empty() && asked.view.is_none() && !asked.archived;    let reorders = reorders(definition, &asked, group_page.is_some());    let mut acts: Map<String, Value> = Map::new();    let under_links: Vec<String> = asked.filter.iter()        .filter(|(key, value)| value.is_string() && definition.column(key).is_some_and(|column| column.column_type == cotton_core::definitions::ColumnType::Link))        .map(|(key, _)| key.clone()).collect();    let without = (!under_links.is_empty()).then(|| shell_slip::without_links(definition, &under_links));    let reading = Reading::new(without.as_ref().unwrap_or(definition), &asked.zone, Some(held.now), day_headed(definition, &asked), &held.words);    let reading = if without.is_some() { reading.narrowed() } else { reading };    let mut answered = Vec::with_capacity(sections.len());    for section in sections {        let rows = section.rows.iter().map(|row| row_of(&held, &asked, &reading, row, reorders, &mut acts)).collect::<Result<Vec<_>, _>>()?;        let mut said = json!({            "id": section.id, "heading": section.heading, "open": section.open, "folds": section.folds,            "count": section.folds.then(|| words_of_count(section.count.unwrap_or(rows.len() as u64))),            "note": section.note, "lines": section.lines.as_slice(), "rows": rows,        });        if let Some(said) = said.as_object_mut() { said.retain(|_, value| !value.is_null()); }        if section.id == "today" {            if let Some(leaf) = month_leaf(&read.today_key(), &held.lines) { said["leaf"] = leaf; }        }        answered.push(said);    }    tests::phase("dress page");    // What no page changes, kept with the cut while the file has not moved on.    let key = kept::key(&asked, definition, &read.today_key());    let aside = key.is_some().then(|| (*held.aside).clone());    let frame = match key.as_ref().and_then(|key| kept::frame(&held.at(), key)).filter(|frame| frame.earlier == planned.earlier) {        Some(frame) => frame,        None => {            let counts = link_counts(&held, native)?;            tests::phase("frame counts");            let links = links(&held, &asked, &counts, &planned, native)?;            tests::phase("frame links");            let menu = menu(client, &held, &asked, &counts, shows_groups, group_page.as_deref())?;            tests::phase("frame menu");            let groups = if shows_groups { Some(groups(&held, native)?) } else { None };            tests::phase("frame groups");            let head = crate::phone::list_head::read(client, &json!({"table": definition.id}))?;            tests::phase("frame head");            let mut plus = crate::methods::shell_deck::plus_of(definition);            crate::phone::fan_tile::dress_doors(crate::phone::fan_tile::of_table(client, definition, METHOD)?.as_ref(), &mut plus);            let frame = std::sync::Arc::new(kept::Frame {                counts, links, earlier: planned.earlier, menu, groups,                title: title(&held, &asked, native)?, head: head["lines"].clone(), plus,            });            if let Some(key) = key { kept::keep_frame(&held.at(), key, std::sync::Arc::clone(&frame)); }            frame        }    };    tests::phase("frame");    let (counts, links, groups) = (&frame.counts, &frame.links, &frame.groups);    let offers_new_group = shows_groups && definition.groups.as_ref().is_some_and(|groups| groups.kept_in.is_none());    let holds_nothing = count == 0 && next.is_none() && planned.earlier == 0        && !answered.iter().any(|section| section["folds"] == true && section["count"].as_str().is_some_and(|count| count != "0"));    let empty = (holds_nothing && (asked.query.is_some() || !links.iter().any(|link| link["count"].as_u64().unwrap_or(0) > 0)))        .then(|| empty_words(client, &held, &asked, native)).transpose()?;    let clear = definition.clear.as_ref().filter(|_| count > 0 && !narrowed && asked.pick.is_none() && !asked.archived).map(|clear| {        let filled = |text: &str| text.replace("{count}", &count.to_string());        json!({"label": clear.label, "note": clear.note, "question": filled(clear.title.as_deref().unwrap_or(&clear.label)),               "message": filled(clear.message.as_deref().unwrap_or_default()), "confirm": clear.confirm.clone().unwrap_or_else(|| line("lists", "delete.confirm", &held.lines, &[])),               "done": clear.done})    });    let index = planned.index.clone();    let recent = recent_rows(definition, &asked, &answered, next);    let notes = foot_notes(definition, &answered, &planned);    if definition.slip.ordinal == Some(true) { number_rows(&mut answered, asked.cursor, &definition.name); }    let answer = json!({        "table": definition.id,        "title": frame.title,        "head": {"lines": frame.head},        "sections": answered, "acts": acts,        "menu": frame.menu, "links": links,        "groups": groups, "offers_new_group": offers_new_group,        "index": index,        "filter": filter_row(&held, &asked, counts),        "empty": empty, "clear": clear,        "select": {"deletes": definition.select.is_some() || definition.delete != Some(false), "adds_to_group": keeps_groups,                   "word": definition.deletion.as_ref().and_then(|words| words.label.clone()).unwrap_or_else(|| line("definitions", "select.delete", &held.lines, &[]))},        "reorders": reorders,        "search": definition.search_placeholder.clone().unwrap_or_else(|| line("lists", "search", &held.lines, &[("plural", &definition.plural.to_lowercase())])),        "section_words": section_words(&held),        "polls": (definition.polled == Some(true)).then_some(POLL_SECONDS),        "across": across(definition),        "plus": frame.plus,        "recent": recent, "notes": notes,        "count": count, "next": next,    });    tests::phase("answer");    Ok((answer, aside))}/// A numbered table's rows, each with its `place` on the list counted from 1:/// the archived are not counted, and a record listed twice keeps its first/// place. A row with no title of its own is titled by its place.fn number_rows(sections: &mut [Value], from: usize, name: &str) {    let mut places: std::collections::HashMap<String, usize> = Default::default();    for row in sections.iter_mut().filter_map(|section| section["rows"].as_array_mut()).flatten() {        let data = &row["slip"]["record"]["data"];        if data[shell_slip::SAID_KEY]["archived"] == true { continue; }        let id = row["id"].as_str().unwrap_or_default().to_string();        let next = from + places.len() + 1;        let place = *places.entry(id).or_insert(next);        row["place"] = json!(place);        if row["slip"]["title"].is_null() {            let title = json!(format!("{name} {place}"));            row["slip"]["record"]["data"][shell_slip::SAID_KEY]["slip"]["title"] = title.clone();            row["slip"]["title"] = title;        }    }}/// Records across a list drawn as cards or a contact sheet: its `grid`'s/// count, else its covers' — one postcard, or three paperbacks. Null for a/// list of slips.fn across(definition: &TableDefinition) -> Option<u32> {    use cotton_core::definitions::ListLayout;    if matches!(definition.layout, None | Some(ListLayout::List)) { return None; }    Some(match &definition.grid {        Some(grid) => grid.columns.max(1),        None if definition.slip.trailing_picture.is_some() => 1,        None => 3,    })}/// The "Recent" rows above a list (the definition's `recent`): its latest by/// the column, once the list holds more than `over` — only over the whole/// table read to its end, unnarrowed, nothing archived among them.fn recent_rows(definition: &TableDefinition, asked: &Asked, sections: &[Value], next: Option<usize>) -> Vec<Value> {    let Some(recent) = &definition.recent else { return Vec::new() };    if asked.query.is_some() || asked.project.is_some() || !asked.filter.is_empty() || asked.view.is_some() || asked.archived        || asked.pick.is_some() || asked.section.is_some() || asked.cursor > 0 || next.is_some() {        return Vec::new();    }    let archive = definition.archived.as_deref();    let rows: Vec<&Value> = sections.iter().flat_map(|section| section["rows"].as_array().into_iter().flatten())        .filter(|row| archive.is_none_or(|key| !set(&row["slip"]["record"]["data"][key]))).collect();    if rows.len() <= recent.over.unwrap_or(3) as usize { return Vec::new(); }    let moment = |row: &Value| -> Option<i64> {        let text = row["slip"]["record"]["data"][&recent.column].as_str()?;        chrono::DateTime::parse_from_rfc3339(text).map(|at| at.timestamp()).ok()            .or_else(|| chrono::NaiveDate::parse_from_str(text.get(..10)?, "%Y-%m-%d").ok().and_then(|day| day.and_hms_opt(0, 0, 0)).map(|at| at.and_utc().timestamp()))    };    let mut dated: Vec<(i64, usize, &Value)> = rows.into_iter().enumerate().filter_map(|(at, row)| Some((moment(row)?, at, row))).collect();    dated.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));    dated.into_iter().take(recent.count.unwrap_or(2) as usize).map(|(_, _, row)| {        let data = &row["slip"]["record"]["data"];        json!({"id": row["id"], "title": row["slip"]["title"], "when": data[cotton_core::records::page::DAY_PARTS_KEY][&recent.column]["recent"]})    }).collect()}/// The notes of the definition's group sections the list holds none of, each/// once: said under the list, where their section would have stood.fn foot_notes(definition: &TableDefinition, sections: &[Value], planned: &Planned) -> Vec<String> {    let Some(groups) = definition.group.as_ref().and_then(|group| group.sections.as_ref()) else { return Vec::new() };    let shown: Vec<Option<String>> = planned.headings.clone()        .unwrap_or_else(|| sections.iter().map(|section| section["heading"].as_str().map(str::to_string)).collect());    let mut out: Vec<String> = Vec::new();    for group in groups {        let Some(note) = group.note.as_ref().filter(|note| !note.is_empty()) else { continue };        if shown.contains(&group.heading) || out.contains(note) { continue; }        out.push(note.clone());    }    out}fn asked(client: &ClientController, request: &Value) -> Result<Asked, MethodError> {    let table = named(request, "table").ok_or_else(|| bad("shell.list takes a table"))?.to_string();    let cursor = match request.get("cursor") {        None | Some(Value::Null) => 0,        Some(value) => value.as_u64().ok_or_else(|| bad("cursor is the next answer's own cursor"))? as usize,    };    let limit = match request.get("limit") {        None | Some(Value::Null) => PAGE,        Some(value) => value.as_u64().filter(|limit| *limit > 0).ok_or_else(|| bad("limit is a count of rows"))? as usize,    }    .min(cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE as usize);    let filter = match request.get("where") {        None | Some(Value::Null) => Map::new(),        Some(Value::Object(filter)) => filter.clone(),        Some(_) => return Err(bad("where is {column: value}")),    };    let archived = match request.get("archived") {        None | Some(Value::Null) => false,        Some(Value::Bool(archived)) => *archived,        Some(_) => return Err(bad("archived is true or false")),    };    let pick = match request.get("pick") {        None | Some(Value::Null) => None,        Some(Value::Object(pick)) => Some(Pick {            held: pick.get("held").and_then(Value::as_array).into_iter().flatten().filter_map(|id| id.as_str().map(str::to_string)).collect(),        }),        Some(_) => return Err(bad("pick is {column, held?}")),    };    Ok(Asked {        table,        view: named(request, "view").map(str::to_string),        filter,        query: named(request, "query").map(str::to_string),        project: named(request, "project").map(str::to_string),        archived,        section: named(request, "section").map(str::to_string),        pick,        cursor,        limit,        zone: request["timezone"].as_str().unwrap_or(client.time_zone().unwrap_or("UTC")).to_string(),        today: request.get("today").filter(|today| !today.is_null()).cloned(),        handed: request.get("rows").is_some_and(Value::is_array),        bin_shown: request["bin_shown"] == true,    })}fn read_held(client: &ClientController, asked: &Asked) -> Result<Held, MethodError> {    let mut tables = None;    client.read_rows(METHOD, &mut |ctx| {        tables = Some(cotton_tools::definitions::shared_table_definitions(ctx).map_err(|e| e.to_string())?);        Ok(Value::Null)    }).map_err(|reason| MethodError::new("unreadable", reason))?;    let lines = crate::phone::records::line_rows_kept(client).as_ref().clone();    let tables = tables.ok_or_else(|| MethodError::new("unreadable", "no definitions were read"))?;    let definition = tables.definitions.iter().find(|found| found.id == asked.table).cloned().ok_or_else(|| bad(&format!("No table {}", asked.table)))?;    let tools = crate::phone::tool_acts::standing(client, &definition, asked.view.as_deref(), METHOD)?.iter().filter_map(CardAction::tool).collect();    let words = cotton_core::records::page::Words::of_rows(&lines);    let aside = std::sync::Arc::new(crate::methods::shell_kept::aside(&tables.definitions, &definition));    Ok(Held { definition, tables, lines, tools, words, now: client.clock().now(), moved: client.moved(), bus: client.bus(), aside })}// MARK: The rows and their sections/// What the plan counted beside the rows.#[derive(Default)]struct Planned {    /// How many records the plan holds before today, on a read of what is coming.    earlier: u64,    /// Every section's heading the whole read holds, where it was read whole    /// and paged here; None where the page's own sections are all there are.    headings: Option<Vec<Option<String>>>,    /// The index rail's landings over the whole read, where it was read whole.    index: Option<Vec<Value>>,}struct Read<'a> {    asked: &'a Asked,    held: &'a Held,    native: Native<'a>,}impl Read<'_> {    /// The records.list ask every read of this list starts from.    fn base(&self) -> Map<String, Value> {        let asked = self.asked;        let mut args = Map::new();        args.insert("table".into(), json!(asked.table));        args.insert("timezone".into(), json!(asked.zone));        if let Some(today) = &asked.today { args.insert("today".into(), today.clone()); }        if let Some(query) = &asked.query { args.insert("query".into(), json!(query)); }        if let Some(project) = &asked.project { args.insert("project".into(), json!(project)); }        if asked.archived { args.insert("archived".into(), json!(true)); }        if !asked.filter.is_empty() { args.insert("where".into(), Value::Object(asked.filter.clone())); }        if let Some(view) = &asked.view {            if !view.contains("/group:") { args.insert("view".into(), json!(view)); }        }        args    }    fn page(&self, args: &Map<String, Value>, page: usize, limit: usize) -> Result<Value, MethodError> {        let mut asked = Value::Object(args.clone());        asked["page"] = json!(page);        asked["limit"] = json!(limit);        (self.native)("records.list", &asked)    }    /// Every row `args` reads, page after page.    fn every_row(&self, args: &Map<String, Value>) -> Result<(Vec<Value>, Value), MethodError> {        self.every_row_as(args, |row| row, |columns, row| narrow_row(columns, row))    }    /// Every row `args` reads as the cut reads it, each its id, place and columns.    fn every_cut_row(&self, args: &Map<String, Value>) -> Result<(Vec<CutRow>, Value), MethodError> {        self.every_row_as(args, CutRow::of_record, CutRow::of_narrow)    }    /// Every row `args` reads, page after page: a record made a row by    /// `record`, a narrow cut's array by `narrow` (with the cut's columns).    fn every_row_as<T>(&self, args: &Map<String, Value>, record: impl Fn(Value) -> T, narrow: impl Fn(&std::sync::Arc<[String]>, Value) -> T) -> Result<(Vec<T>, Value), MethodError> {        use cotton_tools::mcp::handlers::tables::{MAX_LIGHT_PAGE, MAX_PAGE_SIZE};        let most = if args.contains_key(COLUMNS) { MAX_LIGHT_PAGE } else { MAX_PAGE_SIZE } as usize;        let mut page = 0usize;        let mut rows = Vec::new();        let mut first = Value::Null;        let mut asked = args.clone();        loop {            tests::phase("prep");            let mut answer = self.page(&asked, page, most)?;            tests::phase("store cut");            // The group heads are over every row: the first page says them.            asked.insert(HEADS.into(), json!(false));            // The rows are moved out, never copied: a whole book's worth. A            // narrow cut's arrays are made the rows the cut reads, `{id, data}`.            if let Value::Array(read) = answer["records"].take() { rows.extend(read.into_iter().map(&record)); }            if let Value::Array(read) = answer["rows"].take() {                // The columns after the id, shared by every row.                let columns: std::sync::Arc<[String]> = answer["columns"].as_array().into_iter().flatten().skip(1).filter_map(|key| key.as_str().map(str::to_string)).collect();                rows.reserve(read.len());                rows.extend(read.into_iter().map(|row| narrow(&columns, row)));            }            tests::phase("narrow");            let next = answer["next_page"].as_u64().map(|next| next as usize);            if first.is_null() { first = answer; }            match next {                Some(next) if next > page => page = next,                Some(_) => return Err(MethodError::new("unreadable", format!("{METHOD}: a page did not advance"))),                None => return Ok((rows, first)),            }        }    }    /// The page's sections, the whole list's count, the next cursor and what    /// the plan counted.    fn sections(&self) -> Result<(Vec<Section>, usize, Option<usize>, Planned), MethodError> {        let definition = &self.held.definition;        let asked = self.asked;        let flat = asked.view.is_some() || asked.archived;        let planned = !flat && !asked.handed && asked.query.is_none() && planned_list(definition, &asked.filter);        // A day plan: Todos' Today, its days ahead and its closed sections;        // a calendar's days, what is coming and what is earlier.        if planned && definition.upcoming.is_some() {            return self.todo_plan();        }        if planned && definition.day_grouping.is_some() {            return self.calendar_plan();        }        let base = self.base();        // A plain list, flat or one unheaded section: paged by the store.        if flat || !sections_whole(definition) || (asked.filter.contains_key(GROUP_KEY) && definition.upcoming.is_none()) {            let answer = self.page(&base, asked.cursor, asked.limit)?;            let rows = answer["records"].as_array().cloned().unwrap_or_default();            let count = answer["total"].as_u64().map(|total| total as usize).unwrap_or(asked.cursor + rows.len());            let next = answer["next_page"].as_u64().map(|next| next as usize);            let mut section = Section::new(ALL, None, rows);            if !flat { section.lines = heads_of(&answer, &Value::Null).into(); }            let sections = if section.rows.is_empty() { Vec::new() } else { vec![section] };            return Ok((sections, count, next, Planned::default()));        }        // A list whose sections are cut over all its rows (groups, days,        // months, the index): cut once over a light read of every row and        // kept while the file has not moved on (`shell_list_kept`); a page        // reads only its own rows.        let whole = self.whole(&base)?;        let count = whole.count;        let planned = Planned { earlier: 0, headings: Some(whole.headings.clone()), index: whole.index.clone() };        let mut sections = paged(&whole.sections, asked.cursor, asked.limit);        tests::phase("page slice");        self.headed(&base, &mut sections, &whole)?;        tests::phase("page heads");        let sections = self.filled(&base, sections)?;        tests::phase("store page");        Ok((sections, count, (asked.cursor + asked.limit < count).then_some(asked.cursor + asked.limit), planned))    }    /// The list cut into its sections over every row it holds, each row    /// only its id and its place in the store's order (`@at`): kept per ask    /// while the file has not moved on; patched for the rows a move named    /// where it can be (`patched`); else read and cut now.    fn whole(&self, base: &Map<String, Value>) -> Result<std::sync::Arc<Whole>, MethodError> {        let key = kept::key(self.asked, &self.held.definition, &self.today_key()).filter(|_| !tests::wide());        if let Some(key) = &key {            if let Some(whole) = kept::whole(&self.held.at(), key) {                return Ok(whole);            }            if let Some(whole) = self.patched(base, key)? {                let whole = std::sync::Arc::new(whole);                kept::keep_whole(&self.held.at(), key.clone(), std::sync::Arc::clone(&whole));                tests::phase("ids");                return Ok(whole);            }        }        let (args, dressed) = self.cut_args(base);        let (mut rows, first) = self.every_cut_row(&args)?;        let mut said = std::collections::HashMap::new();        if dressed {            for row in rows.iter_mut() { self.dress(row.dressing(), &mut said); }        }        tests::phase("dress cut");        // A cut whose sections say heads summed over their rows is read        // whole again: a moved row moves its section's figures.        let headless = first["group_heads"].as_array().is_none_or(Vec::is_empty);        let patches = key.is_some() && headless && self.patches(dressed);        let whole = std::sync::Arc::new(self.made(rows, &first, patches));        if let Some(key) = key { kept::keep_whole(&self.held.at(), key, std::sync::Arc::clone(&whole)); }        tests::phase("ids");        Ok(whole)    }    /// The records.list ask a whole cut reads, and whether its rows are    /// dressed after: a light read, the stored columns alone, no slip or card    /// said; the day parts the cut reads are said by `dress`, as the full read    /// says them. Where every column the cut reads is stored, a narrow cut:    /// the ids and those columns alone, read straight off the list's own query.    fn cut_args(&self, base: &Map<String, Value>) -> (Map<String, Value>, bool) {        let definition = &self.held.definition;        let light = light_reads(definition) && !self.asked.handed;        let columns = cut_columns(definition).filter(|_| light);        let narrow = columns.is_some() && !tests::wide();        let mut args = base.clone();        if light { args.insert(LIGHT.into(), json!(true)); }        if let Some(columns) = columns {            args.insert(COLUMNS.into(), json!(columns));            if narrow { args.insert(CUT.into(), json!(true)); }        }        // Heads a page reads for its own sections are not read over the cut.        if self.page_heads().is_some() { args.insert(HEADS.into(), json!(false)); }        // A narrow cut's columns hold no computed one: only a cut by days        // reads what dressing says (`cut_reads_days`).        (args, light && (!narrow || cut_reads_days(definition)))    }    /// Whether a whole cut may be patched for the rows a write names: read    /// in no view, and narrowed, ordered, searched and cut by columns each    /// row holds of itself, none computed (a running balance moves with    /// every row before it).    fn patches(&self, dressed: bool) -> bool {        let definition = &self.held.definition;        if self.asked.view.is_some() || self.asked.handed || cut_columns(definition).is_none() { return false; }        if definition.has_computed() && (dressed || self.asked.query.is_some()) { return false; }        crate::methods::shell_order::row_local(definition, self.asked.filter.keys())    }    /// The kept cut this ask read before its file moved, patched for the    /// rows every move since named: each read again through the list's own    /// read narrowed to them (`among`), so a row the filter no longer keeps    /// is gone; placed by the store's own order among the kept rows    /// (`place`); and the whole cut again in memory, no row of it read. None    /// where what moved cannot be told (a move naming no rows: a pull, a    /// bulk write, a definition) or the cut was not kept to be patched.    fn patched(&self, base: &Map<String, Value>, key: &str) -> Result<Option<Whole>, MethodError> {        let Some((moved, aside, old)) = kept::stale_whole(&self.held.at(), key) else { return Ok(None) };        let Some(changed) = self.held.bus.rows_since(moved, &aside) else { return Ok(None) };        // A table another engine reads (Email's) refuses `among`: its cut is read whole.        if !cotton_tools::mcp::handlers::tables::builtin::reads_among(&self.held.definition) { return Ok(None); }        let own = crate::methods::shell_kept::stores(&self.held.definition);        if changed.len() > crate::methods::shell_order::MOST_PATCHED || changed.iter().any(|(table, _)| !own.contains(table)) { return Ok(None); }        let Some(data) = old.rows.lock().ok().and_then(|mut rows| rows.take()) else { return Ok(None) };        let ids: std::collections::HashSet<&str> = changed.iter().map(|(_, id)| id.as_str()).collect();        // The group values the moved rows stood under, and stand under now:        // their heads are read again, every other value's kept.        let group = self.page_heads().map(str::to_string);        let mut touched: std::collections::HashSet<String> = std::collections::HashSet::new();        let mut cuts: Vec<(usize, &Value)> = old.sections.iter().flat_map(|section| section.rows.iter().map(|cut| (cut.at, &cut.id))).collect();        cuts.sort_unstable_by_key(|(at, _)| *at);        let mut rows: Vec<CutRow> = Vec::with_capacity(cuts.len());        for ((at, id), data) in cuts.into_iter().zip(data) {            let row = CutRow { id: id.clone(), at, data };            if !id.as_str().is_some_and(|id| ids.contains(id)) { rows.push(row); continue; }            if let Some(group) = &group { touched.insert(row.get(group).to_string()); }        }        tests::phase("patch take");        if !ids.is_empty() {            let (args, dressed) = self.cut_args(base);            let mut among = args.clone();            among.insert(crate::methods::shell_order::AMONG.into(), json!(ids.iter().collect::<Vec<_>>()));            among.insert(HEADS.into(), json!(false));            let (mut read, _) = self.every_cut_row(&among)?;            let mut said = std::collections::HashMap::new();            if dressed {                for row in read.iter_mut() { self.dress(row.dressing(), &mut said); }            }            for row in read {                if let Some(group) = &group { touched.insert(row.get(group).to_string()); }                let Some(at) = self.place(&args, &rows, &row.id)? else { return Ok(None) };                rows.insert(at, row);            }        }        tests::phase("patch place");        tests::patching();        let whole = self.made(rows, &Value::Null, true);        if let (Ok(old), Ok(mut new)) = (old.heads.lock(), whole.heads.lock()) {            new.extend(old.iter().filter(|(value, _)| !touched.contains(*value)).map(|(value, lines)| (value.clone(), std::sync::Arc::clone(lines))));        }        Ok(Some(whole))    }    /// Where a row the list's own read keeps falls among `rows` (the kept    /// cut, in the store's order), asked of the store (`shell_order::place`).    fn place(&self, args: &Map<String, Value>, rows: &[CutRow], id: &Value) -> Result<Option<usize>, MethodError> {        crate::methods::shell_order::place(&|ask| (self.native)("records.list", ask), args, rows.len(), &|at| rows[at].id.clone(), id)    }    /// The cut of `rows` (in the store's order, each its id and columns):    /// its sections, landings and count, each row only its id and place.    /// What the cut read beside each id is kept, in the store's order, for a    /// patch (`patches`, where the cut holds every row read), else let go on    /// another thread, never on the answer's path: a whole book's values.    fn made(&self, mut rows: Vec<CutRow>, first: &Value, patches: bool) -> Whole {        let definition = &self.held.definition;        let read = rows.len();        for (at, row) in rows.iter_mut().enumerate() { row.at = at; }        let sections = self.cut(rows, first);        tests::phase("cut");        let index = landings(definition, &sections, self.asked);        tests::phase("landings");        let headings = sections.iter().map(|section| section.heading.clone()).collect();        let count: usize = sections.iter().map(|section| section.rows.len()).sum();        let patches = patches && count == read;        let mut held: Vec<Option<Data>> = if patches { (0..count).map(|_| None).collect() } else { Vec::new() };        let mut spent: Vec<Data> = Vec::with_capacity(if patches { 0 } else { count });        let sections = sections.into_iter().map(|section| {            let (rows, section) = section.into_parts();            section.with_moved_rows(rows.into_iter().map(|row| {                if patches { held[row.at] = Some(row.data); } else { spent.push(row.data); }                Cut { id: row.id, at: row.at }            }).collect())        }).collect();        if !spent.is_empty() { let_go(spent); }        let held: Option<Vec<Data>> = patches.then(|| held.into_iter().flatten().collect());        Whole { sections, count, headings, index, rows: std::sync::Mutex::new(held.filter(|held| held.len() == count)), heads: Default::default() }    }    /// The group column whose heads a page reads for its own sections alone,    /// after the cut: a grouped list whose group says figures, read by the core.    fn page_heads(&self) -> Option<&str> {        let group = self.held.definition.group.as_ref().filter(|group| !group.summary.is_empty())?;        (!self.asked.handed).then_some(group.column.as_str())    }    /// The page's sections' head lines, read for the group values the page    /// holds alone: the store sums each value's rows whole, as it would for    /// every value. A value no `where` can name (none) reads every head.    fn headed(&self, base: &Map<String, Value>, sections: &mut [Section], whole: &Whole) -> Result<(), MethodError> {        let Some(column) = self.page_heads() else { return Ok(()) };        let mut values: Vec<Value> = Vec::new();        for value in sections.iter().filter_map(|section| section.head.as_ref()) {            if !values.contains(value) { values.push(value.clone()); }        }        if values.is_empty() { return Ok(()); }        // The values whose heads the cut keeps are not read again.        let mut known: std::collections::HashMap<String, std::sync::Arc<Vec<Value>>> = match whole.heads.lock() {            Ok(heads) => values.iter().filter_map(|value| heads.get(&value.to_string()).map(|lines| (value.to_string(), std::sync::Arc::clone(lines)))).collect(),            Err(_) => Default::default(),        };        let missing: Vec<Value> = values.into_iter().filter(|value| !known.contains_key(&value.to_string())).collect();        if !missing.is_empty() {            let mut args = base.clone();            args.insert(LIGHT.into(), json!(true));            let narrowed = args.get("where").and_then(Value::as_object).is_some_and(|filter| filter.contains_key(column));            if !narrowed && missing.iter().all(|value| value.as_str().is_some_and(|value| !value.is_empty())) {                let filter = args.entry("where").or_insert_with(|| json!({}));                filter[column] = Value::Array(missing.clone());            }            let answer = self.page(&args, 0, 1)?;            let mut heads = whole.heads.lock().ok();            for value in &missing {                let lines = std::sync::Arc::new(heads_of(&answer, value));                if let Some(heads) = heads.as_mut() { heads.insert(value.to_string(), std::sync::Arc::clone(&lines)); }                known.insert(value.to_string(), lines);            }        }        for section in sections.iter_mut() {            if let Some(lines) = section.head.as_ref().and_then(|value| known.get(&value.to_string())) { section.lines = std::sync::Arc::clone(lines); }        }        Ok(())    }    /// A light row's date parts and computed columns, as the full read    /// says them (`records::attach_slip_lines`).    /// The parts are said once per distinct set of dates (`said`): a whole    /// read holds a few hundred days over tens of thousands of rows.    fn dress(&self, data: &mut Value, said: &mut std::collections::HashMap<String, Map<String, Value>>) {        use cotton_core::records::page;        let definition = &self.held.definition;        let Some(data) = data.as_object_mut() else { return };        let computed = page::computed_column_values(definition, data, Some(self.held.now));        data.extend(computed);        let dates: String = definition.columns.iter().filter(|column| column.column_type == cotton_core::definitions::ColumnType::Date)            .map(|column| data.get(&column.key).and_then(Value::as_str).unwrap_or_default()).collect::<Vec<_>>().join("\u{1}");        let days = said.entry(dates).or_insert_with(|| page::day_parts(definition, data, &self.asked.zone, self.held.now, &self.held.words.dates)).clone();        if !days.is_empty() { data.insert(page::DAY_PARTS_KEY.into(), Value::Object(days)); }    }    /// The page's sections with their rows read whole: each run of places    /// that follow one another in the store's order is one page of the    /// store's own read; a row that moved since the cut (or a page of too    /// many runs) is read by its id.    fn filled(&self, base: &Map<String, Value>, mut sections: Vec<Section>) -> Result<Vec<Section>, MethodError> {        let mut wanted: Vec<(usize, String)> = sections.iter().flat_map(|section| section.rows.iter())            .filter_map(|row| Some((row[AT].as_u64()? as usize, row["id"].as_str()?.to_string()))).collect();        wanted.sort();        let mut runs: Vec<(usize, usize)> = Vec::new();        for (at, _) in &wanted {            match runs.last_mut() {                Some((from, length)) if *from + *length == *at => *length += 1,                _ => runs.push((*at, 1)),            }        }        let mut read: std::collections::HashMap<String, Value> = std::collections::HashMap::new();        if runs.len() <= MOST_RUNS {            let mut args = base.clone();            args.insert(HEADS.into(), json!(false));            // The cut counted the list: a page of it never counts it again.            args.insert("total".into(), json!(false));            for (from, length) in runs {                let answer = self.page(&args, from, length)?;                for row in answer["records"].as_array().into_iter().flatten() {                    if let Some(id) = row["id"].as_str() { read.insert(id.to_string(), row.clone()); }                }            }        }        let missing: Vec<String> = wanted.into_iter().map(|(_, id)| id).filter(|id| !read.contains_key(id)).collect();        let most = cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE as usize;        for ids in missing.chunks(most) {            let mut args = Map::new();            args.insert("table".into(), json!(self.asked.table));            args.insert("timezone".into(), json!(self.asked.zone));            if let Some(today) = &self.asked.today { args.insert("today".into(), today.clone()); }            args.insert("ids".into(), json!(ids));            let answer = (self.native)("records.list", &Value::Object(args))?;            for row in answer["records"].as_array().into_iter().flatten() {                if let Some(id) = row["id"].as_str() { read.insert(id.to_string(), row.clone()); }            }        }        // A row gone since the cut is left out; the next data event cuts again.        for section in &mut sections {            section.rows = section.rows.iter().filter_map(|row| row["id"].as_str().and_then(|id| read.get(id)).cloned()).collect();        }        Ok(sections)    }    /// The rows cut into the definition's sections, in its order.    fn cut(&self, rows: Vec<CutRow>, first: &Value) -> Vec<Section<CutRow>> {        let definition = &self.held.definition;        let today = self.today_key();        if definition.index.is_some() && self.asked.query.is_none() {            return vec![Section::new(ALL, None, letter_runs(definition, rows))];        }        if let Some(by_day) = &definition.by_day {            return day_sections(definition, by_day, rows, &today, &self.held.lines);        }        if let Some(key) = &definition.day_grouping {            return grouped_days(key, rows, &today, &self.held.lines);        }        if definition.by_month.is_some() {            return month_sections(definition, rows);        }        if definition.upcoming.is_some() {            return upcoming_sections(definition, rows, &today, &self.held.lines);        }        grouped(definition, rows, first, &today)    }    fn today_key(&self) -> String {        if let Some(today) = self.asked.today.as_ref().and_then(Value::as_str) { return today.to_string(); }        cotton_core::records::page::Moment::now(self.held.now, &self.asked.zone)            .map(|moment| {                let (year, month, day) = cotton_core::transforms::zoned_clock::civil_from_days(moment.day);                format!("{year:04}-{month:02}-{day:02}")            })            .unwrap_or_default()    }    /// One page of one section of a list of work still to do, as the plan    /// reads it: off the kept plan (`shell_plan`) where the list is the    /// table's own, unnarrowed, else the plan's own read.    fn plan_page(&self, args: &Map<String, Value>, page: usize, limit: usize) -> Result<Value, MethodError> {        if self.asked.filter.is_empty() && !self.asked.handed && kept::key(self.asked, &self.held.definition, "").is_some() {            let mut asked = args.clone();            asked.insert("page".into(), json!(page));            asked.insert("limit".into(), json!(limit));            let own = crate::methods::shell_kept::stores(&self.held.definition);            let at = crate::methods::shell_plan::At { bus: &self.held.bus, moved: self.held.moved, own: &own, aside: &self.held.aside };            if let Some(answer) = crate::methods::shell_plan::page(at, &asked, &self.today_key(), &|ask| (self.native)("records.list", ask))? {                return Ok(answer);            }        }        self.page(args, page, limit)    }    /// Todos read as their day plan: Today paged by the cursor, each day    /// ahead the plan counts read whole on the first page, and every other    /// section the plan counts shut under its heading with its whole count.    /// Asked with `section`, that section alone, open, paged.    fn todo_plan(&self) -> Result<(Vec<Section>, usize, Option<usize>, Planned), MethodError> {        let definition = &self.held.definition;        let upcoming = definition.upcoming.as_ref().expect("a planned list");        let asked = self.asked;        let mut base = self.base();        let key = asked.section.clone().unwrap_or_else(|| "today".to_string());        base.insert("section".into(), json!(plan_section(&key)));        if let Some(day) = key.strip_prefix("day:") { base.insert("day".into(), json!(day)); }        let answer = self.plan_page(&base, asked.cursor, asked.limit)?;        let rows = answer["records"].as_array().cloned().unwrap_or_default();        let plan: Vec<(String, u64)> = answer["sections"].as_array().into_iter().flatten().filter_map(|section| {            let count = section["count"].as_u64()?;            let key = match section["day"].as_str() {                Some(day) => format!("day:{day}"),                None => section["key"].as_str()?.to_string(),            };            Some((key, count))        }).collect();        let whole = |key: &str| plan.iter().find(|(held, _)| held == key).map(|(_, count)| *count).unwrap_or(0);        let next = answer["next_page"].as_u64().map(|next| next as usize);        let count = plan.iter().map(|(_, count)| *count as usize).sum::<usize>().max(asked.cursor + rows.len());        let heading = |key: &str, rows: &[Value]| -> Option<String> {            match key {                "today" => Some(line("dates", "heading.today", &self.held.lines, &[])),                "late" => upcoming.late.clone(),                "later" => upcoming.later.clone(),                "undated" => upcoming.undated.clone(),                _ if key.starts_with("day:") => {                    let parts = rows.first().map(|row| &row["data"][cotton_core::records::page::SLIP_DAY_KEY]).cloned().unwrap_or(Value::Null);                    day_heading(key.trim_start_matches("day:"), &parts, &self.today_key(), &self.held.lines)                }                _ => definition.group.as_ref().and_then(|group| group.sections.as_ref())                    .and_then(|sections| sections.iter().find(|section| section.values.first().is_some_and(|value| value.to_lowercase() == key)))                    .and_then(|section| section.heading.clone()),            }        };        if asked.section.is_some() {            // One section asked alone: open, its whole count.            let mut section = Section::new(key.clone(), heading(&key, &rows), rows);            section.count = Some(whole(&key));            let sections = if section.rows.is_empty() { Vec::new() } else { vec![section] };            return Ok((sections, whole(&key) as usize, next, Planned::default()));        }        let mut sections = Vec::new();        if !rows.is_empty() {            let mut today = Section::new("today", heading("today", &rows), rows);            today.count = Some(whole("today"));            sections.push(today);        }        if asked.cursor > 0 {            return Ok((sections, count, next, Planned::default()));        }        let shut = |key: &str, sections: &mut Vec<Section>| {            let held = whole(key);            if held == 0 { return; }            let mut section = Section::new(key, heading(key, &[]), Vec::new());            section.folds = true;            section.open = false;            section.count = Some(held);            if let Some(note) = definition.group.as_ref().and_then(|group| group.sections.as_ref())                .and_then(|groups| groups.iter().find(|group| group.heading == section.heading)).and_then(|group| group.note.clone()) {                section.note = Some(note);            }            sections.push(section);        };        if upcoming.late.is_some() { shut("late", &mut sections); }        // Each day ahead, read whole off the plan (`readAhead`).        for (key, held) in plan.iter().filter(|(key, held)| key.starts_with("day:") && *held > 0) {            let mut args = base.clone();            args.insert("section".into(), json!("day"));            args.insert("day".into(), json!(key.trim_start_matches("day:")));            let rows = match self.plan_page(&args, 0, cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE as usize)? {                answer if answer["next_page"].is_null() => answer["records"].as_array().cloned().unwrap_or_default(),                _ => self.every_row(&args)?.0,            };            let mut section = Section::new(key.clone(), heading(key, &rows), rows);            section.count = Some(*held);            sections.push(section);        }        if upcoming.later.is_some() { shut("later", &mut sections); }        if upcoming.undated.is_some() { shut("undated", &mut sections); }        for (key, _) in plan.iter().filter(|(key, _)| !["today", "late", "later", "undated"].contains(&key.as_str()) && !key.starts_with("day:")) {            shut(key, &mut sections);        }        Ok((sections, count, next, Planned::default()))    }    /// A list split into days read as its plan: what is coming, today and    /// after, each day under its heading — or, with nothing coming and a past,    /// what is earlier, newest first. `section: earlier` reads the past.    fn calendar_plan(&self) -> Result<(Vec<Section>, usize, Option<usize>, Planned), MethodError> {        let asked = self.asked;        let key = self.held.definition.day_grouping.clone().expect("a day-split list");        let mut base = self.base();        let section = asked.section.clone().unwrap_or_else(|| "coming".to_string());        base.insert("section".into(), json!(section));        let mut answer = self.page(&base, asked.cursor, asked.limit)?;        let counted = |answer: &Value, key: &str| -> u64 {            answer["sections"].as_array().into_iter().flatten().filter(|held| held["key"] == key).filter_map(|held| held["count"].as_u64()).sum()        };        let mut reading = section.clone();        if asked.section.is_none() && asked.cursor == 0 && counted(&answer, "coming") == 0 && counted(&answer, "earlier") > 0 {            base.insert("section".into(), json!("earlier"));            answer = self.page(&base, asked.cursor, asked.limit)?;            reading = "earlier".to_string();        }        let rows = answer["records"].as_array().cloned().unwrap_or_default();        let count = counted(&answer, &reading) as usize;        let next = answer["next_page"].as_u64().map(|next| next as usize);        let planned = Planned { earlier: if reading == "coming" { counted(&answer, "earlier") } else { 0 }, headings: None, index: None };        Ok((grouped_days(&key, rows, &self.today_key(), &self.held.lines), count.max(asked.cursor), next, planned))    }}/// The plan's own name for a section key: `day:<d>` is read as `day`.fn plan_section(key: &str) -> &str {    if key.starts_with("day:") { "day" } else { key }}/// Whether a list is read as its table's day plan: unnarrowed, or one group's/// page of a planned table (the core reads it by the plan over every member).fn planned_list(definition: &TableDefinition, filter: &Map<String, Value>) -> bool {    let planned = definition.upcoming.is_some() || (definition.day_grouping.is_some() && definition.date.is_some());    planned && (filter.is_empty() || (filter.len() == 1 && filter.contains_key(GROUP_KEY)))}/// Whether a list's sections are cut over all of its rows.fn sections_whole(definition: &TableDefinition) -> bool {    definition.group.is_some() || definition.by_day.is_some() || definition.by_month.is_some()        || definition.index.is_some() || definition.day_grouping.is_some() || definition.upcoming.is_some()}/// A list cut over every row it holds, its rows ids and places alone.pub(super) struct Whole {    sections: Vec<Section<Cut>>,    count: usize,    headings: Vec<Option<String>>,    index: Option<Vec<Value>>,    /// What the cut read of each row beside its id, in the store's order    /// (`@at`), for the one patch that takes it (`Read::patched`); None for    /// a cut never patched.    rows: std::sync::Mutex<Option<Vec<Data>>>,    /// The head lines a page read for each group value (`Read::headed`), by    /// the value's JSON: summed over that value's rows alone, so a patch    /// keeps every value but those of the rows it moved.    heads: std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<Vec<Value>>>>,}/// The columns a whole list is cut by: its group's and its parts' due/// dates, its days, months, date and index or title. None (every column)/// where one of them is computed over the others.fn cut_columns(definition: &TableDefinition) -> Option<Vec<String>> {    let group = definition.group.as_ref();    let dues = group.and_then(|group| group.sections.as_ref()).into_iter().flatten().filter_map(|section| section.due.as_ref().map(|due| due.column.clone()));    // A cut by its group alone (no days, no index) reads the group's column alone.    let by_group_alone = group.is_some() && definition.index.is_none() && !cut_reads_days(definition);    let columns: Vec<String> = if by_group_alone { group.map(|group| group.column.clone()).into_iter().collect() } else {        group.map(|group| group.column.clone()).into_iter().chain(dues)            .chain([definition.by_day.clone(), definition.by_month.clone(), definition.date.clone(), definition.day_grouping.clone(), definition.index.clone(), Some(definition.title.clone())].into_iter().flatten())            .collect()    };    let computed = columns.iter().any(|key| definition.column(key).is_some_and(|column| column.computed.is_some()));    (!computed).then_some(columns)}/// Whether a list's cut reads its rows' day parts (`dress`): its days,/// months, or a group's parts by due date.fn cut_reads_days(definition: &TableDefinition) -> bool {    definition.by_day.is_some() || definition.by_month.is_some() || definition.day_grouping.is_some() || definition.upcoming.is_some()        || definition.group.as_ref().and_then(|group| group.sections.as_ref()).into_iter().flatten().any(|section| section.due.is_some())}/// A narrow cut's row (`[id, …columns]`, `columns` naming those after the/// id) as a record: `{id, data}`, a column holding nothing left out.fn narrow_row(columns: &[String], row: Value) -> Value {    let Value::Array(values) = row else { return Value::Null };    let mut values = values.into_iter();    let id = values.next().unwrap_or(Value::Null);    let data: Map<String, Value> = columns.iter().cloned().zip(values).filter(|(_, value)| !value.is_null()).collect();    json!({"id": id, "data": data})}/// A row as a whole list's cut reads it: its id, its place in the store's/// order, and its columns.struct CutRow {    id: Value,    at: usize,    data: Data,}/// A cut row's columns: a narrow cut's values by position (the columns/// shared by every row of the read), or a record's data, dressed.enum Data {    Columns(std::sync::Arc<[String]>, Vec<Value>),    Dressed(Value),}impl CutRow {    /// A narrow cut's row (`[id, …columns]`), its values kept by position.    fn of_narrow(columns: &std::sync::Arc<[String]>, row: Value) -> CutRow {        let Value::Array(mut values) = row else { return CutRow { id: Value::Null, at: 0, data: Data::Dressed(Value::Object(Map::new())) } };        let id = if values.is_empty() { Value::Null } else { values.remove(0) };        CutRow { id, at: 0, data: Data::Columns(std::sync::Arc::clone(columns), values) }    }    /// A light record (`{id, data, …}`), its id and data moved out.    fn of_record(mut record: Value) -> CutRow {        CutRow { id: record["id"].take(), at: 0, data: Data::Dressed(record["data"].take()) }    }    /// The row's data as a record holds it, to be dressed: a column holding    /// nothing left out, as the narrow cut's map always left it.    fn dressing(&mut self) -> &mut Value {        if let Data::Columns(columns, values) = &mut self.data {            let data: Map<String, Value> = columns.iter().cloned().zip(std::mem::take(values)).filter(|(_, value)| !value.is_null()).collect();            self.data = Data::Dressed(Value::Object(data));        }        match &mut self.data {            Data::Dressed(data) => data,            Data::Columns(..) => unreachable!("made dressed above"),        }    }}/// A row the sections are cut by: a record read whole, or a cut's row.trait Row {    fn id(&self) -> &Value;    /// A column's value, or null.    fn get(&self, key: &str) -> &Value;}static NOTHING: Value = Value::Null;impl Row for Value {    fn id(&self) -> &Value { &self["id"] }    fn get(&self, key: &str) -> &Value { &self["data"][key] }}impl<T: Row> Row for &T {    fn id(&self) -> &Value { (**self).id() }    fn get(&self, key: &str) -> &Value { (**self).get(key) }}impl Row for CutRow {    fn id(&self) -> &Value { &self.id }    fn get(&self, key: &str) -> &Value {        match &self.data {            Data::Columns(columns, values) => columns.iter().position(|held| held == key).and_then(|at| values.get(at)).unwrap_or(&NOTHING),            Data::Dressed(data) => &data[key],        }    }}/// Whether a whole read cuts over light rows: a table whose rows a live/// read or a day plan's own words dress is read whole as it draws.fn light_reads(definition: &TableDefinition) -> bool {    definition.live_read.is_none() && definition.upcoming.is_none()}/// `limit` rows from `cursor` across the kept cut's sections in order,/// each section keeping its heading and its whole count: only the sections/// the page reaches are taken, each row as `{id, @at}`.fn paged(sections: &[Section<Cut>], cursor: usize, limit: usize) -> Vec<Section> {    let mut at = 0usize;    let mut out = Vec::new();    for section in sections {        if at >= cursor + limit.max(1) { break; }        let held = section.rows.len();        let (from, to) = (cursor.max(at), (cursor + limit).min(at + held));        // A shut section of no rows read stands where it falls: on the page        // that reaches its place.        if held == 0 {            if section.folds && at >= cursor { out.push(section.with_rows(Vec::new())); }            continue;        }        if from < to {            let rows = section.rows[(from - at)..(to - at)].iter().map(|row| json!({"id": row.id, AT: row.at})).collect();            let mut taken = section.with_rows(rows);            if taken.count.is_none() && taken.folds { taken.count = Some(held as u64); }            out.push(taken);        }        at += held;    }    out}fn data(row: &Value) -> &Value { &row["data"] }pub(super) fn text(value: &Value) -> Option<String> {    match value {        Value::String(text) if !text.trim().is_empty() => Some(text.clone()),        Value::Number(number) => Some(number.to_string()),        Value::Bool(flag) => Some(flag.to_string()),        _ => None,    }}fn day_parts<'a, R: Row>(row: &'a R, key: &str) -> &'a Value {    &row.get(cotton_core::records::page::DAY_PARTS_KEY)[key]}/// The heads the core said for a group's value (`group_heads`).fn heads_of(answer: &Value, value: &Value) -> Vec<Value> {    answer["group_heads"].as_array().into_iter().flatten()        .find(|head| &head["value"] == value || (value.is_null() && head["value"].as_str() == Some("")))        .and_then(|head| head["lines"].as_array().cloned()).unwrap_or_default()}/// The `group` sections, runs or due parts; one section without a group.fn grouped<R: Row>(definition: &TableDefinition, rows: Vec<R>, first: &Value, today: &str) -> Vec<Section<R>> {    let Some(group) = &definition.group else {        let mut section = Section::new(ALL, None, rows);        section.lines = heads_of(first, &Value::Null).into();        return if section.rows.is_empty() { Vec::new() } else { vec![section] };    };    let Some(sections) = group.sections.as_ref().filter(|sections| !sections.is_empty()) else {        // Runs of one column's value, unheaded, as the list reads; each        // run's head found by its value, not by a walk of the heads per run.        let heads: std::collections::HashMap<String, std::sync::Arc<Vec<Value>>> = first["group_heads"].as_array().into_iter().flatten()            .rev().map(|head| (head["value"].to_string(), std::sync::Arc::new(head["lines"].as_array().cloned().unwrap_or_default()))).collect();        // With no heads read (a page reads its own), every run shares none.        let none: std::sync::Arc<Vec<Value>> = Default::default();        let head = |value: &Value| if heads.is_empty() { std::sync::Arc::clone(&none) } else {            heads.get(&value.to_string()).or_else(|| value.is_null().then(|| heads.get(&json!("").to_string())).flatten()).cloned().unwrap_or_default()        };        let mut out: Vec<Section<R>> = Vec::new();        for row in rows {            let value = row.get(&group.column);            match out.last_mut() {                Some(run) if run.head.as_ref() == Some(value) => run.rows.push(row),                _ => {                    let value = value.clone();                    let mut run = Section::new(format!("run:{}", out.len()), None, vec![row]);                    run.lines = head(&value);                    run.head = Some(value);                    out.push(run);                }            }        }        return out;    };    let place = |value: Option<&str>| -> (usize, usize) {        for (index, section) in sections.iter().enumerate() {            if let Some(rank) = value.and_then(|value| section.values.iter().position(|held| held == value)) { return (index, rank); }        }        (0, sections[0].values.len())    };    let mut held: Vec<Vec<(usize, usize, R)>> = (0..sections.len()).map(|_| Vec::new()).collect();    for (offset, row) in rows.into_iter().enumerate() {        let (at, rank) = place(row.get(&group.column).as_str());        held[at].push((rank, offset, row));    }    let mut out = Vec::new();    for (index, (section, mut rows)) in sections.iter().zip(held).enumerate() {        if rows.is_empty() { continue; }        rows.sort_by_key(|(rank, offset, _)| (*rank, *offset));        let rows: Vec<R> = rows.into_iter().map(|(_, _, row)| row).collect();        let id = section.values.first().map(|value| value.to_lowercase()).unwrap_or_else(|| format!("group:{index}"));        let value = section.values.first().map(|value| json!(value)).unwrap_or(Value::Null);        match &section.due {            Some(due) => {                // Owed from a day gone, due by the month's end, after, undated.                let month = today.get(..7).unwrap_or_default();                let mut parts: [Vec<R>; 4] = Default::default();                for row in rows {                    let day = day_parts(&row, &due.column)["day"].as_str().map(str::to_string);                    let at = match day {                        None => 3,                        Some(day) if day.as_str() < today => 0,                        Some(day) if day.get(..7).unwrap_or_default() <= month => 1,                        Some(_) => 2,                    };                    parts[at].push(row);                }                for ((part, heading), rows) in ["late", "soon", "later", "undated"].iter().zip([&due.late, &due.soon, &due.later, &due.undated]).zip(parts) {                    if rows.is_empty() { continue; }                    out.push(Section::new(format!("{id}:{part}"), Some(heading.clone()), rows));                }            }            None => {                let mut drawn = Section::new(id, section.heading.clone(), rows);                drawn.folds = section.closed == Some(true) && section.heading.is_some();                drawn.open = !drawn.folds;                drawn.note = section.note.clone();                drawn.lines = heads_of(first, &value).into();                drawn.head = Some(value);                out.push(drawn);            }        }    }    out}/// A list split by its `by_day` column: one section per day, newest first,/// headed by the day; the undated last, under no heading. A moment stands/// under its own day on the reader's clock.fn day_sections<R: Row>(definition: &TableDefinition, by_day: &str, rows: Vec<R>, today: &str, lines: &[LineRow]) -> Vec<Section<R>> {    let mut days: Vec<(String, String, Vec<R>)> = Vec::new();    let mut undated = Vec::new();    for row in rows {        let moment = definition.date.as_deref().filter(|date| row.get(date).as_str().is_some_and(|text| text.len() > 10));        let parts = day_parts(&row, moment.unwrap_or(by_day));        let Some(day) = parts["day"].as_str() else {            undated.push(row);            continue;        };        let heading = day_heading(day, parts, today, lines).unwrap_or_default();        match days.iter_mut().find(|(held, _, _)| held == day) {            Some((_, _, rows)) => rows.push(row),            None => days.push((day.to_string(), heading.to_string(), vec![row])),        }    }    days.sort_by(|a, b| b.0.cmp(&a.0));    let mut out: Vec<Section<R>> = days.into_iter().map(|(day, heading, rows)| Section::new(format!("day:{day}"), Some(heading), rows)).collect();    if !undated.is_empty() { out.push(Section::new("undated", None, undated)); }    out}/// The heading over a day's rows, on the reader's day (`today`): Today,/// Tomorrow, Yesterday, else the weekday date the core said ("Tue 6 Oct").fn day_heading(day: &str, parts: &Value, today: &str, lines: &[LineRow]) -> Option<String> {    let near = |offset: i64| chrono::NaiveDate::parse_from_str(today, "%Y-%m-%d").ok()        .map(|today| (today + chrono::Duration::days(offset)).format("%Y-%m-%d").to_string());    for (offset, name) in [(0, "heading.today"), (1, "heading.tomorrow"), (-1, "heading.yesterday")] {        if near(offset).as_deref() == Some(day) { return Some(line("dates", name, lines, &[])); }    }    parts["weekday_date"].as_str().or(parts["heading"].as_str()).map(str::to_string)}/// A list split into days by its `day_grouping` date: today, the days after/// in time order, the days gone newest first (their rows too), the undated.fn grouped_days<R: Row>(key: &str, rows: Vec<R>, today: &str, lines: &[LineRow]) -> Vec<Section<R>> {    let mut days: Vec<(String, Option<String>, Vec<R>)> = Vec::new();    for row in rows {        let parts = day_parts(&row, key);        let day = parts["day"].as_str().unwrap_or_default().to_string();        let heading = day_heading(&day, parts, today, lines);        match days.iter_mut().find(|(held, _, _)| *held == day) {            Some((_, _, rows)) => rows.push(row),            None => days.push((day, heading, vec![row])),        }    }    let rank = |day: &str| if day == today { 0 } else if day.is_empty() { 3 } else if day > today { 1 } else { 2 };    days.sort_by(|a, b| rank(&a.0).cmp(&rank(&b.0)).then_with(|| if rank(&a.0) == 2 { b.0.cmp(&a.0) } else { a.0.cmp(&b.0) }));    days.into_iter().map(|(day, heading, mut rows)| {        if rank(&day) == 2 {            rows.sort_by(|a, b| b.get(key).as_str().unwrap_or_default().cmp(a.get(key).as_str().unwrap_or_default()));        }        if day.is_empty() {            Section::new("undated", Some(line("dates", "undated", lines, &[])), rows)        } else {            Section::new(format!("day:{day}"), heading, rows)        }    }).collect()}/// A list split by its `by_month` column: by `months`, every month once it/// holds more than `over`; else runs of a month once it holds more than a/// dozen over more than one month. Shorter, one unheaded section.fn month_sections<R: Row>(definition: &TableDefinition, rows: Vec<R>) -> Vec<Section<R>> {    let by_month = definition.by_month.as_deref().unwrap_or_default();    let over = definition.months.as_ref().and_then(|months| months.over).map(|over| over as usize).unwrap_or(MONTHS_OVER);    if rows.len() <= over {        return vec![Section::new(ALL, None, rows)];    }    let every = definition.months.is_some();    let mut runs: Vec<(String, Option<String>, Vec<R>)> = Vec::new();    let mut undated = Vec::new();    for row in rows {        let parts = day_parts(&row, by_month);        let month = parts["month"].as_str().map(str::to_string);        let title = parts["month_title"].as_str().map(str::to_string);        match (month, every) {            (None, true) => undated.push(row),            (Some(month), true) => match runs.iter_mut().find(|(held, _, _)| *held == month) {                Some((_, _, rows)) => rows.push(row),                None => runs.push((month, title, vec![row])),            },            (month, false) => {                let key = month.clone().or_else(|| runs.last().map(|run| run.0.clone())).unwrap_or_default();                match runs.last_mut() {                    Some(run) if run.0 == key => run.2.push(row),                    _ => runs.push((key, title, vec![row])),                }            }        }    }    if !every && runs.iter().map(|run| &run.0).collect::<std::collections::HashSet<_>>().len() <= 1 {        return vec![Section::new(ALL, None, runs.into_iter().flat_map(|run| run.2).collect())];    }    let mut out: Vec<Section<R>> = Vec::new();    for (month, title, rows) in runs {        let mut id = format!("month:{month}");        if out.iter().any(|held| held.id == id) { id = format!("{id}:{}", out.len()); }        out.push(Section::new(id, title, rows));    }    if !undated.is_empty() {        out.push(Section::new("undated", definition.months.as_ref().and_then(|months| months.undated.clone()), undated));    }    out}/// A list of work still to do searched (no plan): split by the day each row/// is next due as the core filed it (`@slip_day`), the late shut after today.fn upcoming_sections<R: Row>(definition: &TableDefinition, rows: Vec<R>, today: &str, lines: &[LineRow]) -> Vec<Section<R>> {    let upcoming = definition.upcoming.as_ref().expect("an upcoming list");    let mut days: Vec<(String, Option<String>, Vec<R>)> = Vec::new();    let (mut late, mut undated) = (Vec::new(), Vec::new());    for row in rows {        let parts = row.get(cotton_core::records::page::SLIP_DAY_KEY);        let Some(day) = parts["day"].as_str().map(str::to_string) else { undated.push(row); continue };        if upcoming.late.is_some() && day.as_str() < today { late.push(row); continue; }        let day = if day.as_str() < today { today.to_string() } else { day };        let heading = day_heading(&day, parts, today, lines);        match days.iter_mut().find(|(held, _, _)| *held == day) {            Some((_, _, rows)) => rows.push(row),            None => days.push((day, heading, vec![row])),        }    }    days.sort_by(|a, b| a.0.cmp(&b.0));    let mut out: Vec<Section<R>> = days.into_iter().map(|(day, heading, rows)| {        Section::new(if day == today { "today".to_string() } else { format!("day:{day}") }, heading, rows)    }).collect();    let shut = |id: &str, heading: Option<String>, rows: Vec<R>| {        let mut section = Section::new(id, heading, rows);        section.folds = section.heading.is_some();        section.open = !section.folds;        section    };    if !late.is_empty() {        let at = usize::from(out.first().is_some_and(|section| section.id == "today"));        out.insert(at, shut("late", upcoming.late.clone(), late));    }    if !undated.is_empty() { out.push(shut("undated", upcoming.undated.clone(), undated)); }    out}/// The rows in runs by letter, in rail order (A–Z, then `#`), each run in/// name order with case and accents folded; ties keep their order.fn letter_runs<R: Row>(definition: &TableDefinition, rows: Vec<R>) -> Vec<R> {    let key = definition.index.clone().unwrap_or_else(|| definition.title.clone());    let mut named: Vec<(String, String, usize, R)> = rows.into_iter().enumerate().map(|(offset, row)| {        let name = text(row.get(&key)).unwrap_or_default();        (letter_of(&name), folded(&name), offset, row)    }).collect();    let rank = |letter: &str| if letter == OTHER_LETTER { 26 } else { letter.as_bytes()[0] - b'A' };    named.sort_by(|a, b| rank(&a.0).cmp(&rank(&b.0)).then_with(|| a.1.cmp(&b.1)).then_with(|| a.2.cmp(&b.2)));    named.into_iter().map(|(_, _, _, row)| row).collect()}/// The letter a name files under: its first letter, case and accents folded, or `#`.fn letter_of(name: &str) -> String {    match folded(name).chars().next() {        Some(first) if first.is_ascii_alphabetic() => first.to_ascii_uppercase().to_string(),        _ => OTHER_LETTER.to_string(),    }}fn folded(name: &str) -> String {    cotton_core::rules::ink_match::fold(name.trim())}/// The index rail's landings: each letter's first row and its place in the/// whole list (the cursor that reaches it). Only a list with an `index`,/// unsearched and no view's, read whole.fn landings<R: Row>(definition: &TableDefinition, sections: &[Section<R>], asked: &Asked) -> Option<Vec<Value>> {    definition.index.as_ref().filter(|_| asked.query.is_none() && asked.view.is_none())?;    let key = definition.index.clone().unwrap_or_default();    let mut out: Vec<Value> = Vec::new();    for (at, row) in sections.iter().flat_map(|section| section.rows.iter()).enumerate() {        let letter = letter_of(&text(row.get(&key)).unwrap_or_default());        if !out.iter().any(|held| held["letter"] == letter.as_str()) {            out.push(json!({"letter": letter, "row": row.id(), "at": at}));        }    }    Some(out)}// MARK: One rowfn row_of(held: &Held, asked: &Asked, reading: &Reading, row: &Value, reorders: bool, acts: &mut Map<String, Value>) -> Result<Value, MethodError> {    let definition = &held.definition;    let id = row["id"].as_str().unwrap_or_default().to_string();    let record = data(row).as_object().cloned().unwrap_or_default();    let mut press: Vec<Value> = Vec::new();    let (tap, offered) = if asked.pick.is_some() {        acts.entry("pick".to_string()).or_insert_with(|| json!({"label": line("lists", "select", &held.lines, &[]), "kind": "toggle", "red": false}));        ("pick".to_string(), Vec::new())    } else {        let opening = crate::methods::shell_deck::opening(definition, "", &record);        let open = format!("open.{opening}");        acts.entry(open.clone()).or_insert_with(|| json!({"label": line("cards", &format!("deck.open.{opening}"), &held.lines, &[]), "kind": "open", "red": false}));        let mut ids = Vec::new();        if !reorders {            for act in card_actions::opened(definition, &record, &held.lines, card_actions::Held { face: None, blank: false }, held.tools.clone()) {                ids.push(act.id.clone());                let kind = serde_json::to_value(act.kind).map_err(|why| MethodError::new("unreadable", why.to_string()))?;                if act.step.is_none() { press.push(press_act(definition, &act, &held.lines)?); }                acts.entry(act.id).or_insert_with(|| json!({"label": act.label, "kind": kind, "red": act.red, "primary": act.primary, "icon": act.icon}));            }        }        if asked.archived && brings_back(definition, &record) {            let label = line("lists", "bring_back", &held.lines, &[]);            acts.entry("bring_back".to_string()).or_insert_with(|| json!({"label": label, "kind": "write", "red": false}));            ids.push("bring_back".to_string());            press.push(json!({"id": "bring_back", "label": label, "kind": "write", "rank": "more", "primary": false, "red": false,                              "write": archive_write(definition, false, held.now)}));        }        // A table put away by its archive column, with no act of its own        // that archives: its press archives it, asked first.        if !asked.archived && !reorders && archives_by_hand(definition, &record) && !press.iter().any(|act| act["id"] == "archive") {            let name = definition.name.to_lowercase();            let beside = if press.iter().any(|act| act["id"] == "bin") { line("definitions", "offers.archive_beside_delete", &held.lines, &[]) } else { String::new() };            let at = press.iter().position(|act| act["red"] == true).unwrap_or(press.len());            press.insert(at, json!({"id": "archive", "label": line("definitions", "offers.archive", &held.lines, &[("name", &name)]), "kind": "write",                "rank": "more", "primary": false, "red": false, "icon": "act-archive", "write": archive_write(definition, true, held.now),                "question": {"title": line("definitions", "offers.archive_question", &held.lines, &[("name", &name)]),                             "message": line("definitions", "offers.archive_question_body", &held.lines, &[("plural", &definition.plural), ("beside", &beside)]),                             "confirm": line("definitions", "offers.archive_confirm", &held.lines, &[])}}));        }        (open, ids)    };    // The row is the record's one answer (`shell_slip`), with its acts beside it.    let said = shell_slip::said_of(reading, row);    let mut slip = said["slip"].clone();    if let Some(words) = slip.as_object_mut() { words.remove("trailing"); }    let mut whole = row.clone();    whole["data"][shell_slip::SAID_KEY] = said.clone();    slip["record"] = whole;    let mut answer = json!({        "id": id,        "slip": slip,        "toggled": said.get("toggled"),        "toggle": said.get("toggle"),        "dimmed": said["dimmed"],        "stamp": said.get("stamp"),        "held": asked.pick.as_ref().map(|pick| pick.held.contains(&id)),        "deletes": said["deletes"],        "acts": offered, "press": press, "tap": tap,    });    if asked.pick.is_none() {        answer["opens"] = crate::phone::routes::opens(definition, &id, &record, "", &|table| held.tables.definitions.iter().find(|found| found.id == table).cloned());    }    if let Some(answer) = answer.as_object_mut() { answer.retain(|_, value| !value.is_null()); }    Ok(answer)}/// One act of a row's long press, whole as `shell.opened` answers it (its/// address, its tool's words), with the question a command asks first: a/// delete, a destructive or destroying command, one that says `confirm` —/// asked in its label, its `confirm` words else the record line's.fn press_act(definition: &TableDefinition, act: &CardAction, lines: &[LineRow]) -> Result<Value, MethodError> {    use cotton_core::definitions::{CommandDoes, CommandKind};    let mut said = serde_json::to_value(act).map_err(|why| MethodError::new("unreadable", why.to_string()))?;    let command = (act.kind == card_actions::ActionKind::Command)        .then(|| definition.commands.iter().flatten().find(|command| command.id == act.id)).flatten();    if let Some(command) = command.filter(|command| command.kind == CommandKind::Delete || command.destructive == Some(true)        || command.confirm.is_some() || command.does == Some(CommandDoes::Destroys)) {        let message = command.confirm.clone().unwrap_or_else(|| line("record", "changes_your_copy", lines, &[]));        said["question"] = json!({"title": command.label, "message": message, "confirm": command.label});    }    Ok(said)}/// Whether the slips under day headings say their time alone (the core's rule).fn day_headed(definition: &TableDefinition, asked: &Asked) -> bool {    (definition.day_grouping.is_some() || definition.by_day.is_some())        && matches!(asked.section.as_deref(), None | Some("coming" | "earlier" | "today" | "day"))}/// Whether a live record is archived by a hand's write of its archive column/// (a note's `archived_at`), the bin's column aside.fn archives_by_hand(definition: &TableDefinition, record: &Map<String, Value>) -> bool {    use cotton_core::definitions::ColumnType;    let Some(column) = definition.archived.as_deref().filter(|key| *key != "trashed_at").and_then(|key| definition.column(key)) else { return false };    column.readonly != Some(true) && matches!(column.column_type, ColumnType::Date | ColumnType::Bool) && !record.get(&column.key).is_some_and(set)}/// The write that puts a record away (`archive`) or brings it back: its/// archive column set to now (a date) or true, or cleared.fn archive_write(definition: &TableDefinition, archive: bool, now: chrono::DateTime<chrono::Utc>) -> Value {    use cotton_core::definitions::ColumnType;    let Some(column) = definition.archived.as_deref().and_then(|key| definition.column(key)) else { return Value::Null };    let value = match (&column.column_type, archive) {        (ColumnType::Bool, archive) => json!(archive),        (_, true) => json!(now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)),        (_, false) => Value::Null,    };    json!({ (column.key.clone()): value })}/// Whether an archived record can be brought back from its list.fn brings_back(definition: &TableDefinition, record: &Map<String, Value>) -> bool {    let Some(column) = definition.archived.as_deref().filter(|key| *key != "trashed_at").and_then(|key| definition.column(key)) else { return false };    column.readonly != Some(true) && record.get(&column.key).is_some_and(set)}/// `deleting: [id]` — Select's Delete over the records picked, in the/// table's words: which of them it takes (`ids`, those whose row `deletes`,/// in the order picked), whether it asks first, the question, the act's/// word, the receipt's words over them all (`done`) and its undone words; with/// `failed: [id]` (those the store refused), what is said after (`outcome`).fn deleting(held: &Held, request: &Value, picked: &Value, native: Native) -> Result<Value, MethodError> {    let definition = &held.definition;    let lines = &held.lines;    let asked: Vec<String> = picked.as_array().ok_or_else(|| bad("deleting is the ids picked"))?.iter()        .map(|id| id.as_str().map(str::to_string).ok_or_else(|| bad("deleting is the ids picked"))).collect::<Result<_, _>>()?;    let read = native("records.list", &json!({"table": definition.id, "ids": asked}))?;    let rows: Vec<&Value> = asked.iter().filter_map(|id| read["records"].as_array().into_iter().flatten().find(|row| row["id"] == id.as_str())).collect();    let taken: Vec<&Value> = rows.into_iter().filter(|row| deletes(definition, data(row).as_object().unwrap_or(&Map::new()))).collect();    let n = taken.len();    let deletion = definition.deletion.as_ref();    let word = deletion.and_then(|words| words.label.clone()).unwrap_or_else(|| line("definitions", "select.delete", lines, &[]));    let name = definition.name.to_lowercase();    let plural = definition.plural.to_lowercase();    let number = shell_lines::number(n as i64);    let kind_of = |row: &Value| -> String {        definition.count_words.as_ref().and_then(|words| data(row)[&words.column].as_str().and_then(|value| words.units.get(value)))            .map(|units| units.one.clone()).unwrap_or_else(|| name.clone())    };    let question = match deletion {        Some(words) if n > 0 => {            let title = if n == 1 {                line("definitions", "select.delete_one", lines, &[("verb", &word), ("kind", &kind_of(taken[0]))])            } else {                let counts = count_line(definition, &taken).join(&line("definitions", "select.and", lines, &[]));                line("definitions", "select.delete_many", lines, &[("verb", &word), ("counts", &counts)])            };            let mut said: Vec<String> = Vec::new();            if let Some(size) = &words.size {                let bytes: f64 = taken.iter().filter_map(|row| data(row)[size].as_f64()).sum();                if bytes > 0.0 { said.push(cotton_core::records::page::bytes_words(bytes)); }            }            if words.bin == Some(true) {                let reach = if request["bin_shown"] == true { "shown" } else { "hidden" };                said.push(line("bin", &format!("deleted.{reach}.{}", if n == 1 { "one" } else { "many" }), lines, &[("plural", &definition.plural)]));            }            if let Some(sentence) = if n == 1 { words.one.clone() } else { words.other.clone().or_else(|| words.one.clone()) } { said.push(sentence); }            if words.undo == Some(true) { said.push(line("definitions", "select.undo_brings_back", lines, &[])); }            json!({"title": title, "message": said.join("\n"), "confirm": words.confirm.clone().unwrap_or_else(|| word.clone()), "cancel": words.cancel})        }        _ => {            let title = if n == 1 { line("lists", "delete.one", lines, &[("kind", &name)]) } else { line("lists", "delete.many", lines, &[("n", &number), ("plural", &plural)]) };            json!({"title": title, "message": "", "confirm": line("lists", "delete.confirm", lines, &[]), "cancel": deletion.and_then(|words| words.cancel.clone())})        }    };    let verb = if word == line("definitions", "select.delete", lines, &[]) { line("definitions", "select.deleted", lines, &[]) } else { line("definitions", "select.removed", lines, &[]) };    let failed = request["failed"].as_array().map(Vec::len).unwrap_or(0);    let outcome = if failed == 0 {        line("definitions", "select.outcome", lines, &[("n", &number), ("verb", &verb)])    } else {        line("definitions", "select.outcome_failed", lines, &[("failed", &failed.to_string()), ("total", &(n + failed).to_string()), ("verb", &verb)])    };    let mut answer = json!({"table": definition.id, "deleting": {        "ids": taken.iter().map(|row| row["id"].clone()).collect::<Vec<_>>(),        "asks": deletion.and_then(|words| words.asks) != Some(false),        "word": word, "question": question,        "done": line("lists", "delete.done", lines, &[("n", &number), ("plural", &plural)]),        "undone": line("record", "restored", lines, &[("n", &number)]),        "outcome": outcome,    }});    if let Some(question) = answer["deleting"]["question"].as_object_mut() { question.retain(|_, value| !value.is_null()); }    Ok(answer)}/// The records counted by the table's `count_words` ("3 photos", "1 video"),/// in its order, the rest under the table's own name ("2 todos").fn count_line(definition: &TableDefinition, rows: &[&Value]) -> Vec<String> {    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();    let mut rest = 0usize;    let Some(words) = &definition.count_words else {        return vec![format!("{} {}", rows.len(), if rows.len() == 1 { definition.name.to_lowercase() } else { definition.plural.to_lowercase() })];    };    for row in rows {        match data(row)[&words.column].as_str().filter(|value| words.units.get(value).is_some()) {            Some(value) => *counts.entry(value.to_string()).or_default() += 1,            None => rest += 1,        }    }    let order: Vec<String> = words.order.clone()        .or_else(|| definition.column(&words.column).and_then(|column| column.choices.clone()))        .unwrap_or_else(|| { let mut keys: Vec<String> = words.units.iter().map(|(key, _)| key.clone()).collect(); keys.sort(); keys });    let mut parts: Vec<String> = order.iter().filter_map(|value| {        let n = *counts.get(value)?;        let units = words.units.get(value)?;        Some(format!("{n} {}", if n == 1 { &units.one } else { &units.other }))    }).collect();    if rest > 0 { parts.push(format!("{rest} {}", if rest == 1 { definition.name.to_lowercase() } else { definition.plural.to_lowercase() })); }    if parts.is_empty() { parts.push("0".to_string()); }    parts}pub(super) fn blank(value: &Value) -> bool {    match value {        Value::Null => true,        Value::String(text) => text.trim().is_empty(),        Value::Array(items) => items.is_empty(),        _ => false,    }}pub(super) fn set(value: &Value) -> bool { value != &json!(false) && !blank(value) }/// Whether a long press drags: the table has an order a hand writes, and the/// list is the whole of it (or one group's page, which drags the group's).fn reorders(definition: &TableDefinition, asked: &Asked, group_page: bool) -> bool {    if definition.order.is_none() || definition.listed_when.is_some() || asked.query.is_some() || asked.pick.is_some() || asked.view.is_some() { return false; }    let archives = definition.archived.as_deref().is_some_and(|key| key != "trashed_at");    if definition.archived.is_some() && !(asked.archived || archives) { return false; }    if group_page {        return definition.upcoming.is_none() && definition.day_grouping.is_none();    }    definition.reorder.unwrap_or_else(|| definition.order.as_deref().and_then(|order| definition.column(order)).is_none_or(|column| column.readonly != Some(true)))}// MARK: The list around its rows/// The title: a tool's home list unnarrowed is the tool's name; a list/// narrowed to linked records names them ("Sessions · Cotton") while that/// fits one line; else the plural.fn title(held: &Held, asked: &Asked, native: Native) -> Result<String, MethodError> {    let definition = &held.definition;    if asked.filter.is_empty() {        if let Some(tool) = &definition.tool { return Ok(tool.name.clone()); }    }    let mut names = Vec::new();    for column in definition.columns.iter().filter(|column| column.link_to.is_some()) {        let ids: Vec<String> = match asked.filter.get(&column.key) {            Some(Value::String(id)) => vec![id.clone()],            Some(Value::Array(ids)) => ids.iter().filter_map(|id| id.as_str().map(str::to_string)).collect(),            _ => continue,        };        let table = column.link_to.clone().unwrap_or_default();        let Some(linked) = held.tables.definitions.iter().find(|found| found.id == table) else { continue };        let read = native("records.list", &json!({"table": table, "ids": ids}))?;        for row in read["records"].as_array().into_iter().flatten() {            if let Some(name) = text(&row["data"][&linked.title]) { names.push(name); }        }    }    let joined = format!("{} · {}", definition.plural, names.join(" · "));    Ok(if names.is_empty() || joined.chars().count() > 24 { definition.plural.clone() } else { joined })}/// Each link's count, by its label: a list link's from its read's total, a/// menu link's the same — a menu line onto this list's own table,/// unnarrowed, counts nothing (the list already shows that number).fn link_counts(held: &Held, native: Native) -> Result<Map<String, Value>, MethodError> {    let definition = &held.definition;    let mut counts = Map::new();    for link in definition.links.iter().flatten() {        if !held.tables.definitions.iter().any(|table| table.id == link.table) { continue; }        let filter = link.where_.as_ref().map(|filter| serde_json::to_value(filter).unwrap_or(Value::Null)).unwrap_or(Value::Null);        if link.path.is_some() && link.table == definition.id && filter.as_object().is_none_or(Map::is_empty) { continue; }        let mut asked = json!({"table": link.table, "count_only": true});        if filter.as_object().is_some_and(|filter| !filter.is_empty()) { asked["where"] = filter; }        if let Ok(read) = native("records.list", &asked) {            if let Some(total) = read["total"].as_u64() { counts.insert(link.label.clone(), json!(total)); }        }    }    Ok(counts)}/// The links drawn on the list: each list link (one with no `path`) that/// counts something or whose list takes an add; a planned list's past/// ("Earlier · n"); what this read finds archived ("Archived · n").fn links(held: &Held, asked: &Asked, counts: &Map<String, Value>, planned: &Planned, native: Native) -> Result<Vec<Value>, MethodError> {    let definition = &held.definition;    if asked.pick.is_some() { return Ok(Vec::new()); }    let mut out = Vec::new();    // A list narrowed by a `where` is another list's part: the table's own    // links belong on its whole list, never inside a list (R12).    if asked.query.is_none() && asked.filter.is_empty() {        for link in definition.links.iter().flatten().filter(|link| link.path.is_none()) {            let Some(target) = held.tables.definitions.iter().find(|table| table.id == link.table) else { continue };            let count = counts.get(&link.label).and_then(Value::as_u64);            if count.unwrap_or(0) == 0 && target.create.is_none() { continue; }            // The link with its count said: the definition's units, else "Senders 12".            let words = match (&link.units, count) {                (Some(units), Some(n)) if n > 0 => cotton_core::records::page::units_count_words(units, n as f64, &cotton_core::records::page::unit_without_fields).unwrap_or_else(|| link.label.clone()),                (None, Some(n)) if n > 0 => line("lists", "link.side", &held.lines, &[("label", &link.label), ("n", &shell_lines::number(n as i64))]),                _ => link.label.clone(),            };            out.push(json!({"id": format!("link:{}", link.label), "label": link.label, "words": words, "count": count, "lead": link.lead == Some(true), "above": link.above == Some(true),                "opens": {"table": link.table, "where": link.where_, "title": format!("{} · {}", link.label, definition.plural)}}));        }    }    if planned.earlier > 0 && asked.query.is_none() {        let label = line("lists", "earlier", &held.lines, &[]);        out.push(json!({"id": "earlier", "label": label, "words": line("lists", "link.count", &held.lines, &[("label", &label), ("n", &shell_lines::number(planned.earlier as i64))]), "count": planned.earlier, "lead": false, "above": true,            "opens": {"table": definition.id, "where": asked.filter, "section": "earlier", "title": format!("{label} · {}", definition.plural)}}));    }    let archives = definition.archived.as_deref().is_some_and(|key| key != "trashed_at");    if archives && !asked.archived {        let mut ask = json!({"table": definition.id, "archived": true, "limit": 0});        if !asked.filter.is_empty() { ask["where"] = Value::Object(asked.filter.clone()); }        if let Some(query) = &asked.query { ask["query"] = json!(query); }        if let Some(project) = &asked.project { ask["project"] = json!(project); }        let count = native("records.list", &ask).ok().and_then(|read| read["total"].as_u64()).unwrap_or(0);        if count > 0 {            let label = line("lists", "archived", &held.lines, &[]);            out.push(json!({"id": "archived", "label": label, "words": line("lists", "link.count", &held.lines, &[("label", &label), ("n", &shell_lines::number(count as i64))]), "count": count, "lead": false, "above": false,                "opens": {"table": definition.id, "where": asked.filter, "query": asked.query, "archived": true, "title": format!("{label} · {}", definition.plural)}}));        }    }    Ok(out)}/// The list's menu: New, Select, its related lists, its menu links counted,/// its own screens, and New group — or, on a group's page, the group's own/// acts (`tool_acts::list_acts`, the deck's own).fn menu(client: &ClientController, held: &Held, asked: &Asked, counts: &Map<String, Value>, shows_groups: bool, group_page: Option<&str>) -> Result<Vec<Value>, MethodError> {    let definition = &held.definition;    let mut items = Vec::new();    if asked.pick.is_some() { return Ok(items); }    let item = |id: String, label: String| json!({"id": id, "label": label, "red": false});    if let (Some(create), None) = (&definition.create, group_page) {        items.push(item("new".into(), create.label.clone()));    }    if definition.select.is_some() || definition.groups.is_some() {        items.push(item("select".into(), line("lists", "select", &held.lines, &[])));    }    for (at, related) in definition.related.iter().flatten().enumerate().filter(|(_, related)| related.column.is_none() && related.when.is_none()) {        let mut entry = item(format!("related:{at}"), related.label.clone());        entry["opens"] = json!({"table": related.table, "where": related.filter, "archived": related.archived == Some(true), "title": related.title, "empty": related.empty});        items.push(entry);        // A related list that takes new records offers its add beside it.        if related.new == Some(true) {            if let Some(target) = held.tables.definitions.iter().find(|table| table.id == related.table) {                let mut add = item(format!("related:{at}:new"), line("record", "related.add", &held.lines, &[("kind", &target.name.to_lowercase())]));                add["opens"] = json!({"table": related.table, "where": related.filter, "adds": true});                items.push(add);            }        }    }    if group_page.is_none() {        for link in definition.links.iter().flatten().filter(|link| link.path.is_some() && asked.filter.is_empty()) {            if !held.tables.definitions.iter().any(|table| table.id == link.table) { continue; }            let count = counts.get(&link.label).and_then(Value::as_u64).filter(|count| *count > 0);            if link.hides_empty == Some(true) && count.is_none() { continue; }            let label = match count {                None => link.label.clone(),                Some(n) => match (&link.units, &link.words) {                    (Some(units), _) => cotton_core::records::page::units_count_words(units, n as f64, &cotton_core::records::page::unit_without_fields).unwrap_or_else(|| link.label.clone()),                    (None, Some(words)) => line("lists", "link.count_words", &held.lines, &[("label", &link.label), ("n", &shell_lines::number(n as i64)), ("words", words)]),                    (None, None) => line("lists", "link.count", &held.lines, &[("label", &link.label), ("n", &shell_lines::number(n as i64))]),                },            };            let mut entry = item(format!("link:{}", link.table), label);            entry["opens"] = json!({"path": link.path});            items.push(entry);        }        for line in definition.menu.iter().flatten() {            let mut entry = item(format!("menu:{}", line.path), line.label.clone());            entry["opens"] = json!({"path": line.path});            if let Some(object) = &line.object { entry["object"] = json!(object); }            items.push(entry);        }    }    match group_page {        Some(group) => {            let view = match &asked.view {                Some(view) if view.contains("/group:") => view.clone(),                _ => format!("{}/group:{group}", definition.tool.as_ref().map(|_| definition.id.as_str()).unwrap_or(definition.id.as_str())),            };            // Its picks first: the table's records put in, the list's taken out.            let plural = definition.plural.to_lowercase();            let acted = crate::phone::tool_acts::list_acts(client, Some(&view), None)?;            if let Some(tool) = acted.first().map(|act| act["tool"].clone()) {                for (act, words, picks) in [(crate::phone::tool_acts::LIST_ADD, "add_plural", "add"), (crate::phone::tool_acts::LIST_TAKE_OUT, "remove_plural", "remove")] {                    let label = line("lists", words, &held.lines, &[("plural", &plural)]);                    items.push(json!({"id": act, "label": label, "red": false, "picks": picks,                        "act": {"id": act, "label": label, "kind": "tool", "tool": tool, "group": group}}));                }            }            let name = acted.iter().find_map(|act| act["words"]["prefill"].as_str().map(str::to_string)).unwrap_or_default();            for act in acted {                let mut entry = json!({"id": act["id"], "label": act["label"], "red": act["red"].as_bool().unwrap_or(false), "act": act});                if act["asks"] == true {                    entry["asks"] = json!(true);                    // Remove list asks in the list's words: where it goes, that its records stay.                    let elsewhere = line("bin", if asked.bin_shown { "elsewhere.shown" } else { "elsewhere.hidden" }, &held.lines, &[]);                    entry["question"] = json!({                        "title": line("lists", "group.delete_title", &held.lines, &[("group", &name)]),                        "message": line("lists", "group.delete_message", &held.lines, &[("elsewhere", &elsewhere), ("plural", &plural), ("home", &definition.plural)]),                        "confirm": line("lists", "group.delete", &held.lines, &[]),                    });                }                items.push(entry);            }        }        None if shows_groups && definition.groups.as_ref().is_some_and(|groups| groups.kept_in.is_none()) => {            let mut entry = item("group-new".into(), line("lists", "group.new", &held.lines, &[]));            entry["asks"] = json!({"words": {"hint": line("lists", "group.name", &held.lines, &[])}});            items.push(entry);        }        None => {}    }    items.iter_mut().for_each(menu_card);    Ok(items)}/// The card a menu line stands on: the object and what it does, which the/// tray colours it by (a line that takes something away is the bin, red).fn menu_card(item: &mut Value) {    let id = item["id"].as_str().unwrap_or_default();    let (object, does) = if item["red"] == true {        ("bin".to_string(), Some("destroys"))    } else if id == "new" || id.ends_with(":new") || item["picks"] == "add" {        ("edit".to_string(), None)    } else if id == "select" {        ("done".to_string(), None)    } else if id == "group-new" {        ("group".to_string(), Some("moves"))    } else {        let named = item["object"].as_str().map(str::to_string)            .or_else(|| item["act"]["icon"].as_str().map(|icon| icon.trim_start_matches("act-").to_string()));        (named.unwrap_or_else(|| "link".to_string()), Some("moves"))    };    item["object"] = json!(object);    item["does"] = json!(does);}/// The table's groups as its row of stacks: each with its count, the top of/// its pile (at most three of its records, the first wearing its words) and/// what opening it asks — a group kept as another table's record opens that/// record; any other its own page, this list narrowed to it.fn groups(held: &Held, native: Native) -> Result<Vec<Value>, MethodError> {    let definition = &held.definition;    let read = native("groups.list", &json!({"table": definition.id}))?;    let kept = definition.groups.as_ref().and_then(|groups| groups.kept_in.as_ref());    Ok(read["groups"].as_array().into_iter().flatten().map(|group| {        let top: Vec<Value> = group["top"].as_array().into_iter().flatten().take(3).map(|row| {            let data = &row["data"];            let title = text(&data[&definition.slip.title]).or_else(|| text(&data[&definition.title]));            let picture = definition.slip.photo.as_ref().and_then(|key| text(&data[key]));            let mut said = json!({"id": row["id"], "title": title, "picture": picture, "record": row});            if let Some(said) = said.as_object_mut() { said.retain(|_, value| !value.is_null()); }            said        }).collect();        let opens = match kept {            Some(kept) => json!({"table": kept.table, "id": group["id"]}),            None => json!({"table": definition.id, "where": {GROUP_KEY: group["id"]}, "title": group["name"]}),        };        json!({"id": group["id"], "name": group["name"], "count": group["count"], "picture": group["picture"], "byline": group["byline"], "top": top, "opens": opens})    }).collect())}/// The filter row: all, then each value's word; and what waits on the owner/// (the links marked `review`, summed). Null where neither is drawn.fn filter_row(held: &Held, asked: &Asked, counts: &Map<String, Value>) -> Value {    let definition = &held.definition;    if asked.pick.is_some() { return Value::Null; }    let reviews: Vec<_> = definition.links.iter().flatten().filter(|link| link.review == Some(true) && link.path.is_some()).collect();    if definition.filter.is_none() && reviews.is_empty() { return Value::Null; }    let waiting: u64 = reviews.iter().filter_map(|link| counts.get(&link.label).and_then(Value::as_u64)).sum();    let filter = definition.filter.as_ref();    let values: Vec<Value> = filter.map(|filter| {        let column = definition.column(&filter.column);        let order = filter.order.clone().or_else(|| column.and_then(|column| column.choices.clone())).unwrap_or_default();        order.iter().map(|value| json!({"value": value, "word": filter.words.as_ref().and_then(|words| words.get(value)).cloned().unwrap_or_else(|| value.clone())})).collect()    }).unwrap_or_default();    json!({        "column": filter.map(|filter| filter.column.clone()),        "all": filter.and_then(|filter| filter.all.clone()),        "tabs": filter.is_some_and(|filter| filter.tabs != Some(false)),        "values": values,        "reviews": !reviews.is_empty(),        "review": (waiting > 0).then(|| line("lists", "to_review", &held.lines, &[("n", &waiting.to_string())])),    })}/// What an empty list says: a view's own line; a search's no-match words (the/// table's, else the shell's); the definition's words, else "No <things> yet".fn empty_words(client: &ClientController, held: &Held, asked: &Asked, native: Native) -> Result<Value, MethodError> {    let definition = &held.definition;    let picture = definition.picture.as_ref().and_then(|picture| match picture {        cotton_core::definitions::ToolPicture::Asset(key) => Some(json!(key)),        _ => None,    });    let words = |title: String, message: String| {        let mut said = json!({"title": title, "message": message, "picture": picture});        if let Some(said) = said.as_object_mut() { said.retain(|_, value| !value.is_null()); }        said    };    if let Some(query) = &asked.query {        if let Some(search) = definition.empty.as_ref().and_then(|empty| empty.search.as_ref()) {            return Ok(words(search.title.clone(), search.message.clone().unwrap_or_default()));        }        return Ok(words(line("empty", "search.title", &held.lines, &[("query", query)]), line("empty", "search.message", &held.lines, &[])));    }    if let Some(view) = asked.view.as_deref().filter(|view| !view.contains("/group:")) {        if let Some((tool, id)) = view.split_once('/') {            let mut ask = json!({"tool": tool, "only": id, "timezone": asked.zone});            if let Some(today) = &asked.today { ask["today"] = today.clone(); }            let read = crate::phone::tool_views::read_with(client, &ask, &|args| native("records.list", args))?;            let empty = read["views"].as_array().and_then(|views| views.iter().find(|found| found["id"] == id)).map(|found| found["read"]["empty"].clone()).unwrap_or(Value::Null);            if let (Some(line_name), false) = (empty["line"].as_str(), empty["total"] == 0) {                let said = shell_lines::resolve("cards", line_name, &held.lines, &[("view", empty["view"].as_str().unwrap_or_default())]).unwrap_or_default();                return Ok(words(said, String::new()));            }        }    }    let (title, message) = crate::methods::shell_deck::table_empty(client, definition, &held.lines);    Ok(words(title, message))}/// A count as a heading says it.fn words_of_count(count: u64) -> String {    shell_lines::number(count as i64)}fn line(set: &str, name: &str, lines: &[LineRow], fills: &[(&str, &str)]) -> String {    shell_lines::resolve(set, name, lines, fills).unwrap_or_default()}fn named<'a>(request: &'a Value, key: &str) -> Option<&'a str> {    request.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}#[path = "shell_list_kept.rs"]mod kept;#[cfg(test)]#[path = "shell_list_tests.rs"]mod tests;#[cfg(not(test))]mod tests {    /// Never wide outside tests: a whole cut is read narrow where it can be.    pub(super) fn wide() -> bool { false }    /// A phase of an ask timed for the bench; nothing outside tests.    #[inline(always)]    pub(super) fn phase(_: &'static str) {}    /// A kept cut patched, counted for tests; nothing outside them.    #[inline(always)]    pub(super) fn patching() {}}/// The month leaf beside Today's name: `{day, month}` of the day key, the/// month's short name in the `dates` set's words.fn month_leaf(today: &str, lines: &[LineRow]) -> Option<Value> {    let day = chrono::NaiveDate::parse_from_str(today, "%Y-%m-%d").ok()?;    use chrono::Datelike;    const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];    let month = line("dates", &format!("months.{}", MONTHS[day.month0() as usize]), lines, &[]);    Some(json!({"day": day.day(), "month": month}))}