not_tailwind/
visit_selectors.rs

1use lightningcss::{
2    selector::Selector,
3    values::string::CowArcStr,
4    visit_types,
5    visitor::{VisitTypes, Visitor},
6};
7use parcel_selectors::parser::Component;
8
9use crate::short_classes::{CSSToken, ClassContainer};
10use lightningcss::stylesheet::StyleSheet;
11
12#[derive(Clone, PartialEq, Eq, Default)]
13pub struct ClassVisitor {
14    container: ClassContainer,
15}
16
17impl ClassVisitor {
18    pub fn show(&self, stylesheet: StyleSheet) {
19        self.container.into_file(stylesheet);
20    }
21
22    pub fn get(&self, class: &str) -> Option<String> {
23        self.container.get(class.to_owned(), CSSToken::Class)
24    }
25
26    pub fn get_custom_property(&self, class: &str) -> Option<String> {
27        self.container
28            .get(class.to_owned(), CSSToken::CustomProperty)
29    }
30}
31
32impl<'i> Visitor<'i> for ClassVisitor {
33    type Error = ();
34
35    fn visit_types(&self) -> VisitTypes {
36        visit_types!(SELECTORS | DASHED_IDENTS)
37    }
38
39    #[allow(clippy::collapsible_match)]
40    fn visit_selector(
41        &mut self,
42        selector: &mut Selector<'i>,
43    ) -> Result<(), Self::Error> {
44        let iter = selector.iter_mut_raw_match_order();
45        for i in iter {
46            match i {
47                Component::Class(c) => {
48                    if let Some(n) =
49                        self.container.add(c.0.to_string(), CSSToken::Class)
50                    {
51                        c.0 = CowArcStr::from(n);
52                    }
53                }
54                Component::Negation(selectors)
55                | Component::Is(selectors)
56                | Component::Where(selectors)
57                | Component::Has(selectors)
58                | Component::Any(_, selectors) => {
59                    for i in selectors.iter_mut() {
60                        self.visit_selector(i)?;
61                    }
62                }
63                Component::Slotted(selectors) => {
64                    self.visit_selector(selectors)?;
65                }
66                Component::Host(selector) => {
67                    if let Some(selector) = selector {
68                        self.visit_selector(selector)?;
69                    }
70                }
71                _ => (),
72            }
73        }
74        Ok(())
75    }
76
77    fn visit_dashed_ident(
78        &mut self,
79        ident: &mut lightningcss::values::ident::DashedIdent,
80    ) -> Result<(), Self::Error> {
81        if let Some(n) = self.container.add(
82            ident.0.to_string(),
83            crate::short_classes::CSSToken::CustomProperty,
84        ) {
85            let n = format!("--{}", n);
86            ident.0 = CowArcStr::from(n);
87        }
88
89        Ok(())
90    }
91}