use scraper::{ElementRef, Html, Node};
use crate::jumbo::without_repeated_skin_tone;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontSize {
Small,
Large,
Hidden,
Pixels(u16),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Span {
Text(String),
Bold(Vec),
Italic(Vec),
Code(String),
CodeBlock {
language: Option,
code: String,
},
Link {
url: String,
children: Vec,
},
Mention {
name: String,
id: Option,
},
Strike(Vec),
Superscript(Vec),
Subscript(Vec),
Sized(FontSize, Vec),
Underline(Vec),
Colored {
color: Option,
background: Option,
children: Vec,
},
Heading {
level: u8,
children: Vec,
},
LineBreak,
Rule,
List {
ordered: bool,
start: u32,
items: Vec>,
},
Table {
header: bool,
rows: Vec>>,
},
Image {
hosted_content_url: String,
},
CustomEmoji {
name: String,
url: String,
},
Quote {
message_id: Option,
children: Vec,
},
BlockQuote(Vec),
Indent {
level: u8,
children: Vec,
},
}
const BLOCK_ELEMENTS: [&str; 12] = [
"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "ul", "ol", "hr",
];
const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
const LANGUAGE_PREFIX: &str = "language-";
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
const MAX_HEADING_LEVEL: u8 = 3;
const MARK_BACKGROUND: u32 = 0xffff00;
const MAX_CONSECUTIVE_BREAKS: usize = 2;
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];
const INDENT_STEP_PIXELS: f32 = 40.;
const MAX_INDENT_LEVEL: u8 = 8;
const PLAIN_LANGUAGE: &str = "plaintext";
pub fn html_to_spans(html: &str) -> Vec {
let fragment = Html::parse_fragment(html);
let mut spans = convert_children(fragment.root_element());
tidy(&mut spans);
spans
}
fn convert_children(element: ElementRef<'_>) -> Vec {
let mut spans = Vec::new();
let mut break_pending = false;
for child in element.children() {
match child.value() {
Node::Text(text) => {
let text: &str = text;
if break_pending && text.trim().is_empty() {
continue;
}
if break_pending && !spans.is_empty() {
spans.push(Span::LineBreak);
}
break_pending = false;
push_text(&mut spans, text);
}
Node::Element(_) => {
let Some(child_element) = ElementRef::wrap(child) else {
continue;
};
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());
if (is_block || break_pending) && !spans.is_empty() {
spans.push(Span::LineBreak);
}
convert_element(child_element, &mut spans);
break_pending = is_block;
}
_ => {}
}
}
spans
}
fn convert_element(element: ElementRef<'_>, spans: &mut Vec) {
let name = element.value().name();
if SKIPPED_ELEMENTS.contains(&name) {
return;
}
match block_indent(element) {
Some(level) => {
let mut children = Vec::new();
convert_unindented(element, &mut children);
spans.push(Span::Indent { level, children });
}
None => convert_unindented(element, spans),
}
}
fn block_indent(element: ElementRef<'_>) -> Option {
let value = element.value();
if !INDENTED_ELEMENTS.contains(&value.name()) {
return None;
}
let margin = style_value(value.attr("style")?, "margin-left")?;
let pixels: f32 = margin.trim().strip_suffix("px")?.trim().parse().ok()?;
let level = (pixels / INDENT_STEP_PIXELS).round();
(level >= 1.).then(|| level.min(f32::from(MAX_INDENT_LEVEL)) as u8)
}
fn convert_unindented(element: ElementRef<'_>, spans: &mut Vec) {
let name = element.value().name();
match name {
"b" | "strong" => spans.push(Span::Bold(convert_children(element))),
"h1" | "h2" | "h3" | "h4" | "h5" | "h6" => spans.push(Span::Heading {
level: name[1..].parse::().unwrap_or(1).min(MAX_HEADING_LEVEL),
children: convert_children(element),
}),
"i" | "em" => spans.push(Span::Italic(convert_children(element))),
"s" | "strike" | "del" => spans.push(Span::Strike(convert_children(element))),
"sup" => spans.push(Span::Superscript(convert_children(element))),
"sub" => spans.push(Span::Subscript(convert_children(element))),
"u" | "ins" => spans.push(Span::Underline(convert_children(element))),
"span" | "font" | "mark" => push_colored(element, spans),
"ul" | "ol" => spans.push(list(element)),
"table" => spans.push(table(element)),
"code" => spans.push(Span::Code(raw_text(element))),
"pre" | "codeblock" => spans.push(code_block(element)),
"a" => push_link(element, spans),
"at" => spans.push(Span::Mention {
name: raw_text(element).trim().to_owned(),
id: element.value().attr("id").map(str::to_owned),
}),
"br" => spans.push(Span::LineBreak),
"hr" => spans.push(Span::Rule),
"li" => spans.push(Span::List {
ordered: false,
start: 1,
items: vec![convert_children(element)],
}),
"blockquote" if is_reply(element) => spans.push(Span::Quote {
message_id: element.value().attr("itemid").map(str::to_owned),
children: convert_children(element),
}),
"blockquote" => spans.push(Span::BlockQuote(convert_children(element))),
"emoji" => push_emoji(element, spans),
"customemoji" => push_custom_emoji(element, spans),
"img" => push_image(element, spans),
_ => spans.extend(convert_children(element)),
}
}
fn is_reply(element: ElementRef<'_>) -> bool {
element
.value()
.attr("itemtype")
.is_some_and(|itemtype| itemtype.contains(REPLY_ITEMTYPE))
}
fn list(element: ElementRef<'_>) -> Span {
let mut items: Vec> = Vec::new();
for child in element.children().filter_map(ElementRef::wrap) {
match child.value().name() {
"li" => items.push(convert_children(child)),
"ul" | "ol" => match items.last_mut() {
Some(previous) => previous.push(list(child)),
None => items.push(vec![list(child)]),
},
_ => {}
}
}
Span::List {
ordered: element.value().name() == "ol",
start: element
.value()
.attr("start")
.and_then(|start| start.trim().parse().ok())
.unwrap_or(1),
items,
}
}
fn table(element: ElementRef<'_>) -> Span {
let rows: Vec> = element
.descendants()
.filter_map(ElementRef::wrap)
.filter(|row| row.value().name() == "tr" && belongs_to(*row, element))
.collect();
let header = rows.first().is_some_and(|row| {
let in_head = row
.parent()
.and_then(ElementRef::wrap)
.is_some_and(|parent| parent.value().name() == "thead");
let mut cells = cells_of(*row).peekable();
in_head || (cells.peek().is_some() && cells.all(|cell| cell.value().name() == "th"))
});
Span::Table {
header,
rows: rows
.into_iter()
.map(|row| cells_of(row).map(convert_children).collect())
.filter(|cells: &Vec>| !cells.is_empty())
.collect(),
}
}
fn belongs_to(row: ElementRef<'_>, table: ElementRef<'_>) -> bool {
row.ancestors()
.filter_map(ElementRef::wrap)
.find(|ancestor| ancestor.value().name() == "table")
.is_some_and(|owner| owner.id() == table.id())
}
fn cells_of<'a>(row: ElementRef<'a>) -> impl Iterator- > {
row.children()
.filter_map(ElementRef::wrap)
.filter(|cell| matches!(cell.value().name(), "td" | "th"))
}
fn push_colored(element: ElementRef<'_>, spans: &mut Vec) {
let value = element.value();
let style = value.attr("style").unwrap_or_default();
let color = style_value(style, "color")
.or_else(|| value.attr("color"))
.and_then(parse_color);
let background = style_value(style, "background-color")
.or_else(|| style_value(style, "background"))
.and_then(parse_color)
.or((value.name() == "mark").then_some(MARK_BACKGROUND));
let size = style_value(style, "font-size").and_then(parse_font_size);
let mut children = convert_children(element);
if color.is_some() || background.is_some() {
children = vec![Span::Colored {
color,
background,
children,
}];
}
match size {
Some(size) => spans.push(Span::Sized(size, children)),
None => spans.extend(children),
}
}
fn parse_font_size(value: &str) -> Option {
let value = value.trim().to_ascii_lowercase();
match value.as_str() {
"xx-small" => Some(FontSize::Small),
"x-large" => Some(FontSize::Large),
"x-small" => Some(FontSize::Pixels(10)),
"small" | "smaller" => Some(FontSize::Pixels(13)),
"large" | "larger" => Some(FontSize::Pixels(18)),
"xx-large" => Some(FontSize::Pixels(32)),
"0" => Some(FontSize::Hidden),
_ => {
let pixels: f32 = value.strip_suffix("px")?.trim().parse().ok()?;
if pixels <= 0. {
Some(FontSize::Hidden)
} else {
Some(FontSize::Pixels(
pixels.round().min(f32::from(u16::MAX)) as u16
))
}
}
}
}
fn style_value<'a>(style: &'a str, property: &str) -> Option<&'a str> {
style.split(';').find_map(|declaration| {
let (name, value) = declaration.split_once(':')?;
(name.trim().eq_ignore_ascii_case(property)).then(|| value.trim())
})
}
pub fn parse_color(value: &str) -> Option {
let value = value.trim().to_ascii_lowercase();
if let Some(hex) = value.strip_prefix('#') {
return match hex.len() {
3 => {
let expanded: String = hex.chars().flat_map(|digit| [digit, digit]).collect();
u32::from_str_radix(&expanded, 16).ok()
}
6 => u32::from_str_radix(hex, 16).ok(),
_ => None,
};
}
if let Some(arguments) = value
.strip_prefix("rgba(")
.or_else(|| value.strip_prefix("rgb("))
.and_then(|rest| rest.strip_suffix(')'))
{
let channels: Vec = arguments
.split(',')
.take(3)
.map(|channel| {
channel
.trim()
.parse::()
.ok()
.map(|level| level.clamp(0., 255.) as u32)
})
.collect::