style/stylesheets/
container_rule.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//! A [`@container`][container] rule.
6//!
7//! [container]: https://drafts.csswg.org/css-contain-3/#container-rule
8
9use crate::computed_value_flags::ComputedValueFlags;
10use crate::dom::TElement;
11use crate::logical_geometry::{LogicalSize, WritingMode};
12use crate::parser::ParserContext;
13use crate::properties::ComputedValues;
14use crate::queries::feature::{AllowsRanges, Evaluator, FeatureFlags, QueryFeatureDescription};
15use crate::queries::values::Orientation;
16use crate::queries::{FeatureType, QueryCondition};
17use crate::shared_lock::{
18    DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard,
19};
20use crate::str::CssStringWriter;
21use crate::stylesheets::CssRules;
22use crate::stylist::Stylist;
23use crate::values::computed::{CSSPixelLength, ContainerType, Context, Ratio};
24use crate::values::specified::ContainerName;
25use app_units::Au;
26use cssparser::{Parser, SourceLocation};
27use euclid::default::Size2D;
28#[cfg(feature = "gecko")]
29use malloc_size_of::{MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
30use selectors::kleene_value::KleeneValue;
31use servo_arc::Arc;
32use std::fmt::{self, Write};
33use style_traits::{CssWriter, ParseError, ToCss};
34
35/// A container rule.
36#[derive(Debug, ToShmem)]
37pub struct ContainerRule {
38    /// The container query and name.
39    pub condition: Arc<ContainerCondition>,
40    /// The nested rules inside the block.
41    pub rules: Arc<Locked<CssRules>>,
42    /// The source position where this rule was found.
43    pub source_location: SourceLocation,
44}
45
46impl ContainerRule {
47    /// Returns the query condition.
48    pub fn query_condition(&self) -> &QueryCondition {
49        &self.condition.condition
50    }
51
52    /// Returns the query name filter.
53    pub fn container_name(&self) -> &ContainerName {
54        &self.condition.name
55    }
56
57    /// Measure heap usage.
58    #[cfg(feature = "gecko")]
59    pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
60        // Measurement of other fields may be added later.
61        self.rules.unconditional_shallow_size_of(ops)
62            + self.rules.read_with(guard).size_of(guard, ops)
63    }
64}
65
66impl DeepCloneWithLock for ContainerRule {
67    fn deep_clone_with_lock(&self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard) -> Self {
68        let rules = self.rules.read_with(guard);
69        Self {
70            condition: self.condition.clone(),
71            rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
72            source_location: self.source_location.clone(),
73        }
74    }
75}
76
77impl ToCssWithGuard for ContainerRule {
78    fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
79        dest.write_str("@container ")?;
80        {
81            let mut writer = CssWriter::new(dest);
82            if !self.condition.name.is_none() {
83                self.condition.name.to_css(&mut writer)?;
84                writer.write_char(' ')?;
85            }
86            self.condition.condition.to_css(&mut writer)?;
87        }
88        self.rules.read_with(guard).to_css_block(guard, dest)
89    }
90}
91
92/// A container condition and filter, combined.
93#[derive(Debug, ToShmem, ToCss)]
94pub struct ContainerCondition {
95    #[css(skip_if = "ContainerName::is_none")]
96    name: ContainerName,
97    condition: QueryCondition,
98    #[css(skip)]
99    flags: FeatureFlags,
100}
101
102/// The result of a successful container query lookup.
103pub struct ContainerLookupResult<E> {
104    /// The relevant container.
105    pub element: E,
106    /// The sizing / writing-mode information of the container.
107    pub info: ContainerInfo,
108    /// The style of the element.
109    pub style: Arc<ComputedValues>,
110}
111
112fn container_type_axes(ty_: ContainerType, wm: WritingMode) -> FeatureFlags {
113    if ty_.intersects(ContainerType::SIZE) {
114        FeatureFlags::all_container_axes()
115    } else if ty_.intersects(ContainerType::INLINE_SIZE) {
116        let physical_axis = if wm.is_vertical() {
117            FeatureFlags::CONTAINER_REQUIRES_HEIGHT_AXIS
118        } else {
119            FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS
120        };
121        FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS | physical_axis
122    } else {
123        FeatureFlags::empty()
124    }
125}
126
127enum TraversalResult<T> {
128    InProgress,
129    StopTraversal,
130    Done(T),
131}
132
133fn traverse_container<E, F, R>(
134    mut e: E,
135    originating_element_style: Option<&ComputedValues>,
136    evaluator: F,
137) -> Option<(E, R)>
138where
139    E: TElement,
140    F: Fn(E, Option<&ComputedValues>) -> TraversalResult<R>,
141{
142    if originating_element_style.is_some() {
143        match evaluator(e, originating_element_style) {
144            TraversalResult::InProgress => {},
145            TraversalResult::StopTraversal => return None,
146            TraversalResult::Done(result) => return Some((e, result)),
147        }
148    }
149    while let Some(element) = e.traversal_parent() {
150        match evaluator(element, None) {
151            TraversalResult::InProgress => {},
152            TraversalResult::StopTraversal => return None,
153            TraversalResult::Done(result) => return Some((element, result)),
154        }
155        e = element;
156    }
157
158    None
159}
160
161impl ContainerCondition {
162    /// Parse a container condition.
163    pub fn parse<'a>(
164        context: &ParserContext,
165        input: &mut Parser<'a, '_>,
166    ) -> Result<Self, ParseError<'a>> {
167        let name = input
168            .try_parse(|input| ContainerName::parse_for_query(context, input))
169            .ok()
170            .unwrap_or_else(ContainerName::none);
171        let condition = QueryCondition::parse(context, input, FeatureType::Container)?;
172        let flags = condition.cumulative_flags();
173        Ok(Self {
174            name,
175            condition,
176            flags,
177        })
178    }
179
180    fn valid_container_info<E>(
181        &self,
182        potential_container: E,
183        originating_element_style: Option<&ComputedValues>,
184    ) -> TraversalResult<ContainerLookupResult<E>>
185    where
186        E: TElement,
187    {
188        let data;
189        let style = match originating_element_style {
190            Some(s) => s,
191            None => {
192                data = match potential_container.borrow_data() {
193                    Some(d) => d,
194                    None => return TraversalResult::InProgress,
195                };
196                &**data.styles.primary()
197            },
198        };
199        let wm = style.writing_mode;
200        let box_style = style.get_box();
201
202        // Filter by container-type.
203        let container_type = box_style.clone_container_type();
204        let available_axes = container_type_axes(container_type, wm);
205        if !available_axes.contains(self.flags.container_axes()) {
206            return TraversalResult::InProgress;
207        }
208
209        // Filter by container-name.
210        let container_name = box_style.clone_container_name();
211        for filter_name in self.name.0.iter() {
212            if !container_name.0.contains(filter_name) {
213                return TraversalResult::InProgress;
214            }
215        }
216
217        let size = potential_container.query_container_size(&box_style.clone_display());
218        let style = style.to_arc();
219        TraversalResult::Done(ContainerLookupResult {
220            element: potential_container,
221            info: ContainerInfo { size, wm },
222            style,
223        })
224    }
225
226    /// Performs container lookup for a given element.
227    pub fn find_container<E>(
228        &self,
229        e: E,
230        originating_element_style: Option<&ComputedValues>,
231    ) -> Option<ContainerLookupResult<E>>
232    where
233        E: TElement,
234    {
235        match traverse_container(
236            e,
237            originating_element_style,
238            |element, originating_element_style| {
239                self.valid_container_info(element, originating_element_style)
240            },
241        ) {
242            Some((_, result)) => Some(result),
243            None => None,
244        }
245    }
246
247    /// Tries to match a container query condition for a given element.
248    pub(crate) fn matches<E>(
249        &self,
250        stylist: &Stylist,
251        element: E,
252        originating_element_style: Option<&ComputedValues>,
253        invalidation_flags: &mut ComputedValueFlags,
254    ) -> KleeneValue
255    where
256        E: TElement,
257    {
258        let result = self.find_container(element, originating_element_style);
259        let (container, info) = match result {
260            Some(r) => (Some(r.element), Some((r.info, r.style))),
261            None => (None, None),
262        };
263        // Set up the lookup for the container in question, as the condition may be using container
264        // query lengths.
265        let size_query_container_lookup = ContainerSizeQuery::for_option_element(
266            container, /* known_parent_style = */ None, /* is_pseudo = */ false,
267        );
268        Context::for_container_query_evaluation(
269            stylist.device(),
270            Some(stylist),
271            info,
272            size_query_container_lookup,
273            |context| {
274                let matches = self.condition.matches(context);
275                if context
276                    .style()
277                    .flags()
278                    .contains(ComputedValueFlags::USES_VIEWPORT_UNITS)
279                {
280                    // TODO(emilio): Might need something similar to improve
281                    // invalidation of font relative container-query lengths.
282                    invalidation_flags
283                        .insert(ComputedValueFlags::USES_VIEWPORT_UNITS_ON_CONTAINER_QUERIES);
284                }
285                matches
286            },
287        )
288    }
289}
290
291/// Information needed to evaluate an individual container query.
292#[derive(Copy, Clone)]
293pub struct ContainerInfo {
294    size: Size2D<Option<Au>>,
295    wm: WritingMode,
296}
297
298impl ContainerInfo {
299    fn size(&self) -> Option<Size2D<Au>> {
300        Some(Size2D::new(self.size.width?, self.size.height?))
301    }
302}
303
304fn eval_width(context: &Context) -> Option<CSSPixelLength> {
305    let info = context.container_info.as_ref()?;
306    Some(CSSPixelLength::new(info.size.width?.to_f32_px()))
307}
308
309fn eval_height(context: &Context) -> Option<CSSPixelLength> {
310    let info = context.container_info.as_ref()?;
311    Some(CSSPixelLength::new(info.size.height?.to_f32_px()))
312}
313
314fn eval_inline_size(context: &Context) -> Option<CSSPixelLength> {
315    let info = context.container_info.as_ref()?;
316    Some(CSSPixelLength::new(
317        LogicalSize::from_physical(info.wm, info.size)
318            .inline?
319            .to_f32_px(),
320    ))
321}
322
323fn eval_block_size(context: &Context) -> Option<CSSPixelLength> {
324    let info = context.container_info.as_ref()?;
325    Some(CSSPixelLength::new(
326        LogicalSize::from_physical(info.wm, info.size)
327            .block?
328            .to_f32_px(),
329    ))
330}
331
332fn eval_aspect_ratio(context: &Context) -> Option<Ratio> {
333    let info = context.container_info.as_ref()?;
334    Some(Ratio::new(
335        info.size.width?.0 as f32,
336        info.size.height?.0 as f32,
337    ))
338}
339
340fn eval_orientation(context: &Context, value: Option<Orientation>) -> KleeneValue {
341    let size = match context.container_info.as_ref().and_then(|info| info.size()) {
342        Some(size) => size,
343        None => return KleeneValue::Unknown,
344    };
345    KleeneValue::from(Orientation::eval(size, value))
346}
347
348/// https://drafts.csswg.org/css-contain-3/#container-features
349///
350/// TODO: Support style queries, perhaps.
351pub static CONTAINER_FEATURES: [QueryFeatureDescription; 6] = [
352    feature!(
353        atom!("width"),
354        AllowsRanges::Yes,
355        Evaluator::OptionalLength(eval_width),
356        FeatureFlags::CONTAINER_REQUIRES_WIDTH_AXIS,
357    ),
358    feature!(
359        atom!("height"),
360        AllowsRanges::Yes,
361        Evaluator::OptionalLength(eval_height),
362        FeatureFlags::CONTAINER_REQUIRES_HEIGHT_AXIS,
363    ),
364    feature!(
365        atom!("inline-size"),
366        AllowsRanges::Yes,
367        Evaluator::OptionalLength(eval_inline_size),
368        FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS,
369    ),
370    feature!(
371        atom!("block-size"),
372        AllowsRanges::Yes,
373        Evaluator::OptionalLength(eval_block_size),
374        FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS,
375    ),
376    feature!(
377        atom!("aspect-ratio"),
378        AllowsRanges::Yes,
379        Evaluator::OptionalNumberRatio(eval_aspect_ratio),
380        // XXX from_bits_truncate is const, but the pipe operator isn't, so this
381        // works around it.
382        FeatureFlags::from_bits_truncate(
383            FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits()
384                | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
385        ),
386    ),
387    feature!(
388        atom!("orientation"),
389        AllowsRanges::No,
390        keyword_evaluator!(eval_orientation, Orientation),
391        FeatureFlags::from_bits_truncate(
392            FeatureFlags::CONTAINER_REQUIRES_BLOCK_AXIS.bits()
393                | FeatureFlags::CONTAINER_REQUIRES_INLINE_AXIS.bits()
394        ),
395    ),
396];
397
398/// Result of a container size query, signifying the hypothetical containment boundary in terms of physical axes.
399/// Defined by up to two size containers. Queries on logical axes are resolved with respect to the querying
400/// element's writing mode.
401#[derive(Copy, Clone, Default)]
402pub struct ContainerSizeQueryResult {
403    width: Option<Au>,
404    height: Option<Au>,
405}
406
407impl ContainerSizeQueryResult {
408    fn get_viewport_size(context: &Context) -> Size2D<Au> {
409        use crate::values::specified::ViewportVariant;
410        context.viewport_size_for_viewport_unit_resolution(ViewportVariant::Small)
411    }
412
413    fn get_logical_viewport_size(context: &Context) -> LogicalSize<Au> {
414        LogicalSize::from_physical(
415            context.builder.writing_mode,
416            Self::get_viewport_size(context),
417        )
418    }
419
420    /// Get the inline-size of the query container.
421    pub fn get_container_inline_size(&self, context: &Context) -> Au {
422        if context.builder.writing_mode.is_horizontal() {
423            if let Some(w) = self.width {
424                return w;
425            }
426        } else {
427            if let Some(h) = self.height {
428                return h;
429            }
430        }
431        Self::get_logical_viewport_size(context).inline
432    }
433
434    /// Get the block-size of the query container.
435    pub fn get_container_block_size(&self, context: &Context) -> Au {
436        if context.builder.writing_mode.is_horizontal() {
437            self.get_container_height(context)
438        } else {
439            self.get_container_width(context)
440        }
441    }
442
443    /// Get the width of the query container.
444    pub fn get_container_width(&self, context: &Context) -> Au {
445        if let Some(w) = self.width {
446            return w;
447        }
448        Self::get_viewport_size(context).width
449    }
450
451    /// Get the height of the query container.
452    pub fn get_container_height(&self, context: &Context) -> Au {
453        if let Some(h) = self.height {
454            return h;
455        }
456        Self::get_viewport_size(context).height
457    }
458
459    // Merge the result of a subsequent lookup, preferring the initial result.
460    fn merge(self, new_result: Self) -> Self {
461        let mut result = self;
462        if let Some(width) = new_result.width {
463            result.width.get_or_insert(width);
464        }
465        if let Some(height) = new_result.height {
466            result.height.get_or_insert(height);
467        }
468        result
469    }
470
471    fn is_complete(&self) -> bool {
472        self.width.is_some() && self.height.is_some()
473    }
474}
475
476/// Unevaluated lazy container size query.
477pub enum ContainerSizeQuery<'a> {
478    /// Query prior to evaluation.
479    NotEvaluated(Box<dyn Fn() -> ContainerSizeQueryResult + 'a>),
480    /// Cached evaluated result.
481    Evaluated(ContainerSizeQueryResult),
482}
483
484impl<'a> ContainerSizeQuery<'a> {
485    fn evaluate_potential_size_container<E>(
486        e: E,
487        originating_element_style: Option<&ComputedValues>,
488    ) -> TraversalResult<ContainerSizeQueryResult>
489    where
490        E: TElement,
491    {
492        let data;
493        let style = match originating_element_style {
494            Some(s) => s,
495            None => {
496                data = match e.borrow_data() {
497                    Some(d) => d,
498                    None => return TraversalResult::InProgress,
499                };
500                &**data.styles.primary()
501            },
502        };
503        if !style
504            .flags
505            .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE)
506        {
507            // We know we won't find a size container.
508            return TraversalResult::StopTraversal;
509        }
510
511        let wm = style.writing_mode;
512        let box_style = style.get_box();
513
514        let container_type = box_style.clone_container_type();
515        let size = e.query_container_size(&box_style.clone_display());
516        if container_type.intersects(ContainerType::SIZE) {
517            TraversalResult::Done(ContainerSizeQueryResult {
518                width: size.width,
519                height: size.height,
520            })
521        } else if container_type.intersects(ContainerType::INLINE_SIZE) {
522            if wm.is_horizontal() {
523                TraversalResult::Done(ContainerSizeQueryResult {
524                    width: size.width,
525                    height: None,
526                })
527            } else {
528                TraversalResult::Done(ContainerSizeQueryResult {
529                    width: None,
530                    height: size.height,
531                })
532            }
533        } else {
534            TraversalResult::InProgress
535        }
536    }
537
538    /// Find the query container size for a given element. Meant to be used as a callback for new().
539    fn lookup<E>(
540        element: E,
541        originating_element_style: Option<&ComputedValues>,
542    ) -> ContainerSizeQueryResult
543    where
544        E: TElement + 'a,
545    {
546        match traverse_container(
547            element,
548            originating_element_style,
549            |e, originating_element_style| {
550                Self::evaluate_potential_size_container(e, originating_element_style)
551            },
552        ) {
553            Some((container, result)) => {
554                if result.is_complete() {
555                    result
556                } else {
557                    // Traverse up from the found size container to see if we can get a complete containment.
558                    result.merge(Self::lookup(container, None))
559                }
560            },
561            None => ContainerSizeQueryResult::default(),
562        }
563    }
564
565    /// Create a new instance of the container size query for given element, with a deferred lookup callback.
566    pub fn for_element<E>(
567        element: E,
568        known_parent_style: Option<&'a ComputedValues>,
569        is_pseudo: bool,
570    ) -> Self
571    where
572        E: TElement + 'a,
573    {
574        let parent;
575        let data;
576        let parent_style = match known_parent_style {
577            Some(s) => Some(s),
578            None => {
579                // No need to bother if we're the top element.
580                parent = match element.traversal_parent() {
581                    Some(parent) => parent,
582                    None => return Self::none(),
583                };
584                data = parent.borrow_data();
585                data.as_ref().map(|data| &**data.styles.primary())
586            },
587        };
588
589        // If there's no style, such as being `display: none` or so, we still want to show a
590        // correct computed value, so give it a try.
591        let should_traverse = parent_style.map_or(true, |s| {
592            s.flags
593                .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE)
594        });
595        if !should_traverse {
596            return Self::none();
597        }
598        return Self::NotEvaluated(Box::new(move || {
599            Self::lookup(element, if is_pseudo { known_parent_style } else { None })
600        }));
601    }
602
603    /// Create a new instance, but with optional element.
604    pub fn for_option_element<E>(
605        element: Option<E>,
606        known_parent_style: Option<&'a ComputedValues>,
607        is_pseudo: bool,
608    ) -> Self
609    where
610        E: TElement + 'a,
611    {
612        if let Some(e) = element {
613            Self::for_element(e, known_parent_style, is_pseudo)
614        } else {
615            Self::none()
616        }
617    }
618
619    /// Create a query that evaluates to empty, for cases where container size query is not required.
620    pub fn none() -> Self {
621        ContainerSizeQuery::Evaluated(ContainerSizeQueryResult::default())
622    }
623
624    /// Get the result of the container size query, doing the lookup if called for the first time.
625    pub fn get(&mut self) -> ContainerSizeQueryResult {
626        match self {
627            Self::NotEvaluated(lookup) => {
628                *self = Self::Evaluated((lookup)());
629                match self {
630                    Self::Evaluated(info) => *info,
631                    _ => unreachable!("Just evaluated but not set?"),
632                }
633            },
634            Self::Evaluated(info) => *info,
635        }
636    }
637}