//! `@Name` in a composer, phones in the file. //! //! The port of `packages/core/src/messages/mentions.ts`, itself ported from //! Tinmen's `packages/chat/src/utils/mentions.ts` with one change that matters: a //! mention resolves to a PHONE, not a user id. Cotton has no shared user table — //! the counterpart is somebody with their own file, and the only name for them //! every file agrees on is their number. //! //! ONE scanner serves both extraction and rendering ([`find_mention_ranges`]), so //! "who gets notified" and "what gets highlighted" can never drift apart. A //! mention overrides mute, which is why the matching rule is strict: a false //! positive rings a phone somebody deliberately silenced. //! //! # Everything here is indexed in UTF-16 code units //! //! `indexOf`, `slice`, `length` and a cursor position in a text input all count //! UTF-16 code units, and the ranges this module returns are handed straight to a //! renderer that slices the same string. So the scan runs over `Vec` and //! every index in [`MentionRange`], [`get_mention_query`] and [`insert_mention`] //! is a code-unit index — NOT a byte offset and NOT a `char` count. An emoji //! before a mention moves every index by two, on both sides, identically. use std::sync::LazyLock; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::messages::{units_to_string, utf16_units}; /// Somebody who can be @-mentioned here — a participant's contact, resolved. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MentionCandidate { /// Digits, no `+`. pub phone: String, pub name: String, } /// What a run of message text IS, for a renderer. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum SegmentKind { #[serde(rename = "text")] Text, #[serde(rename = "mention")] Mention, #[serde(rename = "link")] Link, } /// One run of message text for rendering. [`super::links`] splits these further. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MessageSegment { /// `type` on the wire — the TypeScript's discriminant, kept under its own /// name because `type` is a Rust keyword. #[serde(rename = "type")] pub kind: SegmentKind, pub content: String, /// Set on mention segments — the phone the name resolved to. #[serde(default, skip_serializing_if = "Option::is_none")] pub phone: Option, /// Set on link segments — the cleaned http(s) URL to open on tap. #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option, } impl MessageSegment { pub fn text(content: impl Into) -> Self { MessageSegment { kind: SegmentKind::Text, content: content.into(), phone: None, url: None, } } pub fn mention(content: impl Into, phone: impl Into) -> Self { MessageSegment { kind: SegmentKind::Mention, content: content.into(), phone: Some(phone.into()), url: None, } } pub fn link(content: impl Into, url: impl Into) -> Self { MessageSegment { kind: SegmentKind::Link, content: content.into(), phone: None, url: Some(url.into()), } } } /// A matched `@Name`, in UTF-16 code-unit indices. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MentionRange { pub start: usize, pub end: usize, pub phone: String, pub name: String, } /// `/[\p{L}\p{N}_]/u` — a word character, as the UNICODE GENERAL CATEGORIES. /// /// The `u` flag matters and the regex is written with `\p{…}` rather than with /// Rust's `char::is_alphanumeric` on purpose: `is_alphabetic` is the derived /// *Alphabetic* property (it takes in `Nl` and `Other_Alphabetic` marks), while /// `\p{L}` is the letter CATEGORY. The two disagree on characters real names /// contain, and a disagreement here decides whether "@Meera" inside a word is a /// mention. static WORD_CHARACTER: LazyLock = LazyLock::new(|| Regex::new(r"^[\p{L}\p{N}_]$").expect("the word-character class compiles")); /// `/\s/.test(unit)` — one UTF-16 code unit against ECMAScript's whitespace /// class. A lone surrogate is not whitespace, which is what the TypeScript's /// single-unit string test concludes too. fn unit_is_space(unit: u16) -> bool { char::from_u32(u32::from(unit)).is_some_and(cotton_store::protocol::js::is_js_whitespace) } /// True when `text[index]` ends a mention cleanly — end of string, or a non-word /// character. /// /// A lone surrogate reads as a clean boundary, exactly as the TypeScript's /// `/[\p{L}\p{N}_]/u.test(halfOfAnEmoji)` does: with the `u` flag a lone /// surrogate is in no category at all. fn is_right_boundary(units: &[u16], index: usize) -> bool { let Some(unit) = units.get(index) else { return true; }; match char::from_u32(u32::from(*unit)) { None => true, Some(ch) => !WORD_CHARACTER.is_match(ch.encode_utf8(&mut [0u8; 4])), } } /// `haystack.indexOf(needle, from)` over code units. fn index_of(haystack: &[u16], needle: &[u16], from: usize) -> Option { if needle.is_empty() { return Some(from.min(haystack.len())); } if needle.len() > haystack.len() { return None; } (from..=haystack.len() - needle.len()) .find(|start| &haystack[*start..start + needle.len()] == needle) } /// Non-overlapping `@Name` occurrences, LONGEST names first so "@Meera Iyer" is /// not also counted as a mention of "Meera". The `@` must start a word, so /// "ravi@Meera.com" is never a mention. /// /// Both sorts are STABLE, as `Array.prototype.sort` has been since ES2019: two /// candidates whose names are the same length keep the caller's order, and so do /// two ranges that start at the same index (which the non-overlap rule makes /// unreachable, but the order is still the one the TypeScript would produce). pub fn find_mention_ranges(text: &str, items: &[MentionCandidate]) -> Vec { let units = utf16_units(text); let mut sorted: Vec<&MentionCandidate> = items.iter().collect(); // `b.name.length - a.name.length` — UTF-16 length, descending. sorted.sort_by(|a, b| { crate::messages::utf16_len(&b.name).cmp(&crate::messages::utf16_len(&a.name)) }); let mut ranges: Vec = Vec::new(); for item in sorted { if item.name.is_empty() { continue; } let token = utf16_units(&format!("@{}", item.name)); let mut from = 0usize; while let Some(index) = index_of(&units, &token, from) { from = index + 1; let end = index + token.len(); // The `@` must open a word: anything but whitespace before it means // the text is "ravi@Meera.com", not a mention of Meera. if index > 0 && !unit_is_space(units[index - 1]) { continue; } if !is_right_boundary(&units, end) { continue; } if ranges .iter() .any(|range| index < range.end && end > range.start) { continue; } ranges.push(MentionRange { start: index, end, phone: item.phone.clone(), name: item.name.clone(), }); } } ranges.sort_by_key(|range| range.start); ranges } /// The phones a finished body mentions — de-duped, in first-seen order. pub fn extract_mentions(text: &str, candidates: &[MentionCandidate]) -> Vec { if text.is_empty() || candidates.is_empty() { return Vec::new(); } let mut found: Vec = Vec::new(); for range in find_mention_ranges(text, candidates) { if !found.contains(&range.phone) { found.push(range.phone); } } found } /// The active mention query at the cursor. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MentionQuery { pub query: String, /// The `@`'s index, in UTF-16 code units. pub start: usize, } /// The active mention query at the cursor: the text between the nearest /// word-starting `@` before the cursor and the cursor itself. Once the person /// types a space the picker closes, WhatsApp-style. /// /// `cursor` is a UTF-16 index — what a text input reports. The TypeScript's /// `cursor <= 0` covers a negative, which a `usize` cannot be; zero answers /// `None` on both sides, and a cursor past the end clamps to the end exactly as /// `String.prototype.slice` does. pub fn get_mention_query(text: &str, cursor: usize) -> Option { if cursor == 0 { return None; } let units = utf16_units(text); let before = &units[..cursor.min(units.len())]; // `beforeCursor.lastIndexOf("@")` — the nearest `@` BEFORE the cursor, never // one further along the line the person has not reached yet. let at = before.iter().rposition(|unit| *unit == u16::from(b'@'))?; if at > 0 && !unit_is_space(before[at - 1]) { return None; } let query = &before[at + 1..]; if query.iter().copied().any(unit_is_space) { return None; } Some(MentionQuery { query: units_to_string(query), start: at, }) } /// The text and cursor after a mention is picked. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MentionInsertion { pub text: String, /// UTF-16 code units, ready to hand back to a text input. pub cursor: usize, } /// Replace the active query with `@Name ` and put the cursor after it. pub fn insert_mention( text: &str, query_start: usize, cursor: usize, name: &str, ) -> MentionInsertion { let units = utf16_units(text); let inserted = utf16_units(&format!("@{name} ")); let head = &units[..query_start.min(units.len())]; let tail = &units[cursor.min(units.len())..]; let mut out: Vec = Vec::with_capacity(head.len() + inserted.len() + tail.len()); out.extend_from_slice(head); out.extend_from_slice(&inserted); out.extend_from_slice(tail); MentionInsertion { text: units_to_string(&out), cursor: query_start + inserted.len(), } } /// Split body text into plain and mention runs for rendering. pub fn segment_mentions(text: &str, candidates: &[MentionCandidate]) -> Vec { if text.is_empty() { return Vec::new(); } let matches = if candidates.is_empty() { Vec::new() } else { find_mention_ranges(text, candidates) }; if matches.is_empty() { return vec![MessageSegment::text(text)]; } let units = utf16_units(text); let mut segments: Vec = Vec::new(); let mut pos = 0usize; for range in matches { if range.start > pos { segments.push(MessageSegment::text(units_to_string( &units[pos..range.start], ))); } segments.push(MessageSegment::mention( units_to_string(&units[range.start..range.end]), range.phone, )); pos = range.end; } if pos < units.len() { segments.push(MessageSegment::text(units_to_string(&units[pos..]))); } segments } /// The one question that overrides a muted thread (spec §5.7). pub fn mentions_phone(mentions: &[String], phone: Option<&str>) -> bool { match phone { None => false, Some(phone) => mentions.iter().any(|one| one == phone), } } #[cfg(test)] #[path = "mentions_tests.rs"] mod tests;