BlueGit

ict rusty-teams

Files

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

spans.rs

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