BlueGit

ict rusty-teams

Files

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

spans.rs

spans.rs 21.9 KiB Download Raw
1use scraper::{ElementRef, Html, Node};
2
3use crate::ams_video::video_thumbnail_url;
4use crate::jumbo::without_repeated_skin_tone;
5use crate::stored::quote_time;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum FontSize {
9 Small,
10 Large,
11 Hidden,
12 Pixels(u16),
13}
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Span {
17 Text(String),
18 Bold(Vec<Span>),
19 Italic(Vec<Span>),
20 Code(String),
21 CodeBlock {
22 language: Option<String>,
23 code: String,
24 },
25 Link {
26 url: String,
27 children: Vec<Span>,
28 },
29 Mention {
30 name: String,
31 id: Option<String>,
32 },
33 Strike(Vec<Span>),
34 Superscript(Vec<Span>),
35 Subscript(Vec<Span>),
36 Sized(FontSize, Vec<Span>),
37 Underline(Vec<Span>),
38 Colored {
39 color: Option<u32>,
40 background: Option<u32>,
41 children: Vec<Span>,
42 },
43 Heading {
44 level: u8,
45 children: Vec<Span>,
46 },
47 LineBreak,
48 Rule,
49 List {
50 ordered: bool,
51 start: u32,
52 items: Vec<Vec<Span>>,
53 },
54 Table {
55 header: bool,
56 rows: Vec<Vec<Vec<Span>>>,
57 },
58 Image {
59 hosted_content_url: String,
60 },
61 CustomEmoji {
62 name: String,
63 url: String,
64 },
65 Quote {
66 message_id: Option<String>,
67 children: Vec<Span>,
68 },
69 BlockQuote(Vec<Span>),
70 Indent {
71 level: u8,
72 children: Vec<Span>,
73 },
74}
75
76const BLOCK_ELEMENTS: [&str; 12] = [
77 "p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "ul", "ol", "hr",
78];
79const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
80const LANGUAGE_PREFIX: &str = "language-";
81const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
82const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
83const MAX_HEADING_LEVEL: u8 = 3;
84const MARK_BACKGROUND: u32 = 0xffff00;
85const MAX_CONSECUTIVE_BREAKS: usize = 2;
86const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];
87const INDENT_STEP_PIXELS: f32 = 40.;
88const MAX_INDENT_LEVEL: u8 = 8;
89const PLAIN_LANGUAGE: &str = "plaintext";
90
91pub fn html_to_spans(html: &str) -> Vec<Span> {
92 let fragment = Html::parse_fragment(html);
93 let mut spans = convert_children(fragment.root_element());
94 tidy(&mut spans);
95 spans
96}
97
98fn convert_children(element: ElementRef<'_>) -> Vec<Span> {
99 let mut spans = Vec::new();
100 let mut break_pending = false;
101 for child in element.children() {
102 match child.value() {
103 Node::Text(text) => {
104 let text: &str = text;
105 if break_pending && text.trim().is_empty() {
106 continue;
107 }
108 if break_pending && !spans.is_empty() {
109 spans.push(Span::LineBreak);
110 }
111 break_pending = false;
112 push_text(&mut spans, text);
113 }
114 Node::Element(_) => {
115 let Some(child_element) = ElementRef::wrap(child) else {
116 continue;
117 };
118 let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());
119 if (is_block || break_pending) && !spans.is_empty() {
120 spans.push(Span::LineBreak);
121 }
122 convert_element(child_element, &mut spans);
123 break_pending = is_block;
124 }
125 _ => {}
126 }
127 }
128 spans
129}
130
131fn convert_element(element: ElementRef<'_>, spans: &mut Vec<Span>) {
132 let name = element.value().name();
133 if SKIPPED_ELEMENTS.contains(&name) {
134 return;
135 }
136 match block_indent(element) {
137 Some(level) => {
138 let mut children = Vec::new();
139 convert_unindented(element, &mut children);
140 spans.push(Span::Indent { level, children });
141 }
142 None => convert_unindented(element, spans),
143 }
144}
145
146fn block_indent(element: ElementRef<'_>) -> Option<u8> {
147 let value = element.value();
148 if !INDENTED_ELEMENTS.contains(&value.name()) {
149 return None;
150 }
151 let margin = style_value(value.attr("style")?, "margin-left")?;
152 let pixels: f32 = margin.trim().strip_suffix("px")?.trim().parse().ok()?;
153 let level = (pixels / INDENT_STEP_PIXELS).round();
154 (level >= 1.).then(|| level.min(f32::from(MAX_INDENT_LEVEL)) as u8)
155}
156
157fn convert_unindented(element: ElementRef<'_>, spans: &mut Vec<Span>) {
158 let name = element.value().name();
159 match name {
160 "b" | "strong" => spans.push(Span::Bold(convert_children(element))),
161 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {
162 level: name[1..].parse::<u8>().unwrap_or(1).min(MAX_HEADING_LEVEL),
163 children: convert_children(element),
164 }),
165 "i" | "em" => spans.push(Span::Italic(convert_children(element))),
166 "s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),
167 "sup" => spans.push(Span::Superscript(convert_children(element))),
168 "sub" => spans.push(Span::Subscript(convert_children(element))),
169 "u" | "ins" => spans.push(Span::Underline(convert_children(element))),
170 "span" if element.value().attr("itemprop") == Some("time") => {
171 push_quote_time(element, spans)
172 }
173 "span" | "font" | "mark" => push_colored(element, spans),
174 "ul" | "ol" => spans.push(list(element)),
175 "table" => spans.push(table(element)),
176 "code" => spans.push(Span::Code(raw_text(element))),
177 "pre" | "codeblock" => spans.push(code_block(element)),
178 "a" => push_link(element, spans),
179 "at" => spans.push(Span::Mention {
180 name: raw_text(element).trim().to_owned(),
181 id: element.value().attr("id").map(str::to_owned),
182 }),
183 "br" => spans.push(Span::LineBreak),
184 "hr" => spans.push(Span::Rule),
185 "li" => spans.push(Span::List {
186 ordered: false,
187 start: 1,
188 items: vec![convert_children(element)],
189 }),
190 "blockquote" if is_reply(element) => spans.push(Span::Quote {
191 message_id: element.value().attr("itemid").map(str::to_owned),
192 children: convert_children(element),
193 }),
194 "blockquote" => spans.push(Span::BlockQuote(convert_children(element))),
195 "emoji" => push_emoji(element, spans),
196 "customemoji" => push_custom_emoji(element, spans),
197 "img" => push_image(element, spans),
198 "video" => push_video(element, spans),
199 _ => spans.extend(convert_children(element)),
200 }
201}
202
203fn is_reply(element: ElementRef<'_>) -> bool {
204 element
205 .value()
206 .attr("itemtype")
207 .is_some_and(|itemtype| itemtype.contains(REPLY_ITEMTYPE))
208}
209
210fn list(element: ElementRef<'_>) -> Span {
211 let mut items: Vec<Vec<Span>> = Vec::new();
212 for child in element.children().filter_map(ElementRef::wrap) {
213 match child.value().name() {
214 "li" => items.push(convert_children(child)),
215 "ul" | "ol" => match items.last_mut() {
216 Some(previous) => previous.push(list(child)),
217 None => items.push(vec![list(child)]),
218 },
219 _ => {}
220 }
221 }
222 Span::List {
223 ordered: element.value().name() == "ol",
224 start: element
225 .value()
226 .attr("start")
227 .and_then(|start| start.trim().parse().ok())
228 .unwrap_or(1),
229 items,
230 }
231}
232
233fn table(element: ElementRef<'_>) -> Span {
234 let rows: Vec<ElementRef<'_>> = element
235 .descendants()
236 .filter_map(ElementRef::wrap)
237 .filter(|row| row.value().name() == "tr" && belongs_to(*row, element))
238 .collect();
239 let header = rows.first().is_some_and(|row| {
240 let in_head = row
241 .parent()
242 .and_then(ElementRef::wrap)
243 .is_some_and(|parent| parent.value().name() == "thead");
244 let mut cells = cells_of(*row).peekable();
245 in_head || (cells.peek().is_some() && cells.all(|cell| cell.value().name() == "th"))
246 });
247 Span::Table {
248 header,
249 rows: rows
250 .into_iter()
251 .map(|row| cells_of(row).map(convert_children).collect())
252 .filter(|cells: &Vec<Vec<Span>>| !cells.is_empty())
253 .collect(),
254 }
255}
256
257fn belongs_to(row: ElementRef<'_>, table: ElementRef<'_>) -> bool {
258 row.ancestors()
259 .filter_map(ElementRef::wrap)
260 .find(|ancestor| ancestor.value().name() == "table")
261 .is_some_and(|owner| owner.id() == table.id())
262}
263
264fn cells_of<'a>(row: ElementRef<'a>) -> impl Iterator<Item = ElementRef<'a>> {
265 row.children()
266 .filter_map(ElementRef::wrap)
267 .filter(|cell| matches!(cell.value().name(), "td" | "th"))
268}
269
270fn push_colored(element: ElementRef<'_>, spans: &mut Vec<Span>) {
271 let value = element.value();
272 let style = value.attr("style").unwrap_or_default();
273 let color = style_value(style, "color")
274 .or_else(|| value.attr("color"))
275 .and_then(parse_color);
276 let background = style_value(style, "background-color")
277 .or_else(|| style_value(style, "background"))
278 .and_then(parse_color)
279 .or((value.name() == "mark").then_some(MARK_BACKGROUND));
280 let size = style_value(style, "font-size").and_then(parse_font_size);
281 let mut children = convert_children(element);
282 if color.is_some() || background.is_some() {
283 children = vec![Span::Colored {
284 color,
285 background,
286 children,
287 }];
288 }
289 match size {
290 Some(size) => spans.push(Span::Sized(size, children)),
291 None => spans.extend(children),
292 }
293}
294
295fn parse_font_size(value: &str) -> Option<FontSize> {
296 let value = value.trim().to_ascii_lowercase();
297 match value.as_str() {
298 "xx-small" => Some(FontSize::Small),
299 "x-large" => Some(FontSize::Large),
300 "x-small" => Some(FontSize::Pixels(10)),
301 "small" | "smaller" => Some(FontSize::Pixels(13)),
302 "large" | "larger" => Some(FontSize::Pixels(18)),
303 "xx-large" => Some(FontSize::Pixels(32)),
304 "0" => Some(FontSize::Hidden),
305 _ => {
306 let pixels: f32 = value.strip_suffix("px")?.trim().parse().ok()?;
307 if pixels <= 0. {
308 Some(FontSize::Hidden)
309 } else {
310 Some(FontSize::Pixels(
311 pixels.round().min(f32::from(u16::MAX)) as u16
312 ))
313 }
314 }
315 }
316}
317
318fn style_value<'a>(style: &'a str, property: &str) -> Option<&'a str> {
319 style.split(';').find_map(|declaration| {
320 let (name, value) = declaration.split_once(':')?;
321 (name.trim().eq_ignore_ascii_case(property)).then(|| value.trim())
322 })
323}
324
325pub fn parse_color(value: &str) -> Option<u32> {
326 let value = value.trim().to_ascii_lowercase();
327 if let Some(hex) = value.strip_prefix('#') {
328 return match hex.len() {
329 3 => {
330 let expanded: String = hex.chars().flat_map(|digit| [digit, digit]).collect();
331 u32::from_str_radix(&expanded, 16).ok()
332 }
333 6 => u32::from_str_radix(hex, 16).ok(),
334 _ => None,
335 };
336 }
337 if let Some(arguments) = value
338 .strip_prefix("rgba(")
339 .or_else(|| value.strip_prefix("rgb("))
340 .and_then(|rest| rest.strip_suffix(')'))
341 {
342 let channels: Vec<u32> = arguments
343 .split(',')
344 .take(3)
345 .map(|channel| {
346 channel
347 .trim()
348 .parse::<f32>()
349 .ok()
350 .map(|level| level.clamp(0., 255.) as u32)
351 })
352 .collect::<Option<_>>()?;
353 let [red, green, blue] = channels[..] else {
354 return None;
355 };
356 return Some(red << 16 | green << 8 | blue);
357 }
358 NAMED_COLORS
359 .iter()
360 .find(|(name, _)| *name == value)
361 .map(|(_, hex)| *hex)
362}
363
364const NAMED_COLORS: [(&str, u32); 14] = [
365 ("black", 0x000000),
366 ("white", 0xffffff),
367 ("red", 0xff0000),
368 ("green", 0x008000),
369 ("lime", 0x00ff00),
370 ("blue", 0x0000ff),
371 ("yellow", 0xffff00),
372 ("orange", 0xffa500),
373 ("purple", 0x800080),
374 ("fuchsia", 0xff00ff),
375 ("aqua", 0x00ffff),
376 ("teal", 0x008080),
377 ("gray", 0x808080),
378 ("grey", 0x808080),
379];
380
381fn code_block(element: ElementRef<'_>) -> Span {
382 let language = language_of(element).or_else(|| {
383 element
384 .descendants()
385 .filter_map(ElementRef::wrap)
386 .find_map(language_of)
387 });
388 Span::CodeBlock {
389 language: language.filter(|language| language != PLAIN_LANGUAGE),
390 code: code_text(element).trim_end_matches('\n').to_owned(),
391 }
392}
393
394fn code_text(element: ElementRef<'_>) -> String {
395 let mut text = String::new();
396 for node in element.descendants() {
397 match node.value() {
398 Node::Text(piece) => text.push_str(piece),
399 Node::Element(child) if child.name() == "br" => text.push('\n'),
400 _ => {}
401 }
402 }
403 text
404}
405
406fn language_of(element: ElementRef<'_>) -> Option<String> {
407 element
408 .value()
409 .classes()
410 .find_map(|class| class.strip_prefix(LANGUAGE_PREFIX))
411 .filter(|language| !language.is_empty())
412 .map(str::to_owned)
413}
414
415fn push_link(element: ElementRef<'_>, spans: &mut Vec<Span>) {
416 let children = convert_children(element);
417 match element.value().attr("href") {
418 Some(url) if !url.is_empty() => spans.push(Span::Link {
419 url: url.to_owned(),
420 children,
421 }),
422 _ => spans.extend(children),
423 }
424}
425
426fn push_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
427 let glyph = element
428 .value()
429 .attr("alt")
430 .map(str::to_owned)
431 .filter(|alt| !alt.is_empty())
432 .unwrap_or_else(|| raw_text(element));
433 push_text(spans, &without_repeated_skin_tone(&glyph));
434}
435
436fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
437 let value = element.value();
438 let name = value.attr("alt").unwrap_or_default().to_owned();
439 match value.attr("source").filter(|source| !source.is_empty()) {
440 Some(source) => spans.push(Span::CustomEmoji {
441 name,
442 url: source.to_owned(),
443 }),
444 None if !name.is_empty() => push_text(spans, &format!(":{name}:")),
445 None => {}
446 }
447}
448
449fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
450 let value = element.value();
451 let is_emoji = value
452 .attr("itemtype")
453 .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
454 if is_emoji {
455 if let Some(alt) = value.attr("alt") {
456 push_text(spans, &without_repeated_skin_tone(alt));
457 }
458 return;
459 }
460 if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) {
461 spans.push(Span::Image {
462 hosted_content_url: source.to_owned(),
463 });
464 }
465}
466
467/// A Teams video clip draws as its thumbnail; other videos keep only their fallback content.
468fn push_video(element: ElementRef<'_>, spans: &mut Vec<Span>) {
469 match element.value().attr("src").and_then(video_thumbnail_url) {
470 Some(thumbnail) => spans.push(Span::Image {
471 hosted_content_url: thumbnail,
472 }),
473 None => spans.extend(convert_children(element)),
474 }
475}
476
477fn raw_text(element: ElementRef<'_>) -> String {
478 element.text().collect()
479}
480
481/// The service sends the reply time as an empty span that only carries the quoted message id.
482fn push_quote_time(element: ElementRef<'_>, spans: &mut Vec<Span>) {
483 if !raw_text(element).trim().is_empty() {
484 push_colored(element, spans);
485 return;
486 }
487 if let Some(time) = element.value().attr("itemid").and_then(quote_time) {
488 push_text(spans, &format!(" {time}"));
489 }
490}
491
492fn push_text(spans: &mut Vec<Span>, text: &str) {
493 if text.is_empty() {
494 return;
495 }
496 if let Some(Span::Text(existing)) = spans.last_mut() {
497 existing.push_str(text);
498 } else {
499 spans.push(Span::Text(text.to_owned()));
500 }
501}
502
503fn tidy(spans: &mut Vec<Span>) {
504 tidy_children(spans, true);
505}
506
507fn tidy_children(spans: &mut Vec<Span>, block: bool) {
508 for span in spans.iter_mut() {
509 match span {
510 Span::Bold(children)
511 | Span::Italic(children)
512 | Span::Strike(children)
513 | Span::Superscript(children)
514 | Span::Subscript(children)
515 | Span::Sized(_, children)
516 | Span::Underline(children)
517 | Span::Colored { children, .. }
518 | Span::Link { children, .. } => tidy_children(children, false),
519 Span::Heading { children, .. }
520 | Span::Quote { children, .. }
521 | Span::BlockQuote(children)
522 | Span::Indent { children, .. } => tidy(children),
523 Span::List { items, .. } => items.iter_mut().for_each(tidy),
524 Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
525 _ => {}
526 }
527 }
528 collapse_whitespace(spans, block);
529 if block {
530 trim_inline_edge(spans, true);
531 trim_inline_edge(spans, false);
532 }
533 limit_breaks(spans);
534 trim_breaks(spans);
535}
536
537fn trim_inline_edge(spans: &mut Vec<Span>, leading: bool) {
538 let edge = if leading {
539 spans.first_mut()
540 } else {
541 spans.last_mut()
542 };
543 let emptied = match edge {
544 Some(Span::Text(text)) => {
545 *text = if leading {
546 text.trim_start().to_owned()
547 } else {
548 text.trim_end().to_owned()
549 };
550 text.is_empty()
551 }
552 Some(
553 Span::Bold(children)
554 | Span::Italic(children)
555 | Span::Strike(children)
556 | Span::Superscript(children)
557 | Span::Subscript(children)
558 | Span::Sized(_, children)
559 | Span::Underline(children)
560 | Span::Colored { children, .. }
561 | Span::Link { children, .. },
562 ) => {
563 trim_inline_edge(children, leading);
564 false
565 }
566 _ => false,
567 };
568 if emptied {
569 if leading {
570 spans.remove(0);
571 } else {
572 spans.pop();
573 }
574 }
575}
576
577fn collapse_whitespace(spans: &mut Vec<Span>, block: bool) {
578 let mut collapsed: Vec<Span> = Vec::with_capacity(spans.len());
579 let count = spans.len();
580 for (index, span) in std::mem::take(spans).into_iter().enumerate() {
581 let Span::Text(text) = span else {
582 collapsed.push(span);
583 continue;
584 };
585 let mut text = squeeze_spaces(&text);
586 let at_edge = |neighbour: Option<&Span>| {
587 matches!(
588 neighbour,
589 None if block
590 ) || matches!(
591 neighbour,
592 Some(
593 Span::LineBreak
594 | Span::Rule
595 | Span::List { .. }
596 | Span::Table { .. }
597 | Span::Heading { .. }
598 | Span::Quote { .. }
599 | Span::BlockQuote(_)
600 | Span::Indent { .. }
601 )
602 )
603 };
604 if at_edge(collapsed.last()) {
605 text = text.trim_start().to_owned();
606 }
607 if block && index + 1 == count {
608 text = text.trim_end().to_owned();
609 }
610 if !text.is_empty() {
611 collapsed.push(Span::Text(text));
612 }
613 }
614 for index in 0..collapsed.len() {
615 let followed_by_break = matches!(collapsed.get(index + 1), Some(Span::LineBreak));
616 if followed_by_break && let Span::Text(text) = &mut collapsed[index] {
617 *text = text.trim_end().to_owned();
618 }
619 }
620 collapsed.retain(|span| !matches!(span, Span::Text(text) if text.is_empty()));
621 *spans = collapsed;
622}
623
624fn squeeze_spaces(text: &str) -> String {
625 let mut squeezed = String::with_capacity(text.len());
626 let mut previous_space = false;
627 for character in text.chars() {
628 let is_space = character.is_whitespace() && character != '\u{a0}';
629 if is_space {
630 if !previous_space {
631 squeezed.push(' ');
632 }
633 } else {
634 squeezed.push(character);
635 }
636 previous_space = is_space;
637 }
638 squeezed
639}
640
641fn limit_breaks(spans: &mut Vec<Span>) {
642 let mut run = 0;
643 spans.retain(|span| {
644 if matches!(span, Span::LineBreak) {
645 run += 1;
646 run <= MAX_CONSECUTIVE_BREAKS
647 } else {
648 run = 0;
649 true
650 }
651 });
652}
653
654fn trim_breaks(spans: &mut Vec<Span>) {
655 while matches!(spans.last(), Some(Span::LineBreak)) {
656 spans.pop();
657 }
658 let leading = spans
659 .iter()
660 .take_while(|span| matches!(span, Span::LineBreak))
661 .count();
662 spans.drain(..leading);
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668
669 #[test]
670 fn an_empty_reply_time_shows_the_time_of_the_quoted_message() {
671 let quoted = r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="1751975663649"><strong itemprop="mri">Ann</strong><span itemprop="time" itemid="1751975663649"></span><p itemprop="preview">old</p></blockquote>"#;
672 let expected = quote_time("1751975663649").unwrap();
673 let spans = html_to_spans(quoted);
674 let [Span::Quote { children, .. }] = spans.as_slice() else {
675 panic!("expected a quote");
676 };
677 assert!(
678 children.contains(&Span::Text(format!(" {expected}"))),
679 "{children:?}"
680 );
681 }
682
683 #[test]
684 fn spaces_at_the_edge_of_inline_formatting_survive() {
685 assert_eq!(
686 html_to_spans("Hello<b> world</b>"),
687 vec![
688 Span::Text("Hello".into()),
689 Span::Bold(vec![Span::Text(" world".into())])
690 ]
691 );
692 assert_eq!(
693 html_to_spans("<b> Note </b>"),
694 vec![Span::Bold(vec![Span::Text("Note".into())])]
695 );
696 assert_eq!(
697 html_to_spans("<strong>Note: </strong>text"),
698 vec![
699 Span::Bold(vec![Span::Text("Note: ".into())]),
700 Span::Text("text".into())
701 ]
702 );
703 }
704}