Cotton code
128 lines · 6.7 KB · RustRaw
//! `shell.reading {table, id, columns?, lines?, dark?}` — A RECORD'S READING//! PAGE, ANSWERED WHOLE (the shell boundary: iOS's `ReadPage` reads its own//! slots and cuts its own pages; here the core does both, so a platform shell//! draws the page and decides nothing).//!//! ```json//! { "table", "id", "title"?, "byline"?,//!   "bodies": [{ "column", "markdown", "writes" }],//!   "pages": [{ "body", "text" }], "words_per_page",//!   "settings": { "face": "paper|sepia|night", "worn", "knobs" },//!   "faces": { "cards": [{ "id", "label" }], "raised" } }//! ```//!//! - The page reads what `rules::reading_page::slots` names: a card that is//!   its own words (a note, a memory, a book's notes and quote). A record//!   whose table opens no reading page is refused.//! - `title`: the head's column as its card says it, else as the record//!   holds it (a note's markdown let go), a book's author after it; when it//!   says nothing, the card's date words where the slots read a date (a//!   memory's), else the first sentence of the words, as the torn page titles//!   an untitled note. `byline`: the slip's byline for the record.//! - `bodies`: each body column holding words, in order, whether it is set//!   as markdown, and whether a person writes it here (`writes`: a long press//!   on its pages asks `shell.input {op: ask, kind: column}` for it).//! - `pages`: the bodies cut by `rules::reading_page::cut`, each body//!   starting its own pages, at the words a page holds — measured by the//!   shell at the reader's type, `columns` characters a line and `lines`//!   lines (`words_on_page`); unmeasured, each body is one page.//! - `settings` and `faces`: the reader's own face (`face_settings` row//!   `reader`, the book reader's: Paper, Sepia, Night) and its FACES tier; a//!   face is chosen with `reader.settings {face}`, and `worn` is Night while//!   the phone is `dark` and the person follows it.use crate::handle::CottonHandle;use crate::methods::MethodError;use cotton_core::rules::reading_page;use cotton_core::transforms::note_title::strip_markdown;use serde_json::{json, Value};const METHOD: &str = "shell.reading";pub fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let card = crate::phone::card_actions::read_card(&client, request, METHOD)?;    let definition = &card.definition;    let slots = reading_page::slots(definition)        .ok_or_else(|| MethodError::new("refused", format!("a {} opens no reading page", definition.id)))?;    // The card the record wears, as the deck says it: the head's words are its.    let mut said = json!({"id": card.id, "table": card.table, "data": Value::Object(card.data.clone())});    crate::phone::records::resolve_live_slips_on(handle, "records.get", &json!({"table": card.table}), &mut said)?;    let fields = said["data"][cotton_core::records::card::CARD_KEY]["fields"].as_object().cloned().unwrap_or_default();    let data = &card.data;    let on_card = |column: &str| -> Option<String> {        let field = definition.card.as_ref()?.fields.iter().find(|field| field.column.as_deref() == Some(column))?;        let slot = serde_json::to_value(field.slot).ok()?.as_str()?.to_string();        trimmed(fields.get(&slot).and_then(Value::as_str))    };    let held = |column: &str| trimmed(data.get(column).and_then(Value::as_str));    let said_of = |column: &Option<String>| column.as_deref().and_then(|column| on_card(column).or_else(|| held(column)));    let columns: Vec<&String> = slots.bodies.iter().filter(|column| held(column).is_some()).collect();    let note = definition.card.as_ref().is_some_and(|card| card.face == "note.page");    let title = match said_of(&slots.title) {        Some(named) => {            let named = if note { strip_markdown(&named) } else { named };            Some([Some(named), said_of(&slots.with)].into_iter().flatten().collect::<Vec<_>>().join(" · "))        }        None => match &slots.date {            Some(date) => on_card(date),            None => columns.first().and_then(|column| held(column)).and_then(|words| first_sentence(&strip_markdown(&words))),        },    };    let byline = definition.slip.byline.as_ref().and_then(|line| data.get(&line.column).and_then(Value::as_str).and_then(|value| line.words.get(value).cloned()));    let count = |field: &str| request.get(field).and_then(Value::as_u64).filter(|n| *n > 0).map(|n| n as usize);    let cap = match (count("columns"), count("lines")) {        (Some(columns), Some(lines)) => Some(reading_page::words_on_page(columns, lines)),        _ => None,    };    let mut bodies = Vec::new();    let mut pages = Vec::new();    for (at, column) in columns.iter().enumerate() {        let words = held(column).unwrap_or_default();        let markdown = definition.column(column).and_then(|found| found.markdown) == Some(true)            || definition.card.iter().flat_map(|card| card.fields.iter()).any(|field| field.column.as_deref() == Some(column.as_str()) && field.markdown);        let writes = crate::methods::shell_input::call(handle, &json!({"op": "ask", "kind": "column", "table": card.table, "id": card.id, "column": column})).is_ok();        bodies.push(json!({"column": column, "markdown": markdown, "writes": writes}));        let cut = match cap {            Some(cap) => reading_page::cut(&words, cap),            None => vec![words],        };        pages.extend(cut.into_iter().map(|text| json!({"body": at, "text": text})));    }    let dark = request.get("dark").and_then(Value::as_bool).unwrap_or(false);    let (settings, faces) = crate::phone::reader::look(&client, dark)?;    Ok(json!({        "table": card.table, "id": card.id,        "title": title, "byline": byline,        "bodies": bodies, "pages": pages, "words_per_page": cap,        "settings": settings, "faces": faces,    }))}fn trimmed(words: Option<&str>) -> Option<String> {    words.map(str::trim).filter(|words| !words.is_empty()).map(str::to_string)}/// The first sentence of `text`, as the torn page titles an untitled note:/// up to the first full stop, question or exclamation that ends a word, or/// the first line's end; a full stop let go.fn first_sentence(text: &str) -> Option<String> {    let text = text.trim();    let line = text.lines().next()?.trim();    let mut end = line.len();    let mut chars = line.char_indices().peekable();    while let Some((at, c)) = chars.next() {        if matches!(c, '.' | '!' | '?') && chars.peek().is_none_or(|(_, next)| next.is_whitespace()) {            end = at + c.len_utf8();            break;        }    }    let sentence = line[..end].trim().trim_end_matches('.').trim();    (!sentence.is_empty()).then(|| sentence.to_string())}#[cfg(test)]#[path = "shell_reading_tests.rs"]mod tests;