//! A RECORD'S READING PAGE — what it reads and how its words are cut into //! pages (the shell boundary: iOS's `ReadSlots` and `ReadPages`, here so an //! Android shell draws the same page and decides nothing). //! //! - [`slots`]: the columns a reading page reads, from the record's //! definition. A card of a kind that is its own words (a note, a memory, a //! book), with no picture unless it is a book; its bodies are the table's //! title column when that is long text (a memory's one sentence), then the //! card's body column, then its quote column, each long text; the head is //! the table's title column when it is not read as a body — with the card's //! subtitle after it (a book's author) — else the card's subtitle's column, //! and then its date's. //! - [`words_on_page`]: the words a page holds at a comfortable depth, from //! the characters a line takes and the lines the text block takes, as the //! shell measured them at the reader's type. //! - [`cut`]: a body cut into pages of about that many words: whole //! paragraphs while they fit, a paragraph that fits on a page never split //! (it starts the next), one too long for any page poured on a sentence at //! a time — a list an item at a time — so a page breaks only at a //! sentence's end. A body that fits is one page. use crate::definitions::card::CardSlot; use crate::definitions::{ColumnType, TableDefinition}; /// The faces whose cards are their own words. pub const READ_FACES: [&str; 3] = ["note.page", "memory", "book.hardback"]; /// The letters an average word takes (`FaceMeasureKnobs.wordLetters`). const WORD_LETTERS: f64 = 4.7; /// Of the words the text block holds, the share that reads comfortably: /// a few sentences, empty paper around them (`ReadPageKnobs.comfort`). const COMFORT: f64 = 0.5; /// The columns a reading page reads. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReadSlots { /// The column whose words are the running head. pub title: Option, /// A column said after the head's, " · " between them: a book's author. pub with: Option, /// The column whose card words stand as the head when the title says /// nothing: a memory's date. pub date: Option, /// The columns read, in order, each starting its own pages. pub bodies: Vec, } /// The reading page's slots for `definition`; `None` for a table that opens /// no reading page. pub fn slots(definition: &TableDefinition) -> Option { let card = definition.card.as_ref()?; let face = card.face.as_str(); if !READ_FACES.contains(&face) { return None; } if face != "book.hardback" && card.fields.iter().any(|field| field.slot == CardSlot::Photo) { return None; } let column = |slot: CardSlot| card.fields.iter().find(|field| field.slot == slot).and_then(|field| field.column.clone()); let long = |key: &str| definition.column(key).is_some_and(|column| column.column_type == ColumnType::Longtext); let title_is_body = long(&definition.title); let mut bodies: Vec = if title_is_body { vec![definition.title.clone()] } else { Vec::new() }; for slot in [CardSlot::Body, CardSlot::Quote] { if let Some(body) = column(slot) { if !bodies.contains(&body) && long(&body) { bodies.push(body); } } } if bodies.is_empty() { return None; } if title_is_body { return Some(ReadSlots { title: column(CardSlot::Subtitle), with: None, date: column(CardSlot::Date), bodies }); } Some(ReadSlots { title: Some(definition.title.clone()), with: column(CardSlot::Subtitle), date: None, bodies }) } /// The words a page holds at a comfortable depth: `columns` characters a /// line and `lines` lines, a word being its letters and the space after it. pub fn words_on_page(columns: usize, lines: usize) -> usize { let per_line = columns as f64 / (WORD_LETTERS + 1.0); ((per_line * lines as f64 * COMFORT) as usize).max(1) } /// The words in `text`. pub fn count(text: &str) -> usize { text.split_whitespace().count() } /// A paragraph of a body, or a list: what a page keeps whole while it can. struct Block { text: String, /// What it is poured on by when it is too long for a page: its /// sentences, or a list's items. units: Vec, /// What its units are joined with on a page. join: &'static str, } /// A line that starts a list's item: a dash, a star, a bullet, or a number /// with its stop. fn is_item(line: &str) -> bool { let line = line.trim_start(); let mut chars = line.chars(); let Some(first) = chars.next() else { return false }; let rest: &str = if "-*•–☐☑".contains(first) { &line[first.len_utf8()..] } else if first.is_ascii_digit() { let digits = line.chars().take_while(char::is_ascii_digit).count(); let after = &line[digits..]; match after.chars().next() { Some('.') | Some(')') => &after[1..], _ => return false, } } else { return false; }; rest.starts_with(char::is_whitespace) && rest.trim_start().chars().next().is_some() } /// The sentences of a paragraph, each as written: a sentence ends at a full /// stop, question or exclamation (with any closing quote or bracket after /// it) followed by a space. pub fn sentences(text: &str) -> Vec { let mut found = Vec::new(); let mut start = 0; let chars: Vec<(usize, char)> = text.char_indices().collect(); let mut i = 0; while i < chars.len() { let (_, c) = chars[i]; if matches!(c, '.' | '!' | '?') { let mut j = i + 1; while j < chars.len() && matches!(chars[j].1, '.' | '!' | '?' | '"' | '\'' | '’' | '”' | ')' | ']') { j += 1; } if j == chars.len() || chars[j].1.is_whitespace() { let end = chars.get(j).map(|(at, _)| *at).unwrap_or(text.len()); let sentence = text[start..end].trim(); if !sentence.is_empty() { found.push(sentence.to_string()); } start = end; i = j; continue; } } i += 1; } let tail = text[start..].trim(); if !tail.is_empty() { found.push(tail.to_string()); } if found.is_empty() { vec![text.to_string()] } else { found } } /// The paragraphs of `text` (split at a blank line), each a list when a line /// of it starts as a list's item does. fn blocks(text: &str) -> Vec { let normal = text.replace("\r\n", "\n"); let mut paragraphs: Vec> = vec![Vec::new()]; for line in normal.split('\n') { if line.trim().is_empty() { if !paragraphs.last().is_some_and(Vec::is_empty) { paragraphs.push(Vec::new()); } } else { paragraphs.last_mut().expect("a paragraph").push(line); } } paragraphs .into_iter() .filter(|lines| !lines.is_empty()) .map(|lines| { let text = lines.join("\n"); if lines.iter().any(|line| is_item(line)) { let mut items: Vec> = Vec::new(); for line in &lines { if is_item(line) || items.is_empty() { items.push(vec![line]); } else { items.last_mut().expect("an item").push(line); } } Block { text, units: items.into_iter().map(|item| item.join("\n")).collect(), join: "\n" } } else { let units = sentences(&text); Block { text, units, join: " " } } }) .collect() } /// `text` cut into pages of about `cap` words (see the module's words). pub fn cut(text: &str, cap: usize) -> Vec { let cap = cap.max(1); let mut pages: Vec = Vec::new(); let mut page: Vec = Vec::new(); let mut held = 0; let turn = |pages: &mut Vec, page: &mut Vec, held: &mut usize| { if !page.is_empty() { pages.push(page.join("\n\n")); } page.clear(); *held = 0; }; for block in blocks(text) { let size = count(&block.text); if held + size <= cap { page.push(block.text); held += size; continue; } if size <= cap { turn(&mut pages, &mut page, &mut held); page.push(block.text); held = size; continue; } // Too long for any page: its sentences (a list's items) poured on, // the page turning only between two of them. let mut run: Vec = Vec::new(); for unit in block.units { let size = count(&unit); if held + size > cap && !(page.is_empty() && run.is_empty()) { if !run.is_empty() { page.push(run.join(block.join)); } turn(&mut pages, &mut page, &mut held); run.clear(); } run.push(unit); held += size; } if !run.is_empty() { page.push(run.join(block.join)); } } turn(&mut pages, &mut page, &mut held); pages } #[cfg(test)] #[path = "reading_page_tests.rs"] mod tests;