Skip to main content

eternal_styler/
element.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//! What a UI toolkit has to provide for its widgets to be styled.
6
7use std::fmt;
8use std::ptr::NonNull;
9
10use bitflags::bitflags;
11use selectors::OpaqueElement;
12use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
13use selectors::bloom::BloomFilter;
14use selectors::context::MatchingContext;
15use selectors::matching::ElementSelectorFlags;
16
17use crate::atom::{Atom, AttrValue};
18use crate::selector::{PseudoClass, PseudoElement, SelectorImpl};
19
20bitflags! {
21    /// The interactive state of an element, matched by pseudo-classes.
22    ///
23    /// The toolkit keeps these up to date; the styler only reads them. Each
24    /// flag has a pseudo-class, and a few pseudo-classes are the absence of a
25    /// flag: `:enabled` is not `DISABLED`, `:read-write` is not `READ_ONLY`,
26    /// `:optional` is not `REQUIRED` and `:valid` is not `INVALID`.
27    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
28    pub struct ElementState: u16 {
29        /// `:hover`
30        const HOVER = 1 << 0;
31        /// `:active`
32        const ACTIVE = 1 << 1;
33        /// `:focus`
34        const FOCUS = 1 << 2;
35        /// `:focus-visible`
36        const FOCUS_VISIBLE = 1 << 3;
37        /// `:focus-within`
38        const FOCUS_WITHIN = 1 << 4;
39        /// `:disabled`
40        const DISABLED = 1 << 5;
41        /// `:checked`
42        const CHECKED = 1 << 6;
43        /// `:indeterminate`
44        const INDETERMINATE = 1 << 7;
45        /// `:read-only`
46        const READ_ONLY = 1 << 8;
47        /// `:required`
48        const REQUIRED = 1 << 9;
49        /// `:invalid`
50        const INVALID = 1 << 10;
51        /// `:placeholder-shown`
52        const PLACEHOLDER_SHOWN = 1 << 11;
53    }
54}
55
56/// A handle to a node in the toolkit's widget tree.
57///
58/// Implement this for a cheap handle type, such as `&Node` or an arena index
59/// paired with a reference to the arena, and the styler can match selectors
60/// against your tree. Everything except identity, tree navigation and the
61/// element name has a default that reports nothing.
62///
63/// Tree-structural pseudo-classes (`:first-child`, `:nth-of-type()`, `:empty`
64/// and friends) are answered from the navigation methods. The interactive
65/// ones come from [`state`](Self::state), and `:state(name)` from
66/// [`has_custom_state`](Self::has_custom_state).
67pub trait Element: Clone + fmt::Debug {
68    /// A value that identifies this element and no other for as long as the
69    /// tree is alive.
70    ///
71    /// For a handle that is a reference, `OpaqueElement::new(node)` is the
72    /// natural choice. For an arena index, use
73    /// [`opaque_element_from_index`].
74    fn opaque(&self) -> OpaqueElement;
75
76    fn parent(&self) -> Option<Self>;
77
78    fn prev_sibling(&self) -> Option<Self>;
79
80    fn next_sibling(&self) -> Option<Self>;
81
82    fn first_child(&self) -> Option<Self>;
83
84    /// The name matched by a type selector, such as `button`.
85    fn local_name(&self) -> &str;
86
87    /// The name matched by an id selector, such as `#save`.
88    fn id(&self) -> Option<&str> {
89        None
90    }
91
92    /// The names matched by class selectors, such as `.primary`.
93    fn classes(&self) -> impl Iterator<Item = &str> {
94        std::iter::empty()
95    }
96
97    /// The value of an attribute, for `[name]` and `[name="value"]` selectors.
98    fn attribute(&self, name: &str) -> Option<&str> {
99        let _ = name;
100        None
101    }
102
103    fn state(&self) -> ElementState {
104        ElementState::empty()
105    }
106
107    /// Whether the element is in the custom state `name`, for `:state(name)`.
108    fn has_custom_state(&self, name: &str) -> bool {
109        let _ = name;
110        false
111    }
112
113    /// Whether the element matches `:empty`. The default is "has no
114    /// children"; override it if your elements can hold text.
115    fn is_empty(&self) -> bool {
116        self.first_child().is_none()
117    }
118
119    /// Whether the element matches `:root`.
120    fn is_root(&self) -> bool {
121        self.parent().is_none()
122    }
123}
124
125/// An [`OpaqueElement`] for an element stored at `index` in an arena.
126///
127/// Two elements in the same tree must never share an index, and an index must
128/// not be reused while styles are being computed.
129pub fn opaque_element_from_index(index: usize) -> OpaqueElement {
130    // OpaqueElement is only ever compared and hashed, never dereferenced, so
131    // any distinct non-zero value will do.
132    let address = index.wrapping_add(1).max(1) as *mut ();
133    OpaqueElement::from_non_null_ptr(NonNull::new(address).expect("address is non-zero"))
134}
135
136/// Bridges the toolkit's [`Element`] to the `selectors` crate's own trait.
137#[derive(Clone, Debug)]
138pub(crate) struct Adapter<E>(pub(crate) E);
139
140impl<E: Element> selectors::Element for Adapter<E> {
141    type Impl = SelectorImpl;
142
143    fn opaque(&self) -> OpaqueElement {
144        self.0.opaque()
145    }
146
147    fn parent_element(&self) -> Option<Self> {
148        self.0.parent().map(Adapter)
149    }
150
151    fn parent_node_is_shadow_root(&self) -> bool {
152        false
153    }
154
155    fn containing_shadow_host(&self) -> Option<Self> {
156        None
157    }
158
159    fn is_pseudo_element(&self) -> bool {
160        false
161    }
162
163    fn prev_sibling_element(&self) -> Option<Self> {
164        self.0.prev_sibling().map(Adapter)
165    }
166
167    fn next_sibling_element(&self) -> Option<Self> {
168        self.0.next_sibling().map(Adapter)
169    }
170
171    fn first_element_child(&self) -> Option<Self> {
172        self.0.first_child().map(Adapter)
173    }
174
175    fn is_html_element_in_html_document(&self) -> bool {
176        false
177    }
178
179    fn has_local_name(&self, local_name: &str) -> bool {
180        self.0.local_name() == local_name
181    }
182
183    fn has_namespace(&self, ns: &str) -> bool {
184        ns.is_empty()
185    }
186
187    fn is_same_type(&self, other: &Self) -> bool {
188        self.0.local_name() == other.0.local_name()
189    }
190
191    fn attr_matches(
192        &self,
193        ns: &NamespaceConstraint<&Atom>,
194        local_name: &Atom,
195        operation: &AttrSelectorOperation<&AttrValue>,
196    ) -> bool {
197        match ns {
198            NamespaceConstraint::Any => {}
199            NamespaceConstraint::Specific(url) if url.is_empty() => {}
200            NamespaceConstraint::Specific(_) => return false,
201        }
202        match self.0.attribute(local_name) {
203            Some(value) => operation.eval_str(value),
204            None => false,
205        }
206    }
207
208    fn match_non_ts_pseudo_class(
209        &self,
210        pseudo_class: &PseudoClass,
211        _context: &mut MatchingContext<Self::Impl>,
212    ) -> bool {
213        pseudo_class.matches(&self.0)
214    }
215
216    fn match_pseudo_element(
217        &self,
218        pseudo_element: &PseudoElement,
219        _context: &mut MatchingContext<Self::Impl>,
220    ) -> bool {
221        match *pseudo_element {}
222    }
223
224    fn apply_selector_flags(&self, _flags: ElementSelectorFlags) {}
225
226    fn is_link(&self) -> bool {
227        false
228    }
229
230    fn is_html_slot_element(&self) -> bool {
231        false
232    }
233
234    fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
235        self.0
236            .id()
237            .is_some_and(|own| case_sensitivity.eq(own.as_bytes(), id.as_bytes()))
238    }
239
240    fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
241        self.0
242            .classes()
243            .any(|class| case_sensitivity.eq(class.as_bytes(), name.as_bytes()))
244    }
245
246    fn has_custom_state(&self, name: &Atom) -> bool {
247        self.0.has_custom_state(name)
248    }
249
250    fn imported_part(&self, _name: &Atom) -> Option<Atom> {
251        None
252    }
253
254    fn is_part(&self, _name: &Atom) -> bool {
255        false
256    }
257
258    fn is_empty(&self) -> bool {
259        self.0.is_empty()
260    }
261
262    fn is_root(&self) -> bool {
263        self.0.is_root()
264    }
265
266    fn add_element_unique_hashes(&self, _filter: &mut BloomFilter) -> bool {
267        // No ancestor bloom filter: it is an optimisation for very deep
268        // documents, and UI trees are shallow.
269        false
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn arena_indices_map_to_distinct_identities() {
279        assert_ne!(opaque_element_from_index(0), opaque_element_from_index(1));
280        assert_eq!(opaque_element_from_index(7), opaque_element_from_index(7));
281        // usize::MAX wraps to zero, which is not a valid pointer; make sure it
282        // is still non-null rather than a panic.
283        let _ = opaque_element_from_index(usize::MAX);
284    }
285}