BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / emoji / mod.rs

mod.rs

mod.rs 7.6 KiB Download Raw
1mod recent;
2mod typing;
3
4use std::ops::Range;
5use std::sync::OnceLock;
6
7pub use recent::Recent;
8pub use typing::{active_query, closing_code, smiley_before_space, trailing_smiley, typed_char};
9
10const INDEX: &str = include_str!("../../assets/emoji/emoji.tsv");
11
12#[derive(Debug)]
13pub struct Emoji {
14 pub glyph: &'static str,
15 pub codes: Vec<&'static str>,
16 pub aliases: Vec<&'static str>,
17}
18
19impl Emoji {
20 pub fn display_code(&self) -> &'static str {
21 self.codes
22 .iter()
23 .find(|code| code.starts_with(char::is_alphabetic))
24 .or(self.codes.first())
25 .copied()
26 .unwrap_or_default()
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Match {
32 pub glyph: &'static str,
33 pub code: &'static str,
34 pub alias: Option<&'static str>,
35 pub highlight: Range<usize>,
36 pub recent: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
40enum Tier {
41 Exact,
42 CodePrefix,
43 AliasPrefix,
44 WordStart,
45 Contains,
46}
47
48fn index() -> &'static [Emoji] {
49 static PARSED: OnceLock<Vec<Emoji>> = OnceLock::new();
50 PARSED.get_or_init(|| {
51 INDEX
52 .lines()
53 .filter_map(|line| {
54 let mut fields = line.split('\t');
55 let glyph = fields.next()?;
56 let codes = fields.next()?.split(' ').collect();
57 let aliases = fields
58 .next()
59 .unwrap_or_default()
60 .split('|')
61 .filter(|alias| !alias.is_empty())
62 .collect();
63 Some(Emoji {
64 glyph,
65 codes,
66 aliases,
67 })
68 })
69 .collect()
70 })
71}
72
73fn tier(candidate: &str, query: &str, separator: char) -> Option<(Tier, usize)> {
74 if candidate == query {
75 return Some((Tier::Exact, 0));
76 }
77 if candidate.starts_with(query) {
78 return Some((Tier::CodePrefix, 0));
79 }
80 let start = candidate.find(query)?;
81 let tier = if candidate[..start].ends_with(separator) {
82 Tier::WordStart
83 } else {
84 Tier::Contains
85 };
86 Some((tier, start))
87}
88
89/// Tier, then the alias position: a label beats a loose tag. Only the label (position 0) can be exact.
90fn best_match(emoji: &'static Emoji, query: &str) -> Option<(Tier, usize, Match)> {
91 let code_hit = emoji
92 .codes
93 .iter()
94 .filter_map(|code| tier(code, query, '_').map(|(tier, start)| (tier, start, *code)))
95 .min_by_key(|(tier, ..)| *tier);
96 let alias_query = query.replace('_', " ");
97 let alias_hit = emoji
98 .aliases
99 .iter()
100 .enumerate()
101 .filter_map(|(position, alias)| {
102 tier(alias, &alias_query, ' ').map(|(tier, start)| {
103 let tier = match tier {
104 Tier::Exact if position == 0 => Tier::Exact,
105 Tier::Exact | Tier::CodePrefix => Tier::AliasPrefix,
106 other => other,
107 };
108 (tier, position, start, *alias)
109 })
110 })
111 .min_by_key(|(tier, position, ..)| (*tier, *position));
112 let code_wins = match (&code_hit, &alias_hit) {
113 (Some(code), Some(alias)) => code.0 <= alias.0,
114 (code, _) => code.is_some(),
115 };
116 if code_wins {
117 let (tier, start, code) = code_hit?;
118 return Some((
119 tier,
120 0,
121 Match {
122 glyph: emoji.glyph,
123 code,
124 alias: None,
125 highlight: start..start + query.len(),
126 recent: false,
127 },
128 ));
129 }
130 let (tier, position, start, alias) = alias_hit?;
131 Some((
132 tier,
133 position,
134 Match {
135 glyph: emoji.glyph,
136 code: emoji.display_code(),
137 alias: Some(alias),
138 highlight: start..start + alias_query.len(),
139 recent: false,
140 },
141 ))
142}
143
144/// Ranked by: recent, exact, English prefix, German prefix, word start, contains, emoji order.
145pub fn search(query: &str, recent: &[String], limit: usize) -> Vec<Match> {
146 let query = query.to_lowercase();
147 if query.is_empty() {
148 return Vec::new();
149 }
150 let mut hits: Vec<(usize, Tier, usize, usize, Match)> = index()
151 .iter()
152 .enumerate()
153 .filter_map(|(order, emoji)| {
154 let (tier, position, mut found) = best_match(emoji, &query)?;
155 let recent_rank = recent
156 .iter()
157 .position(|glyph| glyph == emoji.glyph)
158 .filter(|_| tier < Tier::Contains);
159 found.recent = recent_rank.is_some();
160 Some((
161 recent_rank.unwrap_or(usize::MAX),
162 tier,
163 position,
164 order,
165 found,
166 ))
167 })
168 .collect();
169 hits.sort_by_key(|(recent_rank, tier, position, order, _)| {
170 (*recent_rank, *tier, *position, *order)
171 });
172 hits.into_iter()
173 .take(limit)
174 .map(|(.., found)| found)
175 .collect()
176}
177
178/// A full English code, or a German alias written with underscores.
179pub fn lookup(code: &str) -> Option<&'static str> {
180 let code = code.to_lowercase();
181 if let Some(emoji) = index()
182 .iter()
183 .find(|emoji| emoji.codes.contains(&code.as_str()))
184 {
185 return Some(emoji.glyph);
186 }
187 let alias = code.replace('_', " ");
188 index()
189 .iter()
190 .filter_map(|emoji| {
191 let position = emoji.aliases.iter().position(|known| *known == alias)?;
192 Some((position, emoji.glyph))
193 })
194 .min_by_key(|(position, _)| *position)
195 .map(|(_, glyph)| glyph)
196}
197
198#[cfg(test)]
199mod tests {
200 use super::{Recent, lookup, search};
201
202 fn glyphs(query: &str, recent: &[String]) -> Vec<&'static str> {
203 search(query, recent, 7)
204 .into_iter()
205 .map(|found| found.glyph)
206 .collect()
207 }
208
209 #[test]
210 fn english_prefix_finds_thumbs() {
211 let found = glyphs("th", &[]);
212 assert!(found.contains(&"👍"));
213 assert!(found.contains(&"👎"));
214 }
215
216 #[test]
217 fn a_tag_never_beats_an_english_prefix() {
218 let found = glyphs("th", &[]);
219 assert!(!found.contains(&"🇹🇭"));
220 }
221
222 #[test]
223 fn recent_emoji_rank_first() {
224 let recent = vec!["🤔".to_owned()];
225 assert_eq!(glyphs("th", &recent)[0], "🤔");
226 assert!(search("th", &recent, 7)[0].recent);
227 }
228
229 #[test]
230 fn german_alias_finds_english_code() {
231 let found = search("dau", &[], 7);
232 let thumbs = found.iter().find(|found| found.glyph == "👍").unwrap();
233 assert_eq!(thumbs.code, "thumbsup");
234 assert_eq!(thumbs.alias, Some("daumen hoch"));
235 assert_eq!(thumbs.highlight, 0..3);
236 }
237
238 #[test]
239 fn exact_alias_beats_alias_prefix() {
240 let found = search("herz", &[], 40);
241 let exact = found.iter().position(|found| found.glyph == "💔").unwrap();
242 let prefix = found.iter().position(|found| found.glyph == "😍").unwrap();
243 assert!(exact < prefix);
244 }
245
246 #[test]
247 fn quick_reactions_lead_with_a_case_insensitive_query() {
248 let found = search("Herz", &Recent::default().glyphs(), 7);
249 assert_eq!(found[0].glyph, "❤️");
250 assert_eq!(found[0].alias, Some("herz"));
251 }
252
253 #[test]
254 fn lookup_takes_english_and_german_codes() {
255 assert_eq!(lookup("thumbsup"), Some("👍"));
256 assert_eq!(lookup("+1"), Some("👍"));
257 assert_eq!(lookup("daumen_hoch"), Some("👍"));
258 assert_eq!(lookup("ganzneu"), None);
259 }
260}