Skip to main content

eternal_styler/
styler.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The engine: stylesheets in, computed styles out.
6
7use 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/// Holds stylesheets and computes styles for elements against them.
16///
17/// Stylesheets are consulted in the order they were added, and a later
18/// stylesheet wins over an earlier one when specificity ties, so add the
19/// theme first and overrides after.
20///
21/// Computing a style needs the parent's computed style for inheritance, so
22/// walk the tree top-down and keep each parent's result around for its
23/// children.
24#[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    /// An engine with no stylesheets and a root font size of 16px.
38    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    /// The font size `rem` is relative to, in pixels. Tie it to the user's
58    /// text scale to make every `rem` in the stylesheets follow it.
59    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    /// The style of `element` given its parent's computed style, or `None`
68    /// for the root.
69    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    /// Like [`compute`](Self::compute), with an inline style that beats every
78    /// stylesheet declaration of the same importance.
79    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        // Normal declarations first, weakest to strongest, then the important
88        // ones in the same order. Inline sits above every stylesheet within
89        // its importance.
90        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    /// The rules that match `element`, weakest first: what
110    /// [`compute`](Self::compute) applies, in the order it applies them.
111    /// Handy for a style inspector.
112    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                // A rule with several selectors is as specific as the most
123                // specific selector that matches.
124                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}