BlueGit

ict rusty-teams

Files

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

spans.rs

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