BlueGit

ict rusty-teams

Files

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

reactions.rs

fb874ac1 History
reactions.rs 6.5 KiB Download Raw
1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::sync::OnceLock;
4
5const EMOTIONS: &str = include_str!("../assets/emotions.tsv");
6const EMOTICONS: &str = include_str!("../../app/assets/emoticons.tsv");
7const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}';
8const TONE_MARKER: &str = "-tone";
9const ZERO_WIDTH_JOINER: char = '\u{200d}';
10const VARIATION_SELECTOR: char = '\u{fe0f}';
11const MAX_TONE: u8 = 5;
12
13type Index = HashMap<&'static str, Vec<&'static str>>;
14
15fn index() -> &'static Index {
16 static PARSED: OnceLock<Index> = OnceLock::new();
17 PARSED.get_or_init(|| {
18 EMOTIONS
19 .lines()
20 .filter_map(|line| {
21 let (glyph, keys) = line.split_once('\t')?;
22 Some((glyph, keys.split(' ').collect()))
23 })
24 .collect()
25 })
26}
27
28fn diverse_ids() -> &'static std::collections::HashSet<&'static str> {
29 static PARSED: OnceLock<std::collections::HashSet<&'static str>> = OnceLock::new();
30 PARSED.get_or_init(|| {
31 EMOTICONS
32 .lines()
33 .filter_map(|line| {
34 let fields: Vec<&str> = line.split('\t').collect();
35 (fields.get(4) == Some(&"1")).then_some(fields[0])
36 })
37 .collect()
38 })
39}
40
41fn split_tone(glyph: &str) -> (String, Option<u32>) {
42 let tone = glyph
43 .chars()
44 .find(|character| SKIN_TONES.contains(character))
45 .map(|tone| tone as u32 - *SKIN_TONES.start() as u32 + 1);
46 let base = glyph
47 .chars()
48 .filter(|character| !SKIN_TONES.contains(character))
49 .collect();
50 (base, tone)
51}
52
53/// Teams sends a toned reaction as `{diverse id}-tone{n}`, so 👍🏼 is `yes-tone2`, not `like`.
54pub fn reaction_key(glyph: &str) -> Option<String> {
55 let (base, tone) = split_tone(glyph);
56 let keys = emotion_keys(&base);
57 match tone {
58 Some(tone) => keys
59 .iter()
60 .find(|key| diverse_ids().contains(*key))
61 .map(|key| format!("{key}{TONE_MARKER}{tone}"))
62 .or_else(|| keys.first().map(|key| key.to_string())),
63 None => keys.first().map(|key| key.to_string()),
64 }
65}
66
67/// Graph reads a toned reaction back without its tone, so removing one also clears the plain keys.
68pub fn reaction_keys(glyph: &str) -> Vec<String> {
69 let (base, tone) = split_tone(glyph);
70 let plain = emotion_keys(&base).iter().map(|key| key.to_string());
71 match tone {
72 Some(_) => {
73 let toned = reaction_key(glyph);
74 toned
75 .clone()
76 .into_iter()
77 .chain(plain.filter(|key| Some(key) != toned.as_ref()))
78 .collect()
79 }
80 None => plain.collect(),
81 }
82}
83
84/// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end;
85/// a variation selector at that spot is dropped.
86pub fn insert_skin_tone(base: &str, tone: u8) -> String {
87 let Some(modifier) = (1..=MAX_TONE)
88 .contains(&tone)
89 .then(|| char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1))
90 .flatten()
91 else {
92 return base.to_owned();
93 };
94 let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len()));
95 format!(
96 "{}{modifier}{tail}",
97 head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head)
98 )
99}
100
101/// `yes-tone2` is 👍🏼: the chat service key of a reaction as the glyph Graph would report,
102/// but with the tone Graph drops.
103pub fn reaction_glyph_for_key(key: &str) -> Option<String> {
104 let (base_key, tone) = match key.rsplit_once(TONE_MARKER) {
105 Some((base, tone)) => match tone.parse::<u8>() {
106 Ok(tone) => (base, Some(tone)),
107 Err(_) => (key, None),
108 },
109 None => (key, None),
110 };
111 let base = emotion_glyph(base_key)?;
112 Some(match tone {
113 Some(tone) => insert_skin_tone(base, tone),
114 None => base.to_owned(),
115 })
116}
117
118pub fn emotion_glyph(key: &str) -> Option<&'static str> {
119 static GLYPHS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
120 GLYPHS
121 .get_or_init(|| {
122 EMOTIONS
123 .lines()
124 .filter_map(|line| line.split_once('\t'))
125 .flat_map(|(glyph, keys)| keys.split(' ').map(move |key| (key, glyph)))
126 .collect()
127 })
128 .get(key)
129 .copied()
130}
131
132pub fn emotion_keys(glyph: &str) -> &'static [&'static str] {
133 let bare = if glyph.contains('\u{FE0F}') {
134 Cow::Owned(glyph.replace('\u{FE0F}', ""))
135 } else {
136 Cow::Borrowed(glyph)
137 };
138 index().get(bare.as_ref()).map_or(&[], Vec::as_slice)
139}
140
141pub fn emotion_key(glyph: &str) -> Option<&'static str> {
142 emotion_keys(glyph).first().copied()
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148
149 #[test]
150 fn resolves_teams_keys() {
151 assert_eq!(
152 emotion_key("\u{1F603}"),
153 Some("1f603_grinningfacewithbigeyes")
154 );
155 assert_eq!(emotion_key("\u{1F44D}"), Some("like"));
156 }
157
158 #[test]
159 fn ignores_variation_selectors() {
160 assert_eq!(emotion_key("\u{2764}"), Some("heart"));
161 assert_eq!(emotion_key("\u{2764}\u{FE0F}"), Some("heart"));
162 }
163
164 #[test]
165 fn lists_alias_keys_with_the_primary_first() {
166 assert_eq!(
167 emotion_keys("\u{1F603}"),
168 ["1f603_grinningfacewithbigeyes", "happyface"]
169 );
170 assert_eq!(emotion_keys("\u{2764}\u{FE0F}")[0], "heart");
171 }
172
173 #[test]
174 fn toned_reactions_use_the_diverse_id_with_the_tone() {
175 assert_eq!(reaction_key("👍").as_deref(), Some("like"));
176 assert_eq!(reaction_key("👍🏼").as_deref(), Some("yes-tone2"));
177 assert_eq!(reaction_keys("👍🏿"), ["yes-tone5", "like", "yes"]);
178 assert_eq!(reaction_keys("👍"), ["like", "yes"]);
179 assert_eq!(reaction_key("❤️").as_deref(), Some("heart"));
180 }
181
182 #[test]
183 fn keys_turn_into_glyphs_with_their_tone() {
184 assert_eq!(reaction_glyph_for_key("yes-tone2").as_deref(), Some("👍🏼"));
185 assert_eq!(reaction_glyph_for_key("like").as_deref(), Some("👍"));
186 assert_eq!(reaction_glyph_for_key("heart").as_deref(), Some("❤"));
187 assert_eq!(reaction_glyph_for_key("nope"), None);
188 assert_eq!(insert_skin_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️");
189 assert_eq!(insert_skin_tone("✌️", 3), "✌🏽");
190 }
191
192 #[test]
193 fn unknown_glyph_has_no_key() {
194 assert_eq!(emotion_key("x"), None);
195 assert!(emotion_keys("x").is_empty());
196 }
197}