BlueGit

ict rusty-teams

Files

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

spans.rs

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