BlueGit

ict rusty-teams

Files

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

spans.rs

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