use serde_json::Value; use unicode_segmentation::UnicodeSegmentation; use crate::model::Facet; pub fn grapheme_count(text: &str) -> usize { text.graphemes(true).count() } /// Remove a trailing thread counter such as `1/`, `2/7`, `(3/9)` or `🧵`. pub fn strip_thread_counter(text: &str) -> String { let mut text = text.trim_end().to_string(); loop { let trimmed = text.trim_end(); let token_start = trimmed .rfind(char::is_whitespace) .map(|index| index + 1) .unwrap_or(0); let token = &trimmed[token_start..]; if !is_counter(token) { break; } text = trimmed[..token_start].trim_end().to_string(); } text } fn is_counter(token: &str) -> bool { let token = token.trim_matches(|character| matches!(character, '(' | ')' | '[' | ']' | '【' | '】')); if token.is_empty() { return false; } if token.contains('🧵') { let rest = token.replace('🧵', ""); return rest.trim().is_empty() || rest .trim() .chars() .all(|character| character.is_ascii_digit() || character == '/'); } let parts: Vec<&str> = token.split('/').collect(); if parts.len() != 2 || !token.contains('/') { return false; } let left = parts[0].trim(); let right = parts[1].trim(); !left.is_empty() && left.chars().all(|character| character.is_ascii_digit()) && (right.is_empty() || right.chars().all(|character| character.is_ascii_digit())) } /// Render facets as Markdown. Facet offsets are UTF-8 bytes. pub fn render_facets(text: &str, facets: &[Facet]) -> String { let mut spans: Vec<(usize, usize, String)> = facets .iter() .filter_map(|facet| { let start = facet.index.byte_start; let end = facet.index.byte_end; if start >= end || end > text.len() || !text.is_char_boundary(start) || !text.is_char_boundary(end) { return None; } let original = &text[start..end]; let replacement = facet.features.iter().find_map(|feature| { let kind = feature.get("$type").and_then(Value::as_str).unwrap_or(""); if kind.ends_with("#link") { let uri = feature.get("uri").and_then(Value::as_str)?; Some(format!("[{original}]({uri})")) } else if kind.ends_with("#mention") { let did = feature.get("did").and_then(Value::as_str)?; Some(format!("[{original}](https://bsky.app/profile/{did})")) } else if kind.ends_with("#tag") { Some(original.to_string()) } else { None } })?; Some((start, end, replacement)) }) .collect(); spans.sort_by_key(|(start, _, _)| *start); let mut rendered = String::new(); let mut cursor = 0; for (start, end, replacement) in spans { if start < cursor { continue; } rendered.push_str(&text[cursor..start]); rendered.push_str(&replacement); cursor = end; } rendered.push_str(&text[cursor..]); rendered } /// The first line, trimmed and cut to `max` characters. pub fn first_line(text: &str, max: usize) -> String { let line = text.lines().next().unwrap_or("").trim(); line.chars().take(max).collect() }