//! `read.find` WORDED — every word a person reads off a search answered by //! the core, so a platform shell only draws (the core moves, #294). //! //! The engine's raw answer (`{hits, totals, defined?}`, `reads::find`) keeps //! every key it had; this adds, one shape for Swift and Android alike: //! //! ```json //! { "hits": [{ …raw…, "section": "todo", "words": { "title", "subtitle"?, //! "caption"?, "stamp"?, "slip"?, "opens"?, "picture"?, //! "record"? } }], //! "sections": [{ "id", "words", "count", "defined"?: true, "kinds"?, //! "hits": [{ "id", "kind", "databaseId"?, "title", //! "subtitle"?, "caption"?, "stamp"?, "slip"?, //! "opens"?, "picture"?, "record"?, //! "struck"? }] }] } //! ``` //! //! - `sections`: the built-in sections in the editorial order ([`ORDER`]), //! each named by its tool (`search` set, `section.`), then the imported //! tables' (`defined`, by their definition's plural, sorted by it). Only a //! section holding a hit stands. `count` is how many the database holds //! (`totals`, never fewer than the hits in hand): `count` minus the hits //! shown is the section's "see more". In Messages the chats stand before //! the messages — the name typed is usually the chat meant. `kinds` (a //! built-in section's): every kind that folds into it, the ones its hits //! hold first in their order — what an expanded section pages through, one //! kind at a time (`{kind, offset, limit}`). //! - `title`: the record's own, else the `search` set's `untitled.*` words. //! `subtitle`: the matched line, when it says something the title does not. //! `caption`: the marks (archived, a mail stack) then the page a document //! matched on, else the record's day as the core spells it (`@day_parts` //! `recent`), joined by " · ". `stamp`: the raw moment (`when`). //! - `slip`: the slip `shell.list` rows carry, for a hit whose kind is a //! table this database defines — the very rows shell.list words: the hits' //! records read by id (`records.list {table, ids}`) and handed to //! `shell.list {table, rows}`, whose `slip_of` dresses them, so there is no //! second wording path. `opens`: shell.list's row `opens` //! (`routes::opens`) — except the kinds addressed by more than their row //! id (a message by its thread, an email by its thread at the email, a //! pull, issue or release under its repository, a password, a //! repository), which this module addresses; a kind with no page of its //! own (a session message, a decision, a post, a scene) carries none and //! opens nothing. //! - `picture`: a person hit's photo key. //! - `record`: `{table, id}`, the record a hit stands for — the one its card //! is read from: a message's and an email's are their conversation's, a //! photo's and a video's the media row; a message on the bus, or a message //! or email whose conversation is unnamed, stands for none. An imported //! table's hit stands for its own row. use cotton_core::rules::search_everything::{section_of, EverythingKind, EverythingSection, EVERYTHING_KINDS}; use cotton_core::rules::shell_lines::{self, LineRow}; use serde_json::{json, Value}; use std::collections::BTreeMap; use crate::handle::CottonHandle; use crate::methods::MethodError; /// The order the sections stand in: the kinds a day turns on first, the /// reflective and found-by-accident kinds after, a password last of all. pub const ORDER: [EverythingSection; 19] = { use EverythingSection::*; [ Todo, Event, Note, Message, Email, Person, Document, Transaction, Memory, Session, Pull, Issue, Repository, Release, SessionMessage, Photo, Video, Call, Secret, ] }; const SET: &str = "search"; const DOT: &str = " \u{00B7} "; /// `read.find`'s answer, worded in place. pub(crate) fn word(handle: &CottonHandle, request: &Value, mut answer: Value) -> Result { let lines = line_rows(handle); let say = |key: &str, fills: &[(&str, &str)]| shell_lines::resolve(SET, key, &lines, fills).unwrap_or_default(); let named = request.get(crate::phone::databases::DATABASE).and_then(Value::as_str) .filter(|database| *database != crate::phone::databases::ALL_DATABASES); let dressed = dress(handle, named, answer["hits"].as_array().map(Vec::as_slice).unwrap_or_default()); for hit in answer["hits"].as_array_mut().into_iter().flatten() { let Some(kind) = hit["kind"].as_str().and_then(EverythingKind::parse) else { continue }; let row = dressed.get(&key(hit, named)).cloned(); let words = hit_words(hit, kind, row.as_ref(), &say); hit["section"] = json!(section_of(kind).as_str()); hit["words"] = words; } answer["sections"] = Value::Array(sections(&answer, &say)); Ok(answer) } /// A hit's words: title, subtitle, caption, stamp, slip, opens, picture. pub(crate) fn hit_words(hit: &Value, kind: EverythingKind, row: Option<&Value>, say: &dyn Fn(&str, &[(&str, &str)]) -> String) -> Value { let title = text(&hit["title"]).unwrap_or_else(|| say(untitled(kind, hit["journal"] == true), &[])); let subtitle = text(&hit["snippet"]).filter(|snippet| *snippet != title); let mut said: Vec = Vec::new(); if hit["archived"] == true { said.push(say("marks.archived", &[])); } if let Some(stack) = hit["stack"].as_str().filter(|stack| ["people", "records", "junk"].contains(stack)) { said.push(say(&format!("marks.{stack}"), &[])); } let page = (kind == EverythingKind::Document).then(|| hit["page"].as_i64()).flatten(); match page { Some(page) => said.push(say("marks.page", &[("n", &page.to_string())])), None => said.extend(text(&hit[cotton_core::records::page::DAY_PARTS_KEY]["when"]["recent"])), } said.retain(|words| !words.is_empty()); let mut words = json!({ "title": title, "subtitle": subtitle, "caption": (!said.is_empty()).then(|| said.join(DOT)), "stamp": hit["when"], "slip": row.map(|row| row["slip"].clone()), "opens": opens(hit, kind, row), "picture": hit["photoKey"], "record": record(hit, kind), }); if let Some(words) = words.as_object_mut() { words.retain(|_, value| !value.is_null()); } words } /// The `untitled.*` line a nameless hit of `kind` is called. fn untitled(kind: EverythingKind, journal: bool) -> &'static str { match kind { EverythingKind::Note if journal => "untitled.journal", EverythingKind::Note => "untitled.note", EverythingKind::Session => "untitled.session", EverythingKind::Transaction => "untitled.transaction", _ => "untitled.other", } } /// Where a hit opens: shell.list's row `opens`, else the address its kind /// takes beyond a row id; `None` opens nothing. fn opens(hit: &Value, kind: EverythingKind, row: Option<&Value>) -> Value { use EverythingKind::*; let id = hit["id"].as_str().unwrap_or_default(); let thread = text(&hit["threadId"]); let repo = text(&hit["repoId"]); let at = |table: &str, id: &str, path: String, screen: &str| json!({"table": table, "id": id, "path": path, "screen": screen}); match kind { Message => thread.map(|thread| at("thread", &thread, format!("/messages/{thread}"), "chat")).unwrap_or(Value::Null), Thread => at("thread", id, format!("/messages/{id}"), "chat"), EmailThread => at("email_thread", id, format!("/email/{id}"), "outside"), Email => thread.map(|thread| { let mut opens = at("email_thread", &thread, format!("/email/{thread}"), "outside"); opens["at"] = json!(id); opens }).unwrap_or(Value::Null), Pull | Issue => match (repo, hit["number"].as_i64().filter(|number| *number > 0)) { (Some(repo), Some(number)) => { let segment = if kind == Pull { "pulls" } else { "issues" }; at(kind.as_str(), id, format!("/repos/{repo}/{segment}/{number}"), "outside") } _ => Value::Null, }, Release => match (repo, text(&hit["tag"])) { (Some(repo), Some(tag)) => at("release", id, format!("/repos/{repo}/releases/{tag}"), "outside"), _ => Value::Null, }, Repository => at("repository", id, format!("/repos/{id}"), "outside"), Secret => at("secret", id, format!("/passwords/{id}"), "outside"), SessionMessage => Value::Null, _ => row.map(|row| row["opens"].clone()).unwrap_or(Value::Null), } } /// The record a hit stands for, its card's: see the module doc. fn record(hit: &Value, kind: EverythingKind) -> Value { use EverythingKind::*; let at = |table: &str, id: String| json!({"table": table, "id": id}); let id = text(&hit["id"]).unwrap_or_default(); match kind { Message => text(&hit["threadId"]).map(|thread| at("thread", thread)).unwrap_or(Value::Null), Email => text(&hit["threadId"]).map(|thread| at("email_thread", thread)).unwrap_or(Value::Null), Photo | Video => at("media", id), SessionMessage => Value::Null, _ => at(kind.as_str(), id), } } /// The sections in order, each worded with its hits'. pub(crate) fn sections(answer: &Value, say: &dyn Fn(&str, &[(&str, &str)]) -> String) -> Vec { let hits = answer["hits"].as_array().map(Vec::as_slice).unwrap_or_default(); let mut out = Vec::new(); for section in ORDER { let mut held: Vec<&Value> = hits.iter().filter(|hit| hit["section"] == section.as_str()).collect(); if held.is_empty() { continue; } if section == EverythingSection::Message { held.sort_by_key(|hit| hit["kind"] != "thread"); } let total = answer["totals"][section.as_str()].as_u64().unwrap_or(0).max(held.len() as u64); let mut kinds: Vec<&str> = Vec::new(); let folded = EVERYTHING_KINDS.iter().filter(|kind| section_of(**kind) == section).map(|kind| kind.as_str()); for kind in held.iter().filter_map(|hit| hit["kind"].as_str()).chain(folded) { if !kinds.contains(&kind) { kinds.push(kind); } } out.push(json!({ "id": section.as_str(), "words": say(&format!("section.{}", section.as_str()), &[]), "count": total, "kinds": kinds, "hits": held.iter().map(|hit| shown(hit)).collect::>(), })); } let mut defined: Vec<(&String, &Value)> = answer["defined"].as_object().map(|map| map.iter().collect()).unwrap_or_default(); defined.retain(|(_, section)| section["hits"].as_array().is_some_and(|hits| !hits.is_empty())); defined.sort_by(|a, b| { let label = |section: &Value| section["label"].as_str().unwrap_or_default().to_lowercase(); label(a.1).cmp(&label(b.1)).then(a.0.cmp(b.0)) }); for (table, section) in defined { let hits: Vec = section["hits"].as_array().into_iter().flatten().map(|hit| defined_hit(table, hit)).collect(); out.push(json!({ "id": table, "words": section["label"].as_str().unwrap_or(table), "defined": true, "count": section["total"].as_u64().unwrap_or(0).max(hits.len() as u64), "hits": hits, })); } out } /// A worded hit as its section lists it. fn shown(hit: &Value) -> Value { let mut row = hit["words"].as_object().cloned().unwrap_or_default(); row.insert("id".into(), hit["id"].clone()); row.insert("kind".into(), hit["kind"].clone()); if hit["struck"] == true { row.insert("struck".into(), json!(true)); } for key in ["databaseId", "databaseName"] { if let Some(value) = hit.get(key) { row.insert(key.into(), value.clone()); } } Value::Object(row) } /// An imported table's hit, worded: its mark then its day as the caption, /// opened at its list's address. fn defined_hit(table: &str, hit: &Value) -> Value { let id = hit["id"].as_str().unwrap_or_default(); let title = text(&hit["title"]).unwrap_or_default(); let subtitle = text(&hit["snippet"]).filter(|snippet| *snippet != title); let said: Vec = [text(&hit["mark"]), text(&hit[cotton_core::records::page::DAY_PARTS_KEY]["when"]["recent"])] .into_iter().flatten().collect(); let mut row = json!({ "id": id, "kind": table, "title": title, "subtitle": subtitle, "caption": (!said.is_empty()).then(|| said.join(DOT)), "stamp": hit["when"], "opens": {"table": table, "id": id, "path": format!("/lists/{table}/{id}"), "screen": "deck"}, "record": {"table": table, "id": id}, "databaseId": hit.get("databaseId"), "databaseName": hit.get("databaseName"), }); if let Some(row) = row.as_object_mut() { row.retain(|_, value| !value.is_null()); } row } /// shell.list's rows for the hits, keyed by database and id: per database /// and table, the records read by id and handed to `shell.list` to dress. fn dress(handle: &CottonHandle, named: Option<&str>, hits: &[Value]) -> BTreeMap { let mut asked: BTreeMap<(Option, String), Vec> = BTreeMap::new(); for hit in hits { let Some(kind) = hit["kind"].as_str().and_then(EverythingKind::parse) else { continue }; if !dressed_kind(kind) { continue; } let table = if kind == EverythingKind::Note && hit["journal"] == true { "journal" } else { kind.as_str() }; let database = hit["databaseId"].as_str().or(named).map(str::to_string); if let Some(id) = hit["id"].as_str() { asked.entry((database, table.to_string())).or_default().push(id.to_string()); } } let mut out = BTreeMap::new(); for ((database, table), ids) in asked { let scoped = |mut args: Value| { if let Some(database) = &database { args[crate::phone::databases::DATABASE] = json!(database); } args }; let Ok(read) = crate::methods::dispatch(handle, "records.list", &scoped(json!({"table": table, "ids": ids}))) else { continue }; let rows: Vec = read["records"].as_array().into_iter().flatten() .filter(|row| row["id"].is_string() && row["data"].is_object()) .map(|row| json!({"id": row["id"], "data": row["data"]})).collect(); if rows.is_empty() { continue; } let Ok(list) = crate::methods::dispatch(handle, "shell.list", &scoped(json!({"table": table, "rows": rows}))) else { continue }; for row in list["sections"].as_array().into_iter().flatten().flat_map(|section| section["rows"].as_array().into_iter().flatten()) { if let Some(id) = row["id"].as_str() { out.insert(format!("{}:{id}", database.as_deref().unwrap_or("")), row.clone()); } } } out } /// A kind whose hit id is a row of the table of its name, which shell.list /// can dress. The others are addressed by more than a row (`opens`). fn dressed_kind(kind: EverythingKind) -> bool { use EverythingKind::*; !matches!(kind, Message | Thread | Email | EmailThread | Pull | Issue | Release | Repository | Secret | SessionMessage) } fn key(hit: &Value, named: Option<&str>) -> String { format!("{}:{}", hit["databaseId"].as_str().or(named).unwrap_or(""), hit["id"].as_str().unwrap_or("")) } fn text(value: &Value) -> Option { value.as_str().map(str::trim).filter(|words| !words.is_empty()).map(str::to_string) } /// The personal database's line rows, laid over the kit's. fn line_rows(handle: &CottonHandle) -> Vec { let mut rows = Vec::new(); let _ = handle.client().read_rows("find_words", &mut |ctx| { rows = cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); Ok(Value::Null) }); rows } #[cfg(test)] #[path = "find_words_tests.rs"] mod tests;