BlueGit

ict rusty-teams

Files

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

spans.rs

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