use std::fmt::Write as _;
use roxmltree::{Document, Node};
use simplecss::{AttributeOperator, Declaration, PseudoClass, StyleSheet};
use super::resources;
use crate::{Error, Result};
struct Element<'a, 'input>(Node<'a, 'input>);
impl simplecss::Element for Element<'_, '_> {
fn parent_element(&self) -> Option<Self> {
self.0.parent_element().map(Self)
}
fn prev_sibling_element(&self) -> Option<Self> {
self.0.prev_sibling_element().map(Self)
}
fn has_local_name(&self, name: &str) -> bool {
self.0.tag_name().name() == name
}
fn attribute_matches(&self, name: &str, operator: AttributeOperator<'_>) -> bool {
self.0.attribute(name).is_some_and(|value| match operator {
AttributeOperator::Contains(word) => {
value.split_ascii_whitespace().any(|part| part == word)
}
_ => operator.matches(value),
})
}
fn pseudo_class_matches(&self, class: PseudoClass<'_>) -> bool {
match class {
PseudoClass::FirstChild => self.0.prev_sibling_element().is_none(),
PseudoClass::Link => {
self.0.has_tag_name("a") && self.0.attributes().any(|attr| attr.name() == "href")
}
PseudoClass::Lang(lang) => self
.0
.ancestors()
.find_map(|node| node.attribute(("http://www.w3.org/XML/1998/namespace", "lang")))
.is_some_and(|value| AttributeOperator::StartsWith(lang).matches(value)),
_ => false,
}
}
}
pub(super) fn sheet<'a>(document: &'a Document<'_>) -> StyleSheet<'a> {
let mut sheet = StyleSheet::new();
for style in document
.descendants()
.filter(|node| node.has_tag_name("style"))
{
if style
.attribute("media")
.is_none_or(|media| media.eq_ignore_ascii_case("all"))
{
sheet.parse_more(style.text().unwrap_or(""));
}
}
sheet
}
pub(super) fn declarations<'a>(node: Node<'a, '_>, sheet: &StyleSheet<'a>) -> Vec<Declaration<'a>> {
let mut declarations = Vec::new();
for rule in &sheet.rules {
if rule.selector.matches(&Element(node)) {
declarations.extend(rule.declarations.iter().copied());
}
}
if let Some(style) = node.attribute("style") {
declarations.extend(simplecss::DeclarationTokenizer::from(style));
}
declarations.sort_by_key(|declaration| declaration.important);
declarations
}
fn inspect(css: &str) -> Result<()> {
use simplecss::{Selector, SelectorToken, SelectorTokenizer};
let invalid = |selector: &str| {
Error::Data(format!("cannot isolate external SVG stylesheet rule {selector:?}").into())
};
let mut rest = css.trim();
while !rest.is_empty() {
if let Some(comment) = rest.strip_prefix("/*") {
rest = comment
.split_once("*/")
.ok_or_else(|| invalid("unterminated comment"))?
.1
.trim();
continue;
}
let (selectors, body) = rest.split_once('{').ok_or_else(|| invalid(rest))?;
if selectors.trim_start().starts_with('@') {
return Err(invalid(selectors));
}
for selector in selectors.split(',').map(str::trim) {
if Selector::parse(selector).is_none() {
return Err(invalid(selector));
}
for token in SelectorTokenizer::from(selector) {
match token {
Ok(SelectorToken::PseudoClass(name))
if !matches!(name, "first-child" | "link") =>
{
return Err(invalid(selector))
}
Err(_) => return Err(invalid(selector)),
_ => {}
}
}
}
let (_, tail) = body.split_once('}').ok_or_else(|| invalid(selectors))?;
rest = tail.trim();
}
Ok(())
}
pub(super) fn inline_static_styles(source: &str) -> Result<String> {
let document = resources::parse(source)?;
let styles: Vec<_> = document
.descendants()
.filter(|node| node.has_tag_name("style"))
.collect();
if styles.is_empty() {
return Ok(source.to_owned());
}
for style in &styles {
if style
.attribute("media")
.is_some_and(|media| !media.eq_ignore_ascii_case("all"))
{
return Err(Error::Data(
"cannot isolate a conditional external SVG stylesheet".into(),
));
}
inspect(style.text().unwrap_or(""))?;
}
let sheet = sheet(&document);
let mut edits: Vec<_> = styles
.iter()
.map(|node| (node.range(), String::new()))
.collect();
for node in document
.descendants()
.filter(Node::is_element)
.filter(|node| !node.has_tag_name("style"))
{
crate::operation::check()?;
let declarations = declarations(node, &sheet);
if declarations.is_empty() {
continue;
}
let mut style = String::new();
for declaration in declarations {
let _ = write!(style, "{}:{};", declaration.name, declaration.value);
}
let style = resources::escape(&style);
if let Some(attr) = node.attribute_node("style") {
edits.push((attr.range_value(), style));
} else {
let end = resources::opening_end(source, node);
let offset = if source.as_bytes()[end - 1] == b'/' {
end - 1
} else {
end
};
edits.push((offset..offset, format!(" style=\"{style}\"")));
}
}
resources::apply_edits(source, edits)
}