| 1 | pub mod recent; |
| 2 | |
| 3 | use app_base::emoji::typing; |
| 4 | use std::ops::Range; |
| 5 | use std::sync::OnceLock; |
| 6 | |
| 7 | pub use recent::Recent; |
| 8 | pub use typing::{active_query, closing_code, smiley_before_space, trailing_smiley, typed_char}; |
| 9 | |
| 10 | const INDEX: &str = include_str!("../../../app/assets/emoji/emoji.tsv"); |
| 11 | |
| 12 | #[derive(Debug)] |
| 13 | pub struct Emoji { |
| 14 | pub glyph: &'static str, |
| 15 | pub codes: Vec<&'static str>, |
| 16 | pub aliases: Vec<&'static str>, |
| 17 | } |
| 18 | |
| 19 | impl 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)] |
| 31 | pub 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)] |
| 40 | enum Tier { |
| 41 | Exact, |
| 42 | CodePrefix, |
| 43 | AliasPrefix, |
| 44 | WordStart, |
| 45 | Contains, |
| 46 | } |
| 47 | |
| 48 | fn 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 | |
| 73 | fn 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. |
| 90 | fn 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 | pub fn glyphs() -> impl Iterator<Item = &'static str> { |
| 145 | index().iter().map(|emoji| emoji.glyph) |
| 146 | } |
| 147 | |
| 148 | /// Ranked by: recent, exact, English prefix, German prefix, word start, contains, emoji order. |
| 149 | pub fn search(query: &str, recent: &[String], limit: usize) -> Vec<Match> { |
| 150 | let query = query.to_lowercase(); |
| 151 | if query.is_empty() { |
| 152 | return Vec::new(); |
| 153 | } |
| 154 | let mut hits: Vec<(usize, Tier, usize, usize, Match)> = index() |
| 155 | .iter() |
| 156 | .enumerate() |
| 157 | .filter_map(|(order, emoji)| { |
| 158 | let (tier, position, mut found) = best_match(emoji, &query)?; |
| 159 | let recent_rank = recent |
| 160 | .iter() |
| 161 | .position(|glyph| glyph == emoji.glyph) |
| 162 | .filter(|_| tier < Tier::Contains); |
| 163 | found.recent = recent_rank.is_some(); |
| 164 | Some(( |
| 165 | recent_rank.unwrap_or(usize::MAX), |
| 166 | tier, |
| 167 | position, |
| 168 | order, |
| 169 | found, |
| 170 | )) |
| 171 | }) |
| 172 | .collect(); |
| 173 | hits.sort_by_key(|(recent_rank, tier, position, order, _)| { |
| 174 | (*recent_rank, *tier, *position, *order) |
| 175 | }); |
| 176 | hits.into_iter() |
| 177 | .take(limit) |
| 178 | .map(|(.., found)| found) |
| 179 | .collect() |
| 180 | } |
| 181 | |
| 182 | /// A full English code, or a German alias written with underscores. |
| 183 | pub fn lookup(code: &str) -> Option<&'static str> { |
| 184 | let code = code.to_lowercase(); |
| 185 | if let Some(emoji) = index() |
| 186 | .iter() |
| 187 | .find(|emoji| emoji.codes.contains(&code.as_str())) |
| 188 | { |
| 189 | return Some(emoji.glyph); |
| 190 | } |
| 191 | let alias = code.replace('_', " "); |
| 192 | index() |
| 193 | .iter() |
| 194 | .filter_map(|emoji| { |
| 195 | let position = emoji.aliases.iter().position(|known| *known == alias)?; |
| 196 | Some((position, emoji.glyph)) |
| 197 | }) |
| 198 | .min_by_key(|(position, _)| *position) |
| 199 | .map(|(_, glyph)| glyph) |
| 200 | } |
| 201 | |
| 202 | #[cfg(test)] |
| 203 | mod tests { |
| 204 | use super::{Recent, lookup, search}; |
| 205 | |
| 206 | fn glyphs(query: &str, recent: &[String]) -> Vec<&'static str> { |
| 207 | search(query, recent, 7) |
| 208 | .into_iter() |
| 209 | .map(|found| found.glyph) |
| 210 | .collect() |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn english_prefix_finds_thumbs() { |
| 215 | let found = glyphs("th", &[]); |
| 216 | assert!(found.contains(&"👍")); |
| 217 | assert!(found.contains(&"👎")); |
| 218 | } |
| 219 | |
| 220 | #[test] |
| 221 | fn a_tag_never_beats_an_english_prefix() { |
| 222 | let found = glyphs("th", &[]); |
| 223 | assert!(!found.contains(&"🇹🇭")); |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn recent_emoji_rank_first() { |
| 228 | let recent = vec!["🤔".to_owned()]; |
| 229 | assert_eq!(glyphs("th", &recent)[0], "🤔"); |
| 230 | assert!(search("th", &recent, 7)[0].recent); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn german_alias_finds_english_code() { |
| 235 | let found = search("dau", &[], 7); |
| 236 | let thumbs = found.iter().find(|found| found.glyph == "👍").unwrap(); |
| 237 | assert_eq!(thumbs.code, "thumbsup"); |
| 238 | assert_eq!(thumbs.alias, Some("daumen hoch")); |
| 239 | assert_eq!(thumbs.highlight, 0..3); |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn exact_alias_beats_alias_prefix() { |
| 244 | let found = search("herz", &[], 40); |
| 245 | let exact = found.iter().position(|found| found.glyph == "💔").unwrap(); |
| 246 | let prefix = found.iter().position(|found| found.glyph == "😍").unwrap(); |
| 247 | assert!(exact < prefix); |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn quick_reactions_lead_with_a_case_insensitive_query() { |
| 252 | let found = search("Herz", &Recent::default().glyphs(), 7); |
| 253 | assert_eq!(found[0].glyph, "❤️"); |
| 254 | assert_eq!(found[0].alias, Some("herz")); |
| 255 | } |
| 256 | |
| 257 | #[test] |
| 258 | fn lookup_takes_english_and_german_codes() { |
| 259 | assert_eq!(lookup("thumbsup"), Some("👍")); |
| 260 | assert_eq!(lookup("+1"), Some("👍")); |
| 261 | assert_eq!(lookup("daumen_hoch"), Some("👍")); |
| 262 | assert_eq!(lookup("ganzneu"), None); |
| 263 | } |
| 264 | } |