polished_css/selector/
class.rs

1use regex::{Captures, Regex};
2
3use super::SelectorDisplay;
4
5#[derive(Clone, Debug, Default, PartialEq)]
6pub struct Class(pub String);
7
8impl std::ops::Deref for Class {
9    type Target = String;
10
11    fn deref(&self) -> &Self::Target {
12        &self.0
13    }
14}
15
16impl SelectorDisplay for Class {
17    #[must_use]
18    fn as_styles_content(&self) -> String {
19        format!(".{}", escape_special_chars_in_class_name(&self.0))
20    }
21
22    #[must_use]
23    fn as_attribute_value(&self) -> String {
24        (self.0).to_string()
25    }
26}
27
28impl From<&str> for Class {
29    fn from(value: &str) -> Self {
30        Self(value.to_string())
31    }
32}
33
34/// # Panics
35///
36/// Pacnis when the Regex couldn't be created
37#[must_use]
38pub fn escape_special_chars_in_class_name(value: &str) -> String {
39    Regex::new(r#"[!@#$%^&*()+\=\[\]{};':"\\|,.<>\\/?]"#)
40        .expect("Failed to create a regex for matching special characters in CSS class name.")
41        .replace_all(value, |caps: &Captures| {
42            caps.iter()
43                .map(|char| {
44                    if let Some(char) = char {
45                        format!("\\{}", char.as_str())
46                    } else {
47                        String::new()
48                    }
49                })
50                .collect::<String>()
51        })
52        .to_string()
53}