use std::collections::HashSet;
use crate::coordinate::{Coordinate, string_from_column_index};
use crate::spreadsheet::Worksheet;
use crate::style::{Horizontal, Style, Vertical};
use crate::value::{Value, bind_default};
pub(crate) struct Tag<'a> {
pub(crate) name: String,
pub(crate) closing: bool,
pub(crate) attributes: &'a str,
}
pub(crate) fn parse_tag(raw: &str) -> Option<Tag<'_>> {
let raw = raw.trim();
let (closing, raw) = match raw.strip_prefix('/') {
Some(rest) => (true, rest.trim_start()),
None => (false, raw),
};
let end = raw
.find(|c: char| c.is_whitespace() || c == '/' || c == '>')
.unwrap_or(raw.len());
let name = raw[..end].to_ascii_lowercase();
if name.is_empty() {
return None;
}
Some(Tag {
name,
closing,
attributes: &raw[end..],
})
}
pub(crate) fn attribute(attributes: &str, name: &str) -> Option<String> {
let lower = attributes.to_ascii_lowercase();
let mut search = 0;
while let Some(found) = lower[search..].find(name) {
let start = search + found;
let before_ok =
start == 0 || !lower.as_bytes()[start - 1].is_ascii_alphanumeric() && lower.as_bytes()[start - 1] != b'-';
let rest = lower[start + name.len()..].trim_start();
if before_ok && rest.starts_with('=') {
let offset = attributes.len() - rest.len() + 1;
let value = attributes[offset..].trim_start();
return Some(match value.chars().next() {
Some(quote @ ('"' | '\'')) => value[1..].split(quote).next().unwrap_or_default().to_owned(),
_ => value
.split(|c: char| c.is_whitespace() || c == '>')
.next()
.unwrap_or_default()
.to_owned(),
});
}
search = start + name.len();
}
None
}
pub(crate) fn decode_entities(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(amp) = rest.find('&') {
out.push_str(&rest[..amp]);
rest = &rest[amp..];
let Some(semi) = rest[..rest.len().min(12)].find(';') else {
out.push('&');
rest = &rest[1..];
continue;
};
let entity = &rest[1..semi];
let decoded = match entity {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" | "#39" => Some('\''),
"nbsp" => Some('\u{a0}'),
_ => entity
.strip_prefix("#x")
.or_else(|| entity.strip_prefix("#X"))
.and_then(|hex| u32::from_str_radix(hex, 16).ok())
.or_else(|| entity.strip_prefix('#').and_then(|dec| dec.parse().ok()))
.and_then(char::from_u32),
};
match decoded {
Some(c) => {
out.push(c);
rest = &rest[semi + 1..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
pub(crate) fn color(value: &str) -> Option<String> {
let value = value.trim().trim_start_matches('#');
(value.len() == 6 && value.chars().all(|c| c.is_ascii_hexdigit())).then(|| value.to_ascii_uppercase())
}
fn inline_style(attributes: &str) -> Style {
let mut style = Style::new();
if let Some(bg) = attribute(attributes, "bgcolor").as_deref().and_then(color) {
style = style.background(bg);
}
if let Some(horizontal) = attribute(attributes, "align").as_deref().and_then(horizontal) {
style = style.horizontal(horizontal);
}
let Some(css) = attribute(attributes, "style") else {
return style;
};
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() {
"background-color" | "background" => {
if let Some(bg) = color(value) {
style = style.background(bg);
}
}
"color" => {
if let Some(fg) = color(value) {
style = style.font_color(fg);
}
}
"font-weight" if value.eq_ignore_ascii_case("bold") || value.parse::<u32>().is_ok_and(|w| w >= 600) => {
style = style.bold();
}
"font-style" if value.eq_ignore_ascii_case("italic") => style = style.italic(),
"text-decoration" if value.contains("underline") => style = style.underline(),
"text-decoration" if value.contains("line-through") => style = style.strikethrough(),
"font-size" => {
if let Ok(size) = value
.trim_end_matches("pt")
.trim_end_matches("px")
.trim()
.parse::<f64>()
{
style = style.font_size(size);
}
}
"text-align" => {
if let Some(horizontal) = horizontal(value) {
style = style.horizontal(horizontal);
}
}
"vertical-align" => {
let vertical = match value.to_ascii_lowercase().as_str() {
"top" => Some(Vertical::Top),
"middle" => Some(Vertical::Center),
"bottom" => Some(Vertical::Bottom),
_ => None,
};
if let Some(vertical) = vertical {
style = style.vertical(vertical);
}
}
"white-space" if value.eq_ignore_ascii_case("normal") || value.eq_ignore_ascii_case("pre-wrap") => {
style = style.wrap_text();
}
_ => {}
}
}
style
}
fn horizontal(value: &str) -> Option<Horizontal> {
match value.trim().to_ascii_lowercase().as_str() {
"left" => Some(Horizontal::Left),
"right" => Some(Horizontal::Right),
"center" => Some(Horizontal::Center),
"justify" => Some(Horizontal::Justify),
_ => None,
}
}
struct OpenCell {
column: u32,
row: u32,
colspan: u32,
rowspan: u32,
text: String,
style: Style,
width: Option<f64>,
}
pub(crate) fn load(html: &str, worksheet: &mut Worksheet) {
let mut row = if worksheet.cells().next().is_some() {
worksheet.highest_row()
} else {
0
};
let mut column = 1;
let mut occupied: HashSet<(u32, u32)> = HashSet::new();
let mut cell: Option<OpenCell> = None;
let mut bold = 0u32;
let mut italic = 0u32;
let mut skip_depth = 0u32;
let mut row_height: Option<f64> = None;
let mut rest = html;
while !rest.is_empty() {
let Some(open) = rest.find('<') else {
if let Some(cell) = cell.as_mut() {
cell.text.push_str(rest);
}
break;
};
if skip_depth == 0
&& let Some(cell) = cell.as_mut()
{
cell.text.push_str(&rest[..open]);
}
rest = &rest[open..];
if rest.starts_with("<!--") {
rest = rest.find("-->").map_or("", |end| &rest[end + 3..]);
continue;
}
let Some(close) = rest.find('>') else {
break;
};
let raw = &rest[1..close];
rest = &rest[close + 1..];
let Some(tag) = parse_tag(raw) else {
continue;
};
match (tag.name.as_str(), tag.closing) {
("script" | "style" | "head", false) => skip_depth += 1,
("script" | "style" | "head", true) => skip_depth = skip_depth.saturating_sub(1),
("tr", false) => {
row += 1;
column = 1;
row_height = attribute(tag.attributes, "height").and_then(|h| h.trim_end_matches("px").parse().ok());
if let Some(height) = row_height {
worksheet.set_row_height(row, height);
}
}
("td" | "th", false) => {
if let Some(open) = cell.take() {
finish(worksheet, open, &mut occupied);
}
if row == 0 {
row = 1;
}
while occupied.contains(&(row, column)) {
column += 1;
}
let mut style = inline_style(tag.attributes);
if tag.name == "th" {
style = Style::new().bold().merged(&style);
}
let colspan = attribute(tag.attributes, "colspan")
.and_then(|v| v.parse().ok())
.unwrap_or(1u32)
.max(1);
let rowspan = attribute(tag.attributes, "rowspan")
.and_then(|v| v.parse().ok())
.unwrap_or(1u32)
.max(1);
let width = attribute(tag.attributes, "width").and_then(|w| w.trim_end_matches("px").parse().ok());
cell = Some(OpenCell {
column,
row,
colspan,
rowspan,
text: String::new(),
style,
width,
});
column += colspan;
}
("td" | "th", true) => {
if let Some(open) = cell.take() {
finish(worksheet, open, &mut occupied);
}
}
("tr", true) => {
if let Some(open) = cell.take() {
finish(worksheet, open, &mut occupied);
}
}
("br", _) => {
if let Some(cell) = cell.as_mut() {
cell.text.push('\n');
cell.style = cell.style.clone().wrap_text();
}
}
("b" | "strong", false) => {
bold += 1;
if let Some(cell) = cell.as_mut() {
cell.style = cell.style.clone().bold();
}
}
("b" | "strong", true) => bold = bold.saturating_sub(1),
("i" | "em", false) => {
italic += 1;
if let Some(cell) = cell.as_mut() {
cell.style = cell.style.clone().italic();
}
}
("i" | "em", true) => italic = italic.saturating_sub(1),
_ => {}
}
}
if let Some(open) = cell.take() {
finish(worksheet, open, &mut occupied);
}
let _ = (bold, italic, row_height);
}
fn finish(worksheet: &mut Worksheet, cell: OpenCell, occupied: &mut HashSet<(u32, u32)>) {
let text = decode_entities(&cell.text);
let text = text
.split('\n')
.map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n");
let text = text.trim().replace('\u{a0}', " ");
let coordinate = Coordinate::new(cell.column, cell.row);
if !text.is_empty() {
worksheet.set_value_at(coordinate, bind_default(Value::String(text)));
}
for row in cell.row..cell.row + cell.rowspan {
for column in cell.column..cell.column + cell.colspan {
occupied.insert((row, column));
}
}
let last = Coordinate::new(cell.column + cell.colspan - 1, cell.row + cell.rowspan - 1);
let range = if last == coordinate {
coordinate.to_string()
} else {
format!("{coordinate}:{last}")
};
if !cell.style.is_empty() {
let _ = worksheet.apply_style(&range, &cell.style);
}
if last != coordinate {
let _ = worksheet.merge_cells(&range);
}
if let Some(width) = cell.width {
let _ = worksheet.set_column_width(&string_from_column_index(cell.column), width / 7.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_table_becomes_rows() {
let mut sheet = Worksheet::new("Worksheet");
load(
"<table><thead><tr><th>Name</th><th>Email</th></tr></thead>\
<tbody><tr><td>Patrick & co</td><td style=\"color: #FF0000\">p@example.com</td></tr>\
<tr><td colspan=\"2\">12</td></tr></tbody></table>",
&mut sheet,
);
assert_eq!(sheet.get("A1").unwrap(), &Value::String("Name".into()));
assert_eq!(sheet.get("A2").unwrap(), &Value::String("Patrick & co".into()));
assert_eq!(sheet.get("A3").unwrap(), &Value::Int(12));
assert_eq!(sheet.merges(), ["A3:B3"]);
assert_eq!(sheet.effective_style(Coordinate::new(1, 1)).font.bold, Some(true));
assert_eq!(
sheet.effective_style(Coordinate::new(2, 2)).font.color.as_deref(),
Some("FF0000")
);
}
}