BlueGit

ict rusty-teams

Files

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

spans.rs

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