Cotton code
144 lines · 8.8 KB · RustRaw
//! `read.find` worded: hits across three tables, the sections in order, and//! a day spelled by the core equal to what the app spelled (R7 vectors).use serde_json::{json, Value};use crate::handle::CottonHandle;const ZONE: &str = "Asia/Kolkata";fn phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest: Value = serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("a manifest");    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some(ZONE.to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    crate::methods::dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn make(handle: &CottonHandle, table: &str, data: Value) -> String {    let made = ask(handle, "records.create", json!({"table": table, "data": data}));    made["id"].as_str().or_else(|| made["record"]["id"].as_str()).unwrap_or_else(|| panic!("a made id: {made}")).to_string()}/// A todo, a note and a person the word "quillon" finds.fn three_tables(handle: &CottonHandle) -> (String, String, String) {    let person = make(handle, "person", json!({"full_name": "Quillon Walker"}));    let note = make(handle, "note", json!({"title": "Quillon fence plans", "body": "posts and wire"}));    let todo = make(handle, "todo", json!({"title": "Mend the quillon fence"}));    (todo, note, person)}// RULE: read.find words every hit — section, title, opens, the slip shell.list rows carry — across tables, so the app picks no title and builds no route.#[test]fn find_words_its_hits_across_three_tables() {    let (_dir, handle) = phone();    let (todo, note, person) = three_tables(&handle);    let answer = ask(&handle, "read.find", json!({"query": "quillon"}));    let hit = |id: &str| answer["hits"].as_array().unwrap().iter().find(|hit| hit["id"] == id).cloned().unwrap_or_else(|| panic!("{id} in {answer}"));    for (id, section, title, table) in [(&todo, "todo", "Mend the quillon fence", "todo"), (&note, "note", "Quillon fence plans", "note"), (&person, "person", "Quillon Walker", "person")] {        let hit = hit(id);        assert_eq!(hit["section"], section, "{hit}");        assert_eq!(hit["words"]["title"], title, "{hit}");        assert_eq!(hit["words"]["opens"]["table"], table, "{hit}");        assert_eq!(hit["words"]["opens"]["id"], id.as_str(), "{hit}");        assert!(hit["words"]["opens"]["path"].as_str().is_some_and(|path| path.contains(id.as_str())), "{hit}");        // The very slip shell.list dresses: its title and its record.        assert_eq!(hit["words"]["slip"]["title"], title, "{hit}");        assert_eq!(hit["words"]["slip"]["record"]["id"], id.as_str(), "{hit}");    }}// RULE: read.find answers its sections in the editorial order — Todos, Notes, then People — each named by its tool and counted, every hit in it worded.#[test]fn find_answers_its_sections_in_order_with_counts() {    let (_dir, handle) = phone();    let (todo, _, _) = three_tables(&handle);    make(&handle, "todo", json!({"title": "Oil the quillon gate"}));    let answer = ask(&handle, "read.find", json!({"query": "quillon", "limit": 1}));    let sections = answer["sections"].as_array().unwrap_or_else(|| panic!("{answer}"));    let ids: Vec<&str> = sections.iter().filter_map(|section| section["id"].as_str()).collect();    assert_eq!(ids, ["todo", "note", "person"], "{answer}");    let words: Vec<&str> = sections.iter().filter_map(|section| section["words"].as_str()).collect();    assert_eq!(words, ["Todos", "Notes", "People"]);    // A page of one, the count is the whole: one more to see.    assert_eq!(sections[0]["count"], 2, "{answer}");    assert_eq!(sections[0]["hits"].as_array().map(Vec::len), Some(1));    let first = &sections[0]["hits"][0];    assert!(first["title"].is_string() && first["opens"]["path"].is_string(), "{first}");    let _ = todo;}// RULE: a nameless hit is called by the search set's untitled words, a document says the page it matched on, and an archived junk email says both marks.#[test]fn a_hit_the_file_could_not_name_is_worded_by_the_core() {    use cotton_core::rules::search_everything::EverythingKind;    let lines = Vec::new();    let say = |key: &str, fills: &[(&str, &str)]| cotton_core::rules::shell_lines::resolve("search", key, &lines, fills).unwrap_or_default();    let journal = super::hit_words(&json!({"kind": "note", "id": "n1", "title": null, "journal": true}), EverythingKind::Note, None, &say);    assert_eq!(journal["title"], "Journal");    let document = super::hit_words(&json!({"kind": "document", "id": "d1", "title": "Lease", "snippet": "Lease", "page": 4}), EverythingKind::Document, None, &say);    assert_eq!(document["caption"], "Page 4");    assert!(document.get("subtitle").is_none(), "a snippet that is the title says nothing more");    let email = super::hit_words(&json!({"kind": "email", "id": "m1", "threadId": "t1", "stack": "junk", "archived": true}), EverythingKind::Email, None, &say);    assert_eq!(email["caption"], "Archived \u{00B7} Junk");    assert_eq!(email["opens"], json!({"table": "email_thread", "id": "t1", "path": "/email/t1", "screen": "outside", "at": "m1"}));}// RULE: a hit's day is spelled once, by the core, exactly as the app's DateFormats.recent spelled it (DateFormatsTests' R7 vectors): the clock today, Yesterday, the weekday date, the year outside this one.#[test]fn a_hits_day_is_the_one_the_app_spelled() {    use chrono::TimeZone;    let now = chrono::FixedOffset::east_opt(19_800).unwrap().with_ymd_and_hms(2026, 10, 5, 23, 30, 0).unwrap().with_timezone(&chrono::Utc);    let stamps = crate::phone::stamps::Stamps::new(ZONE, now, cotton_core::records::page::DateWords::of_rows(&[]));    for (when, said) in [        ("2026-10-05T03:24:00+05:30", "3:24 am"),        ("2026-10-04T03:24:00+05:30", "Yesterday"),        ("2026-10-02T03:24:00+05:30", "Fri 2 Oct"),        ("2025-10-02T03:24:00+05:30", "Thu 2 Oct 2025"),        ("2026-10-03T03:24:00+05:30", "Sat 3 Oct"),    ] {        let mut hit = json!({"kind": "todo", "id": "t1", "title": "Synthetic", "when": when});        stamps.on(&mut hit, &["when"]);        let lines = Vec::new();        let say = |key: &str, fills: &[(&str, &str)]| cotton_core::rules::shell_lines::resolve("search", key, &lines, fills).unwrap_or_default();        let words = super::hit_words(&hit, cotton_core::rules::search_everything::EverythingKind::Todo, None, &say);        assert_eq!(words["caption"], said, "{when}: {hit}");        assert_eq!(words["stamp"], when);    }}// RULE: a hit names the record its card is read from — a message's and an email's conversation, a photo's media row, none for a bus message — and a section names the kinds an expanded section pages through, its held kinds first.#[test]fn a_hit_names_its_card_and_a_section_its_kinds() {    use cotton_core::rules::search_everything::EverythingKind;    let lines = Vec::new();    let say = |key: &str, fills: &[(&str, &str)]| cotton_core::rules::shell_lines::resolve("search", key, &lines, fills).unwrap_or_default();    let record = |hit: Value, kind| super::hit_words(&hit, kind, None, &say)["record"].clone();    assert_eq!(record(json!({"kind": "message", "id": "m1", "threadId": "th1"}), EverythingKind::Message), json!({"table": "thread", "id": "th1"}));    assert_eq!(record(json!({"kind": "message", "id": "m1"}), EverythingKind::Message), Value::Null);    assert_eq!(record(json!({"kind": "email", "id": "e1", "threadId": "et1"}), EverythingKind::Email), json!({"table": "email_thread", "id": "et1"}));    assert_eq!(record(json!({"kind": "photo", "id": "p1"}), EverythingKind::Photo), json!({"table": "media", "id": "p1"}));    assert_eq!(record(json!({"kind": "session_message", "id": "s1"}), EverythingKind::SessionMessage), Value::Null);    assert_eq!(record(json!({"kind": "todo", "id": "t1"}), EverythingKind::Todo), json!({"table": "todo", "id": "t1"}));    let answer = json!({"hits": [        {"id": "m1", "kind": "message", "section": "message", "words": {}},        {"id": "th1", "kind": "thread", "section": "message", "words": {}},    ]});    let sections = super::sections(&answer, &say);    assert_eq!(sections[0]["kinds"], json!(["thread", "message"]), "{}", sections[0]);    assert_eq!(sections[0]["hits"][0]["id"], "th1", "the chat before the message");}