BlueGit

ict rusty-teams

Files

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

spans.rs

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