//! `shell.opened {table, id | draft, view?, face?, step?, timezone?, today?}` //! — THE HELD CARD, ANSWERED WHOLE (move 3 of the shell boundary): the //! shell draws what this says and decides none of it. //! //! Without `step` it answers the card's acts, ranked and flagged //! (`cotton_core::rules::card_actions`), the acts of the tools owning its //! table as they stand on the deck of `view` (`/`) among them: //! //! ```json //! { "acts": [{ "id", "label", "kind": "command|chooser|address|tool", //! "rank": "main|more|away", "primary", "red", //! "icon"?, "column"?, "step"?, "url"?, //! "tool"?, "asks"?, "account"?, "group"?, "pictogram"?, "mark"? }], //! "tile", "parts": { slot: { "does", "column"? } }, "date", //! "opens"?: { "table", "id", "path", "screen", "opening" } } //! ``` //! //! An act's `mark` is the mark drawn over the card at rest that runs it //! (the definition's `marks`: a todo's check runs Mark done), while it holds //! of the record; `date` is the column the card's When writes //! (`card_actions::date_column`), null where it has none. //! //! `opens` (a made card's) is where the record opens (`routes::opens`): //! the route it is reached by and the kind of screen it is. //! //! `parts` is the face's tap map while the card is held: what a tap on each //! of its places opens (`methods::shell_input::parts`) — the days, the //! statuses, the lists, a choice column's values, the viewer, the line or //! the whole screen; a place it leaves out is the card's own tap. //! //! `tile` is the fan tile of the tool owning the table (`phone::fan_tile`), //! null where it names none, and each act's `pictogram` the kit picture it //! names for that act. //! //! A tap on an act with a `step` asks for that step; any other runs as its //! kind says (a command by `records.command`, an address opened by the OS, a //! tool's by `tools.act`, Bin by a delete). //! //! With `step` it answers that step's choice row, in order: //! //! ```json //! { "step": { "kind": "when|time|repeat|status|pick|group|face|options|send", "rows": [{ "value", "words", … }] } } //! ``` //! //! - `when`: No date (`none`), then the days a date can be given in one //! tap — each with its `kind` (`today`, `day`, `week`, `month`, `pick`), //! its `detail` and the `day` it sets — for `today` in `timezone`. //! - `time`: No time, the hours, Pick a time; the record's own `chosen`. //! None where the card's date holds days (`card_when::holds_days`): the //! day chosen is the whole edit. //! - `repeat`: Never, then the presets, in the database's words. //! - `status`: the definition's status verbs the record can take now, each //! by its command id, `red` where it takes the record away (Drop). //! - `pick` (with `act`, the command asking it, and the `answers` so far): //! the pick now due, answered on the device (`methods::shell_input`). //! - `options` (with `column`): a choice column's values, each in its words. //! - `when` and `time` with `all: true`: Pick a date's every day from today //! (`shell_input::PICKED_DAYS`) and Pick a time's every half hour, said //! in the database's `dates` words ("Tue 4 Nov", "9:30 am"). //! - `group`: New list first (value `new`, `new: true`), then the table's //! lists in their own order, each by its id with its `detail` (how many it //! holds) and `holds` (whether this card is in it); each its tile's //! `new_list` or `list` pictogram. New list stands first for every app, so //! it is on the screen however many lists there are, and the arc rests on //! it. New list carries `asks` (the `shell.input` ask naming the list), //! every list `writes` (what `shell.input` commits to join or leave it). //! - `face` (`face`, the face the card wears now, may be left out): the //! faces its table offers, the one chosen on its `face_choices` row first //! and `chosen`, then the others in the table's order, each said by its //! kit title (`cards` `faces.titles.*`), each with its `writes`; none where //! the database keeps no face choices, the table offers one face, or the //! worn face is not of its family (a view naming its own face). //! //! - `send` (a made card's, of a table with a `send` shape): the person's //! people as the object names them (`phone::cotton_send::step`), each a //! person's row that sends at a tap and holds the trust act, the tier's //! `says` naming what goes and its size; none, `empty` says so, with the //! door to Cotton chat's request where the app keeps chat. //! //! A card not yet made is asked by its values (`draft`) instead of its id: //! it offers only what can supply its first row (`Held::blank`). use crate::methods::MethodError; use crate::shell::client::ClientController; use cotton_core::definitions::TableDefinition; use cotton_core::rules::card_actions::{self, CardAction, Held, Step}; use cotton_core::rules::{card_when, date_choices, shell_lines}; use cotton_core::transforms::recurrence_presets::RecurrencePreset; use cotton_core::transforms::zoned_clock; use serde_json::{json, Map, Value}; const METHOD: &str = "shell.opened"; /// The pictures a step's rows are drawn with, each a shipped picture in /// Loom's catalogue (`tests/act_pictures.rs` holds every one): no row is /// words alone. None of anything (No date, No time, Never) is struck out. pub const NONE_PICTURE: &str = "act-cross"; pub const TODAY_PICTURE: &str = "edit-value-today"; pub const DAY_PICTURE: &str = "edit-value-day"; pub const TIME_PICTURE: &str = "act-clock"; pub const REPEAT_PICTURE: &str = "act-cycle"; pub const NEW_LIST_PICTURE: &str = "act-plus"; pub const LIST_PICTURE: &str = "edit-act-group"; pub const FACE_PICTURE: &str = "act-picture"; pub const BIN_PICTURE: &str = "edit-act-bin"; /// Every picture a step's rows name. pub const STEP_PICTURES: &[&str] = &[NONE_PICTURE, TODAY_PICTURE, DAY_PICTURE, TIME_PICTURE, REPEAT_PICTURE, NEW_LIST_PICTURE, LIST_PICTURE, FACE_PICTURE, BIN_PICTURE]; pub fn call(client: &ClientController, request: &Value) -> Result { let rows = client .with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id))) .unwrap_or_default(); // A choice column's values (`chooses`), and Pick a date / Pick a time: // every day or half hour, the same for every card. match (request["step"].as_str(), request["all"] == json!(true)) { (Some("options"), _) => return options(client, request, &rows), (Some("when"), true) => { let today = crate::methods::shell_input::today_number(client, request)?; let rows: Vec = crate::methods::shell_input::picked_days_from(today, &rows)? .into_iter() .map(|(day, words)| json!({ "value": format!("pick-{day}"), "words": words, "kind": "day", "day": day, "picture": DAY_PICTURE })) .collect(); return Ok(json!({ "step": { "kind": "when", "rows": writing(client, request, Step::When, rows)? } })); } (Some("time"), true) => { let rows: Vec = crate::methods::shell_input::half_hours(client, &rows) .into_iter() .map(|(time, words)| json!({ "value": format!("pick-{time}"), "words": words, "time": time, "picture": TIME_PICTURE })) .collect(); return Ok(json!({ "step": { "kind": "time", "rows": writing(client, request, Step::Time, rows)? } })); } _ => {} } let step = match request.get("step").and_then(Value::as_str) { None => None, Some(word) => Some(Step::parse(word).ok_or_else(|| bad(format!("{METHOD} takes a step: when, time, repeat, status, pick, group, face, scope or send")))?), }; match step { // The days and the repeats are the same for every card: no record is read. Some(Step::When) => return Ok(json!({ "step": { "kind": "when", "rows": writing(client, request, Step::When, days(client, request, &rows)?)? } })), Some(Step::Repeat) => return Ok(json!({ "step": { "kind": "repeat", "rows": writing(client, request, Step::Repeat, repeats(&rows))? } })), Some(Step::Face) => return faces(client, request, &rows), Some(Step::Scope) => return Ok(json!({ "step": { "kind": "scope", "rows": writing(client, request, Step::Scope, scopes(&rows))? } })), // The people a copy can go to, as the object names them (`send.offer`). Some(Step::Send) => return super::cotton_send::step(client, request), Some(Step::Time | Step::Status | Step::Pick | Step::Group) | None => {} } let (definition, data, blank) = held(client, request)?; match step { Some(Step::Group) => { let id = request["id"].as_str().filter(|_| !blank && definition.groups.is_some()).ok_or_else(|| bad(format!("{METHOD}'s group step is a made card's, of a table that keeps lists")))?; Ok(json!({ "step": { "kind": "group", "rows": groups(client, &definition, id, &rows)? } })) } Some(Step::Time) => Ok(json!({ "step": { "kind": "time", "rows": writing(client, request, Step::Time, times(client, request, &definition, &data, &rows)?)? } })), Some(Step::Status) => { let tile = super::fan_tile::of_table(client, &definition, METHOD)?; let rows: Vec = card_actions::status_commands(&definition, &data) .into_iter() .map(|command| { let mut row = json!({ "value": command.id, "words": command.label, "red": command.is_away_act() }); if let Some(object) = &command.object { row["picture"] = json!(format!("act-{object}")); } if let Some(photo) = tile.as_ref().and_then(|tile| tile.act(&command.id)) { row["pictogram"] = json!(photo); } row }) .collect(); Ok(json!({ "step": { "kind": "status", "rows": rows } })) } Some(Step::Pick) => Err(bad(format!("{METHOD}'s pick step is answered on the device (`shell_input::pick`)"))), _ => { let tools = if blank { Vec::new() } else { // The tools' acts standing on this deck, then a list's own // on a list's deck, this card's moves along it among them. let view = request["view"].as_str(); let mut standing = super::tool_acts::standing(client, &definition, view, METHOD)?; standing.extend(super::tool_acts::list_acts(client, view, request["id"].as_str())?); standing.iter().filter_map(CardAction::tool).collect() }; // Face is offered only where the database keeps face choices. let face = request["face"].as_str(); let tables = if face.is_some() { super::face_choice::tables(client, METHOD)? } else { Vec::new() }; let worn = face.filter(|_| super::catalogue::FaceChoiceTable::of(&tables).is_some()); let acts = card_actions::opened(&definition, &data, &rows, Held { face: worn, blank }, tools); let acts = serde_json::to_value(acts).map_err(|why| MethodError::new("unreadable", why.to_string()))?; let mut answer = json!({ "acts": acts, "parts": crate::methods::shell_input::parts(&definition, &data), "date": card_actions::date_column(&definition) }); // A mark drawn over the card at rest names the act it runs. for (mark, id) in definition.marks.iter().flatten() { if let Some(act) = answer["acts"].as_array_mut().into_iter().flatten().find(|act| act["kind"] == "command" && act["id"] == id.as_str()) { act["mark"] = json!(mark); } } let tile = super::fan_tile::of_table(client, &definition, METHOD)?; super::fan_tile::dress_acts(tile.as_ref(), &mut answer, "acts"); if let Some(id) = request["id"].as_str().filter(|_| !blank) { super::tool_acts::list_plays(request["view"].as_str(), &definition.id, id, &mut answer["acts"]); answer["opens"] = super::routes::opens(&definition, id, &data, face.unwrap_or_default(), &|table| super::card_actions::read_definition(client, table, METHOD).ok()); } Ok(answer) } } } /// `{step: options, table, column}`: a choice column's values in its /// definition's order, each in its words (`labels`, else the value in words). fn options(client: &ClientController, request: &Value, _rows: &[shell_lines::LineRow]) -> Result { let table = request["table"].as_str().ok_or_else(|| bad(format!("{METHOD}'s options name the table")))?; let asked = request["column"].as_str().ok_or_else(|| bad(format!("{METHOD}'s options name the choice column")))?; let definition = super::card_actions::read_definition(client, table, METHOD)?; let column = definition.column(asked).filter(|column| column.choices.is_some()).ok_or_else(|| bad(format!("{table} has no choice column {asked}")))?; let rows: Vec = column.choices.iter().flatten().map(|value| json!({ "value": value, "words": column.choice_label(value) })).collect(); Ok(json!({ "step": { "kind": "options", "column": asked, "rows": rows } })) } /// `{step: face, table, face?}`: the faces a card of `table` worn as `face` /// (else in the face chosen for it) may be worn in (`card_actions::faces`), /// the chosen one first, then the table's other offers in its order, each /// said by its kit title and carrying what `shell.input` commits to wear it. fn faces(client: &ClientController, request: &Value, rows: &[shell_lines::LineRow]) -> Result { let table = request["table"].as_str().ok_or_else(|| bad(format!("{METHOD}'s face step names the table")))?; let definition = super::card_actions::read_definition(client, table, METHOD)?; let Some(choices) = super::face_choice::of(client, table, METHOD)? else { return Ok(json!({ "step": { "kind": "face", "rows": [] } })); }; let selected = crate::methods::shell_deck::selected(&definition, Some(&choices.chosen)).unwrap_or_default(); let mut offers = card_actions::faces(&definition, request["face"].as_str().unwrap_or(&selected)); // The face the card wears, where it wears an offer; a by-value face stands for the one chosen. let chosen = request["face"].as_str().filter(|face| offers.iter().any(|offer| offer == face)).map_or(selected.clone(), str::to_string); if offers.len() < 2 { offers.clear(); } offers.sort_by_key(|face| *face != chosen); let rows: Vec = offers .into_iter() .map(|face| { json!({ "value": face, "words": crate::methods::shell_deck::face_title(&face, rows), "chosen": face == chosen, "picture": FACE_PICTURE, "writes": { "kind": "face", "table": table, "face": face } }) }) .collect(); Ok(json!({ "step": { "kind": "face", "rows": rows } })) } /// The group step's row: New list, then the table's lists holding or not /// holding `id`, each with its tile's pictogram. fn groups(client: &ClientController, definition: &TableDefinition, id: &str, rows: &[shell_lines::LineRow]) -> Result, MethodError> { let tile = super::fan_tile::of_table(client, definition, METHOD)?; let pictogram = |role: &str| tile.as_ref().and_then(|tile| tile.role(role)).map(|photo| json!(photo)); let table = definition.id.as_str(); let mut new = json!({ "value": "new", "words": shell_lines::resolve("lists", "group.new", rows, &[]).unwrap_or_default(), "new": true, "picture": NEW_LIST_PICTURE, "asks": { "op": "ask", "kind": "group", "table": table, "id": id } }); if let Some(photo) = pictogram("new_list") { new["pictogram"] = photo; } let listed = super::records::call(client, "groups.list", &json!({ "table": definition.id, "record": id }))?; let lists = listed["groups"].as_array().into_iter().flatten().filter_map(|group| { let holds = group["holds"].as_bool() == Some(true); let mut row = json!({ "value": group["id"].as_str()?, "words": group["name"], "holds": holds, "picture": LIST_PICTURE, "writes": { "kind": "group", "table": table, "id": id, "group": group["id"], "holds": holds } }); if let Some(count) = group["count"].as_u64() { row["detail"] = json!(count.to_string()); } if let Some(photo) = pictogram("list") { row["pictogram"] = photo; } Some(row) }); Ok(std::iter::once(new).chain(lists).collect()) } /// The card asked about: its table's definition and its columns — the /// record as `records.get` reads it, or a card not yet made by its values. fn held(client: &ClientController, request: &Value) -> Result<(TableDefinition, Map, bool), MethodError> { if let Some(draft) = request.get("draft") { let table = request["table"].as_str().ok_or_else(|| bad(format!("{METHOD} takes the record's table")))?; let data = draft.as_object().cloned().ok_or_else(|| bad(format!("{METHOD}'s draft is the new card's values")))?; return Ok((super::card_actions::read_definition(client, table, METHOD)?, data, true)); } let card = super::card_actions::read_card(client, request, METHOD)?; Ok((card.definition, card.data, false)) } fn days(client: &ClientController, request: &Value, rows: &[shell_lines::LineRow]) -> Result, MethodError> { let zone = zone_of(client, request); let today = match request["today"].as_str() { Some(day) => { let parts: Vec = day.split('-').filter_map(|part| part.parse().ok()).collect(); match parts[..] { [year, month, date] if cotton_core::records::is_date(day) => zoned_clock::day_number(year, month, date), _ => return Err(bad("today is a day, YYYY-MM-DD".into())), } } None => zoned_clock::local_day(client.clock().now().timestamp_millis(), &zone).map_err(|_| bad_zone())?, }; let none = shell_lines::resolve("editing", "when.no_date", rows, &[]).unwrap_or_default(); let mut said = vec![json!({ "value": "none", "words": none, "kind": "none", "picture": NONE_PICTURE })]; said.extend(date_choices::said_choices(today, rows).into_iter().map(|choice| { let picture = if choice.kind == "today" { TODAY_PICTURE } else { DAY_PICTURE }; let mut row = json!({ "value": choice.key, "words": choice.label, "kind": choice.kind, "picture": picture }); if let Some(detail) = choice.detail { row["detail"] = detail.into(); } if let Some(day) = choice.day { row["day"] = day.into(); } row })); Ok(said) } fn times( client: &ClientController, request: &Value, definition: &TableDefinition, data: &Map, rows: &[shell_lines::LineRow], ) -> Result, MethodError> { let column = card_actions::date_column(definition).ok_or_else(|| bad("this card has no date a person writes".into()))?; if card_when::holds_days(definition, &column) { return Ok(Vec::new()); } let held = card_when::held(data.get(&column), &zone_of(client, request)).map_err(|error| bad(error.to_string()))?; Ok(card_when::time_choices(held.as_ref(), rows) .into_iter() .map(|choice| { let picture = if choice.key == "none" { NONE_PICTURE } else { TIME_PICTURE }; let mut row = json!({ "value": choice.key, "words": choice.label, "chosen": choice.chosen, "picture": picture }); if let Some(time) = choice.time { row["time"] = time.into(); } row }) .collect()) } /// A made card's When, Time and Repeat rows (`table` and `id` asked), each /// with what a tap on it writes — `shell.input {op: commit}`'s `writes` /// (`when`: the card's day and hour through `cards.when`, the half a row does /// not name kept; `repeat`: its preset through `cards.repeat`) — and `then`, /// the step it opens next: a day's hours (with the `day` it chose) where the /// card's date holds an hour, Pick a date's every day, Pick a time's every /// half hour. No date clears the day and its hour; No time the hour. So a /// shell draws the rows, commits what a tap writes and asks what follows, /// deciding nothing (Android Todos, 12 Nov 2026). A card not yet made (a /// draft) is written by its own editor: its rows are said alone. fn writing(client: &ClientController, request: &Value, step: Step, mut rows: Vec) -> Result, MethodError> { let (Some(table), Some(id)) = (request["table"].as_str(), request["id"].as_str()) else { return Ok(rows) }; let when = |date: Option, time: Option| { let mut writes = json!({ "kind": "when", "table": table, "id": id }); if let Some(date) = date { writes["date"] = date; } if let Some(time) = time { writes["time"] = time; } writes }; match step { Step::When => { let definition = super::card_actions::read_definition(client, table, METHOD)?; let timed = card_actions::date_column(&definition).is_some_and(|column| !card_when::holds_days(&definition, &column)); for row in &mut rows { match (row["kind"].as_str(), row["day"].as_str().map(str::to_string)) { (Some("none"), _) => row["writes"] = when(Some(Value::Null), Some(Value::Null)), (Some("pick"), _) => row["then"] = json!({ "step": "when", "all": true }), (_, Some(day)) => { row["writes"] = when(Some(json!(day)), None); if timed { row["then"] = json!({ "step": "time", "day": day }); } } _ => {} } } } Step::Time => { let day = request["day"].as_str().filter(|day| cotton_core::records::is_date(day)).map(|day| json!(day)); for row in &mut rows { if row["value"] == "pick" { let mut then = json!({ "step": "time", "all": true }); if let Some(day) = &day { then["day"] = day.clone(); } row["then"] = then; } else { row["writes"] = when(day.clone(), Some(row.get("time").cloned().unwrap_or(Value::Null))); } } } Step::Repeat => { for row in &mut rows { row["writes"] = json!({ "kind": "repeat", "table": table, "id": id, "preset": row["value"] }); } } Step::Scope => { for row in &mut rows { row["writes"] = json!({ "kind": "delete", "table": table, "id": id, "scope": row["value"] }); } } _ => {} } Ok(rows) } /// Whom a repeating event's Bin takes: only this one, or every one, in the /// database's `definitions` scope lines; each drawn red, it takes away. fn scopes(rows: &[shell_lines::LineRow]) -> Vec { [("this", "scope.only_this"), ("all", "scope.every_one")] .into_iter() .map(|(value, line)| json!({ "value": value, "words": shell_lines::resolve("definitions", line, rows, &[]).unwrap_or_default(), "picture": BIN_PICTURE, "red": true })) .collect() } /// How often a record can come round, in the order the presets run, each /// said in the database's `dates` repeat lines; the first, Never, stops a repeat. fn repeats(rows: &[shell_lines::LineRow]) -> Vec { RecurrencePreset::ALL .into_iter() .map(|preset| { let (set, line) = match preset { RecurrencePreset::None => ("editing", "repeat.never".to_string()), other => ("dates", format!("repeat.{}", other.as_str())), }; let picture = if preset == RecurrencePreset::None { NONE_PICTURE } else { REPEAT_PICTURE }; json!({ "value": preset.as_str(), "words": shell_lines::resolve(set, &line, rows, &[]).unwrap_or_default(), "picture": picture }) }) .collect() } fn zone_of(client: &ClientController, request: &Value) -> String { request["timezone"].as_str().unwrap_or(client.time_zone().unwrap_or("UTC")).to_string() } fn bad(why: String) -> MethodError { MethodError::new("bad_request", why) } fn bad_zone() -> MethodError { bad("timezone is a named time zone".into()) } #[cfg(test)] #[path = "opened_tests.rs"] mod tests;