Skip to main content

yaiko_core/
style.rs

1//! Validated scoped CSS generation.
2use std::collections::BTreeMap;
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum StyleError {
5    InvalidSelector,
6    InvalidProperty,
7    InvalidValue,
8}
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct StyleSheet {
11    scope: String,
12    rules: BTreeMap<String, BTreeMap<String, String>>,
13}
14impl StyleSheet {
15    pub fn new(scope: impl Into<String>) -> Result<Self, StyleError> {
16        let scope = valid(scope.into(), StyleError::InvalidSelector)?;
17        Ok(Self {
18            scope,
19            rules: BTreeMap::new(),
20        })
21    }
22    pub fn rule(
23        mut self,
24        selector: impl Into<String>,
25        property: impl Into<String>,
26        value: impl Into<String>,
27    ) -> Result<Self, StyleError> {
28        let selector = valid(selector.into(), StyleError::InvalidSelector)?;
29        if selector.chars().any(|c| c == ';' || c == '{') {
30            return Err(StyleError::InvalidSelector);
31        }
32        let property = valid(property.into(), StyleError::InvalidProperty)?;
33        if property.chars().any(|c| c == ';' || c == '{' || c == '}') {
34            return Err(StyleError::InvalidProperty);
35        }
36        let value = valid(value.into(), StyleError::InvalidValue)?;
37        if value.chars().any(|c| c == ';' || c == '{' || c == '}') {
38            return Err(StyleError::InvalidValue);
39        }
40        self.rules
41            .entry(selector)
42            .or_default()
43            .insert(property, value);
44        Ok(self)
45    }
46    pub fn render(&self) -> String {
47        let mut out = format!("<style data-scope=\"{}\">", esc(&self.scope));
48        for (selector, props) in &self.rules {
49            out.push_str(&format!(
50                "{}[data-scope=\"{}\"]{{",
51                selector,
52                esc(&self.scope)
53            ));
54            for (property, value) in props {
55                out.push_str(&format!("{}:{};", property, value))
56            }
57            out.push('}')
58        }
59        out.push_str("</style>");
60        out
61    }
62}
63fn valid(x: String, e: StyleError) -> Result<String, StyleError> {
64    if x.is_empty() || x.len() > 256 || x.chars().any(|c| c.is_control() || c.is_whitespace()) {
65        Err(e)
66    } else {
67        Ok(x)
68    }
69}
70fn esc(x: &str) -> String {
71    x.replace('&', "&amp;")
72        .replace('"', "&quot;")
73        .replace('<', "&lt;")
74}
75#[cfg(test)]
76mod tests {
77    use super::*;
78    #[test]
79    fn renders_scoped_sorted_rules() {
80        let s = StyleSheet::new("card")
81            .unwrap()
82            .rule(".title", "color", "red")
83            .unwrap()
84            .rule(".title", "font-size", "1rem")
85            .unwrap();
86        let o = s.render();
87        assert!(o.contains("data-scope=\"card\""));
88        assert!(o.contains("font-size:1rem;"))
89    }
90    #[test]
91    fn rejects_css_injection() {
92        assert!(matches!(
93            StyleSheet::new("x")
94                .unwrap()
95                .rule(".x", "color", "red;body{}"),
96            Err(StyleError::InvalidValue)
97        ));
98        assert!(StyleSheet::new("bad scope").is_err())
99    }
100}