1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::fmt;
use std::fmt::Display;

pub type CssSelectorComponent = String;

#[derive(Debug, Default, Clone)]
pub struct CssSelectorPart {
  components: Vec<CssSelectorComponent>,
}

impl CssSelectorPart {
  pub fn new() -> Self {
    Default::default()
  }

  pub fn component(mut self, component: CssSelectorComponent) -> Self {
    self.components.push(component);
    self
  }

  pub fn class(mut self, class: &str) -> Self {
    self.components.push(format!(".{}", class));
    self
  }

  pub fn element(mut self, element: &str) -> Self {
    self.components.push(element.to_string());
    self
  }
}

impl Display for CssSelectorPart {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.components.to_vec().join(" "))
  }
}

#[derive(Default, Debug, Clone)]
pub struct CssSelector {
  parts: Vec<CssSelectorPart>,
}

impl CssSelector {
  pub fn new() -> Self {
    Default::default()
  }

  pub fn part(mut self, part: CssSelectorPart) -> Self {
    self.parts.push(part);
    self
  }

  pub fn class(mut self, class: &str) -> Self {
    self.parts.push(CssSelectorPart::new().class(class));
    self
  }

  pub fn element(mut self, element: &str) -> Self {
    self.parts.push(CssSelectorPart::new().element(element));
    self
  }
}

impl Display for CssSelector {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.parts.iter().map(|p| p.to_string()).collect::<Vec<String>>().join(", "))
  }
}

impl From<&str> for CssSelector {
  fn from(value: &str) -> Self {
    Self {
      parts: vec![CssSelectorPart::default().component(value.into())],
    }
  }
}

impl From<CssSelectorPart> for CssSelector {
  fn from(value: CssSelectorPart) -> Self {
    Self { parts: vec![value] }
  }
}