BlueGit

ict rusty-teams

Files

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

spans.rs

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