Cotton code
157 lines · 6.9 KB · RustRaw
//! What a note is CALLED on any surface that lists it.//!//! The port of `apps/cotton/src/tools/notes/lib/noteTitle.ts` and the//! `stripMarkdown` half of `apps/cotton/src/tools/notes/lib/markdown.ts` that//! it stands on. It is here rather than in the reader that needed it//! (`cotton-ffi`'s `read.openComments`) for the reason `home_today` is here://! it is a PURE rule about what a record is called, and a second spelling of//! it is how one surface comes to read "Untitled" over the very words another//! surface uses as the name.//!//! `noteTitle.ts`'s own docstring records that this bug was fixed once//! already: *"a note with a perfectly usable first line used to render as//! 'Untitled' — the router files a captured note with `title: null`."*//!//! **The English word is NOT here**, deliberately, and neither is it in any//! caller written in Rust. [`note_display_title`] answers `None` for a note//! with genuinely nothing to call it, and the surface that draws it owns the//! word (`CottonStrings.untitled` on the phone) — which is the TypeScript's//! own division (*"The caller owns the 'Untitled' word, so this stays pure//! copy-free"*) and the only spelling that keeps user copy out of a crate no//! catalogue sweep can reach.use std::sync::OnceLock;use regex::Regex;/// What a note is called: its own title, else its body's whole first line./// Drawing surfaces own truncation; a derived name never drops stored words./// Returns `None` when the body has no words after Markdown is stripped.pub fn note_display_title(title: Option<&str>, body: &str) -> Option<String> {    let named = title.unwrap_or("").trim();    if !named.is_empty() {        return Some(named.to_string());    }    strip_markdown(body).lines().next().map(str::to_string)}/// The original Markdown after the opening line borrowed as a title./// Match the rendered line, but slice the source at its line break: later/// lists, emphasis and blank lines belong to the body exactly as written./// If a multi-line Markdown construct supplied the title, keep its source/// intact rather than removing part of that construct.pub fn body_after_borrowed_title<'a>(body: &'a str, title: &str) -> &'a str {    let mut end = 0;    for line in body.split_inclusive('\n') {        end += line.len();        let plain = strip_markdown(line);        if plain.is_empty() { continue; }        return if plain == title { &body[end..] } else { body };    }    body}/// Plain words for compact previews.pub fn plain_preview(body: &str) -> String {    let plain = markdown_words(body);    let plain = unfinished_link().replace_all(&plain, "$1");    let plain = unfinished_label().replace_all(&plain, "$1");    plain.replace('`', "")}/// Remove Markdown syntax without choosing a caller's whitespace rules.fn markdown_words(body: &str) -> String {    let mut text = fenced_code().replace_all(body, "$1").into_owned();    text = image_link().replace_all(&text, "$1").into_owned();    text = inline_link().replace_all(&text, "$1").into_owned();    text = atx_heading().replace_all(&text, "").into_owned();    text = blockquote().replace_all(&text, "").into_owned();    text = list_marker().replace_all(&text, "").into_owned();    text = horizontal_rule().replace_all(&text, "").into_owned();    // Strong before emphasis, and both by a left-to-right scan rather than a    // regex: the TypeScript writes `(\*\*|__)(.*?)\1`, a BACKREFERENCE, and    // `regex` has none. Running `**…**` over the whole body and then `__…__`    // over the whole body is a DIFFERENT function — it can pair an opening    // mark with a closing one the alternation had already consumed — so the    // scan below reproduces the alternation instead: at each position, try the    // delimiters in the TypeScript's own order, take the first that closes on    // its own line, and resume after it.    text = unwrap_pairs(&text, &["**", "__"]);    text = unwrap_pairs(&text, &["*", "_"]);    text = unwrap_pairs(&text, &["~~"]);    text = inline_code().replace_all(&text, "$1").into_owned();    text}/// Markdown → plain-text preview text, the `stripMarkdown` rules in order.////// A PREVIEW cleaner, not a parser: it removes the common inline and block/// markers and tidies whitespace, and anything exotic passes through as-is./// **Line breaks survive** — a note's lines are its structure, and flattening/// them fuses a reading list into one sentence nobody wrote.pub fn strip_markdown(body: &str) -> String {    let text = markdown_words(body);    text.split('\n')        .map(|line| line.trim_end_matches('\r'))        .map(|line| whitespace_run().replace_all(line, " ").trim().to_string())        .filter(|line| !line.is_empty())        .collect::<Vec<String>>()        .join("\n")}/// `(\*\*|__)(.*?)\1` — the emphasis wrappers, unwrapped left to right.////// `.` does NOT match a newline in the TypeScript (no `s` flag), so a wrapper/// whose closing mark is on the next line is not a wrapper at all and stays as/// it was written. `(.*?)` is lazy: the FIRST closing mark on the line wins.fn unwrap_pairs(text: &str, delimiters: &[&str]) -> String {    let mut out = String::with_capacity(text.len());    let mut rest = text;    'scan: while !rest.is_empty() {        for delimiter in delimiters {            if !rest.starts_with(delimiter) {                continue;            }            let inner = &rest[delimiter.len()..];            let line_end = inner.find('\n').unwrap_or(inner.len());            if let Some(close) = inner[..line_end].find(delimiter) {                out.push_str(&inner[..close]);                rest = &inner[close + delimiter.len()..];                continue 'scan;            }        }        let next = rest.chars().next().expect("a non-empty remainder");        out.push(next);        rest = &rest[next.len_utf8()..];    }    out}/// Each regex compiled once. A `OnceLock` rather than a module constant/// because `Regex::new` is not `const`; the crate holds no other state and/// these are pure tables.macro_rules! cached_regex {    ($name:ident, $pattern:expr) => {        fn $name() -> &'static Regex {            static CELL: OnceLock<Regex> = OnceLock::new();            CELL.get_or_init(|| Regex::new($pattern).expect("a valid pattern"))        }    };}cached_regex!(fenced_code, r"(?s)```[a-zA-Z0-9-]*\n?(.*?)```");cached_regex!(image_link, r"!\[([^\]]*)\]\([^)]*\)");cached_regex!(inline_link, r"\[([^\]]*)\]\([^)]*\)");cached_regex!(atx_heading, r"(?m)^#{1,6}\s+");cached_regex!(blockquote, r"(?m)^>\s?");cached_regex!(list_marker, r"(?m)^\s*(?:[-*+]|\d+\.)\s+");cached_regex!(horizontal_rule, r"(?m)^(?:-{3,}|\*{3,}|_{3,})\s*$");cached_regex!(inline_code, "`([^`]*)`");cached_regex!(whitespace_run, r"\s+");cached_regex!(unfinished_link, r"\[([^\]\n]*)\]\([^)]*$");cached_regex!(unfinished_label, r"\[([^\]\n]*)$");#[cfg(test)]#[path = "note_title_tests.rs"]mod tests;