Cotton code
567 lines · 25.4 KB · RustRaw
//! THE HELD CARD'S ACTS (`shell.opened`): what one record offers when it is//! held, whole, ranked and flagged, read from its table's definition alone —//! the shell draws them and decides none of them.//!//! What stands, before ranking://! - Its commands that hold of the record now, in the definition's order —//!   never the one opening the record runs (`on_open`), a field card's//!   (`sheet`), the form's or a list's. The command that opens the card's//!   repeat rule always stands: it is the card's Repeat.//! - Its handoffs (`actions`: Call, Message, Email) that reach an address on//!   the record, each with the address it opens.//! - One chooser per thing the fan edits in place that no command already//!   targets — When for the card's date, Group where the table keeps groups,//!   Repeat where the card comes round, Status where an update command moves//!   the status, Face where the card may be worn in another of its table's//!   faces — then Bin, where the table lets the record go and no command the//!   kit offers already takes it away.//! - One tile per target: a command that writes or opens a column stands in//!   that column's chooser's place (Set date for When, the repeat rule's//!   Repeat for Repeat), and opens that chooser's step rather than running.//!//! The rank ([`ranked`], the acts redesign): the primary act first — the//! first that reserves (a business's Book), else the kit's main act — then//! the kit's named acts (`parts.acts`: main, more), then the rest in the//! order above; every act that takes the record away last (`away`, `red`),//! the kit's own away act the very last.use crate::definitions::card::CardSlot;use crate::definitions::{ActionScheme, ColumnType, CommandDoes, CommandKind, PageAction, PickKind, RecordCommand, TableDefinition};use crate::rules::shell_lines::{self, LineRow};use serde::Serialize;use serde_json::{Map, Value};/// The reserve engine's verb (`definitions::reserve`): an act running it is/// what a business's card is for, and stands primary.pub const RESERVE_VERB: &str = "reserve_record";/// The media engine's table, whose photos are sent as the photo table's rows (R5).const MEDIA: &str = "media";/// One act of the held card.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct CardAction {    /// The command's own id, the handoff's (`<scheme>:<column>`), the    /// chooser's name (`when`, `group`, `repeat`, `status`, `face`, `bin`)    /// or the tool act's.    pub id: String,    pub label: String,    pub kind: ActionKind,    pub rank: Rank,    /// The one act a business look prints on its brand's fill.    pub primary: bool,    /// Drawn red: it takes the record away, and stands last.    pub red: bool,    /// The picture the shell paints it with, whole (`act-stamp`,    /// `edit-act-when`, a tool's own), where there is one.    #[serde(skip_serializing_if = "Option::is_none")]    pub icon: Option<String>,    /// The column a chooser writes; Group, Face and Bin write none.    #[serde(skip_serializing_if = "Option::is_none")]    pub column: Option<String>,    /// The choice step a tap opens instead of running (`shell.opened    /// {step}`): a chooser's, or the chooser's a command stands for.    #[serde(skip_serializing_if = "Option::is_none")]    pub step: Option<Step>,    /// A handoff's address (`tel:+91…`, `mailto:…`), opened by the OS.    #[serde(skip_serializing_if = "Option::is_none")]    pub url: Option<String>,    /// A tool act's own words for running it (`tool`, `asks`, `account`, `group`).    #[serde(flatten)]    pub extra: Map<String, Value>,    /// It takes the record away (a delete, a destructive or put-away    /// command, Bin): ranked away.    #[serde(skip)]    pub destroys: bool,    /// It runs the reserve engine's verb.    #[serde(skip)]    pub reserves: bool,    /// It asks something before it runs (a pick), so a blank card offers it;    /// said as `picks` so a shell holding no definition asks its picks first    /// (`shell.opened {step: pick, act}`), as Pay by UPI's UPI id is typed.    #[serde(rename = "picks", skip_serializing_if = "std::ops::Not::not", default)]    pub asks: bool,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum ActionKind {    Command,    Chooser,    Address,    Tool,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum Rank {    Main,    More,    Away,}/// A choice step: the row the fan turns into while one thing is chosen.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum Step {    When,    Time,    Repeat,    Status,    Group,    Face,    /// A command's one pick that is a row of named values (Finished's    /// stars, Rate), asked on the device (`shell.opened {step: pick}`).    Pick,    /// Bin on a repeating event: only this one, or every one    /// (`shell.opened {step: scope}`), each a delete in that scope.    Scope,    /// Send: the person's people, one of whom a tap sends a copy to    /// (`shell.opened {step: send}`, answered by the object's `send.offer`).    Send,}impl Step {    pub fn parse(word: &str) -> Option<Step> {        Some(match word {            "when" => Step::When,            "time" => Step::Time,            "repeat" => Step::Repeat,            "status" => Step::Status,            "group" => Step::Group,            "face" => Step::Face,            "pick" => Step::Pick,            "scope" => Step::Scope,            "send" => Step::Send,            _ => return None,        })    }}impl CardAction {    fn new(id: impl Into<String>, label: impl Into<String>, kind: ActionKind) -> CardAction {        CardAction {            id: id.into(),            label: label.into(),            kind,            rank: Rank::More,            primary: false,            red: false,            icon: None,            column: None,            step: None,            url: None,            extra: Map::new(),            destroys: false,            reserves: false,            asks: false,        }    }    /// A command as an act: its picture, whether it takes the record away,    /// reserves, or asks before it runs — the held card's commands and a    /// business's table acts (`business.pages`) alike, ranked by [`ranked`].    pub fn command(command: &RecordCommand) -> CardAction {        CardAction {            icon: command.object.as_ref().map(|object| format!("act-{object}")),            destroys: command.is_away_act(),            reserves: command.verb.as_deref() == Some(RESERVE_VERB),            asks: command.pick.is_some() || command.picks.as_ref().is_some_and(|picks| !picks.is_empty()) || command.pick_table.is_some(),            ..CardAction::new(command.id.clone(), command.label.clone(), ActionKind::Command)        }    }    /// A tool's act as `tools.acts` answers it (`tool_acts::standing`): its    /// id, label and the words that run it.    pub fn tool(entry: &Value) -> Option<CardAction> {        let mut extra = entry.as_object()?.clone();        let id = extra.remove("id")?.as_str()?.to_string();        let label = extra.remove("label")?.as_str()?.to_string();        extra.remove("kind");        let icon = extra.remove("icon").and_then(|icon| icon.as_str().map(str::to_string));        // One that takes something away (a list's Remove list) ranks away, red.        let destroys = extra.remove("red") == Some(Value::Bool(true));        Some(CardAction { icon, extra, destroys, ..CardAction::new(id, label, ActionKind::Tool) })    }}/// What the held card is asked for.#[derive(Debug, Clone, Copy, Default)]pub struct Held<'a> {    /// The face the card wears now, where the database keeps face choices:    /// Face stands while the table offers another in the same family.    pub face: Option<&'a str>,    /// A card not yet made (a deck's new card): only what can supply its    /// first row stands — an act that asks, and Repeat; nothing away.    pub blank: bool,}/// The acts of `record` (its columns by key) under `definition`, ranked:/// choosers said in the database's `editing` lines, the tool acts `tools`/// (`tools.acts`' entries) beside the record's own.pub fn opened(definition: &TableDefinition, record: &Map<String, Value>, rows: &[LineRow], held: Held, tools: Vec<CardAction>) -> Vec<CardAction> {    let mut acts = offered(definition, record, rows, held);    acts.extend(tools);    let acts = ranked(definition, acts);    if !held.blank {        return acts;    }    acts.into_iter().filter(|act| !act.red && (act.asks || act.step == Some(Step::Repeat))).collect()}/// What stands on `record`, before ranking (see the module's header).pub fn offered(definition: &TableDefinition, record: &Map<String, Value>, rows: &[LineRow], held: Held) -> Vec<CardAction> {    let kept = kept_in_step(definition, record);    let repeat_column = definition.card.as_ref().and_then(|card| card.pace.as_ref()).and_then(|pace| pace.repeat.clone());    let date = date_column(definition);    let opens_repeat = |command: &RecordCommand| command.kind == CommandKind::Open && command.opens.is_some() && command.opens == repeat_column;    let commands: Vec<&RecordCommand> = definition        .commands        .iter()        .flatten()        .filter(|command| definition.on_open.as_deref() != Some(command.id.as_str()))        .filter(|command| command.sheet.is_none() && command.list.is_none() && command.form != Some(true))        .filter(|command| command_holds(command, record) || opens_repeat(command))        .collect();    let targeted: Vec<&str> = commands.iter().flat_map(|command| targets(command)).collect();    let mut fan: Vec<CardAction> = commands        .iter()        .map(|command| {            let step = if opens_repeat(command) {                Some(Step::Repeat)            } else if sets_date(command, date.as_deref()) {                Some(Step::When)            } else if picks_a_row(command) {                Some(Step::Pick)            } else {                None            };            CardAction { step, ..CardAction::command(command) }        })        .collect();    fan.extend(definition.actions.iter().flatten().filter_map(|action| {        let url = address(action, record)?;        Some(CardAction { icon: action.object.as_ref().map(|object| format!("act-{object}")), url: Some(url), ..CardAction::new(handoff_id(action), action.label.clone(), ActionKind::Address) })    }));    let chooser = |name: &str, column: Option<String>, step: Option<Step>| CardAction {        column,        step,        icon: Some(chooser_picture(name).to_string()),        ..CardAction::new(name, shell_lines::resolve("editing", &format!("acts.{name}"), rows, &[]).unwrap_or_default(), ActionKind::Chooser)    };    let untargeted = |column: &String| !targeted.contains(&column.as_str());    if let Some(column) = date.clone().filter(|_| !kept).filter(untargeted) {        fan.push(chooser("when", Some(column), Some(Step::When)));    }    if definition.groups.is_some() {        fan.push(chooser("group", None, Some(Step::Group)));    }    if let Some(column) = repeat_column.clone().filter(untargeted) {        fan.push(chooser("repeat", Some(column), Some(Step::Repeat)));    }    if let Some(column) = status_column(definition, record).filter(|_| !kept).filter(untargeted) {        fan.push(chooser("status", Some(column), Some(Step::Status)));    }    if held.face.is_some_and(|face| faces(definition, face).len() > 1) {        fan.push(chooser("face", None, Some(Step::Face)));    }    // RULE (Send, 13 Nov 2026): a made record of a table with a `send` shape can be sent, a copy to one of    // the person's people; one a send brought (its `send_id`) offers to take away everything that send brought.    // A photo on the media engine's deck (Photos) is sent as the photo it is: the photo table's own shape (R5).    let sendable = definition.send.is_some() || (definition.id == MEDIA && record.get("kind").and_then(Value::as_str) == Some("photo"));    if !held.blank && sendable {        fan.push(chooser("send", None, Some(Step::Send)));    }    if !held.blank && definition.send.is_some() && record.get("send_id").and_then(Value::as_str).is_some_and(|id| !id.is_empty()) {        fan.push(CardAction { destroys: true, ..chooser("unsend", None, None) });    }    if bins(definition, record, kept) && !commands.iter().any(|command| command.is_away_act()) {        // RULE (Android Calendar, 12 Nov 2026): a repeating event's Bin asks first whether it is only this one or        // every one (`Step::Scope`), as a delete of one refuses to guess.        let repeats = definition.role == Some(crate::definitions::TableRole::Event)            && repeat_column.as_ref().and_then(|column| record.get(column)).and_then(Value::as_str).is_some_and(|rule| !rule.trim().is_empty());        fan.push(CardAction { destroys: true, ..chooser("bin", None, repeats.then_some(Step::Scope)) });    }    fan}/// The shell's choosers on a held card, each with the picture it is drawn/// with in Loom's catalogue: the inked editing set, and Face — which has no/// glyph of its own — the framed picture (`act-picture`).pub const CHOOSER_PICTURES: &[(&str, &str)] = &[    ("when", "edit-act-when"),    ("group", "edit-act-group"),    ("repeat", "edit-act-repeat"),    ("status", "edit-act-status"),    ("face", "act-picture"),    ("bin", "edit-act-bin"),    ("send", "act-send"),    ("unsend", "act-undo"),];fn chooser_picture(name: &str) -> &'static str {    CHOOSER_PICTURES.iter().find(|(chooser, _)| *chooser == name).map(|(_, picture)| *picture).expect("every chooser names its picture")}/// `acts` in the held card's order, each ranked and flagged (see the/// module's header): primary first, the kit's named acts, the rest, then/// the away acts with the kit's own away act last.pub fn ranked(definition: &TableDefinition, acts: Vec<CardAction>) -> Vec<CardAction> {    let parts = definition.resolved_parts().acts;    let away = |act: &CardAction| act.destroys || (act.kind == ActionKind::Command && parts.away.as_deref() == Some(act.id.as_str()));    let named_ids: Vec<&String> = parts.main.iter().chain(parts.more.iter()).collect();    let kit_away = |act: &CardAction| act.kind == ActionKind::Command && parts.away.as_deref() == Some(act.id.as_str());    let mut order: Vec<usize> = Vec::new();    for id in &named_ids {        if let Some(at) = acts.iter().position(|act| matches!(act.kind, ActionKind::Command | ActionKind::Address) && &&act.id == id) {            if !order.contains(&at) {                order.push(at);            }        }    }    let rest: Vec<usize> = (0..acts.len()).filter(|at| !order.contains(at)).collect();    order.extend(rest);    let primary = acts        .iter()        .position(|act| act.reserves && !away(act))        .or_else(|| parts.main.as_ref().and_then(|main| acts.iter().position(|act| act.kind == ActionKind::Command && &act.id == main && !away(act))));    let ranked: Vec<usize> = primary        .into_iter()        .chain(order.iter().copied().filter(|at| Some(*at) != primary && !away(&acts[*at])))        .chain(order.iter().copied().filter(|at| away(&acts[*at]) && !kit_away(&acts[*at])))        .chain(order.iter().copied().filter(|at| kit_away(&acts[*at])))        .collect();    let mut slots: Vec<Option<CardAction>> = acts.into_iter().map(Some).collect();    ranked        .into_iter()        .filter_map(|at| {            let mut act = slots[at].take()?;            let is_away = away(&act);            act.primary = Some(at) == primary;            act.red = is_away;            act.rank = if is_away {                Rank::Away            } else if act.primary {                Rank::Main            } else {                Rank::More            };            Some(act)        })        .collect()}/// The id a handoff goes by: its scheme and its column (`tel:phones`), as/// the kit's `parts.acts` names it.pub fn handoff_id(action: &PageAction) -> String {    let scheme = serde_json::to_value(action.scheme).ok().and_then(|scheme| scheme.as_str().map(str::to_string)).unwrap_or_default();    format!("{scheme}:{}", action.column)}/// The address `action` opens on `record`: its column's value (a list's/// first; the record's own id where it names `id`) under its scheme, or/// under the scheme its scheme column chooses — none where the value is no/// address that scheme may open.pub fn address(action: &PageAction, record: &Map<String, Value>) -> Option<String> {    let value = match record.get(&action.column) {        Some(Value::Array(values)) => values.first().cloned(),        other => other.cloned(),    };    let handle = value.as_ref().and_then(Value::as_str).filter(|handle| !handle.is_empty())?;    let scheme = action        .scheme_column        .as_ref()        .and_then(|column| record.get(column))        .and_then(Value::as_str)        .and_then(|chosen| action.schemes.as_ref().and_then(|schemes| schemes.0.iter().find(|(key, _)| key == chosen).map(|(_, scheme)| *scheme)))        .unwrap_or(action.scheme);    let word = serde_json::to_value(scheme).ok()?.as_str()?.to_string();    let mails = scheme == ActionScheme::Mailto || (matches!(scheme, ActionScheme::Facetime | ActionScheme::FacetimeAudio) && handle.contains('@'));    let address = if mails {        let halves: Vec<&str> = handle.split('@').collect();        let clean = !handle.chars().any(|c| c.is_whitespace() || c.is_control() || ":/?#&".contains(c));        if !clean || halves.len() != 2 || halves.iter().any(|half| half.is_empty()) {            return None;        }        handle.to_string()    } else {        if !handle.chars().all(|c| "+0123456789(). -*#,;".contains(c)) {            return None;        }        let number: String = handle.chars().filter(|c| "+0123456789*#,;".contains(*c)).collect();        if !number.chars().any(|c| c.is_ascii_digit()) || number.chars().skip(1).any(|c| c == '+') {            return None;        }        number    };    Some(format!("{word}:{address}"))}/// The faces a card of `definition` worn as `face` may be worn in: the/// table's offers where the face is of its family, else none.pub fn faces(definition: &TableDefinition, face: &str) -> Vec<String> {    let Some(card) = definition.card.as_ref() else { return Vec::new() };    let offers: Vec<String> = if card.offers.is_empty() {        vec![card.face.as_str().to_string()]    } else {        card.offers.iter().map(|offer| offer.as_str().to_string()).collect()    };    let family = offers.iter().map(String::as_str).chain(card.faces.iter().map(|by| by.face.as_str())).any(|one| one == face);    if family { offers } else { Vec::new() }}/// Whether `command` asks one pick whose answers are named value by value/// (`labels`), so the fan offers them as a row.fn picks_a_row(command: &RecordCommand) -> bool {    command.picks.as_ref().is_none_or(Vec::is_empty)        && command.pick.as_ref().is_some_and(|pick| pick.kind == PickKind::Number && pick.labels.as_ref().is_some_and(|labels| !labels.is_empty()))}/// Whether `command` sets the card's date as When does: a moment it picks/// for the date column, the act's whole edit.fn sets_date(command: &RecordCommand, date: Option<&str>) -> bool {    command.does == Some(CommandDoes::Times)        && command.pick.as_ref().is_some_and(|pick| {            pick.kind == PickKind::Datetime && Some(pick.argument.rsplit('.').next().unwrap_or_default()) == date        })}/// The columns a command edits as a chooser would: each pick's column (its/// argument, or the key inside `patch.<column>`), and the column an `open`/// goes through. A fixed write (Mark done's status) chooses nothing.fn targets(command: &RecordCommand) -> Vec<&str> {    let picked = command.pick.iter().chain(command.picks.iter().flatten()).map(|pick| {        let argument = pick.argument.as_str();        argument.strip_prefix("patch.").unwrap_or(argument)    });    let opened = command.opens.as_deref().filter(|_| command.kind == CommandKind::Open);    picked.chain(opened).collect()}/// The date the card's When sets: the card's own date slot, else its first/// corner, else the table's date — a date column a person may write.pub fn date_column(definition: &TableDefinition) -> Option<String> {    let card = definition.card.as_ref();    let slot = card.and_then(|card| {        card.fields            .iter()            .find(|field| field.slot == CardSlot::Date)            .and_then(|field| field.column.clone())    });    let corner = card.and_then(|card| card.corner.first()).map(|fact| fact.column.clone());    [slot, corner, definition.date.clone()]        .into_iter()        .flatten()        .find(|key| writable(definition, key, ColumnType::Date))}/// The definition's own status verbs `record` can take now: its update/// commands that hold of it and write a choice column a person may write/// (Mark done, Drop, Reopen…), in the definition's order — the Status step./// One that asks (Set date, Notes) moves no status.pub fn status_commands<'a>(definition: &'a TableDefinition, record: &Map<String, Value>) -> Vec<&'a RecordCommand> {    definition        .commands        .iter()        .flatten()        .filter(|command| command.kind == CommandKind::Update && command_holds(command, record))        .filter(|command| moved_status(definition, command).is_some())        .collect()}/// The status a chooser moves: the choice column the table's status verbs/// write, while at least one of them holds of the record.fn status_column(definition: &TableDefinition, record: &Map<String, Value>) -> Option<String> {    status_commands(definition, record).into_iter().find_map(|command| moved_status(definition, command))}fn moved_status(definition: &TableDefinition, command: &RecordCommand) -> Option<String> {    let mut keys: Vec<&String> = command.data.iter().flat_map(|data| data.0.iter().map(|(key, _)| key)).collect();    keys.sort();    keys.into_iter().find(|key| writable(definition, key, ColumnType::Choice)).cloned()}fn writable(definition: &TableDefinition, key: &str, wanted: ColumnType) -> bool {    definition        .columns        .iter()        .any(|column| column.key == key && column.column_type == wanted && column.readonly != Some(true))}/// Whether a command is offered on the record now: its `when` holds, and an/// `open` or `copy` has something to open or copy.fn command_holds(command: &RecordCommand, record: &Map<String, Value>) -> bool {    // `{"not": …}` holds while the column holds none of what it names, an    // absent column among them (`RecordCommand::offered_on`).    let when = command.when.iter().flat_map(|when| when.0.iter()).all(|(key, wanted)| match crate::definitions::when_not(wanted) {        Some(none) => !matches(record.get(key), none),        None => matches(record.get(key), wanted),    });    let target = match command.kind {        CommandKind::Open => command.opens.as_ref().is_none_or(|key| is_set(record.get(key))),        CommandKind::Copy => command            .copies            .as_ref()            .filter(|key| key.as_str() != crate::definitions::COPY_SEALED)            .is_none_or(|key| is_set(record.get(key))),        _ => true,    };    when && target}/// Equal, one of a list asked for, or among a list held; an absent value/// reads as `false`.fn matches(value: Option<&Value>, wanted: &Value) -> bool {    let value = value.unwrap_or(&Value::Bool(false));    if value == wanted || (value.is_null() && wanted == &Value::Bool(false)) {        return true;    }    if let Value::Array(any) = wanted {        return any.iter().any(|one| matches(Some(value), one));    }    matches!(value, Value::Array(items) if items.contains(wanted))}fn is_set(value: Option<&Value>) -> bool {    match value {        None | Some(Value::Null) => false,        Some(Value::String(text)) => !text.is_empty(),        Some(Value::Array(items)) => !items.is_empty(),        Some(Value::Bool(flag)) => *flag,        Some(_) => true,    }}/// Whether something else keeps the whole record in step (`readonly_when`/// holds a value): the fan then edits none of its columns.fn kept_in_step(definition: &TableDefinition, record: &Map<String, Value>) -> bool {    definition.readonly_when.as_ref().is_some_and(|key| is_set(record.get(key)))}/// Whether the record may be deleted, as every Delete the app offers asks/// it (`bins`, with its kept-in-step reading).pub fn deletes(definition: &TableDefinition, record: &Map<String, Value>) -> bool {    bins(definition, record, kept_in_step(definition, record))}/// Bin, as every Delete the app offers asks it: the table deletes, its/// `delete_when` holds, the core has not said the record cannot go alone,/// and nothing closes it — kept in step, or all its engine's with no/// `delete_when` to say which may go.fn bins(definition: &TableDefinition, record: &Map<String, Value>, kept: bool) -> bool {    if definition.delete == Some(false) || record.get("deletable") == Some(&Value::Bool(false)) || kept {        return false;    }    let all_engine = !definition.columns.is_empty() && definition.columns.iter().all(|column| column.readonly == Some(true));    match &definition.delete_when {        Some(when) => match &when.values {            Some(values) => record.get(&when.column).and_then(Value::as_str).is_some_and(|held| values.iter().any(|value| value == held)),            None => is_set(record.get(&when.column)),        },        None => !all_engine,    }}#[cfg(test)]#[path = "card_actions_tests.rs"]mod tests;