BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / jumbo.rs

jumbo.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
jumbo.rs 8.6 KiB Download Raw
1use scraper::{ElementRef, Html, Node};
2use unicode_segmentation::UnicodeSegmentation;
3
4pub const MAX_JUMBO_EMOJI: usize = 3;
5
6const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
7const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}';
8const BLOCKING_ELEMENTS: [&str; 4] = ["table", "attachment", "blockquote", "pre"];
9const IGNORED_CHARACTERS: [char; 5] = ['\u{a0}', '\u{200b}', '\u{200c}', '\u{200d}', '\u{feff}'];
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct JumboEmoji {
13 pub id: Option<String>,
14 pub glyph: String,
15}
16
17#[derive(Default)]
18struct Scan {
19 emoticons: Vec<JumboEmoji>,
20 text: String,
21 break_pending: bool,
22 break_before_content: bool,
23 blocked: bool,
24}
25
26impl Scan {
27 fn content_follows(&mut self) {
28 if self.break_pending {
29 self.break_before_content = true;
30 }
31 }
32}
33
34/// The Teams emoji-only rule: 1 to 3 emoticons and nothing else, or 1 to 3 unicode emoji
35/// without whitespace between them. Such a message shows big and without a bubble.
36pub fn jumbo_emoji(html: &str) -> Option<Vec<JumboEmoji>> {
37 let fragment = Html::parse_fragment(html);
38 let mut scan = Scan::default();
39 walk(fragment.root_element(), &mut scan);
40 if scan.blocked || scan.break_before_content {
41 return None;
42 }
43 let found = match (scan.emoticons.is_empty(), scan.text.trim().is_empty()) {
44 (false, true) => scan.emoticons,
45 (true, false) => unicode_emoji(scan.text.trim())?,
46 _ => return None,
47 };
48 (1..=MAX_JUMBO_EMOJI)
49 .contains(&found.len())
50 .then_some(found)
51}
52
53fn walk(element: ElementRef<'_>, scan: &mut Scan) {
54 for child in element.children() {
55 if scan.blocked {
56 return;
57 }
58 match child.value() {
59 Node::Text(text) => {
60 let visible: String = text
61 .chars()
62 .filter(|character| !IGNORED_CHARACTERS.contains(character))
63 .collect();
64 if !visible.trim().is_empty() {
65 scan.content_follows();
66 scan.text.push_str(text);
67 }
68 }
69 Node::Element(_) => {
70 if let Some(child_element) = ElementRef::wrap(child) {
71 visit_element(child_element, scan);
72 }
73 }
74 _ => {}
75 }
76 }
77}
78
79fn visit_element(element: ElementRef<'_>, scan: &mut Scan) {
80 let value = element.value();
81 let is_emoji_image = value.name() == "img"
82 && value
83 .attr("itemtype")
84 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
85 match value.name() {
86 "emoji" => {
87 scan.content_follows();
88 scan.emoticons.push(JumboEmoji {
89 id: value.attr("id").map(str::to_owned),
90 glyph: glyph(element),
91 });
92 }
93 "img" if is_emoji_image => {
94 scan.content_follows();
95 scan.emoticons.push(JumboEmoji {
96 id: value.attr("itemid").or(value.attr("id")).map(str::to_owned),
97 glyph: glyph(element),
98 });
99 }
100 "img" => scan.blocked = true,
101 "br" => scan.break_pending = true,
102 name if BLOCKING_ELEMENTS.contains(&name) => scan.blocked = true,
103 _ => walk(element, scan),
104 }
105}
106
107fn glyph(element: ElementRef<'_>) -> String {
108 let raw = element
109 .value()
110 .attr("alt")
111 .filter(|alt| !alt.is_empty())
112 .map(str::to_owned)
113 .unwrap_or_else(|| element.text().collect());
114 without_repeated_skin_tone(&raw)
115}
116
117/// Graph repeats the skin tone in emoticon alt text (`👍🏼🏼`, `🤷🏽‍♂️🏽`); the extra one renders as a colour square.
118pub(crate) fn without_repeated_skin_tone(glyph: &str) -> String {
119 let mut cleaned = String::with_capacity(glyph.len());
120 let mut previous: Option<char> = None;
121 let mut tone_seen = false;
122 for character in glyph.chars() {
123 let is_tone = SKIN_TONES.contains(&character);
124 let stray = is_tone
125 && previous.is_some_and(|previous| {
126 SKIN_TONES.contains(&previous) || (tone_seen && !is_pictographic(previous))
127 });
128 if !stray {
129 cleaned.push(character);
130 }
131 tone_seen |= is_tone;
132 previous = Some(character);
133 }
134 cleaned
135}
136
137fn unicode_emoji(text: &str) -> Option<Vec<JumboEmoji>> {
138 text.graphemes(true)
139 .map(|grapheme| {
140 is_emoji_grapheme(grapheme).then(|| JumboEmoji {
141 id: None,
142 glyph: grapheme.to_owned(),
143 })
144 })
145 .collect()
146}
147
148pub(crate) fn is_emoji_grapheme(grapheme: &str) -> bool {
149 let mut characters = grapheme.chars();
150 characters.next().is_some_and(is_pictographic)
151 && characters.all(|character| {
152 is_pictographic(character)
153 || matches!(
154 character,
155 '\u{1f3fb}'..='\u{1f3ff}' | '\u{200d}' | '\u{fe0f}' | '\u{20e3}'
156 )
157 })
158}
159
160fn is_pictographic(character: char) -> bool {
161 matches!(
162 character,
163 '\u{a9}'
164 | '\u{ae}'
165 | '\u{203c}'
166 | '\u{2049}'
167 | '\u{2122}'
168 | '\u{2139}'
169 | '\u{2194}'..='\u{21aa}'
170 | '\u{231a}'..='\u{23ff}'
171 | '\u{24c2}'
172 | '\u{25aa}'..='\u{27bf}'
173 | '\u{2934}'..='\u{2935}'
174 | '\u{2b05}'..='\u{2b55}'
175 | '\u{3030}'
176 | '\u{303d}'
177 | '\u{3297}'
178 | '\u{3299}'
179 | '\u{1f000}'..='\u{1f0ff}'
180 | '\u{1f10d}'..='\u{1f1ad}'
181 | '\u{1f201}'..='\u{1f3fa}'
182 | '\u{1f400}'..='\u{1faff}'
183 )
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn repeated_skin_tones_from_graph_are_dropped() {
192 assert_eq!(without_repeated_skin_tone("👍🏼🏼"), "👍🏼");
193 assert_eq!(without_repeated_skin_tone("🤷🏽\u{200d}♂️🏽"), "🤷🏽\u{200d}♂️");
194 assert_eq!(
195 without_repeated_skin_tone("🧑🏻\u{200d}🤝\u{200d}🧑🏿"),
196 "🧑🏻\u{200d}🤝\u{200d}🧑🏿"
197 );
198 assert_eq!(
199 jumbo_emoji(r#"<emoji id="yes" alt="👍🏼🏼"></emoji>"#),
200 Some(vec![emoticon("yes", "👍🏼")])
201 );
202 }
203
204 fn emoticon(id: &str, glyph: &str) -> JumboEmoji {
205 JumboEmoji {
206 id: Some(id.to_owned()),
207 glyph: glyph.to_owned(),
208 }
209 }
210
211 fn glyphs(found: Option<Vec<JumboEmoji>>) -> Option<Vec<String>> {
212 found.map(|found| found.into_iter().map(|emoji| emoji.glyph).collect())
213 }
214
215 #[test]
216 fn one_to_three_emoticons_with_whitespace_and_wrappers_are_jumbo() {
217 let html = r#"<p><emoji id="smile" alt="🙂" title="Smile"></emoji>&nbsp;<img itemtype="http://schema.skype.com/Emoji" itemid="heart" alt="❤️" src="https://x/e.png"></p>"#;
218 assert_eq!(
219 jumbo_emoji(html),
220 Some(vec![emoticon("smile", "🙂"), emoticon("heart", "❤️")])
221 );
222 }
223
224 #[test]
225 fn four_emoticons_text_quotes_tables_and_images_are_not_jumbo() {
226 let four = r#"<emoji id="a" alt="🙂"></emoji>"#.repeat(4);
227 assert_eq!(jumbo_emoji(&four), None);
228 assert_eq!(
229 jumbo_emoji(r#"hi <emoji id="smile" alt="🙂"></emoji>"#),
230 None
231 );
232 assert_eq!(
233 jumbo_emoji(r#"<attachment id="1"></attachment><emoji id="smile" alt="🙂"></emoji>"#),
234 None
235 );
236 assert_eq!(
237 jumbo_emoji(r#"<emoji id="smile" alt="🙂"></emoji><img src="https://x/photo.png">"#),
238 None
239 );
240 assert_eq!(jumbo_emoji("<p></p>"), None);
241 }
242
243 #[test]
244 fn a_break_before_the_next_emoji_ends_jumbo_but_a_trailing_break_does_not() {
245 assert_eq!(
246 jumbo_emoji(r#"<emoji id="a" alt="🙂"></emoji><br><emoji id="b" alt="🙂"></emoji>"#),
247 None
248 );
249 assert_eq!(
250 jumbo_emoji(r#"<emoji id="a" alt="🙂"></emoji><br>"#),
251 Some(vec![emoticon("a", "🙂")])
252 );
253 }
254
255 #[test]
256 fn unicode_only_needs_one_to_three_emoji_without_whitespace() {
257 assert_eq!(
258 glyphs(jumbo_emoji("<p>😀👍🏽❤️</p>")),
259 Some(vec!["😀".into(), "👍🏽".into(), "❤️".into()])
260 );
261 assert_eq!(glyphs(jumbo_emoji("<p>👨‍👩‍👧</p>")), Some(vec!["👨‍👩‍👧".into()]));
262 assert_eq!(jumbo_emoji("<p>😀 😀</p>"), None);
263 assert_eq!(jumbo_emoji("<p>😀😀😀😀</p>"), None);
264 assert_eq!(jumbo_emoji("<p>ok 😀</p>"), None);
265 assert_eq!(jumbo_emoji("<p>12</p>"), None);
266 }
267}