BlueGit

ict rusty-teams

Files

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

jumbo.rs

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