// @點名 in a group chat: 「@FSD 追蹤專員 你看呢」 picks who answers. Names may hold spaces, so a // mention is found by the names it can be (the longest one that the words after the @ start with), // not by cutting at the next space. Half- and full-width @ both count (a phone's keyboard gives // either). /// The @ signs a person (or a bot) may type. fn is_at(c: char) -> bool { c == '@' || c == '@' } /// Who the text names, in the order it names them, each once: `names` are (id, name). An @ that /// names nobody (an e-mail address, 「@大家」) is passed over. pub fn mentioned(text: &str, names: &[(u64, String)]) -> Vec { let mut out: Vec = Vec::new(); for (i, c) in text.char_indices() { if !is_at(c) { continue; } let rest = text[i + c.len_utf8()..].to_lowercase(); // The longest name wins: 「@FSD 追蹤專員」 is that bot, not one called 「FSD」. let hit = names.iter().filter(|(_, n)| !n.trim().is_empty() && rest.starts_with(&n.trim().to_lowercase())).max_by_key(|(_, n)| n.trim().chars().count()); if let Some((id, _)) = hit { if !out.contains(id) { out.push(*id); } } } out } /// What is being typed after an @ at the end of a draft (「…問一下 @FS」 → 「FS」): None when the /// draft doesn't end in a mention being typed. A new line ends it; so does a long run of words /// (that is the message, not a name). pub fn typing(draft: &str) -> Option<&str> { let (i, c) = draft.char_indices().rev().find(|(_, c)| is_at(*c))?; let q = &draft[i + c.len_utf8()..]; // An @ glued to the word before it is an address (name@example.com), not a mention. let glued = draft[..i].chars().next_back().is_some_and(|p| p.is_ascii_alphanumeric()); (!glued && !q.contains('\n') && q.chars().count() <= 24).then_some(q) } /// The names that fit what is typed: starting with it first, then containing it. pub fn matches<'a>(q: &str, names: &'a [(u64, String)]) -> Vec<&'a (u64, String)> { let q = q.trim_start().to_lowercase(); let mut hits: Vec<(u8, &(u64, String))> = names .iter() .filter_map(|e| { let n = e.1.to_lowercase(); let rank = if n.starts_with(&q) { 0 } else if n.contains(&q) { 1 } else { return None; }; Some((rank, e)) }) .collect(); hits.sort_by_key(|(r, _)| *r); hits.into_iter().map(|(_, e)| e).collect() } /// The draft with the @ being typed replaced by the whole name and a space. pub fn complete(draft: &str, name: &str) -> String { match draft.char_indices().rev().find(|(_, c)| is_at(*c)) { Some((i, c)) => format!("{}{c}{name} ", &draft[..i]), None => format!("{draft}@{name} "), } } /// The pieces of a text that can be matched against another: pairs of neighbouring CJK /// characters (Chinese has no spaces), and latin words of three letters or more, lowercased. fn pieces(text: &str) -> std::collections::HashSet { const FILLER: &str = "的了是和與或在有也就都要會請幫我你他她它們這那個嗎呢吧啊"; let mut out = std::collections::HashSet::new(); let mut word = String::new(); let mut before: Option = None; for c in text.chars().chain(std::iter::once(' ')) { if c.is_ascii_alphanumeric() { word.push(c.to_ascii_lowercase()); before = None; continue; } if word.chars().count() >= 3 { out.insert(std::mem::take(&mut word)); } word.clear(); let cjk = ('\u{4e00}'..='\u{9fff}').contains(&c) && !FILLER.contains(c); if let (true, Some(b)) = (cjk, before) { out.insert([b, c].iter().collect()); } before = cjk.then_some(c); } out } /// 群組裡沒有點名: the members whose 擅長 the message is about (and whose 「不找它做的事」 it /// isn't). Empty when that says nothing — nobody fits, or everybody does — and then everyone /// answers in turn, as before. `members`: (id, 擅長, 不找它做的事). pub fn suited(text: &str, members: &[(u64, String, String)]) -> Vec { let said = pieces(text); // (A latin word is a whole word: as good as two pairs.) let hits = |field: &str| pieces(field).iter().filter(|p| said.contains(*p)).map(|p| if p.is_ascii() { 2 } else { 1 }).sum::(); let fit: Vec = members.iter().filter(|(_, good, not)| hits(good) >= 2 && hits(not) < 2).map(|m| m.0).collect(); if fit.len() == members.len() { return vec![]; } fit } #[cfg(test)] mod tests { use super::*; fn names() -> Vec<(u64, String)> { vec![(1, "FSD".into()), (2, "FSD 追蹤專員".into()), (3, "明日之星".into()), (4, "Bot".into())] } #[test] fn names_are_found_whole_in_the_order_written() { let n = names(); assert_eq!(mentioned("@FSD 追蹤專員 你看呢?", &n), vec![2], "the longest name wins"); assert_eq!(mentioned("@FSD 先查", &n), vec![1]); assert_eq!(mentioned("@明日之星 和 @bot 一起看,@明日之星 再補充", &n), vec![3, 4], "full-width, any case, each once"); assert!(mentioned("寄到 a@example.com,@大家 早", &n).is_empty()); assert!(mentioned("沒有點名", &n).is_empty()); } #[test] fn the_name_being_typed_is_completed() { assert_eq!(typing("問一下 @FS"), Some("FS")); assert_eq!(typing("@"), Some("")); assert_eq!(typing("@FSD 追"), Some("FSD 追"), "names have spaces"); assert_eq!(typing("沒有"), None); assert_eq!(typing("寄到 a@exam"), None, "an address"); assert_eq!(typing("@明日之星\n下一行"), None); let n = names(); let hit: Vec = matches("fsd", &n).iter().map(|e| e.0).collect(); assert_eq!(hit, vec![1, 2]); assert_eq!(matches("之星", &n).first().map(|e| e.0), Some(3)); assert!(matches("沒有這個", &n).is_empty()); assert_eq!(complete("問一下 @FS", "FSD 追蹤專員"), "問一下 @FSD 追蹤專員 "); assert_eq!(complete("@明", "明日之星"), "@明日之星 "); } #[test] fn a_group_message_goes_to_whoever_is_good_at_it() { let m = vec![(1, "查資料、寫摘要、追 Threads 上的討論".to_string(), "不寫程式".to_string()), (2, "寫程式、修 bug、看 log".to_string(), String::new()), (3, String::new(), String::new())]; assert_eq!(super::suited("幫我查資料:台積電這季的營收", &m), vec![1]); assert_eq!(super::suited("這個 bug 幫我寫程式修掉", &m), vec![2], "1 says not to come to it for this"); assert_eq!(super::suited("threads 上大家怎麼說", &m), vec![1]); assert!(super::suited("大家覺得呢?", &m).is_empty(), "nothing to go on: everyone"); assert!(super::suited("桌上的書", &m).is_empty(), "one chance pair is not a match"); let both = vec![(1, "寫摘要".to_string(), String::new()), (2, "寫摘要".to_string(), String::new())]; assert!(super::suited("寫摘要", &both).is_empty(), "everybody fits: everyone, as before"); } }