Cotton code
122 lines · 4.8 KB · RustRaw
//! A page of messages laid as a thread: which bubbles run together, where//! the tails fall, where a day divider and the unread divider stand.//!//! Pages meet without a seam: the read hands the message just above the//! page (`above`) and just below it (`below`), so the first bubble of a page//! knows whether it continues the run above, and a day's divider stands over//! that day's first message whichever page holds it.use super::shapes::GROUP_GAP_MS;/// One message as the layout needs it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Laid {    pub id: String,    /// Who wrote it: `me`, a participant's key, or the contact's.    pub sender: String,    pub at_ms: i64,    /// The reader's calendar day, as any key that is equal for one day.    pub day: i64,    /// A group event or aside: it never runs with a bubble.    pub event: bool,}/// What stands in a laid page, oldest first.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Slot {    /// A day divider over the message at `index`.    Day { index: usize },    /// The unread divider over the message at `index`.    Unread { index: usize },    /// The message at `index` of the page. `face`: the first of one sender's    /// unbroken words in a day, where their picture (and in a group their    /// name) stands, once however long they took between lines; a run's    /// `head` also starts after a pause, for its spacing.    Message { index: usize, head: bool, tail: bool, face: bool },}fn runs(a: &Laid, b: &Laid) -> bool {    same_stretch(a, b) && (b.at_ms - a.at_ms).abs() <= GROUP_GAP_MS}/// One sender's words with nothing between them on one day: a pause does/// not break it, another sender, an event or a new day does.fn same_stretch(a: &Laid, b: &Laid) -> bool {    !a.event && !b.event && a.sender == b.sender && a.day == b.day}/// Lay `page` (oldest first). `unread_from` is the first unread message's/// id; its divider breaks a run, as a day does.pub fn lay(page: &[Laid], above: Option<&Laid>, below: Option<&Laid>, unread_from: Option<&str>) -> Vec<Slot> {    let mut slots = Vec::with_capacity(page.len() + 4);    let unread_at = unread_from.and_then(|id| page.iter().position(|m| m.id == id));    for (index, message) in page.iter().enumerate() {        let previous = if index == 0 { above } else { page.get(index - 1) };        let next = page.get(index + 1).or(if index + 1 == page.len() { below } else { None });        if previous.is_none_or(|p| p.day != message.day) {            slots.push(Slot::Day { index });        }        let divided_here = unread_at == Some(index);        if divided_here {            slots.push(Slot::Unread { index });        }        let divided_next = unread_at == Some(index + 1) || (index + 1 == page.len() && below.is_some_and(|b| Some(b.id.as_str()) == unread_from));        let head = divided_here || previous.is_none_or(|p| !runs(p, message));        let tail = divided_next || next.is_none_or(|n| !runs(message, n));        let face = !message.event && (divided_here || previous.is_none_or(|p| !same_stretch(p, message)));        slots.push(Slot::Message { index, head, tail, face });    }    slots}/// Initials for a person's or a group's picture, the one place they are made: the first letter of the first two words/// that have one, uppercased. A word of digits gives none, so a number (a person with no name, "+1555…") is no/// letter but the neutral `#`, never its first digit (CALLS WALK 1).pub fn initials(name: &str) -> String {    let letters: String = name        .split_whitespace()        .filter_map(|word| word.chars().find(|c| c.is_alphabetic()))        .take(2)        .flat_map(char::to_uppercase)        .collect();    if letters.is_empty() {        "#".into()    } else {        letters    }}/// A steady tint for a key (a thread's or a sender's id): the same key/// always draws the same colour, on every phone.pub fn tint(key: &str) -> u32 {    // FNV-1a: stable across builds and platforms, unlike the std hasher.    let mut hash: u32 = 0x811c_9dc5;    for byte in key.bytes() {        hash ^= u32::from(byte);        hash = hash.wrapping_mul(0x0100_0193);    }    hash % super::shapes::TINTS}/// A first name: the first word of a name.pub fn first_name(name: &str) -> String {    name.split_whitespace().next().unwrap_or(name).to_string()}/// "0:12", "1:05:09": the chat list's own rule (`preview::format_duration`, rounded up), so a/// bubble and its list line always say the same length.pub fn length(ms: f64) -> String {    crate::messages::preview::format_duration(ms)}/// "820 KB", "2.4 MB".pub fn size(bytes: f64) -> String {    const KB: f64 = 1024.0;    if bytes < KB * KB {        format!("{} KB", (bytes / KB).ceil().max(1.0) as i64)    } else if bytes < KB * KB * KB {        format!("{:.1} MB", bytes / (KB * KB))    } else {        format!("{:.1} GB", bytes / (KB * KB * KB))    }}