Cotton code
243 lines · 9.8 KB · RustRaw
//! Which characters in a body are a link.//!//! The port of `packages/core/src/messages/links.ts`, itself ported from Tinmen's//! `packages/chat/src/utils/links.ts` unchanged in behaviour, because the//! behaviour was right and had been argued over: only EXPLICIT `http(s)://` URLs//! are links. A bare domain stays plain text, so "we discussed it at cottondb.com//! yesterday" does not turn a sentence into a tappable thing nobody meant to tap.//!//! The subtle half is the trailing trim. "see https://a.com/b." must not fetch//! "https://a.com/b." — but "https://en.wikipedia.org/wiki/Rust_(language)" must//! keep its bracket. So a closing bracket is trimmed only while UNBALANCED within//! the match, and the whole trim runs in a loop because punctuation stacks://! "(https://a.com/).".//!//! # Two places this port had to be deliberate//!//! * **The URL pattern is `/https?:\/\/[^\s<>"]+/gi`, and neither flag survives a//!   naive translation.** JavaScript's `i` WITHOUT `u` refuses to fold U+017F//!   (ſ) and U+212A (K) onto ASCII, while Rust's `(?i)` folds both — so//!   `httpſ://x` would be a link here and not there. The scheme is therefore//!   written `(?i-u:https?)`. And `\s` is ECMAScript's class, spelled out below,//!   not Rust's `\s`.//! * **`start` and `end` are UTF-16 code-unit indices**, because the TypeScript's//!   `match.index` is one and [`segment_links`] slices the same string with them.//!   The regex works in bytes; every offset it produces is converted before it//!   leaves this module.use std::sync::LazyLock;use regex::Regex;use crate::messages::mentions::{segment_mentions, MentionCandidate, MessageSegment, SegmentKind};use crate::messages::{units_to_string, utf16_units};/// `/https?:\/\/[^\s<>"]+/gi`.////// `(?i-u:https?)` is the `i`-without-`u` fold: ASCII case only, so the two/// runtimes agree about which strings open a URL. The negated class spells/// ECMAScript's `\s` out — `WhiteSpace` (the `Space_Separator` category plus tab,/// vertical tab, form feed, no-break space and the BOM) and `LineTerminator` (LF,/// CR, LS, PS) — because Rust's `\s` is the Unicode `White_Space` property, which/// excludes U+FEFF and includes U+0085.static URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| {    Regex::new(        "(?i-u:https?)://[^\         \u{9}\u{a}\u{b}\u{c}\u{d}\u{20}\u{a0}\u{1680}\         \u{2000}-\u{200a}\u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}\         <>\"]+",    )    .expect("the URL pattern compiles")});/// `/^https?:\/\/[^\/]/i` — a scheme that actually names a host.static HAS_HOST: LazyLock<Regex> =    LazyLock::new(|| Regex::new("^(?i-u:https?)://[^/]").expect("the host guard compiles"));/// Trailing characters that are almost always the sentence's, not the URL's.////// `/[.,;:!?'"‘’“”…]+$/` — the curly quotes and the ellipsis are single code/// points, so the class is written as a `char` set rather than a regex; trimming/// from the END is a `pop` loop either way.const TRAILING_PUNCTUATION: [char; 13] = [    '.', ',', ';', ':', '!', '?', '\'', '"', '\u{2018}', '\u{2019}', '\u{201c}', '\u{201d}',    '\u{2026}',];const BRACKET_PAIRS: [(char, char); 3] = [('(', ')'), ('[', ']'), ('{', '}')];/// `for (const c of text) if (c === char) count += 1` — a CODE POINT walk, which/// is what `for…of` over a string is. The characters counted are ASCII brackets,/// so this agrees with a code-unit count too.fn count_char(text: &str, ch: char) -> usize {    text.chars().filter(|one| *one == ch).count()}/// Strip the sentence's punctuation off the end of a URL, in a loop, keeping a/// bracket the URL opened itself.pub fn trim_trailing_punctuation(url: &str) -> String {    let mut result = url.to_string();    let mut changed = true;    while changed {        changed = false;        let trimmed = result.trim_end_matches(TRAILING_PUNCTUATION);        if trimmed.len() != result.len() {            result = trimmed.to_string();            changed = true;        }        for (open, close) in BRACKET_PAIRS {            while result.ends_with(close) && count_char(&result, close) > count_char(&result, open)            {                // `result.slice(0, -1)` drops ONE UTF-16 code unit; the guard                // above means the last character is an ASCII bracket, so one unit                // and one `char` are the same thing here.                result.pop();                changed = true;            }        }    }    result}/// One http(s) URL found in a body.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LinkMatch {    /// The cleaned URL.    pub url: String,    /// UTF-16 code-unit index of the match's start within the original text.    pub start: usize,    /// UTF-16 code-unit index one past the CLEANED url's last unit.    pub end: usize,}/// Every link in a message's words, where it stands (UTF-16 `[start, end)`) and the address a tap opens.pub fn links_at(text: &str) -> Vec<crate::messages::app::shapes::LinkAt> {    find_links(text).into_iter().map(|m| crate::messages::app::shapes::LinkAt { at: [m.start as u32, m.end as u32], url: m.url }).collect()}/// Every http(s) URL in `text`, defensively cleaned, in order.////// The TypeScript keeps its regex at module scope with the `/g` flag and has to/// reset `lastIndex` by hand — "the second call over the same string finds/// nothing" otherwise. Rust's `Regex` carries no such cursor, so the hazard does/// not exist here; the TypeScript's own test for it is ported anyway, because the/// BEHAVIOUR (two identical calls, two identical answers) is what callers rely/// on.pub fn find_links(text: &str) -> Vec<LinkMatch> {    if text.is_empty() {        return Vec::new();    }    let mut matches: Vec<LinkMatch> = Vec::new();    for found in URL_PATTERN.find_iter(text) {        let cleaned = trim_trailing_punctuation(found.as_str());        // "https://" alone, or "https:///x", names no host and is not a link.        if !HAS_HOST.is_match(&cleaned) {            continue;        }        // `match.index` is a UTF-16 index in JavaScript; the byte offset the        // regex crate reports has to be converted or every index after an emoji        // would be wrong by one per astral character.        let start = crate::messages::utf16_len(&text[..found.start()]);        let end = start + crate::messages::utf16_len(&cleaned);        matches.push(LinkMatch {            url: cleaned,            start,            end,        });    }    matches}/// The URL the composer fetches a preview for.pub fn extract_first_url(text: &str) -> Option<String> {    find_links(text).into_iter().next().map(|link| link.url)}/// Split the already mention-segmented runs further so URLs become `link`/// segments. A mention run is never re-split: even if a name contained a URL, the/// mention wins.pub fn segment_links(segments: &[MessageSegment]) -> Vec<MessageSegment> {    let mut result: Vec<MessageSegment> = Vec::new();    for segment in segments {        if segment.kind != SegmentKind::Text {            result.push(segment.clone());            continue;        }        let links = find_links(&segment.content);        if links.is_empty() {            result.push(segment.clone());            continue;        }        let units = utf16_units(&segment.content);        let mut pos = 0usize;        for link in links {            if link.start > pos {                result.push(MessageSegment::text(units_to_string(                    &units[pos..link.start],                )));            }            result.push(MessageSegment::link(                units_to_string(&units[link.start..link.end]),                link.url,            ));            pos = link.end;        }        if pos < units.len() {            result.push(MessageSegment::text(units_to_string(&units[pos..])));        }    }    result}/// Full render-segmentation for a body: mention runs first, then URLs.pub fn segment_message_body(text: &str, candidates: &[MentionCandidate]) -> Vec<MessageSegment> {    segment_links(&segment_mentions(text, candidates))}/// The hostname without `www.`, for a preview card's domain line.////// `new URL(url).hostname`, and the `url` crate is what makes that claim/// truthful: WHATWG URL parsing lower-cases the host, punycodes an/// internationalised one and brackets an IPv6 literal, and a hand-rolled split on/// `/` would agree with none of it. A string the parser refuses comes back/// unchanged, which is the TypeScript's `catch`.////// A URL with no host at all (`mailto:someone@example.com`) has `hostname === ""`/// in JavaScript, so it returns the empty string rather than the input — the same/// answer, because `""` does not start with `www.`.pub fn display_domain(url: &str) -> String {    match url::Url::parse(url) {        Err(_) => url.to_string(),        Ok(parsed) => {            let host = parsed.host_str().unwrap_or("");            match host.strip_prefix("www.") {                Some(rest) => rest.to_string(),                None => host.to_string(),            }        }    }}/// Every distinct URL in a message body, in first-seen order.////// The cross-track ruling called this `extractUrls`. It cannot have that name:/// `engine/urls.ts` already exports `extractUrls` for saved pages, with a/// DIFFERENT trailing rule (no balanced-bracket pass), and two of them behind one/// barrel means a caller writing `extractUrls` gets whichever the module graph/// resolved — the silent drift this codebase forbids. The chat rule is this one;/// the pages rule is [`crate::transforms::urls`]; the names now say which.pub fn extract_message_urls(body: &str) -> Vec<String> {    let mut urls: Vec<String> = Vec::new();    for link in find_links(body) {        if !urls.contains(&link.url) {            urls.push(link.url);        }    }    urls}#[cfg(test)]#[path = "links_tests.rs"]mod tests;