BlueGit

ict rusty-teams

Files

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

spans.rs

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