Cotton code
253 lines · 15.6 KB · RustRaw
use super::*;use crate::definitions::builtin_table_definition;use serde_json::json;fn held(table: &str, record: Value, held: Held) -> Vec<CardAction> {    let definition = builtin_table_definition(table).cloned().unwrap_or_else(|| kit_table("books", table));    opened(&definition, record.as_object().unwrap(), &[], held, Vec::new())}fn ids(acts: &[CardAction]) -> Vec<&str> {    acts.iter().map(|act| act.id.as_str()).collect()}fn kit_table(tool: &str, table: &str) -> TableDefinition {    let package = crate::kit::package(tool).expect("the kit holds the tool").expect("it decodes").package;    package.tables.into_iter().find(|held| held.id == table).expect("the package carries the table")}/// RULE: an open todo's Mark done is its primary act, first and ranked main;/// Drop and the kit's Delete take it away, red and last, the kit's own away/// act (Delete) the very last; Bin does not stand beside the kit's Delete.#[test]fn an_open_todos_mark_done_is_primary_and_drop_and_delete_are_red_and_last() {    let acts = held("todo", json!({ "title": "Synthetic water the plants", "status": "open" }), Held::default());    assert_eq!(        ids(&acts),        ["done", "set-date", "open-repeat-rule", "invite", "edit-notes", "group", "status", "send", "drop", "delete"]    );    assert!(acts[0].primary && acts[0].rank == Rank::Main && !acts[0].red);    assert_eq!(acts.iter().filter(|act| act.primary).count(), 1);    assert_eq!(acts.iter().filter(|act| act.red).map(|act| act.id.as_str()).collect::<Vec<_>>(), ["drop", "delete"]);    assert!(acts.iter().filter(|act| act.red).all(|act| act.rank == Rank::Away));    assert!(acts.iter().filter(|act| !act.red && !act.primary).all(|act| act.rank == Rank::More));    assert_eq!(acts[0].icon.as_deref(), Some("act-stamp"));    assert!(!acts.iter().any(|act| act.id == "bin"), "the kit's Delete takes a todo away");}/// RULE: one tile per target. Set date stands for When and opens the When/// step; the repeat rule's Repeat stands for the Repeat chooser and opens/// the Repeat step, whether or not the todo repeats yet; Status opens the/// statuses of a status Mark done and Drop move.#[test]fn a_command_that_stands_for_a_chooser_opens_its_step() {    for todo in [json!({ "title": "Synthetic", "status": "open" }), json!({ "title": "Synthetic", "status": "open", "recurrence_id": "rule-1" })] {        let acts = held("todo", todo, Held::default());        let step = |id: &str| acts.iter().find(|act| act.id == id).and_then(|act| act.step);        assert_eq!(step("set-date"), Some(Step::When));        assert_eq!(step("open-repeat-rule"), Some(Step::Repeat));        assert_eq!(step("status"), Some(Step::Status));        assert_eq!(step("group"), Some(Step::Group));        assert_eq!(step("done"), None);        assert!(!acts.iter().any(|act| act.id == "when" || act.id == "repeat"), "{:?}", ids(&acts));        let status = acts.iter().find(|act| act.id == "status").unwrap();        assert_eq!((status.kind, status.column.as_deref(), status.label.as_str()), (ActionKind::Chooser, Some("status"), "Status"));    }}/// RULE: a todo offers only the commands that hold of it now; nothing moves/// a missed todo's status from the fan, so Status is not offered.#[test]fn a_todo_offers_only_the_commands_that_hold_of_it_now() {    let done = held("todo", json!({ "title": "Synthetic", "status": "done" }), Held::default());    assert!(done.iter().any(|act| act.id == "reopen"));    assert!(!done.iter().any(|act| act.id == "done" || act.id == "drop"));    let missed = held("todo", json!({ "title": "Synthetic", "status": "missed" }), Held::default());    assert!(!missed.iter().any(|act| act.id == "status"), "{:?}", ids(&missed));    let statuses: Vec<&str> = status_commands(builtin_table_definition("todo").unwrap(), json!({ "status": "open" }).as_object().unwrap())        .into_iter()        .map(|command| command.id.as_str())        .collect();    assert_eq!(statuses, ["done", "drop"]);}/// RULE: a book (Cotton Books) offers its own acts as they hold — Read only/// once it has a file (a book the shelf holds by its details alone opens at/// rest, where Add file is: 15a3670f66), Start reading, Keep on phone, Rate,/// Review, Find details, Add file — then When for the day it was started,/// Group, and Bin red and last: nothing the kit offers takes a book away./// Reading, it offers Finished and Stop reading: Stop puts the book away, red/// and last, and Bin does not stand beside it.#[test]fn a_books_acts_hold_by_its_state_and_bin_is_red_and_last() {    let want = held("book", json!({ "title": "Synthetic atlas", "status": "want_to_read", "on_phone": "absent" }), Held::default());    assert_eq!(ids(&want), ["start", "keep_on_phone", "rate", "review", "find_details", "add_file", "when", "group", "send", "bin"], "a book with no file offers no Read");    let with_file = held("book", json!({ "title": "Synthetic atlas", "status": "want_to_read", "on_phone": "absent", "file": "f.epub" }), Held::default());    assert_eq!(ids(&with_file), ["read", "start", "keep_on_phone", "rate", "review", "find_details", "when", "group", "send", "bin"], "a book with a file offers Read first and no Add file");    let bin = want.last().unwrap();    assert!(bin.red && bin.rank == Rank::Away && bin.kind == ActionKind::Chooser && bin.step.is_none());    assert!(!want.iter().any(|act| act.primary), "a book names no main act");    let reading = held("book", json!({ "title": "Synthetic atlas", "status": "reading", "on_phone": "kept", "file": "f.epub" }), Held::default());    assert_eq!(ids(&reading), ["read", "finish", "remove_download", "rate", "review", "find_details", "when", "group", "send", "stop"]);    assert_eq!(reading.iter().filter(|act| act.red).map(|act| act.id.as_str()).collect::<Vec<_>>(), ["stop"]);    let finish = reading.iter().find(|act| act.id == "finish").unwrap();    assert_eq!(finish.step, Some(Step::Pick), "Finished asks its stars as the core's pick row, then runs");}/// RULE: a held highlight offers the reader's four and Group; the kit's/// Remove takes it away, red and last, and no Bin stands beside it.#[test]fn a_highlights_remove_is_red_and_last() {    let acts = held("highlight", json!({ "text": "A synthetic passage", "colour": "yellow" }), Held::default());    assert_eq!(ids(&acts), ["go_to", "recolour", "note", "group", "send", "remove"]);    assert!(acts.last().unwrap().red);    assert!(acts[..4].iter().all(|act| !act.red));}/// RULE: a person's handoffs stand first, in the kit's rank, each with the/// address it opens, and only where the record holds one; Face stands where/// the card wears a face of its table's family and the table offers/// another; Archive puts the person away, red and last.#[test]fn a_persons_handoffs_lead_face_stands_and_archive_is_last() {    let person = json!({ "name": "Synthetic Person", "phones": ["+91 99000 00848"], "emails": ["synthetic@example.test"] });    let acts = held("person", person.clone(), Held { face: Some("person.rolodex"), blank: false });    assert_eq!(ids(&acts)[..3], ["tel:phones", "sms:phones", "mailto:emails"]);    assert_eq!(acts[0].url.as_deref(), Some("tel:+919900000848"));    assert_eq!(acts[2].url.as_deref(), Some("mailto:synthetic@example.test"));    assert_eq!((acts[0].kind, acts[0].icon.as_deref(), acts[0].primary), (ActionKind::Address, Some("act-handset"), false));    assert!(acts[0].rank == Rank::More, "a handoff named main is never the primary act");    let face = acts.iter().position(|act| act.id == "face").expect("Face");    assert_eq!((acts[face].step, acts[face].label.as_str()), (Some(Step::Face), "Face"));    assert_eq!(acts.last().map(|act| (act.id.as_str(), act.red)), Some(("archive", true)));    assert!(acts[..face].iter().all(|act| !act.red));    let plain = held("person", json!({ "name": "Synthetic Person", "phones": ["not a number"] }), Held::default());    assert!(!plain.iter().any(|act| act.kind == ActionKind::Address || act.id == "face"), "{:?}", ids(&plain));    let elsewhere = held("person", person, Held { face: Some("todo.card"), blank: false });    assert!(!elsewhere.iter().any(|act| act.id == "face"), "a face outside the table's family offers none");}/// RULE: an act that reserves (a business's Book, the reserve engine's/// verb) is the primary act, first, ahead of the kit's own main act.#[test]fn the_act_that_reserves_is_primary() {    let mut todo = builtin_table_definition("todo").unwrap().clone();    let book: RecordCommand = serde_json::from_value(json!({ "id": "book", "label": "Book", "kind": "create", "verb": RESERVE_VERB })).unwrap();    todo.commands.get_or_insert_with(Vec::new).push(book);    let acts = opened(&todo, json!({ "status": "open" }).as_object().unwrap(), &[], Held::default(), Vec::new());    assert_eq!(ids(&acts)[..2], ["book", "done"]);    assert_eq!((acts[0].primary, acts[0].rank), (true, Rank::Main));    assert_eq!((acts[1].primary, acts[1].rank), (false, Rank::More));    assert_eq!(acts.iter().filter(|act| act.primary).count(), 1);}/// RULE: a blank card (a deck's new card, not yet made) offers only what/// can supply its first row — the acts that ask, and Repeat — never its/// completion or anything away.#[test]fn a_blank_card_offers_only_what_asks_and_repeat() {    let acts = held("todo", json!({ "status": "open" }), Held { face: None, blank: true });    assert_eq!(ids(&acts), ["set-date", "open-repeat-rule", "invite", "edit-notes"]);    assert!(!acts.iter().any(|act| act.red));}/// RULE: a tool's acts stand beside the record's own, before the away acts,/// carrying the words that run them.#[test]fn a_tools_acts_stand_before_the_away_acts() {    let tool = CardAction::tool(&json!({ "id": "account_back_up", "label": "Back up now", "kind": "tool", "tool": "books", "asks": false })).unwrap();    let definition = kit_table("books", "book");    let acts = opened(&definition, json!({ "title": "Synthetic" }).as_object().unwrap(), &[], Held::default(), vec![tool]);    let at = acts.iter().position(|act| act.id == "account_back_up").unwrap();    assert_eq!(acts[at].kind, ActionKind::Tool);    assert_eq!(acts[at].extra["tool"], "books");    assert_eq!(acts.last().unwrap().id, "bin");    let said = serde_json::to_value(&acts[at]).unwrap();    assert_eq!(said["kind"], "tool");    assert_eq!(said["asks"], false);}#[test]fn a_record_that_cannot_go_alone_has_no_bin() {    let acts = held("book", json!({ "title": "Synthetic", "deletable": false }), Held::default());    assert!(!acts.iter().any(|act| act.id == "bin"), "{:?}", ids(&acts));}/// RULE: every kit table's held card names each chooser once, each act/// once, every act in words, at most one primary, and the red acts last.#[test]fn every_kit_table_answers_each_act_once_and_red_last() {    for definition in crate::definitions::builtin_table_definitions().iter().filter(|definition| definition.card.is_some()) {        let acts = opened(definition, &Map::new(), &[], Held::default(), Vec::new());        let mut seen = std::collections::BTreeSet::new();        assert!(acts.iter().all(|act| seen.insert(act.id.clone())), "{}: {:?}", definition.id, ids(&acts));        assert!(acts.iter().all(|act| !act.label.is_empty()), "{}: {acts:?}", definition.id);        assert!(acts.iter().filter(|act| act.primary).count() <= 1, "{}", definition.id);        let first_red = acts.iter().position(|act| act.red).unwrap_or(acts.len());        assert!(acts[first_red..].iter().all(|act| act.red), "{}: {:?}", definition.id, ids(&acts));    }}/// RULE: The held card reads a `{"not": …}` `when` as the core does: offered/// while the column holds none of what it names, an absent column among/// them. This device's row says `session` only where the app backs up to a/// personal object: without it (Rigby) Sync now and Re-key stay and Sign in/// does not; signed out, Sign in and Erase stand and Sync now does not.#[test]fn rigbys_device_card_holds_its_own_acts() {    let device = |record: Value| -> Vec<String> { held("device", record, Held::default()).into_iter().map(|act| act.id).collect() };    let rigby = device(json!({ "status": "this device" }));    assert!(rigby.iter().any(|id| id == "sync_now") && rigby.iter().any(|id| id == "rekey"), "{rigby:?}");    assert!(!rigby.iter().any(|id| id == "sign_in" || id == "sign_out" || id == "share_ink" || id == "erase_here"), "{rigby:?}");    let signed_out = device(json!({ "status": "this device", "session": "signed_out" }));    assert!(signed_out.iter().any(|id| id == "sign_in"), "{signed_out:?}");    assert_eq!(signed_out.last().map(String::as_str), Some("erase_here"), "Erase is away, last");    assert!(!signed_out.iter().any(|id| id == "sync_now" || id == "rekey" || id == "sign_out"), "{signed_out:?}");}/// RULE: a film offers Keep on phone while this phone keeps nothing of it,/// Keep series on a series, Remove download once kept or coming down, and/// none of them on a film with no file (Cotton Cinemas).#[test]fn a_films_acts_follow_what_this_phone_keeps() {    let film = kit_table("cinemas", "film");    let acts = |record: Value| -> Vec<String> {        opened(&film, record.as_object().unwrap(), &[], Held::default(), Vec::new()).into_iter().map(|act| act.id).collect()    };    let file = json!({ "title": "Synthetic Test Pattern", "kind": "film", "file": "db/films/f1/whole.mp4" });    let with = |key: &str, value: &str| {        let mut record = file.clone();        record[key] = json!(value);        record    };    let absent = acts(with("on_phone", "absent"));    assert!(absent.contains(&"keep_on_phone".into()) && !absent.contains(&"remove_download".into()), "{absent:?}");    let kept = acts(with("on_phone", "kept"));    assert!(kept.contains(&"remove_download".into()) && !kept.contains(&"keep_on_phone".into()), "{kept:?}");    let series = acts(json!({ "title": "Synthetic Serial", "kind": "series", "on_phone": "absent" }));    assert!(series.contains(&"keep_series".into()), "{series:?}");    let bare = acts(json!({ "title": "Synthetic Test Pattern", "kind": "film" }));    assert!(!bare.iter().any(|id| id == "keep_on_phone" || id == "remove_download"), "{bare:?}");}/// RULE (Send, 13 Nov 2026): a made record of a table with a `send` shape/// offers Send, which opens the Send step (the person's people); one a send/// brought (its `send_id`) also offers to take away everything that send/// brought, red, as it takes records away. A table with no shape offers/// neither, and a card not yet made offers no Send.#[test]fn a_sendable_card_offers_send_and_one_a_send_brought_offers_to_remove_it() {    let book = json!({ "title": "Synthetic atlas", "status": "want_to_read" });    let acts = held("book", book.clone(), Held::default());    let send = acts.iter().find(|act| act.id == "send").expect("a book can be sent");    assert_eq!((send.kind, send.step, send.icon.as_deref(), send.label.as_str(), send.red), (ActionKind::Chooser, Some(Step::Send), Some("act-send"), "Send", false));    assert!(!acts.iter().any(|act| act.id == "unsend"), "a book of the person's own brought by no send");    let mut sent = book.clone();    sent["send_id"] = json!("0123456789abcdef0123456789abcdef");    let acts = held("book", sent, Held::default());    let unsend = acts.iter().find(|act| act.id == "unsend").expect("a kept send can be taken away");    assert!(unsend.red && unsend.rank == Rank::Away && unsend.step.is_none());    assert_eq!(unsend.label, "Remove everything from this send");    assert!(!held("event", json!({ "title": "Synthetic" }), Held::default()).iter().any(|act| act.id == "send"), "an event has no send shape");    assert!(!held("book", book, Held { face: None, blank: true }).iter().any(|act| act.id == "send"), "a card not yet made is sent by nobody");}