use crate::html::{attribute, color, decode_entities, parse_tag};
use crate::spreadsheet::TextRun;
use crate::style::Style;
const DEFAULT_FONT: &str = "Calibri";
const DEFAULT_SIZE: f64 = 11.0;
const DEFAULT_COLOR: &str = "000000";
#[derive(Clone, Default)]
struct State {
bold: bool,
italic: bool,
underline: bool,
strikethrough: bool,
superscript: bool,
subscript: bool,
face: Option<String>,
size: Option<f64>,
color: Option<String>,
}
impl State {
fn run(&self, text: String) -> TextRun {
let mut style = Style::new();
if self.bold {
style = style.bold();
}
if self.italic {
style = style.italic();
}
if self.underline {
style = style.underline();
}
if self.strikethrough {
style = style.strikethrough();
}
if let Some(face) = &self.face {
style = style.font_name(face.clone());
}
if let Some(size) = self.size {
style = style.font_size(size);
}
if let Some(color) = &self.color {
style = style.font_color(color.clone());
}
TextRun {
text,
style,
superscript: self.superscript,
subscript: self.subscript,
plain: false,
}
}
}
fn css_color(value: &str) -> Option<String> {
let named = match value.trim().to_ascii_lowercase().as_str() {
"black" => "000000",
"white" => "FFFFFF",
"red" => "FF0000",
"green" => "008000",
"lime" => "00FF00",
"blue" => "0000FF",
"yellow" => "FFFF00",
"cyan" | "aqua" => "00FFFF",
"magenta" | "fuchsia" => "FF00FF",
"gray" | "grey" => "808080",
"silver" => "C0C0C0",
"maroon" => "800000",
"olive" => "808000",
"navy" => "000080",
"purple" => "800080",
"teal" => "008080",
"orange" => "FFA500",
_ => return color(value),
};
Some(named.to_owned())
}
fn apply_css(state: &mut State, css: &str) {
for declaration in css.split(';') {
let Some((property, value)) = declaration.split_once(':') else {
continue;
};
let value = value.trim();
match property.trim().to_ascii_lowercase().as_str() {
"color" => state.color = css_color(value).or(state.color.take()),
"font-weight" => {
state.bold = value.eq_ignore_ascii_case("bold") || value.parse::<u32>().is_ok_and(|w| w >= 600)
}
"font-style" => state.italic = value.eq_ignore_ascii_case("italic"),
"text-decoration" => {
let value = value.to_ascii_lowercase();
state.underline = value.contains("underline");
state.strikethrough = value.contains("line-through");
}
"font-family" => {
let face = value
.split(',')
.next()
.unwrap_or_default()
.trim()
.trim_matches(['\'', '"']);
if !face.is_empty() {
state.face = Some(face.to_owned());
}
}
"font-size" => {
if let Ok(size) = value.trim_end_matches("pt").trim_end_matches("px").trim().parse() {
state.size = Some(size);
}
}
_ => {}
}
}
}
pub(crate) fn from_html(html: &str) -> Vec<TextRun> {
let mut runs: Vec<TextRun> = Vec::new();
let mut stack: Vec<(String, State)> = Vec::new();
let mut state = State::default();
let mut text = String::new();
let mut rest = html;
let mut pending_break = false;
let flush = |text: &mut String, state: &State, runs: &mut Vec<TextRun>| {
if !text.is_empty() {
runs.push(state.run(decode_entities(&std::mem::take(text))));
}
};
while !rest.is_empty() {
match rest.find('<') {
Some(0) => {
let Some(end) = rest.find('>') else {
text.push_str(rest);
break;
};
let raw = &rest[1..end];
rest = &rest[end + 1..];
let Some(tag) = parse_tag(raw) else { continue };
let block = matches!(
tag.name.as_str(),
"p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "li" | "ul" | "ol" | "table" | "tr"
);
if tag.name == "br" {
text.push('\n');
continue;
}
if tag.closing {
flush(&mut text, &state, &mut runs);
if let Some(position) = stack.iter().rposition(|(name, _)| *name == tag.name) {
state = stack[position].1.clone();
stack.truncate(position);
}
if block {
pending_break = true;
}
continue;
}
flush(&mut text, &state, &mut runs);
if block && pending_break && !runs.is_empty() {
text.push('\n');
}
pending_break = false;
if raw.trim_end().ends_with('/') {
continue;
}
stack.push((tag.name.clone(), state.clone()));
match tag.name.as_str() {
"b" | "strong" => state.bold = true,
"i" | "em" => state.italic = true,
"u" | "ins" => state.underline = true,
"s" | "strike" | "del" => state.strikethrough = true,
"sup" => state.superscript = true,
"sub" => state.subscript = true,
"font" => {
if let Some(face) = attribute(tag.attributes, "face") {
state.face = Some(face);
}
if let Some(size) = attribute(tag.attributes, "size").and_then(|size| size.parse().ok()) {
state.size = Some(size);
}
if let Some(color) = attribute(tag.attributes, "color").as_deref().and_then(css_color) {
state.color = Some(color);
}
}
_ => {}
}
if let Some(css) = attribute(tag.attributes, "style") {
apply_css(&mut state, &css);
}
}
Some(start) => {
if pending_break {
text.push('\n');
pending_break = false;
}
text.push_str(&rest[..start]);
rest = &rest[start..];
}
None => {
if pending_break {
text.push('\n');
pending_break = false;
}
text.push_str(rest);
rest = "";
}
}
}
flush(&mut text, &state, &mut runs);
runs
}
fn escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn sanitize_font_name(name: &str) -> String {
name.chars()
.filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '_' | '.' | ',' | '+' | '-'))
.collect::<String>()
.trim()
.to_owned()
}
fn to_css(run: &TextRun) -> String {
let font = &run.style.font;
let mut css: Vec<(&str, String)> = Vec::new();
if font.bold == Some(true) {
css.push(("font-weight", "bold".to_owned()));
}
let underline = font.underline == Some(true);
let strike = font.strikethrough == Some(true);
match (underline, strike) {
(true, true) => css.push(("text-decoration", "underline line-through".to_owned())),
(true, false) => css.push(("text-decoration", "underline".to_owned())),
(false, true) => css.push(("text-decoration", "line-through".to_owned())),
_ => {}
}
if font.italic == Some(true) {
css.push(("font-style", "italic".to_owned()));
}
let color = font.color.as_deref().unwrap_or(DEFAULT_COLOR);
let color = if color.len() == 8 { &color[2..] } else { color };
css.push(("color", format!("#{}", color.to_ascii_uppercase())));
let name = sanitize_font_name(font.name.as_deref().unwrap_or(DEFAULT_FONT));
if !name.is_empty() {
css.push(("font-family", format!("'{name}'")));
}
let size = font.size.unwrap_or(DEFAULT_SIZE);
css.push(("font-size", format!("{}pt", crate::value::format_float(size))));
css.iter()
.map(|(property, value)| format!("{property}:{value}"))
.collect::<Vec<_>>()
.join("; ")
}
pub(crate) fn to_html(runs: &[TextRun]) -> String {
let mut html = String::new();
for run in runs {
if run.plain {
html.push_str(&escape(&run.text));
continue;
}
html.push_str("<span style=\"");
html.push_str(&escape(&to_css(run)).replace("'", "'"));
html.push_str("\">");
let (open, close) = if run.superscript {
("<sup>", "</sup>")
} else if run.subscript {
("<sub>", "</sub>")
} else {
("", "")
};
html.push_str(open);
html.push_str(&escape(&run.text));
html.push_str(close);
html.push_str("</span>");
}
html
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn html_becomes_runs_and_back() {
let runs = from_html("<div>Hello <b>bold</b> and <span style=\"color: #ff0000\">red</span></div>");
let texts: Vec<&str> = runs.iter().map(|run| run.text.as_str()).collect();
assert_eq!(texts, ["Hello ", "bold", " and ", "red"]);
assert_eq!(runs[1].style.font.bold, Some(true));
assert_eq!(runs[3].style.font.color.as_deref(), Some("FF0000"));
assert_eq!(
to_html(&runs[1..2]),
"<span style=\"font-weight:bold; color:#000000; font-family:'Calibri'; font-size:11pt\">bold</span>"
);
}
#[test]
fn breaks_and_entities() {
let runs = from_html("<div>a<br>b & c</div>");
assert_eq!(runs[0].text, "a\nb & c");
}
}