Skip to main content

cosmic_applet_avestruz/
emoji.rs

1// SPDX-License-Identifier: MIT
2
3//! Emoji to react with: the ones this reader uses most, kept for next
4//! time, and all there are, to pick another from.
5//!
6//! The ones offered first are the ones used most, and of those used as
7//! often the ones used last (see [`suggested`]); a few common ones fill
8//! the room until there is that much history. Which were used, how often
9//! and when is kept in the settings of this machine
10//! ([`Config::reaction_emojis`](crate::config::Config::reaction_emojis)),
11//! and nowhere else: it is nobody's business what one reacts with most.
12//!
13//! What an emoji is is what the `emojis` crate knows as one, which is
14//! Unicode's list: that is what tells a reaction that is an emoji from one
15//! that is some other text ([`known`]), and what there is to pick from
16//! ([`found`]).
17
18pub use emojis::Group;
19use serde::{Deserialize, Serialize};
20
21/// How many emoji are kept track of: the most used. Beyond that many the
22/// least used are forgotten.
23const KEPT_MAX: usize = 30;
24
25/// How many emoji a search for one shows at the most.
26const FOUND_MAX: usize = 96;
27
28/// What is offered until there is history enough to offer: a few that
29/// are common as reactions.
30const USUAL: [&str; 7] = ["๐Ÿ‘", "โค๏ธ", "๐Ÿ˜‚", "๐Ÿฅฒ", "๐Ÿ‘€", "๐Ÿซก", "๐Ÿซ‚"];
31
32/// An emoji that was reacted with, how many times, and when last, in
33/// seconds since the Unix epoch.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Used {
36    pub emoji: String,
37    pub count: u32,
38    pub last_used: u64,
39}
40
41/// `text` as the emoji it is, written the one way each is written here,
42/// if it is one: an emoji may be written with or without the mark that
43/// says to show it as a picture.
44pub fn known(text: &str) -> Option<&'static str> {
45    emojis::get(text).map(emojis::Emoji::as_str)
46}
47
48/// The more used of two, the one used last if as often: which comes
49/// first.
50fn by_use(a: &Used, b: &Used) -> std::cmp::Ordering {
51    b.count.cmp(&a.count).then(b.last_used.cmp(&a.last_used))
52}
53
54/// Note in `used` that `emoji` was reacted with at `now`. What is no
55/// emoji is not noted. No more than [`KEPT_MAX`] are kept: the least
56/// used go, the one just used never.
57pub fn record(used: &mut Vec<Used>, emoji: &str, now: u64) {
58    let Some(emoji) = known(emoji) else {
59        return;
60    };
61    match used.iter_mut().find(|entry| known(&entry.emoji) == Some(emoji)) {
62        Some(entry) => {
63            entry.count = entry.count.saturating_add(1);
64            entry.last_used = now;
65        }
66        None => {
67            // Room is made first, so that the newcomer, used once, is not
68            // the one to go.
69            used.sort_by(by_use);
70            used.truncate(KEPT_MAX - 1);
71            used.push(Used { emoji: emoji.to_string(), count: 1, last_used: now });
72        }
73    }
74}
75
76/// The emoji to offer first, `max` at the most: those of `used`, the
77/// most used first, then the usual ones, each once.
78pub fn suggested(used: &[Used], max: usize) -> Vec<String> {
79    let mut used: Vec<&Used> = used.iter().collect();
80    used.sort_by(|a, b| by_use(a, b));
81    let mut offered: Vec<&'static str> = Vec::new();
82    for emoji in used.iter().map(|entry| entry.emoji.as_str()).chain(USUAL).filter_map(known) {
83        if !offered.contains(&emoji) {
84            offered.push(emoji);
85        }
86    }
87    offered.into_iter().take(max).map(String::from).collect()
88}
89
90/// The emoji that stands for `group` where the groups are chosen from:
91/// its first.
92pub fn standing_for(group: Group) -> &'static str {
93    group.emojis().next().map_or("", emojis::Emoji::as_str)
94}
95
96/// The emoji to pick from: those whose name or short code has every word
97/// of `typed` in it, [`FOUND_MAX`] at the most, if anything is typed, and
98/// all of `group` if not.
99pub fn found(typed: &str, group: Group) -> Vec<&'static str> {
100    let words: Vec<String> = typed.split_whitespace().map(str::to_lowercase).collect();
101    if words.is_empty() {
102        return group.emojis().map(emojis::Emoji::as_str).collect();
103    }
104    let named =
105        |emoji: &emojis::Emoji, word: &str| emoji.name().contains(word) || emoji.shortcodes().any(|code| code.contains(word));
106    emojis::iter()
107        .filter(|emoji| words.iter().all(|word| named(emoji, word)))
108        .map(emojis::Emoji::as_str)
109        .take(FOUND_MAX)
110        .collect()
111}
112
113#[cfg(test)]
114mod tests {
115    use super::{FOUND_MAX, Group, KEPT_MAX, USUAL, Used, found, known, record, standing_for, suggested};
116
117    #[test]
118    fn an_emoji_is_known_however_it_is_written_and_nothing_else_is() {
119        // With and without the mark that says to show it as a picture.
120        assert_eq!(known("โค๏ธ"), Some("โค๏ธ"));
121        assert_eq!(known("โค"), Some("โค๏ธ"));
122        assert_eq!(known("๐ŸคŒ"), Some("๐ŸคŒ"));
123        // With a skin tone, it is itself.
124        assert_eq!(known("๐Ÿ‘๐Ÿฝ"), Some("๐Ÿ‘๐Ÿฝ"));
125        for other in ["", "+", "-", ":soapbox:", "lol", "๐Ÿ˜‚๐Ÿ˜‚", "๐Ÿ˜‚ ", "nice ๐Ÿ‘"] {
126            assert_eq!(known(other), None, "{other:?}");
127        }
128        // Every one of the usual ones is one.
129        assert!(USUAL.iter().all(|emoji| known(emoji).is_some()));
130    }
131
132    #[test]
133    fn the_most_used_are_offered_first_and_the_usual_ones_fill_the_room() {
134        // With no history: the usual ones, as many as are asked for.
135        assert_eq!(suggested(&[], 8), USUAL);
136        assert_eq!(suggested(&[], 3), USUAL[..3]);
137
138        let mut used = Vec::new();
139        record(&mut used, "๐ŸคŒ", 10);
140        record(&mut used, "๐Ÿงจ", 20);
141        record(&mut used, "๐ŸคŒ", 30);
142        record(&mut used, "๐Ÿคฏ", 40);
143        // Used twice; then of those used once, the one used last.
144        assert_eq!(suggested(&used, 4), ["๐ŸคŒ", "๐Ÿคฏ", "๐Ÿงจ", "๐Ÿ‘"]);
145        assert_eq!(used.iter().find(|entry| entry.emoji == "๐ŸคŒ"), Some(&Used { emoji: "๐ŸคŒ".into(), count: 2, last_used: 30 }));
146
147        // One of the usual ones, once used, is offered where its use puts
148        // it, and once: however it was written.
149        record(&mut used, "โค", 50);
150        record(&mut used, "โค๏ธ", 60);
151        record(&mut used, "โค", 70);
152        let offered = suggested(&used, 8);
153        assert_eq!(offered[..5], ["โค๏ธ", "๐ŸคŒ", "๐Ÿคฏ", "๐Ÿงจ", "๐Ÿ‘"]);
154        assert_eq!(offered.iter().filter(|emoji| *emoji == "โค๏ธ").count(), 1);
155        assert_eq!(offered.len(), 8);
156    }
157
158    #[test]
159    fn what_is_no_emoji_is_not_kept_and_only_so_many_are() {
160        let mut used = Vec::new();
161        for other in ["+", "", ":shortcode:", "text"] {
162            record(&mut used, other, 1);
163        }
164        assert!(used.is_empty());
165
166        // More than are kept: each used once, one after the other, but
167        // for the first, which was used twice.
168        let all: Vec<&str> = Group::AnimalsAndNature.emojis().map(|emoji| emoji.as_str()).take(KEPT_MAX + 10).collect();
169        assert_eq!(all.len(), KEPT_MAX + 10);
170        record(&mut used, all[0], 0);
171        for (at, emoji) in all.iter().enumerate() {
172            record(&mut used, emoji, at as u64 + 1);
173        }
174        assert_eq!(used.len(), KEPT_MAX);
175        // The one used most is kept, and the one used last; the ones used
176        // once and longest ago are gone.
177        let kept = |emoji: &str| used.iter().any(|entry| entry.emoji == emoji);
178        assert!(kept(all[0]) && kept(all[KEPT_MAX + 9]));
179        assert!(!kept(all[1]) && !kept(all[2]));
180
181        // What was written by hand into the settings and is no emoji is
182        // never offered.
183        let edited = [Used { emoji: "not one".into(), count: 99, last_used: 0 }];
184        assert_eq!(suggested(&edited, 8), USUAL);
185    }
186
187    #[test]
188    fn an_emoji_is_found_by_what_it_is_called_or_in_its_group() {
189        assert!(found("clown", Group::Flags).contains(&"๐Ÿคก"), "whatever group is on show");
190        assert!(found("  Thumbs  UP ", Group::Flags).contains(&"๐Ÿ‘"));
191        // By its short code, where its name says it otherwise.
192        assert!(found("+1", Group::Flags).contains(&"๐Ÿ‘"));
193        assert!(found("no such thing as this", Group::Flags).is_empty());
194        assert!(found("e", Group::Flags).len() <= FOUND_MAX);
195
196        // With nothing typed: the group, all of it, and no other.
197        let flags = found("  ", Group::Flags);
198        assert!(flags.len() > 200 && flags.contains(&"๐Ÿ‡ง๐Ÿ‡ท") && !flags.contains(&"๐Ÿคก"));
199        // Each group has an emoji to stand for it, and no two the same.
200        let standing: Vec<&str> = Group::iter().map(standing_for).collect();
201        assert!(standing.iter().all(|emoji| !emoji.is_empty()));
202        assert_eq!(standing.iter().collect::<std::collections::HashSet<_>>().len(), standing.len());
203    }
204}