Skip to main content

sk_css/
container.rs

1//! `@container` conditions and the container query length units (`cqw` … `cqmax`), answered from the
2//! query containers above the element being cascaded and the content-box sizes the host's last
3//! layout gave them.
4
5use std::cell::{Cell, RefCell};
6use std::rc::Rc;
7
8use lightningcss::media_query::{
9    MediaFeatureComparison, MediaFeatureName, MediaFeatureValue, Operator, QueryFeature,
10};
11use lightningcss::properties::Property;
12use lightningcss::rules::container::{
13    ContainerCondition, ContainerRule, ContainerSizeFeature, ContainerSizeFeatureId, StyleQuery,
14};
15use lightningcss::traits::ToCss;
16use lightningcss::values::length::{Length, LengthValue};
17
18use crate::Vars;
19
20/// The inline (horizontal) axis: `container-type: inline-size` or `size`.
21pub const INLINE: u8 = 1;
22/// The block (vertical) axis: `container-type: size`.
23pub const BLOCK: u8 = 2;
24
25/// A query container among an element's ancestors: an element whose `container-type` is not
26/// `normal` or that has a `container-name`. The chain runs nearest first.
27#[derive(Debug)]
28pub struct Container {
29    pub id: u32,
30    /// [`INLINE`] / [`BLOCK`]; 0 for a named style container.
31    pub axes: u8,
32    pub names: Option<Rc<[Rc<str>]>>,
33    pub vars: Rc<Vars>,
34    pub font_size: f32,
35    pub parent: Chain,
36}
37
38pub type Chain = Option<Rc<Container>>;
39
40impl Container {
41    /// The chain an element's children see: `chain` with the element in front when it is a query
42    /// container.
43    pub fn link(
44        id: u32,
45        extras: &crate::Extras,
46        vars: &Rc<Vars>,
47        font_size: f32,
48        chain: &Chain,
49    ) -> Chain {
50        let axes = extras.container_type.unwrap_or(0);
51        let names = extras.container_name.clone().flatten();
52        if axes == 0 && names.is_none() {
53            return chain.clone();
54        }
55        Some(Rc::new(Container {
56            id,
57            axes,
58            names,
59            vars: vars.clone(),
60            font_size,
61            parent: chain.clone(),
62        }))
63    }
64
65    fn iter(chain: &Chain) -> impl Iterator<Item = &Container> {
66        std::iter::successors(chain.as_deref(), |c| c.parent.as_deref())
67    }
68
69    fn named(&self, name: &str) -> bool {
70        self.names
71            .as_ref()
72            .is_some_and(|names| names.iter().any(|n| &**n == name))
73    }
74}
75
76/// The content box `(width, height)` of a container as last laid out; `None` before its first
77/// layout. The host records each question: an answer that moves must restyle what asked.
78pub type SizeSource = fn(id: u32, axes: u8) -> Option<(f32, f32)>;
79
80thread_local! {
81    static SOURCE: Cell<Option<SizeSource>> = const { Cell::new(None) };
82    static CHAIN: RefCell<Chain> = const { RefCell::new(None) };
83    static UNITS_SEEN: Cell<bool> = const { Cell::new(false) };
84}
85
86pub fn set_size_source(source: SizeSource) {
87    SOURCE.with(|s| s.set(Some(source)));
88}
89
90/// Runs one element's cascade with `chain` as its query containers.
91pub fn with_chain<R>(chain: &Chain, f: impl FnOnce() -> R) -> R {
92    struct Restore(Chain);
93    impl Drop for Restore {
94        fn drop(&mut self) {
95            let outer = self.0.take();
96            CHAIN.with(|c| *c.borrow_mut() = outer);
97        }
98    }
99    let _restore = Restore(CHAIN.with(|c| c.replace(chain.clone())));
100    f()
101}
102
103fn size_of(id: u32, axes: u8) -> Option<(f32, f32)> {
104    SOURCE.with(Cell::get).and_then(|source| source(id, axes))
105}
106
107pub(crate) fn noting_units<R>(f: impl FnOnce() -> R) -> (R, bool) {
108    let before = UNITS_SEEN.with(|c| c.replace(false));
109    let out = f();
110    let seen = UNITS_SEEN.with(|c| c.replace(before));
111    UNITS_SEEN.with(|c| c.set(before || seen));
112    (out, seen)
113}
114
115/// `cqw`, `cqh`, `cqi`, `cqb`, `cqmin`, `cqmax` in px: against the nearest container with that
116/// axis, else the viewport (CSS's "small viewport" fallback, the same here).
117pub(crate) fn unit_px(v: &LengthValue) -> Option<f32> {
118    let (value, axes) = match *v {
119        LengthValue::Cqw(p) | LengthValue::Cqi(p) => (p, INLINE),
120        LengthValue::Cqh(p) | LengthValue::Cqb(p) => (p, BLOCK),
121        LengthValue::Cqmin(p) | LengthValue::Cqmax(p) => (p, INLINE | BLOCK),
122        _ => return None,
123    };
124    UNITS_SEEN.with(|c| c.set(true));
125    crate::mapper::note_font_relative();
126    let (vw, vh) = crate::mapper::viewport_basis();
127    let along = |axis: u8| -> f32 {
128        let size = CHAIN.with(|c| {
129            let chain = c.borrow();
130            let found = Container::iter(&chain).find(|c| c.axes & axis != 0)?;
131            size_of(found.id, axis)
132        });
133        match (size, axis) {
134            (Some((w, _)), INLINE) => w,
135            (Some((_, h)), _) => h,
136            (None, INLINE) => vw,
137            (None, _) => vh,
138        }
139    };
140    let basis = match (v, axes) {
141        (_, INLINE) => along(INLINE),
142        (_, BLOCK) => along(BLOCK),
143        (LengthValue::Cqmin(_), _) => along(INLINE).min(along(BLOCK)),
144        _ => along(INLINE).max(along(BLOCK)),
145    };
146    Some(value / 100.0 * basis)
147}
148
149pub(crate) fn unit_name_px(unit: &str, value: f32) -> Option<f32> {
150    let v = match unit {
151        "cqw" => LengthValue::Cqw(value),
152        "cqh" => LengthValue::Cqh(value),
153        "cqi" => LengthValue::Cqi(value),
154        "cqb" => LengthValue::Cqb(value),
155        "cqmin" => LengthValue::Cqmin(value),
156        "cqmax" => LengthValue::Cqmax(value),
157        _ => return None,
158    };
159    unit_px(&v)
160}
161
162#[derive(Clone, Copy, Debug, PartialEq)]
163enum Cmp {
164    Lt,
165    Le,
166    Gt,
167    Ge,
168    Eq,
169}
170
171impl Cmp {
172    fn from(op: MediaFeatureComparison) -> Cmp {
173        match op {
174            MediaFeatureComparison::LessThan => Cmp::Lt,
175            MediaFeatureComparison::LessThanEqual => Cmp::Le,
176            MediaFeatureComparison::GreaterThan => Cmp::Gt,
177            MediaFeatureComparison::GreaterThanEqual => Cmp::Ge,
178            MediaFeatureComparison::Equal => Cmp::Eq,
179        }
180    }
181
182    fn flip(self) -> Cmp {
183        match self {
184            Cmp::Lt => Cmp::Gt,
185            Cmp::Le => Cmp::Ge,
186            Cmp::Gt => Cmp::Lt,
187            Cmp::Ge => Cmp::Le,
188            Cmp::Eq => Cmp::Eq,
189        }
190    }
191
192    fn eval(self, lhs: f32, rhs: f32) -> bool {
193        match self {
194            Cmp::Lt => lhs < rhs,
195            Cmp::Le => lhs <= rhs,
196            Cmp::Gt => lhs > rhs,
197            Cmp::Ge => lhs >= rhs,
198            Cmp::Eq => (lhs - rhs).abs() < 0.01,
199        }
200    }
201}
202
203#[derive(Clone, Copy, Debug, PartialEq)]
204enum Len {
205    Px(f32),
206    /// Of the query container's own `font-size`.
207    Em(f32),
208}
209
210#[derive(Clone, Debug, PartialEq)]
211enum Feature {
212    Width(Cmp, Len),
213    Height(Cmp, Len),
214    AspectRatio(Cmp, f32),
215    Portrait(bool),
216    /// `(width)`: true when the size is not zero.
217    NonZero(u8),
218}
219
220#[derive(Clone, Debug, PartialEq)]
221enum Cond {
222    Always,
223    Feature(Feature),
224    /// `style(--name)` or `style(--name: value)`.
225    Style(Box<str>, Option<Box<str>>),
226    Not(Box<Cond>),
227    And(Vec<Cond>),
228    Or(Vec<Cond>),
229}
230
231/// One `@container` prelude.
232#[derive(Clone, Debug, PartialEq)]
233struct Part {
234    name: Option<Box<str>>,
235    axes: u8,
236    cond: Cond,
237}
238
239/// The `@container` rules around a style rule, outermost first; every one must hold.
240#[derive(Clone, Debug, PartialEq, Default)]
241pub(crate) struct Query {
242    parts: Vec<Part>,
243}
244
245pub(crate) const SUPPORTED: &str = "supported: an optional container name, then `width`, \
246     `height`, `inline-size`, `block-size`, `aspect-ratio` and `orientation` (px, rem and em \
247     lengths, range and interval syntax) and `style(--custom-property: value)`, combined with \
248     `and`/`or`/`not`";
249
250type Unsupported = &'static str;
251
252impl Query {
253    pub(crate) fn nest(&self, rule: &ContainerRule<'_>) -> Result<Query, Unsupported> {
254        let cond = match &rule.condition {
255            Some(c) => condition(c)?,
256            None => Cond::Always,
257        };
258        let mut parts = self.parts.clone();
259        parts.push(Part {
260            name: rule.name.as_ref().map(|n| n.0 .0.as_ref().into()),
261            axes: axes_of(&cond),
262            cond,
263        });
264        Ok(Query { parts })
265    }
266
267    pub(crate) fn eval(&self, parent_vars: &Rc<Vars>) -> bool {
268        CHAIN.with(|c| {
269            let chain = c.borrow();
270            self.parts
271                .iter()
272                .all(|part| part.eval(&chain, parent_vars) == Some(true))
273        })
274    }
275}
276
277impl Part {
278    /// `None` when no container answers, which CSS calls "unknown" and does not apply.
279    fn eval(&self, chain: &Chain, parent_vars: &Rc<Vars>) -> Option<bool> {
280        let found = Container::iter(chain).find(|c| {
281            c.axes & self.axes == self.axes && self.name.as_deref().is_none_or(|n| c.named(n))
282        });
283        let at = match found {
284            Some(c) => At {
285                size: (self.axes != 0).then(|| size_of(c.id, self.axes)).flatten(),
286                vars: &c.vars,
287                font_size: c.font_size,
288            },
289            // Every element is a style container: with no name, a pure style query asks the
290            // parent.
291            None if self.axes == 0 && self.name.is_none() => At {
292                size: None,
293                vars: parent_vars,
294                font_size: crate::mapper::rem_basis(),
295            },
296            None => return None,
297        };
298        at.eval(&self.cond)
299    }
300}
301
302struct At<'a> {
303    size: Option<(f32, f32)>,
304    vars: &'a Rc<Vars>,
305    font_size: f32,
306}
307
308impl At<'_> {
309    fn eval(&self, cond: &Cond) -> Option<bool> {
310        match cond {
311            Cond::Always => Some(true),
312            Cond::Feature(f) => self.feature(f),
313            Cond::Style(name, value) => Some(match (self.vars.get(name), value) {
314                (Some(have), Some(want)) => normalized(have) == normalized(want),
315                (Some(_), None) => true,
316                (None, _) => false,
317            }),
318            Cond::Not(c) => self.eval(c).map(|b| !b),
319            Cond::And(cs) => {
320                let mut unknown = false;
321                for c in cs {
322                    match self.eval(c) {
323                        Some(false) => return Some(false),
324                        None => unknown = true,
325                        Some(true) => {}
326                    }
327                }
328                (!unknown).then_some(true)
329            }
330            Cond::Or(cs) => {
331                let mut unknown = false;
332                for c in cs {
333                    match self.eval(c) {
334                        Some(true) => return Some(true),
335                        None => unknown = true,
336                        Some(false) => {}
337                    }
338                }
339                (!unknown).then_some(false)
340            }
341        }
342    }
343
344    fn px(&self, len: Len) -> f32 {
345        match len {
346            Len::Px(px) => px,
347            Len::Em(em) => em * self.font_size,
348        }
349    }
350
351    fn feature(&self, f: &Feature) -> Option<bool> {
352        let (w, h) = self.size?;
353        Some(match *f {
354            Feature::Width(cmp, len) => cmp.eval(w, self.px(len)),
355            Feature::Height(cmp, len) => cmp.eval(h, self.px(len)),
356            Feature::AspectRatio(cmp, ratio) => h > 0.0 && cmp.eval(w / h, ratio),
357            Feature::Portrait(portrait) => (h >= w) == portrait,
358            Feature::NonZero(axes) => {
359                (axes & INLINE == 0 || w != 0.0) && (axes & BLOCK == 0 || h != 0.0)
360            }
361        })
362    }
363}
364
365fn normalized(text: &str) -> String {
366    text.split_whitespace().collect::<Vec<_>>().join(" ")
367}
368
369fn axes_of(cond: &Cond) -> u8 {
370    match cond {
371        Cond::Always | Cond::Style(..) => 0,
372        Cond::Feature(Feature::Width(..)) => INLINE,
373        Cond::Feature(Feature::Height(..)) => BLOCK,
374        Cond::Feature(Feature::NonZero(axes)) => *axes,
375        Cond::Feature(Feature::AspectRatio(..) | Feature::Portrait(_)) => INLINE | BLOCK,
376        Cond::Not(c) => axes_of(c),
377        Cond::And(cs) | Cond::Or(cs) => cs.iter().fold(0, |axes, c| axes | axes_of(c)),
378    }
379}
380
381fn condition(c: &ContainerCondition<'_>) -> Result<Cond, Unsupported> {
382    Ok(match c {
383        ContainerCondition::Feature(f) => feature(f)?,
384        ContainerCondition::Not(inner) => Cond::Not(Box::new(condition(inner)?)),
385        ContainerCondition::Operation {
386            operator,
387            conditions,
388        } => {
389            let parsed = conditions
390                .iter()
391                .map(condition)
392                .collect::<Result<Vec<_>, _>>()?;
393            match operator {
394                Operator::And => Cond::And(parsed),
395                Operator::Or => Cond::Or(parsed),
396            }
397        }
398        ContainerCondition::Style(q) => style(q)?,
399        ContainerCondition::ScrollState(_) => return Err("a scroll-state query"),
400        ContainerCondition::Unknown(_) => {
401            return Err("tokens the container query parser could not interpret")
402        }
403    })
404}
405
406fn style(q: &StyleQuery<'_>) -> Result<Cond, Unsupported> {
407    use lightningcss::properties::custom::CustomPropertyName;
408    const STANDARD: &str = "a style query on a standard property (only custom properties are)";
409    Ok(match q {
410        StyleQuery::Declaration(p @ Property::Custom(c)) => match &c.name {
411            CustomPropertyName::Custom(name) => {
412                let text = p
413                    .to_css_string(false, Default::default())
414                    .map_err(|_| "a style query value that cannot be read")?;
415                let value = text.split_once(':').map_or("", |(_, v)| v.trim());
416                Cond::Style(name.0.as_ref().into(), Some(value.into()))
417            }
418            CustomPropertyName::Unknown(_) => return Err(STANDARD),
419        },
420        StyleQuery::Property(id) if id.name().starts_with("--") => {
421            Cond::Style(id.name().into(), None)
422        }
423        StyleQuery::Declaration(_) | StyleQuery::Property(_) => return Err(STANDARD),
424        StyleQuery::Not(inner) => Cond::Not(Box::new(style(inner)?)),
425        StyleQuery::Operation {
426            operator,
427            conditions,
428        } => {
429            let parsed = conditions
430                .iter()
431                .map(style)
432                .collect::<Result<Vec<_>, _>>()?;
433            match operator {
434                Operator::And => Cond::And(parsed),
435                Operator::Or => Cond::Or(parsed),
436            }
437        }
438    })
439}
440
441fn length(value: &MediaFeatureValue<'_>) -> Result<Len, Unsupported> {
442    const NOT_A_LENGTH: &str =
443        "a container length that is not px, rem or em (`%`, `calc()`, viewport units)";
444    match value {
445        MediaFeatureValue::Length(Length::Value(v)) => match v {
446            LengthValue::Em(em) => Ok(Len::Em(*em)),
447            LengthValue::Rem(rem) => Ok(Len::Px(rem * crate::mapper::rem_basis())),
448            other => other.to_px().map(Len::Px).ok_or(NOT_A_LENGTH),
449        },
450        MediaFeatureValue::Length(_) => Err(NOT_A_LENGTH),
451        MediaFeatureValue::Integer(0) => Ok(Len::Px(0.0)),
452        MediaFeatureValue::Number(n) if *n == 0.0 => Ok(Len::Px(0.0)),
453        _ => Err("a container feature value of the wrong type"),
454    }
455}
456
457fn ratio(value: &MediaFeatureValue<'_>) -> Result<f32, Unsupported> {
458    match value {
459        MediaFeatureValue::Ratio(r) if r.1 > 0.0 => Ok(r.0 / r.1),
460        MediaFeatureValue::Number(n) => Ok(*n),
461        MediaFeatureValue::Integer(i) => Ok(*i as f32),
462        _ => Err("an `aspect-ratio` that is not a ratio"),
463    }
464}
465
466fn standard(
467    name: &MediaFeatureName<'_, ContainerSizeFeatureId>,
468) -> Result<ContainerSizeFeatureId, Unsupported> {
469    match name {
470        MediaFeatureName::Standard(id) => Ok(*id),
471        MediaFeatureName::Custom(_) => Err("a custom feature (`--name`)"),
472        MediaFeatureName::Unknown(_) => Err("an unknown container feature"),
473    }
474}
475
476fn ranged(
477    id: ContainerSizeFeatureId,
478    cmp: Cmp,
479    value: &MediaFeatureValue<'_>,
480) -> Result<Feature, Unsupported> {
481    use ContainerSizeFeatureId as Id;
482    Ok(match id {
483        Id::Width | Id::InlineSize => Feature::Width(cmp, length(value)?),
484        Id::Height | Id::BlockSize => Feature::Height(cmp, length(value)?),
485        Id::AspectRatio => Feature::AspectRatio(cmp, ratio(value)?),
486        Id::Orientation => return Err("a range comparison on `orientation`"),
487    })
488}
489
490fn feature(f: &ContainerSizeFeature<'_>) -> Result<Cond, Unsupported> {
491    use ContainerSizeFeatureId as Id;
492    Ok(Cond::Feature(match f {
493        QueryFeature::Plain { name, value } => match standard(name)? {
494            Id::Orientation => match value {
495                MediaFeatureValue::Ident(i) if i.0.eq_ignore_ascii_case("portrait") => {
496                    Feature::Portrait(true)
497                }
498                MediaFeatureValue::Ident(i) if i.0.eq_ignore_ascii_case("landscape") => {
499                    Feature::Portrait(false)
500                }
501                _ => return Err("an unknown `orientation` value"),
502            },
503            id => ranged(id, Cmp::Eq, value)?,
504        },
505        QueryFeature::Boolean { name } => Feature::NonZero(match standard(name)? {
506            Id::Width | Id::InlineSize => INLINE,
507            Id::Height | Id::BlockSize => BLOCK,
508            Id::AspectRatio | Id::Orientation => INLINE | BLOCK,
509        }),
510        QueryFeature::Range {
511            name,
512            operator,
513            value,
514        } => ranged(standard(name)?, Cmp::from(*operator), value)?,
515        QueryFeature::Interval {
516            name,
517            start,
518            start_operator,
519            end,
520            end_operator,
521        } => {
522            let id = standard(name)?;
523            return Ok(Cond::And(vec![
524                Cond::Feature(ranged(id, Cmp::from(*start_operator).flip(), start)?),
525                Cond::Feature(ranged(id, Cmp::from(*end_operator), end)?),
526            ]));
527        }
528    }))
529}
530
531pub(crate) fn prelude_text(rule: &ContainerRule<'_>) -> String {
532    let name = rule.name.as_ref().map(|n| n.0 .0.to_string());
533    let cond = rule
534        .condition
535        .as_ref()
536        .and_then(|c| c.to_css_string(Default::default()).ok());
537    [name, cond]
538        .into_iter()
539        .flatten()
540        .collect::<Vec<_>>()
541        .join(" ")
542}