BlueGit

ict rusty-teams

Files

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

spans.rs

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