Skip to main content

parsec_css/cascade/
compute.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Computed values, CSS Cascade 5 §4.4 and each property's "Computed
5//! value" line: the cascaded value, or the inherited or initial one, with
6//! the CSS-wide keywords and `var()` dealt with, lengths made absolute,
7//! colours worked out, and the keywords that compute to numbers
8//! computed, then written as `getComputedStyle()` writes them.
9
10use std::collections::HashMap;
11
12use super::{Declared, Key, css_wide};
13use crate::media::{Environment, QueryLengths};
14use crate::parser::ComponentValue;
15use crate::values::{
16    Color, Component, CssWide, CustomProperties, Kind, Leaf, Resolved, Specified, Unit, expand,
17    parse_value, property, substitute, write_components,
18};
19
20/// One element's computed values.
21#[derive(Clone, Debug, Default)]
22pub struct Computed {
23    /// Every property that isn't at its initial value, written out.
24    values: HashMap<&'static str, String>,
25    /// Which declaration each value came from, to tell whether a
26    /// shorthand's longhands all still come from it.
27    keys: HashMap<&'static str, Key>,
28    /// Custom properties, written out; `None` is guaranteed-invalid.
29    custom: HashMap<String, Option<String>>,
30    /// `font-size`, in pixels, which `em` here is relative to.
31    pub font_size: f64,
32    /// The root element's, for `rem`.
33    root_font_size: f64,
34    /// `color`, written out, which `currentcolor` here is.
35    color: String,
36    env: Environment,
37    /// The width and height `cqw` and `cqh` are 1% of here: the nearest
38    /// ancestor query container's on each axis, or the small viewport's.
39    cq: (f64, f64),
40    /// What they are for the children: this element's own size on the
41    /// axes it's a size container for, [`Computed::cq`] otherwise.
42    pub(super) cq_children: (f64, f64),
43    /// The parent element, when it was styled too.
44    pub(super) parent: Option<parsec::NodeId>,
45}
46
47impl Computed {
48    /// A property's computed value, as `getComputedStyle()` writes it.
49    pub fn get(&self, name: &str) -> Option<String> {
50        if name.starts_with("--") {
51            return self.custom.get(name).cloned().flatten();
52        }
53        let p = property(name)?;
54        let p = p.alias_of.and_then(property).unwrap_or(p);
55        if p.is_shorthand() {
56            if let Some(v) = self.values.get(p.name)
57                && let Some(k) = self.keys.get(p.name)
58                && p.longhands
59                    .iter()
60                    .all(|l| self.keys.get(l).is_none_or(|lk| lk <= k))
61            {
62                return Some(v.clone());
63            }
64            // The longhands written in order and read back as the
65            // shorthand, which writes itself at its shortest: CSSOM's
66            // shorthand serialization, for the shorthands whose longhands
67            // line up with their grammar.
68            let parts: Vec<String> = p.longhands.iter().filter_map(|l| self.get(l)).collect();
69            if let Some((first, rest)) = parts.split_first()
70                && rest.iter().all(|r| r == first)
71                && p.longhands.len() > 2
72            {
73                return Some(first.clone());
74            }
75            let text = parts.join(" ");
76            let values = crate::parse_component_values(&text);
77            return parse_value(p.name, &values).ok().map(|v| v.to_string());
78        }
79        if let Some(v) = self.values.get(p.name) {
80            return Some(v.clone());
81        }
82        Some(self.initial(p.name))
83    }
84
85    /// The custom properties, as `var()` here sees them.
86    pub fn custom_properties(&self) -> impl Iterator<Item = (&str, Option<&str>)> {
87        self.custom.iter().map(|(k, v)| (k.as_str(), v.as_deref()))
88    }
89
90    fn cx(&self, name: &'static str, parent_font_size: f64) -> Cx<'_> {
91        Cx {
92            property: name,
93            font_size: self.font_size,
94            parent_font_size,
95            root_font_size: self.root_font_size,
96            color: &self.color,
97            env: &self.env,
98            cq: self.cq,
99            vertical: self.vertical(),
100        }
101    }
102
103    /// Whether the writing mode is vertical, which makes `cqi` and the
104    /// inline axis the height.
105    fn vertical(&self) -> bool {
106        self.values.get("writing-mode").is_some_and(|w| {
107            w.starts_with("vertical") || w.starts_with("sideways") || w.starts_with("tb")
108        })
109    }
110
111    /// What a container query's lengths are relative to when this is the
112    /// container: its font size, and its own query containers for `cq*`.
113    pub(super) fn query_lengths(&self) -> QueryLengths {
114        QueryLengths {
115            font_size: self.font_size,
116            viewport: (self.env.width, self.env.height),
117            container: self.cq,
118            vertical: self.vertical(),
119        }
120    }
121
122    /// The physical axes this element is a size container for, width then
123    /// height: none if it has no box.
124    pub(super) fn size_axes(&self) -> (bool, bool) {
125        let Some(ty) = self.values.get("container-type") else {
126            return (false, false);
127        };
128        if matches!(
129            self.values.get("display").map(String::as_str),
130            Some("none" | "contents")
131        ) {
132            return (false, false);
133        }
134        let size = ty.split_ascii_whitespace().any(|w| w == "size");
135        let inline = ty.split_ascii_whitespace().any(|w| w == "inline-size");
136        let vertical = self.vertical();
137        (size || inline && !vertical, size || inline && vertical)
138    }
139
140    /// A style range's value, CSS Conditional 5 §6.2: `var()` substituted
141    /// from the custom properties here, typed as a number, percentage or
142    /// dimension, and computed here.
143    pub(super) fn range_value(&self, text: &str) -> Option<Leaf> {
144        static TYPES: std::sync::OnceLock<Option<crate::values::Grammar>> =
145            std::sync::OnceLock::new();
146        let types = TYPES.get_or_init(|| {
147            crate::values::Grammar::parse(
148                "<number> | <percentage> | <length> | <angle> | <time> | <frequency> | <resolution>",
149            )
150        });
151        let values = crate::parse_component_values(text);
152        let custom = Resolved::from_values(
153            self.custom
154                .iter()
155                .map(|(k, v)| (k.clone(), v.as_deref().map(crate::parse_component_values))),
156        );
157        let values = substitute(&values, &custom).ok()?;
158        let typed = crate::values::match_grammar(types.as_ref()?, &values)?;
159        let cx = self.cx("--", self.font_size);
160        match &components(&typed, &cx, None)[..] {
161            [Component::Number { value, .. }] => Some(Leaf::Number(*value)),
162            [Component::Percentage(p)] => Some(Leaf::Percentage(*p)),
163            [Component::Dimension(v, u)] => Some(Leaf::Dimension(*v, *u)),
164            _ => None,
165        }
166    }
167
168    fn initial(&self, name: &'static str) -> String {
169        initial_of(name, &self.cx(name, self.font_size))
170    }
171}
172
173pub(super) struct Input<'d, 's> {
174    pub declared: &'d HashMap<&'static str, Vec<Declared<'s>>>,
175    pub custom: &'d HashMap<String, Vec<(Key, Vec<ComponentValue<'s>>)>>,
176    pub parent: Option<&'d Computed>,
177    pub root: Option<&'d Computed>,
178    pub is_root: bool,
179    pub env: &'d Environment,
180    /// What `cqw` and `cqh` are 1% of here; see [`Computed::cq`].
181    pub cq: (f64, f64),
182    /// The custom properties `@property` registers, with their syntax.
183    pub registered: &'d HashMap<String, (crate::rules::PropertyRule, crate::rules::Syntax)>,
184}
185
186/// What computing one property needs to know.
187struct Cx<'c> {
188    property: &'static str,
189    font_size: f64,
190    parent_font_size: f64,
191    root_font_size: f64,
192    color: &'c str,
193    env: &'c Environment,
194    cq: (f64, f64),
195    vertical: bool,
196}
197
198/// The order properties are computed in: what others refer to first.
199const FIRST: &[&str] = &["font-size", "color", "writing-mode"];
200
201fn inherited(name: &str) -> bool {
202    property(name).and_then(|p| p.inherited) == Some(true)
203}
204
205pub(super) fn compute(input: Input<'_, '_>) -> Computed {
206    let parent = input.parent;
207    let parent_font_size = parent.map_or(16.0, |p| p.font_size);
208    let root_font_size = input.root.map_or(16.0, |r| r.font_size);
209    let mut out = Computed {
210        values: HashMap::new(),
211        keys: HashMap::new(),
212        custom: HashMap::new(),
213        font_size: parent_font_size,
214        root_font_size,
215        color: parent.map_or_else(|| "rgb(0, 0, 0)".to_string(), |p| p.color.clone()),
216        env: input.env.clone(),
217        cq: input.cq,
218        cq_children: input.cq,
219        parent: None,
220    };
221    // Inherited values first: what isn't declared keeps them.
222    if let Some(p) = parent {
223        for (k, v) in &p.values {
224            if inherited(k) {
225                out.values.insert(k, v.clone());
226            }
227        }
228        out.custom = p.custom.clone();
229    }
230    let custom = resolve_custom(&input, parent);
231    for (name, value) in custom.iter() {
232        out.custom
233            .insert(name.to_string(), value.map(crate::to_css));
234    }
235    let mut order: Vec<&'static str> = input.declared.keys().copied().collect();
236    order.sort_by_key(|n| FIRST.iter().position(|f| f == n).unwrap_or(FIRST.len()));
237    for name in order {
238        let list = &input.declared[name];
239        let value = cascaded(
240            name,
241            list,
242            list.len() - 1,
243            &custom,
244            parent,
245            &out,
246            parent_font_size,
247            input.is_root,
248        );
249        out.keys.insert(name, list[list.len() - 1].key);
250        match value {
251            Some(v) => {
252                out.values.insert(name, v);
253            }
254            None => {
255                out.values.remove(name);
256            }
257        }
258        if name == "font-size" {
259            if let Some(v) = out.values.get("font-size") {
260                out.font_size = px_of(v).unwrap_or(parent_font_size);
261            }
262            if input.is_root {
263                out.root_font_size = out.font_size;
264            }
265        }
266        if name == "color" {
267            out.color = out
268                .values
269                .get("color")
270                .cloned()
271                .unwrap_or_else(|| out.initial("color"));
272        }
273    }
274    if input.is_root {
275        out.root_font_size = out.font_size;
276    }
277    registered(&input, &custom, parent, &mut out);
278    // `currentcolor` and the border widths depend on others, worked out
279    // after everything's in.
280    fix_up(&mut out, input.is_root, parent);
281    out
282}
283
284/// Registered custom properties, CSS Properties and Values API 1 §2: each
285/// takes its declared value if it matches the syntax, computed (`1em` as
286/// pixels, colours worked out); otherwise, or if nothing's declared, the
287/// parent's if it inherits, and its initial value if not.
288fn registered(
289    input: &Input<'_, '_>,
290    custom: &Resolved<'_>,
291    parent: Option<&Computed>,
292    out: &mut Computed,
293) {
294    for (name, (rule, syntax)) in input.registered {
295        let initial = rule.initial_value.clone();
296        let from_parent = || {
297            parent
298                .and_then(|p| p.custom.get(name).cloned().flatten())
299                .or_else(|| initial.clone())
300        };
301        let unset = || {
302            if rule.inherits {
303                from_parent()
304            } else {
305                initial.clone()
306            }
307        };
308        let declared = input
309            .custom
310            .get(name)
311            .and_then(|l| l.last())
312            .map(|(_, v)| v);
313        let keyword = match declared.map(|v| &v[..]) {
314            Some([ComponentValue::Token(crate::Token::Ident(w), _)]) => {
315                Some(w.to_ascii_lowercase())
316            }
317            _ => None,
318        };
319        let value = match (declared, keyword.as_deref()) {
320            (None, _) => unset(),
321            (Some(_), Some("inherit")) => from_parent(),
322            (Some(_), Some("initial")) => initial.clone(),
323            (Some(_), Some("unset" | "revert" | "revert-layer")) => unset(),
324            (Some(_), _) => match custom.get(name) {
325                // Guaranteed-invalid: as `unset`.
326                None => unset(),
327                Some(tokens) if syntax.is_universal() => {
328                    Some(crate::to_css(tokens).trim().to_string())
329                }
330                Some(tokens) => match syntax.parse_value(tokens) {
331                    Some(c) => {
332                        let cx = out.cx("--", out.font_size);
333                        let c: Vec<Component<'_>> = components(&c, &cx, None)
334                            .into_iter()
335                            .map(|x| match x {
336                                Component::Color(c) => Component::Color(c.computed()),
337                                x => x,
338                            })
339                            .collect();
340                        Some(Specified::Value(c).to_string())
341                    }
342                    None => unset(),
343                },
344            },
345        };
346        out.custom.insert(name.clone(), value);
347    }
348}
349
350fn px_of(s: &str) -> Option<f64> {
351    s.strip_suffix("px")?.parse().ok()
352}
353
354/// The custom properties: the cascade's winner for each, then resolved
355/// against each other and the parent's.
356fn resolve_custom<'r>(input: &Input<'_, 'r>, parent: Option<&'r Computed>) -> Resolved<'r> {
357    let mut props = CustomProperties::new();
358    for (name, list) in input.custom {
359        let Some((_, value)) = list.last() else {
360            continue;
361        };
362        // `inherit` and `unset` keep the parent's: not declaring it does.
363        if let [ComponentValue::Token(crate::Token::Ident(w), _)] = &value[..]
364            && ["inherit", "unset", "revert", "revert-layer"]
365                .iter()
366                .any(|k| w.eq_ignore_ascii_case(k))
367        {
368            continue;
369        }
370        props.declare(name, value.clone());
371    }
372    // The parent's, read back from their text.
373    let parent_resolved = Resolved::from_values(parent.into_iter().flat_map(|p| {
374        p.custom
375            .iter()
376            .map(|(k, v)| (k.clone(), v.as_deref().map(crate::parse_component_values)))
377    }));
378    props.resolve(Some(&parent_resolved))
379}
380
381/// The base origin of a cascade rank: user agent, user or author.
382fn base_origin(rank: u8) -> u8 {
383    if rank <= 2 { rank } else { 5 - rank }
384}
385
386/// The computed value from the cascade's list for one property, the
387/// winner at `at`; `None` for the initial value.
388#[allow(clippy::too_many_arguments)]
389fn cascaded(
390    name: &'static str,
391    list: &[Declared<'_>],
392    at: usize,
393    custom: &Resolved<'_>,
394    parent: Option<&Computed>,
395    out: &Computed,
396    parent_font_size: f64,
397    is_root: bool,
398) -> Option<String> {
399    let d = &list[at];
400    let inherit = || parent.and_then(|p| p.get(name)).filter(|_| true);
401    let unset = || if inherited(name) { inherit() } else { None };
402    if let Some(k) = css_wide(&d.value) {
403        return match k {
404            CssWide::Inherit => inherit().or_else(|| Some(out.initial(name))),
405            CssWide::Initial => None,
406            CssWide::Unset => unset(),
407            // Roll back to the origin before, or the layer before.
408            CssWide::Revert | CssWide::RevertLayer => {
409                let origin = base_origin(d.key.origin);
410                let back = list[..at].iter().rposition(|e| {
411                    if k == CssWide::Revert {
412                        base_origin(e.key.origin) < origin
413                    } else {
414                        base_origin(e.key.origin) < origin
415                            || (e.key.origin == d.key.origin
416                                && e.key.layer < d.key.layer
417                                && !e.key.attached)
418                    }
419                });
420                match back {
421                    Some(i) => cascaded(
422                        name,
423                        list,
424                        i,
425                        custom,
426                        parent,
427                        out,
428                        parent_font_size,
429                        is_root,
430                    ),
431                    None => unset(),
432                }
433            }
434        };
435    }
436    let substituted;
437    let value = match &d.value {
438        Specified::Unparsed(v) => {
439            // Invalid once substituted is `unset`.
440            let Ok(values) = substitute(v, custom) else {
441                return unset();
442            };
443            let parsed = match d.from_shorthand {
444                Some(shorthand) => expand(shorthand, &values)
445                    .ok()
446                    .and_then(|l| l.into_iter().find(|(n, _)| *n == name).map(|(_, v)| v)),
447                None => parse_value(name, &values).ok(),
448            };
449            match parsed {
450                Some(v) => {
451                    substituted = v;
452                    if let Some(k) = css_wide(&substituted) {
453                        return match k {
454                            CssWide::Inherit => inherit(),
455                            CssWide::Initial => None,
456                            _ => unset(),
457                        };
458                    }
459                    &substituted
460                }
461                None => return unset(),
462            }
463        }
464        v => v,
465    };
466    let Specified::Value(components) = value else {
467        return None;
468    };
469    let cx = out.cx(name, parent_font_size);
470    Some(compute_value(name, components, &cx, is_root, parent))
471}
472
473fn initial_of(name: &'static str, cx: &Cx<'_>) -> String {
474    let Some(text) = property(name).and_then(|p| p.initial) else {
475        return String::new();
476    };
477    let values = crate::parse_component_values(text);
478    match parse_value(name, &values) {
479        Ok(Specified::Value(c)) => compute_value(name, &c, cx, false, None),
480        _ => text.to_string(),
481    }
482}
483
484// ---- computing values ------------------------------------------------------
485
486/// Pixels in one of `u`, where the context says what the relative ones
487/// are; `None` for a unit that isn't a length.
488fn px(u: Unit, cx: &Cx<'_>) -> Option<f64> {
489    // In `font-size`, `em` is the parent's.
490    let em = if cx.property == "font-size" {
491        cx.parent_font_size
492    } else {
493        cx.font_size
494    };
495    let (w, h) = (cx.env.width, cx.env.height);
496    let (ci, cb) = if cx.vertical {
497        (cx.cq.1, cx.cq.0)
498    } else {
499        cx.cq
500    };
501    Some(match u {
502        Unit::Em => em,
503        Unit::Rem => cx.root_font_size,
504        // No fonts here: the fallbacks the specs give.
505        Unit::Ex | Unit::Ch | Unit::Cap => em * 0.5,
506        Unit::Rex | Unit::Rch | Unit::Rcap => cx.root_font_size * 0.5,
507        Unit::Ic => em,
508        Unit::Ric => cx.root_font_size,
509        Unit::Lh => em * 1.2,
510        Unit::Rlh => cx.root_font_size * 1.2,
511        Unit::Vw
512        | Unit::Svw
513        | Unit::Lvw
514        | Unit::Dvw
515        | Unit::Vi
516        | Unit::Svi
517        | Unit::Lvi
518        | Unit::Dvi => w / 100.0,
519        Unit::Vh
520        | Unit::Svh
521        | Unit::Lvh
522        | Unit::Dvh
523        | Unit::Vb
524        | Unit::Svb
525        | Unit::Lvb
526        | Unit::Dvb => h / 100.0,
527        Unit::Vmin | Unit::Svmin | Unit::Lvmin | Unit::Dvmin => w.min(h) / 100.0,
528        Unit::Vmax | Unit::Svmax | Unit::Lvmax | Unit::Dvmax => w.max(h) / 100.0,
529        // CSS Conditional 5 §6.3: each axis's nearest query container,
530        // the inline one by this element's writing mode.
531        Unit::Cqw => cx.cq.0 / 100.0,
532        Unit::Cqh => cx.cq.1 / 100.0,
533        Unit::Cqi => ci / 100.0,
534        Unit::Cqb => cb / 100.0,
535        Unit::Cqmin => ci.min(cb) / 100.0,
536        Unit::Cqmax => ci.max(cb) / 100.0,
537        u if u.kind() == Kind::Length => u.to_canonical()?,
538        _ => return None,
539    })
540}
541
542/// A leaf computed: lengths in pixels, other dimensions canonical.
543fn leaf(l: Leaf, cx: &Cx<'_>, percent_of: Option<f64>) -> Leaf {
544    match l {
545        Leaf::Dimension(v, u) => match px(u, cx) {
546            Some(f) => Leaf::Dimension(v * f, Unit::Px),
547            // Angles in degrees, times in seconds, and the rest in their
548            // canonical unit, as computed values have them.
549            None => match (u.canonical(), u.to_canonical()) {
550                (Some(c), Some(f)) => Leaf::Dimension(v * f, c),
551                _ => l,
552            },
553        },
554        Leaf::Percentage(p) => match percent_of {
555            Some(base) => Leaf::Dimension(p / 100.0 * base, Unit::Px),
556            None => l,
557        },
558        l => l,
559    }
560}
561
562/// A value's components computed.
563fn components<'a>(c: &[Component<'a>], cx: &Cx<'_>, percent_of: Option<f64>) -> Vec<Component<'a>> {
564    c.iter()
565        .map(|x| match x {
566            Component::Dimension(v, u) => match leaf(Leaf::Dimension(*v, *u), cx, percent_of) {
567                Leaf::Dimension(v, u) => Component::Dimension(v, u),
568                _ => x.clone(),
569            },
570            Component::Percentage(p) => match percent_of {
571                Some(base) => Component::Dimension(p / 100.0 * base, Unit::Px),
572                None => x.clone(),
573            },
574            Component::Math(m) => {
575                let m = m.map_leaves(&|l| leaf(l, cx, percent_of));
576                match m.leaf() {
577                    Some(Leaf::Dimension(v, u)) => Component::Dimension(v, u),
578                    Some(Leaf::Percentage(v)) => Component::Percentage(v),
579                    Some(Leaf::Number(v)) => Component::Number {
580                        value: v,
581                        integer: false,
582                    },
583                    None => Component::Math(m),
584                }
585            }
586            Component::Color(c) => Component::Color(resolved_color(c, cx)),
587            Component::Function { name, arguments } => Component::Function {
588                name,
589                arguments: components(arguments, cx, percent_of),
590            },
591            x => x.clone(),
592        })
593        .collect()
594}
595
596/// The used colour, which is what `getComputedStyle()` gives: named and
597/// system colours as `rgb()`, `currentcolor` as the element's colour.
598fn resolved_color(c: &Color, cx: &Cx<'_>) -> Color {
599    match c {
600        Color::CurrentColor => {
601            // In `color` itself this is the parent's, which is what the
602            // context holds until `color` is computed.
603            let values = crate::parse_component_values(cx.color);
604            values
605                .first()
606                .and_then(Color::parse)
607                .map_or(Color::CurrentColor, |c| c.computed())
608        }
609        Color::System(name) => system_color(name).unwrap_or_else(|| c.clone()),
610        Color::LightDark(a, b) => {
611            let dark = cx
612                .env
613                .keywords
614                .iter()
615                .any(|(f, v)| *f == "prefers-color-scheme" && *v == "dark");
616            resolved_color(if dark { b } else { a }, cx)
617        }
618        Color::Relative(_) | Color::Mix(_) => {
619            // Worked out where it can be: with `currentcolor` inside, its
620            // colour stands in first.
621            let c = resolve_current(c, cx);
622            match c.absolute() {
623                Some(a) => Color::Text(a.write()),
624                None => c,
625            }
626        }
627        // A legacy colour's math, worked out with the element's lengths,
628        // makes it a legacy colour again.
629        Color::Channels(ch) if ch.model_is_legacy() && ch.has_math() => {
630            let mut ch = ch.clone();
631            ch.map_math(&|m| m.map_leaves(&|l| leaf(l, cx, None)));
632            let text = Color::Channels(ch).to_string();
633            let values = crate::parse_component_values(&text);
634            values
635                .first()
636                .and_then(Color::parse)
637                .unwrap_or_else(|| c.clone())
638        }
639        // Math in a channel, worked out with the element's lengths.
640        Color::Channels(ch) if !ch.model_is_legacy() && ch.has_math() => {
641            let mut ch = ch.clone();
642            ch.map_math(&|m| m.map_leaves(&|l| leaf(l, cx, None)));
643            let c = Color::Channels(ch);
644            match c.absolute() {
645                Some(a) => Color::Text(a.write()),
646                None => c,
647            }
648        }
649        c => c.computed(),
650    }
651}
652
653/// `currentcolor` inside a relative colour's origin replaced by the
654/// element's colour.
655fn resolve_current(c: &Color, cx: &Cx<'_>) -> Color {
656    match c {
657        Color::Relative(r) if r.origin == Color::CurrentColor => {
658            let mut r = (**r).clone();
659            r.origin = resolved_color(&Color::CurrentColor, cx);
660            Color::Relative(Box::new(r))
661        }
662        c => c.clone(),
663    }
664}
665
666/// The light-scheme system colours, as browsers render them.
667fn system_color(name: &str) -> Option<Color> {
668    let [r, g, b] = match name {
669        "canvas" | "field" | "highlighttext" | "selecteditemtext" | "accentcolortext"
670        | "window" => [255, 255, 255],
671        "canvastext" | "fieldtext" | "buttontext" | "marktext" | "windowtext" | "menutext"
672        | "captiontext" | "infotext" => [0, 0, 0],
673        "linktext" => [0, 0, 238],
674        "visitedtext" => [85, 26, 139],
675        "activetext" => [255, 0, 0],
676        "buttonface" | "buttonhighlight" | "threedface" | "threedlightshadow" => [240, 240, 240],
677        "buttonborder" | "activeborder" | "inactiveborder" | "threedshadow" => [118, 118, 118],
678        "graytext" => [109, 109, 109],
679        "mark" => [255, 255, 0],
680        "highlight" | "selecteditem" | "accentcolor" => [0, 117, 255],
681        _ => return None,
682    };
683    let css = format!("rgb({r}, {g}, {b})");
684    Color::parse(crate::parse_component_values(&css).first()?)
685}
686
687const FONT_SIZES: &[(&str, f64)] = &[
688    ("xx-small", 9.0),
689    ("x-small", 10.0),
690    ("small", 13.0),
691    ("medium", 16.0),
692    ("large", 18.0),
693    ("x-large", 24.0),
694    ("xx-large", 32.0),
695    ("xxx-large", 48.0),
696];
697
698fn number(v: f64) -> Component<'static> {
699    Component::Number {
700        value: v,
701        integer: v.fract() == 0.0,
702    }
703}
704
705fn compute_value(
706    name: &'static str,
707    c: &[Component<'_>],
708    cx: &Cx<'_>,
709    is_root: bool,
710    parent: Option<&Computed>,
711) -> String {
712    let mut s = String::new();
713    let computed: Vec<Component<'_>> = match (name, c) {
714        ("font-size", [Component::Keyword(k)]) => {
715            let base = cx.parent_font_size;
716            let v = match *k {
717                "larger" => base * 1.2,
718                "smaller" => base / 1.2,
719                k => FONT_SIZES
720                    .iter()
721                    .find(|(n, _)| *n == k)
722                    .map_or(base, |(_, v)| *v),
723            };
724            vec![Component::Dimension(v, Unit::Px)]
725        }
726        ("font-size", _) => components(c, cx, Some(cx.parent_font_size)),
727        ("line-height", _) => components(c, cx, Some(cx.font_size)),
728        ("font-weight", [Component::Keyword(k)]) => {
729            let parent = parent
730                .and_then(|p| p.get("font-weight"))
731                .and_then(|w| w.parse::<f64>().ok())
732                .unwrap_or(400.0);
733            let v = match *k {
734                "normal" => 400.0,
735                "bold" => 700.0,
736                "bolder" if parent < 350.0 => 400.0,
737                "bolder" if parent < 550.0 => 700.0,
738                "bolder" => parent.max(900.0),
739                "lighter" if parent < 100.0 => parent,
740                "lighter" if parent < 550.0 => 100.0,
741                "lighter" if parent < 750.0 => 400.0,
742                "lighter" => 700.0,
743                _ => parent,
744            };
745            vec![number(v)]
746        }
747        ("display", _) => {
748            let mut c = components(c, cx, None);
749            let blockify = is_root
750                || parent.and_then(|p| p.get("display")).is_some_and(|d| {
751                    matches!(d.as_str(), "flex" | "inline-flex" | "grid" | "inline-grid")
752                });
753            if blockify {
754                c = blockified(c);
755            }
756            c
757        }
758        ("opacity" | "fill-opacity" | "stroke-opacity" | "flood-opacity" | "stop-opacity", [_]) => {
759            match &components(c, cx, None)[..] {
760                [Component::Number { value, .. }] => vec![number(value.clamp(0.0, 1.0))],
761                [Component::Percentage(p)] => vec![number((p / 100.0).clamp(0.0, 1.0))],
762                other => other.to_vec(),
763            }
764        }
765        ("object-position" | "background-position" | "mask-position" | "offset-position", _) => {
766            let c = components(c, cx, None);
767            let mut out = Vec::new();
768            for (i, part) in c.split(|x| *x == Component::Literal(',')).enumerate() {
769                if i > 0 {
770                    out.push(Component::Literal(','));
771                }
772                match position(part) {
773                    Some(p) => out.extend(p),
774                    None => out.extend(part.iter().cloned()),
775                }
776            }
777            out
778        }
779        ("background-image" | "mask-image" | "list-style-image" | "border-image-source", _) => {
780            components(c, cx, None).into_iter().map(gradient).collect()
781        }
782        ("filter" | "backdrop-filter", _) => components(c, cx, None)
783            .into_iter()
784            .map(filter_function)
785            .collect(),
786        _ if width_keyword(name) => {
787            let px = |k: &str| match k {
788                "thin" => Some(1.0),
789                "medium" => Some(3.0),
790                "thick" => Some(5.0),
791                _ => None,
792            };
793            match c {
794                [Component::Keyword(k)] if px(k).is_some() => {
795                    vec![Component::Dimension(px(k).unwrap(), Unit::Px)]
796                }
797                _ => components(c, cx, None),
798            }
799        }
800        _ => components(c, cx, None),
801    };
802    write_components(&mut s, &computed).unwrap();
803    s
804}
805
806/// A `<position>` as computed values have it, CSS Values 4 §8.3: two
807/// length-percentages, horizontal first, keywords as percentages and an
808/// offset from the right or bottom as `calc(100% - offset)`.
809fn position<'a>(c: &[Component<'a>]) -> Option<Vec<Component<'a>>> {
810    let kw = |x: &Component<'_>| match x {
811        Component::Keyword(k) => Some(*k),
812        _ => None,
813    };
814    let is_len = |x: &Component<'_>| {
815        matches!(
816            x,
817            Component::Dimension(..) | Component::Percentage(_) | Component::Math(_)
818        )
819    };
820    let axis = |k: &str| match k {
821        "left" | "right" => Some('x'),
822        "top" | "bottom" => Some('y'),
823        "center" => Some('c'),
824        _ => None,
825    };
826    let pct = |k: &str| match k {
827        "left" | "top" => 0.0,
828        "right" | "bottom" => 100.0,
829        _ => 50.0,
830    };
831    // One axis: a keyword, perhaps with an offset from its edge.
832    let side = |k: &str, off: Option<&Component<'a>>| -> Component<'a> {
833        match (k, off) {
834            (_, None) => Component::Percentage(pct(k)),
835            ("left" | "top", Some(o)) => o.clone(),
836            (_, Some(Component::Percentage(p))) => Component::Percentage(100.0 - p),
837            (_, Some(o)) => {
838                let text = format!("calc(100% - {o})");
839                let values = crate::parse_component_values(&text);
840                match values.first() {
841                    Some(crate::ComponentValue::Function(f)) => {
842                        crate::values::Math::parse(f).map_or(o.clone(), Component::Math)
843                    }
844                    _ => o.clone(),
845                }
846            }
847        }
848    };
849    let (x, y) = match c {
850        [a] if is_len(a) => (a.clone(), Component::Percentage(50.0)),
851        [a] => {
852            let k = kw(a)?;
853            match axis(k)? {
854                'y' => (Component::Percentage(50.0), side(k, None)),
855                _ => (side(k, None), Component::Percentage(50.0)),
856            }
857        }
858        [a, b] => {
859            let (ka, kb) = (kw(a), kw(b));
860            match (ka.and_then(axis), kb.and_then(axis)) {
861                (Some('y'), _) | (_, Some('x')) => {
862                    // Written vertical first: swap.
863                    let x = kb.map_or_else(|| b.clone(), |k| side(k, None));
864                    let y = ka.map_or_else(|| a.clone(), |k| side(k, None));
865                    (x, y)
866                }
867                _ => (
868                    ka.map_or_else(|| a.clone(), |k| side(k, None)),
869                    kb.map_or_else(|| b.clone(), |k| side(k, None)),
870                ),
871            }
872        }
873        [a, b, c2] => {
874            // `left 10px center`, `center top 8px` and the like.
875            let (ka, kb, kc) = (kw(a), kw(b), kw(c2));
876            let (first, second) = if is_len(b) {
877                ((ka?, Some(b)), (kc?, None))
878            } else {
879                ((ka?, None), (kb?, Some(c2)))
880            };
881            let (p1, p2) = (side(first.0, first.1), side(second.0, second.1));
882            let vertical_first = axis(first.0) == Some('y') || axis(second.0) == Some('x');
883            if vertical_first { (p2, p1) } else { (p1, p2) }
884        }
885        [a, b, c2, d] => {
886            let (ka, kc) = (kw(a)?, kw(c2)?);
887            let (p1, p2) = (side(ka, Some(b)), side(kc, Some(d)));
888            if axis(ka) == Some('y') {
889                (p2, p1)
890            } else {
891                (p1, p2)
892            }
893        }
894        _ => return None,
895    };
896    Some(vec![x, y])
897}
898
899/// A gradient's computed value: its `at` position computed, and left out
900/// when it's the centre; `from 0deg` left out.
901fn gradient(c: Component<'_>) -> Component<'_> {
902    let Component::Function {
903        name,
904        mut arguments,
905    } = c
906    else {
907        return c;
908    };
909    if !name.ends_with("gradient") {
910        return Component::Function { name, arguments };
911    }
912    let end = arguments
913        .iter()
914        .position(|x| *x == Component::Literal(','))
915        .unwrap_or(arguments.len());
916    if let Some(at) = arguments[..end]
917        .iter()
918        .position(|x| *x == Component::Keyword("at"))
919    {
920        let stop = arguments[at + 1..end]
921            .iter()
922            .position(|x| *x == Component::Keyword("in"))
923            .map_or(end, |i| at + 1 + i);
924        if let Some(p) = position(&arguments[at + 1..stop]) {
925            let center = p == [Component::Percentage(50.0), Component::Percentage(50.0)];
926            if center {
927                arguments.drain(at..stop);
928            } else {
929                arguments.splice(at + 1..stop, p);
930            }
931        }
932    }
933    if let (Some(Component::Keyword("from")), Some(Component::Dimension(v, _))) =
934        (arguments.first(), arguments.get(1))
935        && *v == 0.0
936    {
937        arguments.drain(0..2);
938    }
939    // The default ending shape and size.
940    if let Some(i) = arguments
941        .iter()
942        .position(|x| *x == Component::Keyword("farthest-corner"))
943    {
944        arguments.remove(i);
945    }
946    while arguments.first() == Some(&Component::Literal(',')) {
947        arguments.remove(0);
948    }
949    Component::Function { name, arguments }
950}
951
952/// A filter function's computed value, Filter Effects 1 §6: percentages
953/// as numbers, the defaults written, and the amounts that can't pass 1
954/// held to it.
955fn filter_function(c: Component<'_>) -> Component<'_> {
956    let Component::Function {
957        name,
958        mut arguments,
959    } = c
960    else {
961        return c;
962    };
963    let amount = |args: &[Component<'_>], max: f64| -> Option<Component<'static>> {
964        let v = match args {
965            [] => 1.0,
966            [Component::Number { value, .. }] => *value,
967            [Component::Percentage(p)] => p / 100.0,
968            _ => return None,
969        };
970        Some(number(v.clamp(0.0, max)))
971    };
972    match name {
973        "grayscale" | "invert" | "opacity" | "sepia" => {
974            if let Some(a) = amount(&arguments, 1.0) {
975                arguments = vec![a];
976            }
977        }
978        "brightness" | "contrast" | "saturate" => {
979            if let Some(a) = amount(&arguments, f64::INFINITY) {
980                arguments = vec![a];
981            }
982        }
983        "blur" => {
984            if let [Component::Dimension(v, u)] = &arguments[..] {
985                arguments = vec![Component::Dimension(v.max(0.0), *u)];
986            } else if arguments.is_empty() {
987                arguments = vec![Component::Dimension(0.0, Unit::Px)];
988            }
989        }
990        "hue-rotate" => {
991            if matches!(&arguments[..], [] | [Component::Number { .. }]) {
992                arguments = vec![Component::Dimension(0.0, Unit::Deg)];
993            }
994        }
995        _ => {}
996    }
997    Component::Function { name, arguments }
998}
999
1000/// `display` made a block-level box, CSS Display §2.7, for the root and
1001/// a flex or grid container's children.
1002fn blockified(c: Vec<Component<'_>>) -> Vec<Component<'_>> {
1003    let k = |k| vec![Component::Keyword(k)];
1004    match &c[..] {
1005        [Component::Keyword("inline")]
1006        | [Component::Keyword("inline-block")]
1007        | [Component::Keyword("run-in")] => k("block"),
1008        [Component::Keyword("inline-flex")] => k("flex"),
1009        [Component::Keyword("inline-grid")] => k("grid"),
1010        [Component::Keyword("inline-table")] => k("table"),
1011        [Component::Keyword("contents")] => c,
1012        [Component::Keyword(t)] if t.starts_with("table-") || t.starts_with("ruby") => k("block"),
1013        _ => c,
1014    }
1015}
1016
1017fn width_keyword(name: &str) -> bool {
1018    matches!(
1019        name,
1020        "border-top-width"
1021            | "border-right-width"
1022            | "border-bottom-width"
1023            | "border-left-width"
1024            | "outline-width"
1025            | "column-rule-width"
1026    )
1027}
1028
1029/// A border's width is 0 when its style draws nothing, CSS Backgrounds
1030/// §3.3; an outline's too. Done last, once styles are known.
1031fn fix_up(out: &mut Computed, _is_root: bool, _parent: Option<&Computed>) {
1032    for side in ["top", "right", "bottom", "left"] {
1033        let style = out.get(&format!("border-{side}-style")).unwrap_or_default();
1034        if style == "none" || style == "hidden" {
1035            let w: &'static str = match side {
1036                "top" => "border-top-width",
1037                "right" => "border-right-width",
1038                "bottom" => "border-bottom-width",
1039                _ => "border-left-width",
1040            };
1041            out.values.insert(w, "0px".into());
1042        }
1043    }
1044    if out.get("outline-style").as_deref() == Some("none") {
1045        out.values.insert("outline-width", "0px".into());
1046    }
1047    if matches!(
1048        out.get("column-rule-style").as_deref(),
1049        Some("none" | "hidden")
1050    ) {
1051        out.values.insert("column-rule-width", "0px".into());
1052    }
1053}
1054
1055/// What a pseudo-element's values are beyond the cascade's: `content:
1056/// normal` is `none` on `::before` and `::after`, CSS Content 3 §1; a
1057/// marker's `display` is its list item's position, CSS Lists 3 §3.1.1; and
1058/// a highlight's own properties inherit from its parent element's
1059/// highlight whether they're inherited properties or not, while those
1060/// that don't apply to it are its originating element's, CSS Pseudo 4
1061/// §3.5.
1062pub(super) fn pseudo_fix_up(
1063    out: &mut Computed,
1064    p: &super::Pseudo,
1065    originating: &Computed,
1066    parent_highlight: Option<&Computed>,
1067) {
1068    use super::Pseudo;
1069    match p {
1070        Pseudo::Before | Pseudo::After => {
1071            if out.get("content").as_deref() == Some("normal") {
1072                out.values.insert("content", "none".into());
1073            }
1074        }
1075        Pseudo::Marker => {
1076            let inside = originating.get("list-style-position").as_deref() == Some("inside");
1077            out.values
1078                .insert("display", if inside { "inline" } else { "block" }.into());
1079        }
1080        Pseudo::Selection | Pseudo::Highlight(_) => {
1081            for q in crate::values::properties() {
1082                if q.is_shorthand() || q.alias_of.is_some() {
1083                    continue;
1084                }
1085                let name = q.name;
1086                let value = if super::pseudo::highlight_applies(name) {
1087                    if out.keys.contains_key(name) {
1088                        continue;
1089                    }
1090                    // The root's inherits `color` from the element; the
1091                    // rest start over.
1092                    match parent_highlight {
1093                        Some(h) => h.values.get(name).cloned(),
1094                        None if name == "color" => continue,
1095                        None => None,
1096                    }
1097                } else {
1098                    originating.values.get(name).cloned()
1099                };
1100                match value {
1101                    Some(v) => out.values.insert(name, v),
1102                    None => out.values.remove(name),
1103                };
1104            }
1105            out.font_size = originating.font_size;
1106        }
1107        _ => {}
1108    }
1109}