Skip to main content

style/rule_tree/
level.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#![forbid(unsafe_code)]
6
7//! The cascade level and shadow cascade order for tracking shadow tree rules.
8
9use crate::derives::*;
10use crate::dom::{TElement, TNode, TShadowRoot};
11use crate::properties::Importance;
12use crate::shared_lock::{SharedRwLockReadGuard, StylesheetGuards};
13use crate::stylesheets::Origin;
14
15use std::cmp::{Ord, Ordering, PartialOrd};
16
17/// The cascade level these rules are relevant at, as per[1][2][3].
18///
19/// We store them as a bitfield with:
20///
21///  * Shadow cascade order (4 bits). See ShadowCascadeOrder for details.
22///  * Importance bit. Whether the declaration was !important or not.
23///  * The CascadeOrigin of the declaration as per [1].
24///
25/// Presentational hints for SVG and HTML are in the "author-level zero-specificity" level, that
26/// is, right after user rules, and before author rules.
27///
28/// See also [4] for the Shadow DOM bits. We rely on the invariant that rules
29/// from outside the tree the element is in can't affect the element.
30///
31/// The opposite is not true (i.e., :host and ::slotted) from an "inner" shadow tree may affect an
32/// element connected to the document or an "outer" shadow tree.
33///
34/// [1]: https://drafts.csswg.org/css-cascade/#cascade-origin
35/// [2]: https://drafts.csswg.org/css-cascade/#preshint
36/// [3]: https://html.spec.whatwg.org/multipage/#presentational-hints
37/// [4]: https://drafts.csswg.org/css-scoping/#shadow-cascading
38#[repr(C)]
39#[derive(
40    Clone,
41    Copy,
42    Debug,
43    Eq,
44    Hash,
45    PartialEq,
46    Serialize,
47    Deserialize,
48    ToAnimatedValue,
49    ToResolvedValue,
50    ToShmem,
51)]
52pub struct CascadeLevel(u8);
53bitflags! {
54    impl CascadeLevel: u8 {
55        /// The three bits that represent the CascadeOrigin.
56        const ORIGIN_BITS = 0b00000111;
57        /// Whether the declarations are `!important` or not.
58        const IMPORTANT = 1 << 3;
59        /// The three bits for cascade order absolute value. If you change this, please change
60        /// CASCADE_ORDER_SHIFT accordingly.
61        const CASCADE_ORDER_BITS = 0b01110000;
62        /// The bit for the sign.
63        const CASCADE_ORDER_SIGN = 1 << 7;
64    }
65}
66
67malloc_size_of::malloc_size_of_is_0!(CascadeLevel);
68
69/// The cascade origin of rules.
70///
71/// Presentational hints for SVG and HTML are in the "author-level zero-specificity" level, that
72/// is, right after user rules, and before author rules.
73///
74/// The order of variants declared here is significant, and must be in _ascending_ order of
75/// precedence.
76///
77/// [1]: https://drafts.csswg.org/css-cascade/#cascade-origin
78/// [2]: https://drafts.csswg.org/css-cascade/#cascade-origin
79#[derive(
80    Clone,
81    Copy,
82    Debug,
83    Deserialize,
84    Eq,
85    FromPrimitive,
86    Hash,
87    MallocSizeOf,
88    Ord,
89    PartialEq,
90    PartialOrd,
91    Serialize,
92    ToAnimatedValue,
93    ToResolvedValue,
94    ToShmem,
95)]
96#[repr(u8)]
97pub enum CascadeOrigin {
98    /// Normal User-Agent rules.
99    UA = 0,
100    /// User normal rules.
101    User,
102    /// Presentational hints.
103    PresHints,
104    /// Styles from author styles.
105    Author,
106    /// https://drafts.csswg.org/css-anchor-position-1/#position-fallback-origin
107    PositionFallback,
108    /// SVG SMIL animations.
109    SMILOverride,
110    /// CSS animations and script-generated animations.
111    Animations,
112    /// CSS Transitions
113    Transitions,
114}
115
116impl CascadeOrigin {
117    /// Returns the "simplified" origin.
118    #[inline]
119    pub fn origin(self) -> Origin {
120        match self {
121            Self::UA => Origin::UserAgent,
122            Self::User => Origin::User,
123            _ => Origin::Author,
124        }
125    }
126
127    /// Select a lock guard for this origin.
128    #[inline]
129    pub fn guard<'a>(&self, guards: &'a StylesheetGuards<'a>) -> &'a SharedRwLockReadGuard<'a> {
130        match *self {
131            Self::UA | Self::User => guards.ua_or_user,
132            _ => guards.author,
133        }
134    }
135}
136
137/// Whether the transitions level overrides the given important level
138fn transitions_override(level: CascadeLevel) -> bool {
139    debug_assert!(level.is_important());
140    if level.origin() == CascadeOrigin::UA {
141        return crate::pref!("layout.css.transitions-override-ua");
142    }
143    true
144}
145
146impl Ord for CascadeLevel {
147    fn cmp(&self, other: &Self) -> Ordering {
148        let self_important = self.is_important();
149        if self_important != other.is_important() {
150            return if self_important {
151                if other.origin() == CascadeOrigin::Transitions && transitions_override(*self) {
152                    return Ordering::Less;
153                }
154                Ordering::Greater
155            } else {
156                if self.origin() == CascadeOrigin::Transitions && transitions_override(*other) {
157                    return Ordering::Greater;
158                }
159                Ordering::Less
160            };
161        }
162        let origin_cmp = self
163            .origin()
164            .cmp(&other.origin())
165            .then_with(|| self.shadow_order().cmp(&other.shadow_order()));
166        if self_important {
167            origin_cmp.reverse()
168        } else {
169            origin_cmp
170        }
171    }
172}
173
174impl PartialOrd for CascadeLevel {
175    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
176        Some(self.cmp(other))
177    }
178}
179
180impl CascadeLevel {
181    /// The shift that we apply to the cascade order.
182    pub const CASCADE_ORDER_SHIFT: usize = 4;
183    /// The author level at the same tree. Here for convenience to avoid duplicating it from C++.
184    pub const SAME_TREE_AUTHOR_NORMAL: Self = Self(CascadeOrigin::Author as u8);
185
186    /// Returns a cascade level with a given origin.
187    pub const fn new(origin: CascadeOrigin) -> Self {
188        let bits = origin as u8;
189        debug_assert!((bits & Self::ORIGIN_BITS.bits()) == bits);
190        Self(bits)
191    }
192
193    /// Returns the cascade origin.
194    #[inline]
195    pub fn origin(self) -> CascadeOrigin {
196        use num_traits::FromPrimitive;
197        let origin = (self & Self::ORIGIN_BITS).bits();
198        CascadeOrigin::from_u8(origin).unwrap()
199    }
200
201    /// Convert this level from "unimportant" to "important".
202    pub fn important(self) -> Self {
203        debug_assert!(
204            matches!(
205                self.origin(),
206                CascadeOrigin::UA | CascadeOrigin::User | CascadeOrigin::Author
207            ),
208            "{self:?}"
209        );
210        let mut result = self;
211        result.insert(Self::IMPORTANT);
212        result
213    }
214
215    /// Convert this level from "important" to "non-important".
216    pub fn unimportant(self) -> Self {
217        let mut result = self;
218        result.remove(Self::IMPORTANT);
219        result
220    }
221
222    /// Select a lock guard for this level
223    #[inline]
224    pub fn guard<'a>(&self, guards: &'a StylesheetGuards<'a>) -> &'a SharedRwLockReadGuard<'a> {
225        self.origin().guard(guards)
226    }
227
228    /// Returns the cascade level for author important declarations from the
229    /// same tree as the element.
230    #[inline]
231    pub fn same_tree_author_important() -> Self {
232        Self::new(CascadeOrigin::Author).important()
233    }
234
235    /// Returns the cascade level for author normal declarations from the same
236    /// tree as the element.
237    #[inline]
238    pub fn same_tree_author_normal() -> Self {
239        Self::new(CascadeOrigin::Author)
240    }
241
242    /// Returns whether this cascade level represents important rules of some
243    /// sort.
244    #[inline]
245    pub fn is_important(self) -> bool {
246        self.intersects(Self::IMPORTANT)
247    }
248
249    /// Returns the importance relevant for this rule. Pretty similar to
250    /// `is_important`.
251    #[inline]
252    pub fn importance(self) -> Importance {
253        if self.is_important() {
254            Importance::Important
255        } else {
256            Importance::Normal
257        }
258    }
259
260    /// Returns whether this cascade level represents an animation rules.
261    #[inline]
262    pub fn is_animation(self) -> bool {
263        match self.origin() {
264            CascadeOrigin::SMILOverride
265            | CascadeOrigin::Animations
266            | CascadeOrigin::Transitions => true,
267            _ => false,
268        }
269    }
270
271    /// Returns whether this cascade level is tree.
272    #[inline]
273    pub fn is_tree(self) -> bool {
274        self.origin() == CascadeOrigin::Author
275    }
276
277    /// Returns the shadow tree order.
278    #[inline]
279    pub fn shadow_order(self) -> ShadowCascadeOrder {
280        let neg = self.intersects(Self::CASCADE_ORDER_SIGN);
281        let abs = (self & Self::CASCADE_ORDER_BITS).bits() >> Self::CASCADE_ORDER_SHIFT;
282        ShadowCascadeOrder(if neg { -(abs as i8) } else { abs as i8 })
283    }
284
285    /// Returns an author normal cascade level with the given shadow cascade order.
286    #[inline]
287    pub fn author_normal(shadow_cascade_order: ShadowCascadeOrder) -> Self {
288        let abs = shadow_cascade_order.0.unsigned_abs() << Self::CASCADE_ORDER_SHIFT;
289        let mut result = Self::new(CascadeOrigin::Author);
290        result |= Self::from_bits_truncate(abs);
291        result.set(Self::CASCADE_ORDER_SIGN, shadow_cascade_order.0 < 0);
292        result
293    }
294
295    /// Get the shadow root corresponding to the shadow cascade order, from the given element.
296    pub fn get_shadow_root_for_scoped<E: TElement>(
297        &self,
298        element: E,
299    ) -> Option<<<E as TElement>::ConcreteNode as TNode>::ConcreteShadowRoot> {
300        let mut cascade_order = self.shadow_order().0;
301        if cascade_order < 0 {
302            let element = element.ultimate_originating_element();
303            let mut slot = element.assigned_slot();
304            while let Some(s) = slot {
305                cascade_order += 1;
306                if cascade_order == 0 {
307                    return s.containing_shadow();
308                }
309                slot = s.assigned_slot();
310            }
311            if cascade_order != -1 {
312                return None;
313            }
314
315            return element.shadow_root();
316        }
317        debug_assert!(cascade_order >= 0);
318        let mut containing_shadow = element.containing_shadow();
319        while let Some(s) = containing_shadow {
320            if cascade_order == 0 {
321                break;
322            }
323            cascade_order -= 1;
324            containing_shadow = s.host().containing_shadow();
325        }
326        containing_shadow
327    }
328}
329
330/// A counter to track how many shadow root rules deep we are. This is used to
331/// handle:
332///
333/// https://drafts.csswg.org/css-scoping/#shadow-cascading
334///
335/// See the static functions for the meaning of different values.
336#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
337#[repr(transparent)]
338pub struct ShadowCascadeOrder(i8);
339
340impl ShadowCascadeOrder {
341    /// We keep a maximum of 3 bits of order as a limit so that we can pack CascadeLevel in 1 byte.
342    const MAX: i8 = 0b111;
343    const MIN: i8 = -Self::MAX;
344
345    /// A level for the outermost shadow tree (the shadow tree we own, and the
346    /// ones from the slots we're slotted in).
347    #[inline]
348    pub fn for_outermost_shadow_tree() -> Self {
349        Self(-1)
350    }
351
352    /// A level for the element's tree.
353    #[inline]
354    pub fn for_same_tree() -> Self {
355        Self(0)
356    }
357
358    /// A level for the innermost containing tree (the one closest to the
359    /// element).
360    #[inline]
361    pub fn for_innermost_containing_tree() -> Self {
362        Self(1)
363    }
364
365    /// Returns true if the level is in the same or a containing shadow tree.
366    #[inline]
367    pub fn is_in_same_or_containing_tree(&self) -> bool {
368        self.0 > 0
369    }
370
371    /// Decrement the level, moving inwards. We should only move inwards if
372    /// we're traversing slots.
373    #[inline]
374    pub fn dec(&mut self) {
375        debug_assert!(self.0 < 0);
376        if self.0 != Self::MIN {
377            self.0 -= 1;
378        }
379    }
380
381    /// The level, moving inwards. We should only move inwards if we're
382    /// traversing slots.
383    #[inline]
384    pub fn inc(&mut self) {
385        debug_assert_ne!(self.0, -1);
386        if self.0 != Self::MAX {
387            self.0 += 1;
388        }
389    }
390}
391
392impl std::ops::Neg for ShadowCascadeOrder {
393    type Output = Self;
394    #[inline]
395    fn neg(self) -> Self {
396        Self(self.0.neg())
397    }
398}