BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / reactions.rs

reactions.rs

reactions.rs 1.7 KiB Download Raw
1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::sync::OnceLock;
4
5const EMOTIONS: &str = include_str!("../assets/emotions.tsv");
6
7type Index = HashMap<&'static str, Vec<&'static str>>;
8
9fn index() -> &'static Index {
10 static PARSED: OnceLock<Index> = OnceLock::new();
11 PARSED.get_or_init(|| {
12 EMOTIONS
13 .lines()
14 .filter_map(|line| {
15 let (glyph, keys) = line.split_once('\t')?;
16 Some((glyph, keys.split(' ').collect()))
17 })
18 .collect()
19 })
20}
21
22pub fn emotion_keys(glyph: &str) -> &'static [&'static str] {
23 let bare = if glyph.contains('\u{FE0F}') {
24 Cow::Owned(glyph.replace('\u{FE0F}', ""))
25 } else {
26 Cow::Borrowed(glyph)
27 };
28 index().get(bare.as_ref()).map_or(&[], Vec::as_slice)
29}
30
31pub fn emotion_key(glyph: &str) -> Option<&'static str> {
32 emotion_keys(glyph).first().copied()
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn resolves_teams_keys() {
41 assert_eq!(
42 emotion_key("\u{1F603}"),
43 Some("1f603_grinningfacewithbigeyes")
44 );
45 assert_eq!(emotion_key("\u{1F44D}"), Some("like"));
46 }
47
48 #[test]
49 fn ignores_variation_selectors() {
50 assert_eq!(emotion_key("\u{2764}"), Some("heart"));
51 assert_eq!(emotion_key("\u{2764}\u{FE0F}"), Some("heart"));
52 }
53
54 #[test]
55 fn lists_alias_keys_with_the_primary_first() {
56 assert_eq!(
57 emotion_keys("\u{1F603}"),
58 ["1f603_grinningfacewithbigeyes", "happyface"]
59 );
60 assert_eq!(emotion_keys("\u{2764}\u{FE0F}")[0], "heart");
61 }
62
63 #[test]
64 fn unknown_glyph_has_no_key() {
65 assert_eq!(emotion_key("x"), None);
66 assert!(emotion_keys("x").is_empty());
67 }
68}