1use selectors::matching::matches_selector;
8
9use crate::cascade::{self, Winners};
10use crate::computed::ComputedStyle;
11use crate::element::{Adapter, Element};
12use crate::selector::with_matching_context;
13use crate::stylesheet::{DeclarationBlock, StyleRule, Stylesheet};
14
15#[derive(Clone, Debug)]
25pub struct Styler {
26 sheets: Vec<Stylesheet>,
27 root_font_size: f32,
28}
29
30impl Default for Styler {
31 fn default() -> Self {
32 Self::new()
33 }
34}
35
36impl Styler {
37 pub fn new() -> Self {
39 Self {
40 sheets: Vec::new(),
41 root_font_size: 16.0,
42 }
43 }
44
45 pub fn add_stylesheet(&mut self, sheet: Stylesheet) {
46 self.sheets.push(sheet);
47 }
48
49 pub fn stylesheets(&self) -> &[Stylesheet] {
50 &self.sheets
51 }
52
53 pub fn clear_stylesheets(&mut self) {
54 self.sheets.clear();
55 }
56
57 pub fn set_root_font_size(&mut self, px: f32) {
60 self.root_font_size = px;
61 }
62
63 pub fn root_font_size(&self) -> f32 {
64 self.root_font_size
65 }
66
67 pub fn compute<E: Element>(
70 &self,
71 element: &E,
72 parent: Option<&ComputedStyle>,
73 ) -> ComputedStyle {
74 self.compute_with_inline(element, parent, None)
75 }
76
77 pub fn compute_with_inline<E: Element>(
80 &self,
81 element: &E,
82 parent: Option<&ComputedStyle>,
83 inline: Option<&DeclarationBlock>,
84 ) -> ComputedStyle {
85 let matches = self.matches(element);
86 let mut winners = Winners::new();
87 for important in [false, true] {
91 for m in &matches {
92 for declaration in m.rule.declarations.declarations() {
93 if declaration.important == important {
94 winners.set(&declaration.value);
95 }
96 }
97 }
98 if let Some(inline) = inline {
99 for declaration in inline.declarations() {
100 if declaration.important == important {
101 winners.set(&declaration.value);
102 }
103 }
104 }
105 }
106 cascade::compute(&winners, parent, self.root_font_size)
107 }
108
109 pub fn matching_rules<E: Element>(&self, element: &E) -> Vec<&StyleRule> {
113 self.matches(element).into_iter().map(|m| m.rule).collect()
114 }
115
116 fn matches<E: Element>(&self, element: &E) -> Vec<Match<'_>> {
117 let element = Adapter(element.clone());
118 let mut found = Vec::new();
119 with_matching_context(|context| {
120 let rules = self.sheets.iter().flat_map(Stylesheet::rules);
121 for (order, rule) in rules.enumerate() {
122 let specificity = rule
125 .selectors
126 .raw()
127 .slice()
128 .iter()
129 .filter(|selector| matches_selector(selector, 0, None, &element, context))
130 .map(|selector| selector.specificity())
131 .max();
132 if let Some(specificity) = specificity {
133 found.push(Match {
134 specificity,
135 order,
136 rule,
137 });
138 }
139 }
140 });
141 found.sort_by_key(|m| (m.specificity, m.order));
142 found
143 }
144}
145
146struct Match<'a> {
147 specificity: u32,
148 order: usize,
149 rule: &'a StyleRule,
150}