Skip to main content

uzor/ui/
style.rs

1//! Declarative style layer (DOM-like roadmap item 1): a small CSS subset that widgets and
2//! apps resolve instead of hard-coding colours and metrics.
3//!
4//! ```
5//! use uzor::ui::style::{Sheet, Node, State};
6//! let sheet = Sheet::parse(":root{--acc:#3b82f6} .btn{padding:5px 12px;border-radius:8px}
7//!     .btn:hover{background:#26262b} #send{background:var(--acc)}").unwrap();
8//! let s = sheet.resolve(&Node::new("button").id("send").class("btn").state(State::HOVER), None);
9//! assert_eq!(s.background.as_deref(), Some("#3b82f6")); // id beats :hover
10//! assert_eq!(s.padding, Some([5.0, 12.0, 5.0, 12.0]));
11//! ```
12//!
13//! Supported: compound selectors (`kind`, `#id`, `.class`, `:hover`, `:active`,
14//! `:focus-visible`, `:disabled`, `*`), selector lists, `:root` custom properties with
15//! `var(--name[, fallback])`, and cascade by specificity then source order. Inherited
16//! properties (`color`, `font-*`, `line-height`) come from the parent's resolved style.
17
18use std::collections::HashMap;
19
20/// Interaction state flags a selector can test.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub struct State(u8);
23
24impl State {
25    pub const NONE: State = State(0);
26    pub const HOVER: State = State(1);
27    pub const ACTIVE: State = State(2);
28    pub const FOCUS_VISIBLE: State = State(4);
29    pub const DISABLED: State = State(8);
30    /// `:checked` (a switch, checkbox or radio that is on).
31    pub const CHECKED: State = State(16);
32    /// `:focus` (the element holds keyboard focus, however it got it).
33    pub const FOCUS: State = State(32);
34    pub fn contains(self, o: State) -> bool {
35        self.0 & o.0 == o.0
36    }
37}
38
39impl std::ops::BitOr for State {
40    type Output = State;
41    fn bitor(self, o: State) -> State {
42        State(self.0 | o.0)
43    }
44}
45
46/// What a selector matches against: a widget's kind, id, classes and state.
47#[derive(Clone, Debug, Default)]
48pub struct Node<'a> {
49    pub kind: &'a str,
50    pub id: Option<&'a str>,
51    pub classes: Vec<&'a str>,
52    pub state: State,
53}
54
55impl<'a> Node<'a> {
56    pub fn new(kind: &'a str) -> Self {
57        Node { kind, ..Default::default() }
58    }
59    /// A node from a selector-like spec: `span.tq-pill.ok#x:hover`.
60    pub fn parse(spec: &'a str) -> Self {
61        let head = spec.find(['#', '.', ':']).unwrap_or(spec.len());
62        let mut n = Node::new(&spec[..head]);
63        let mut rest = &spec[head..];
64        while !rest.is_empty() {
65            let (sig, body) = rest.split_at(1);
66            let end = body.find(['#', '.', ':']).unwrap_or(body.len());
67            let name = &body[..end];
68            match sig {
69                "#" => n.id = Some(name),
70                "." => n.classes.push(name),
71                _ => {
72                    n.state = n.state
73                        | match name {
74                            "hover" => State::HOVER,
75                            "active" => State::ACTIVE,
76                            "focus-visible" => State::FOCUS_VISIBLE,
77                            "disabled" => State::DISABLED,
78                            "checked" => State::CHECKED,
79                            "focus" => State::FOCUS,
80                            _ => State::NONE,
81                        }
82                }
83            }
84            rest = &body[end..];
85        }
86        n
87    }
88    pub fn id(mut self, id: &'a str) -> Self {
89        self.id = Some(id);
90        self
91    }
92    pub fn class(mut self, c: &'a str) -> Self {
93        self.classes.push(c);
94        self
95    }
96    pub fn state(mut self, s: State) -> Self {
97        self.state = self.state | s;
98        self
99    }
100}
101
102/// A resolved style. `None` = not set (the widget's default applies).
103#[derive(Clone, Debug, Default, PartialEq)]
104pub struct Style {
105    pub color: Option<String>,
106    pub background: Option<String>,
107    pub border_color: Option<String>,
108    pub border_width: Option<f64>,
109    /// top, right, bottom, left
110    pub padding: Option<[f64; 4]>,
111    pub margin: Option<[f64; 4]>,
112    pub border_radius: Option<f64>,
113    pub font_size: Option<f64>,
114    pub font_weight: Option<u32>,
115    /// px (a unitless multiplier resolves against the font size).
116    pub line_height: Option<f64>,
117    pub font_family: Option<String>,
118    /// `font-metrics` (inherited): `auto` centres each face's own ascent+descent in
119    /// the line box (browser behaviour); unset/`inter` keeps the catalog's Inter
120    /// metrics for every family, so existing layouts are unchanged unless opted in.
121    pub font_metrics: Option<String>,
122    pub opacity: Option<f64>,
123    pub width: Option<f64>,
124    pub height: Option<f64>,
125    /// `gap` (both axes) / `column-gap`.
126    pub gap: Option<f64>,
127    /// `row-gap` (the first value of a two-value `gap`); `None` = same as `gap`.
128    pub row_gap: Option<f64>,
129    pub min_width: Option<f64>,
130    pub max_width: Option<f64>,
131    pub min_height: Option<f64>,
132    pub max_height: Option<f64>,
133    /// `block` (default), `flex`, `grid`, `none`.
134    pub display: Option<String>,
135    /// `row` (default) / `column`.
136    pub flex_direction: Option<String>,
137    pub flex_wrap: Option<String>,
138    pub justify_content: Option<String>,
139    pub align_items: Option<String>,
140    pub align_self: Option<String>,
141    pub flex_grow: Option<f64>,
142    pub flex_shrink: Option<f64>,
143    /// `None` = `auto`.
144    pub flex_basis: Option<f64>,
145    /// Raw `grid-template-columns` (parsed by `ui::flow`).
146    pub grid_template_columns: Option<String>,
147    pub box_shadow: Option<String>,
148    /// `background-clip` (not inherited): `padding-box` / `content-box` keep the
149    /// background off the border (and the padding); unset = `border-box`.
150    pub background_clip: Option<String>,
151    pub cursor: Option<String>,
152    /// `touch-action` (not inherited). `none`: a finger that lands on the element is
153    /// the element's (gestures, no scrolling), see [`crate::ui::dom::Placed::captures_touch`].
154    pub touch_action: Option<String>,
155    /// `object-fit` (not inherited) of a raster element ([`crate::ui::dom::El::image`]):
156    /// `fill` (unset), `contain`, `cover`, `none`, `scale-down`.
157    pub object_fit: Option<String>,
158    pub text_align: Option<String>,
159    /// `white-space` (inherited): `normal` lets [`crate::ui::dom`] text wrap; unset or
160    /// `nowrap` keeps one line (ellipsized when it does not fit).
161    pub white_space: Option<String>,
162    /// `line-clamp` / `-webkit-line-clamp`: wrapping text keeps at most this many lines,
163    /// the last one ends in an ellipsis.
164    pub line_clamp: Option<u16>,
165    /// Custom properties (`--name: value`) set on the element or inherited, as in CSS.
166    pub custom: std::collections::BTreeMap<String, String>,
167    /// `transition` entries (see [`crate::ui::motion`]).
168    pub transitions: Vec<super::motion::Transition>,
169    /// `animation` entries naming `@keyframes` (see [`crate::ui::motion`]).
170    pub animations: Vec<super::motion::Animation>,
171    /// `position`: `static` (unset), `relative`, `absolute`. An absolute box leaves the
172    /// flow and is placed against its nearest positioned ancestor's padding box
173    /// (see [`crate::ui::flow`]); a relative one is shifted by its insets.
174    pub position: Option<String>,
175    /// `top` (px), with `right` / `bottom` / `left` the insets of a positioned box.
176    pub top: Option<f64>,
177    pub right: Option<f64>,
178    pub bottom: Option<f64>,
179    pub left: Option<f64>,
180    /// `z-index` of a positioned box: higher paints (and hit-tests) on top.
181    pub z_index: Option<i32>,
182    /// Per-corner radii `[horizontal, vertical]` in the order top-left, top-right,
183    /// bottom-right, bottom-left, set by a multi-value or elliptical (`a / b`)
184    /// `border-radius` or the `border-*-*-radius` longhands. `None`: every corner is
185    /// [`Style::border_radius`]. Read both through [`Style::radii`].
186    pub border_radii: Option<[[f64; 2]; 4]>,
187    /// Per-side border widths (top, right, bottom, left), set by a multi-value
188    /// `border-width` or the `border-<side>[-width]` longhands. `None`: every side is
189    /// [`Style::border_width`]. Read both through [`Style::border_edges`].
190    pub border_widths: Option<[f64; 4]>,
191    /// Per-side border colours (top, right, bottom, left); `None` sides and a `None`
192    /// list fall back to [`Style::border_color`]. Read through [`Style::border_side_color`].
193    pub border_colors: Option<[Option<String>; 4]>,
194    /// `font-style` (inherited): `italic` / `oblique` slant the font.
195    pub font_style: Option<String>,
196    /// `overflow-wrap` (inherited): `anywhere` / `break-word` let inline runs
197    /// ([`crate::ui::dom::El::runs`]) break inside a word that does not fit a line.
198    pub overflow_wrap: Option<String>,
199    /// `overflow` (`hidden` / `clip` / `auto` / `scroll` clip descendants to the padding
200    /// box; scrolling itself is the host's, see [`crate::ui::dom::Dom::moved`]).
201    pub overflow: Option<String>,
202    /// `scrollbar-width` (not inherited): `none` hides the scrollbar of a scroll
203    /// container the host scrolls (the wheel, touch and keys still move it), for an app
204    /// that draws its own bar; unset / `auto` / `thin` keep the host's.
205    pub scrollbar_width: Option<String>,
206    /// `shape-rendering` (inherited, as in SVG): `geometricPrecision` draws an element's
207    /// [`crate::ui::dom::El::svg`] icon exactly (no pixel-grid snapping of its origin or
208    /// strokes); unset / `auto` / `crispEdges` snap for crispness.
209    pub shape_rendering: Option<String>,
210    /// `width: N%`: a fraction (0.5 for `50%`) of the containing block's width, used when
211    /// [`Style::width`] is unset. See [`crate::ui::flow`].
212    pub width_pct: Option<f64>,
213    /// `height: N%`: a fraction of the containing block's height when that height is
214    /// definite; otherwise the height is `auto`.
215    pub height_pct: Option<f64>,
216    /// `max-width: N%`: a fraction of the containing block's width.
217    pub max_width_pct: Option<f64>,
218    /// `min-width: N%`: a fraction of the containing block's width.
219    pub min_width_pct: Option<f64>,
220    /// `aspect-ratio` as width / height (`16 / 9` → 1.777…): a box with an auto height
221    /// takes `width / ratio`; with only a height, an auto width takes `height × ratio`.
222    pub aspect_ratio: Option<f64>,
223    /// `border-style` (`solid` when unset): `dashed` and `dotted` stroke the border with a
224    /// dash pattern, `none` / `hidden` draw no border.
225    pub border_style: Option<String>,
226    /// `backdrop-filter: blur(N)` (or `-webkit-backdrop-filter`): the pixels already
227    /// painted under the box are blurred with this radius (px) before its background,
228    /// so a translucent background reads as frosted glass. Backends without a readable
229    /// backdrop leave the pixels as they are (the translucent fill alone).
230    pub backdrop_blur: Option<f64>,
231}
232
233impl Style {
234    /// A custom property of the element (`--name`), e.g. a widget-specific knob.
235    pub fn custom(&self, name: &str) -> Option<&str> {
236        self.custom.get(name).map(String::as_str)
237    }
238    /// The custom property for a [`styled!`] field: `pad_x` reads `--pad-x`. One shared body,
239    /// so each styled field costs a call rather than its own name rewrite.
240    #[doc(hidden)]
241    #[inline(never)]
242    pub fn field_css(&self, field: &str) -> Option<&str> {
243        self.custom(&format!("--{}", field.replace('_', "-")))
244    }
245    /// The colour, or `fallback` when unset.
246    pub fn color_or<'a>(&'a self, fallback: &'a str) -> &'a str {
247        self.color.as_deref().unwrap_or(fallback)
248    }
249    /// The background, or `fallback` when unset.
250    pub fn background_or<'a>(&'a self, fallback: &'a str) -> &'a str {
251        self.background.as_deref().unwrap_or(fallback)
252    }
253    /// Padding (top, right, bottom, left), zero when unset.
254    pub fn pad(&self) -> [f64; 4] {
255        self.padding.unwrap_or_default()
256    }
257    /// Margin (top, right, bottom, left), zero when unset.
258    pub fn mar(&self) -> [f64; 4] {
259        self.margin.unwrap_or_default()
260    }
261    /// Font size in px (16 when unset, the CSS initial value).
262    pub fn px(&self) -> f64 {
263        self.font_size.unwrap_or(16.0)
264    }
265    /// Line height in px (`normal` ≈ 1.2 × font size when unset).
266    pub fn lh(&self) -> f64 {
267        self.line_height.unwrap_or(self.px() * 1.2)
268    }
269    /// Font weight (400 when unset).
270    pub fn weight(&self) -> u32 {
271        self.font_weight.unwrap_or(400)
272    }
273    /// Border widths (top, right, bottom, left): the per-side widths, else
274    /// `border-width` on every side, else zero.
275    pub fn border_edges(&self) -> [f64; 4] {
276        self.border_widths.unwrap_or([self.border_width.unwrap_or(0.0); 4])
277    }
278    /// The border colour of side `i` (0 top, 1 right, 2 bottom, 3 left).
279    pub fn border_side_color(&self, i: usize) -> Option<&str> {
280        self.border_colors.as_ref().and_then(|c| c.get(i)?.as_deref()).or(self.border_color.as_deref())
281    }
282    /// Corner radii `[horizontal, vertical]` (top-left, top-right, bottom-right,
283    /// bottom-left): the per-corner radii, else `border-radius` on every corner.
284    pub fn radii(&self) -> [[f64; 2]; 4] {
285        self.border_radii.unwrap_or_else(|| {
286            let r = self.border_radius.unwrap_or(0.0);
287            [[r, r]; 4]
288        })
289    }
290    /// How far in from the border box the background starts on each side (top,
291    /// right, bottom, left): nothing for `border-box` (the default), the border for
292    /// `padding-box`, border and padding for `content-box`.
293    pub fn background_inset(&self) -> Option<[f64; 4]> {
294        let e = self.border_edges();
295        match self.background_clip.as_deref() {
296            Some("padding-box") => Some(e),
297            Some("content-box") => {
298                let p = self.pad();
299                Some([e[0] + p[0], e[1] + p[1], e[2] + p[2], e[3] + p[3]])
300            }
301            _ => None,
302        }
303    }
304    /// `position` is `relative`, `absolute`, `fixed` or `sticky` (a containing block
305    /// for absolutely positioned descendants).
306    pub fn positioned(&self) -> bool {
307        matches!(self.position.as_deref(), Some("relative" | "absolute" | "fixed" | "sticky"))
308    }
309    /// `position: absolute` (or `fixed`): out of the flow.
310    pub fn out_of_flow(&self) -> bool {
311        matches!(self.position.as_deref(), Some("absolute" | "fixed"))
312    }
313    /// `overflow` other than `visible`: descendants are clipped to the padding box.
314    pub fn clips(&self) -> bool {
315        matches!(self.overflow.as_deref(), Some("hidden" | "clip" | "auto" | "scroll"))
316    }
317    /// `position: fixed`: placed against the viewport and left where it is when the
318    /// tree scrolls ([`crate::ui::dom::Dom::moved`]).
319    pub fn fixed(&self) -> bool {
320        self.position.as_deref() == Some("fixed")
321    }
322    /// The border is drawn (`border-style` is not `none` / `hidden`).
323    pub fn border_drawn(&self) -> bool {
324        !matches!(self.border_style.as_deref(), Some("none" | "hidden"))
325    }
326    /// The dash pattern of the border for a stroke `w` wide: `dashed` 3w on 3w off (CSS
327    /// does not fix the ratio; this is what Chromium draws for thin borders), `dotted`
328    /// w on w off, otherwise solid (`None`).
329    pub fn border_dash(&self, w: f64) -> Option<[f64; 2]> {
330        let w = w.max(1.0);
331        match self.border_style.as_deref() {
332            Some("dashed") => Some([3.0 * w, 3.0 * w]),
333            Some("dotted") => Some([w, w]),
334            _ => None,
335        }
336    }
337}
338
339/// The radius of a `blur(N)` in a `backdrop-filter` value (`none` and other filters: `None`).
340fn backdrop_blur(v: &str) -> Option<f64> {
341    let i = v.find("blur(")?;
342    let rest = &v[i + 5..];
343    let n = rest[..rest.find(')')?].trim();
344    let n = n.strip_suffix("px").unwrap_or(n).trim();
345    n.parse::<f64>().ok().filter(|r| r.is_finite() && *r > 0.0).map(|r| r.min(200.0))
346}
347
348/// A string with `'static` lifetime for the `&'static str` fields of widget style
349/// structs. Each distinct value is leaked once and reused, so a stable sheet costs a
350/// bounded amount of memory.
351pub fn intern(s: &str) -> &'static str {
352    use std::collections::HashSet;
353    use std::sync::{Mutex, OnceLock};
354    static POOL: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
355    let mut pool = POOL.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
356    if let Some(v) = pool.get(s) {
357        return v;
358    }
359    let v: &'static str = Box::leak(s.to_string().into_boxed_str());
360    pool.insert(v);
361    v
362}
363
364/// A parse error with the offending text.
365#[derive(Clone, Debug, PartialEq)]
366pub struct StyleError(pub String);
367
368impl std::fmt::Display for StyleError {
369    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370        write!(f, "style: {}", self.0)
371    }
372}
373
374impl std::error::Error for StyleError {}
375
376/// A complex selector: compounds joined by descendant (` `) or child (`>`) combinators,
377/// the last compound is the subject.
378#[derive(Clone, Debug, PartialEq)]
379struct Selector {
380    parts: Vec<Compound>,
381    /// `child[i]`: the combinator between `parts[i]` and `parts[i + 1]` is `>`.
382    child: Vec<bool>,
383}
384
385impl Selector {
386    fn parse(s: &str) -> Result<Selector, StyleError> {
387        let s = s.trim();
388        if s.is_empty() {
389            return Err(StyleError("empty selector".into()));
390        }
391        let spaced = s.replace('>', " > ");
392        let mut parts = Vec::new();
393        let mut child = Vec::new();
394        let mut pending_child = false;
395        for tok in spaced.split_whitespace() {
396            if tok == ">" {
397                if parts.is_empty() || pending_child {
398                    return Err(StyleError(format!("unsupported selector `{s}`")));
399                }
400                pending_child = true;
401                continue;
402            }
403            if !parts.is_empty() {
404                child.push(pending_child);
405            }
406            pending_child = false;
407            parts.push(Compound::parse(tok)?);
408        }
409        if pending_child || parts.is_empty() {
410            return Err(StyleError(format!("unsupported selector `{s}`")));
411        }
412        Ok(Selector { parts, child })
413    }
414    /// CSS specificity (ids, classes + pseudo-classes, kinds), summed over the compounds.
415    fn specificity(&self) -> (u32, u32, u32) {
416        self.parts.iter().map(Compound::specificity).fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
417    }
418    /// A one-compound selector matching `n` (a complex one needs [`Selector::matches_in`]).
419    fn matches(&self, n: &Node<'_>) -> bool {
420        self.parts.len() == 1 && self.parts[0].matches(n)
421    }
422    /// Match `n` whose ancestors are `up` (root first, parent last).
423    fn matches_in(&self, n: &Node<'_>, up: &[Node<'_>]) -> bool {
424        let last = self.parts.len() - 1;
425        self.parts[last].matches(n) && Self::rest(&self.parts[..last], &self.child, up)
426    }
427    /// `parts` (the compounds left of a matched element) against the ancestors `up`;
428    /// `child[parts.len() - 1]` joins the last of `parts` to the element matched before.
429    fn rest(parts: &[Compound], child: &[bool], up: &[Node<'_>]) -> bool {
430        let Some((c, before)) = parts.split_last() else { return true };
431        if child[parts.len() - 1] {
432            // `>`: the parent must match.
433            match up.split_last() {
434                Some((p, above)) => c.matches(p) && Self::rest(before, child, above),
435                None => false,
436            }
437        } else {
438            // descendant: any ancestor, nearest first, with backtracking.
439            (0..up.len()).rev().any(|i| c.matches(&up[i]) && Self::rest(before, child, &up[..i]))
440        }
441    }
442}
443
444#[derive(Clone, Debug, PartialEq)]
445struct Compound {
446    kind: Option<String>,
447    id: Option<String>,
448    classes: Vec<String>,
449    state: State,
450}
451
452impl Compound {
453    fn parse(s: &str) -> Result<Compound, StyleError> {
454        let mut sel = Compound { kind: None, id: None, classes: vec![], state: State::NONE };
455        let mut rest = s;
456        let head_end = rest.find(['#', '.', ':']).unwrap_or(rest.len());
457        let head = &rest[..head_end];
458        if !head.is_empty() && head != "*" {
459            sel.kind = Some(head.to_string());
460        }
461        rest = &rest[head_end..];
462        while !rest.is_empty() {
463            let (sig, body) = rest.split_at(1);
464            let end = body.find(['#', '.', ':']).unwrap_or(body.len());
465            let name = &body[..end];
466            if name.is_empty() {
467                return Err(StyleError(format!("empty name in `{s}`")));
468            }
469            match sig {
470                "#" => sel.id = Some(name.to_string()),
471                "." => sel.classes.push(name.to_string()),
472                _ => {
473                    sel.state = sel.state
474                        | match name {
475                            "hover" => State::HOVER,
476                            "active" => State::ACTIVE,
477                            "focus-visible" => State::FOCUS_VISIBLE,
478                            "disabled" => State::DISABLED,
479                            "checked" => State::CHECKED,
480                            "focus" => State::FOCUS,
481                            o => return Err(StyleError(format!("unsupported pseudo-class `:{o}`"))),
482                        }
483                }
484            }
485            rest = &body[end..];
486        }
487        Ok(sel)
488    }
489    /// CSS specificity (ids, classes + pseudo-classes, kinds).
490    fn specificity(&self) -> (u32, u32, u32) {
491        (self.id.is_some() as u32, self.classes.len() as u32 + self.state.0.count_ones(), self.kind.is_some() as u32)
492    }
493    fn matches(&self, n: &Node<'_>) -> bool {
494        self.kind.as_deref().is_none_or(|k| k == n.kind)
495            && self.id.as_deref().is_none_or(|i| n.id == Some(i))
496            && self.classes.iter().all(|c| n.classes.contains(&c.as_str()))
497            && n.state.contains(self.state)
498    }
499}
500
501#[derive(Clone, Debug)]
502struct Rule {
503    sel: Selector,
504    src: String,
505    order: usize,
506    decls: Vec<(String, String)>,
507}
508
509/// One applied declaration, as reported by [`Sheet::resolve_traced`].
510#[derive(Clone, Debug, PartialEq)]
511pub struct Applied {
512    pub property: String,
513    pub value: String,
514    pub selector: String,
515}
516
517/// Parse an inline `style="..."` declaration list into a [`Style`] (no cascade, no vars).
518pub fn inline(decls: &str) -> Style {
519    let mut s = Style::default();
520    for d in decls.split(';') {
521        if let Some((k, v)) = d.split_once(':') {
522            apply(&mut s, &k.trim().to_ascii_lowercase(), v.trim());
523        }
524    }
525    s
526}
527
528/// A parsed style sheet.
529#[derive(Debug, Default)]
530pub struct Sheet {
531    rules: Vec<Rule>,
532    vars: HashMap<String, String>,
533    keyframes: HashMap<String, super::motion::Keyframes>,
534    cache: std::sync::Mutex<HashMap<String, Style>>,
535}
536
537impl Clone for Sheet {
538    fn clone(&self) -> Self {
539        Sheet { rules: self.rules.clone(), vars: self.vars.clone(), keyframes: self.keyframes.clone(), cache: Default::default() }
540    }
541}
542
543impl Sheet {
544    /// Parse a CSS subset. `/* comments */` are skipped. `@media` blocks and `env()`
545    /// are evaluated against [`super::media::current`] (see [`Sheet::parse_with`]).
546    pub fn parse(css: &str) -> Result<Sheet, StyleError> {
547        Self::parse_with(css, &super::media::current())
548    }
549
550    /// [`Sheet::parse`] against an explicit media environment: rules inside
551    /// `@media <query> { ... }` apply when the query matches `env` (in source order
552    /// with the rules around them), and `env(safe-area-inset-*)` /
553    /// `env(keyboard-inset-height)` become px values.
554    pub fn parse_with(css: &str, env: &super::media::MediaEnv) -> Result<Sheet, StyleError> {
555        let mut src = String::with_capacity(css.len());
556        let mut rest = css;
557        while let Some(i) = rest.find("/*") {
558            src.push_str(&rest[..i]);
559            rest = rest[i..].find("*/").map(|j| &rest[i + j + 2..]).ok_or_else(|| StyleError("unclosed comment".into()))?;
560        }
561        src.push_str(rest);
562        let mut sheet = Sheet::default();
563        sheet.parse_into(&src, env)?;
564        Ok(sheet)
565    }
566
567    fn parse_into(&mut self, src: &str, env: &super::media::MediaEnv) -> Result<(), StyleError> {
568        let sheet = self;
569        let mut rest = src;
570        let block_end = |rest: &str, open: usize| -> Result<usize, StyleError> {
571            let mut depth = 0;
572            rest[open..]
573                .char_indices()
574                .find(|&(_, c)| {
575                    depth += (c == '{') as i32 - (c == '}') as i32;
576                    depth == 0
577                })
578                .map(|(i, _)| open + i)
579                .ok_or_else(|| StyleError("missing `}`".into()))
580        };
581        while let Some(open) = rest.find('{') {
582            if let Some(name) = rest[..open].trim().strip_prefix("@keyframes") {
583                // Nested block: find the brace that closes it.
584                let close = block_end(rest, open)?;
585                let kf = super::motion::Keyframes::parse(&rest[open + 1..close]).ok_or_else(|| StyleError(format!("bad @keyframes `{}`", name.trim())))?;
586                sheet.keyframes.insert(name.trim().to_string(), kf);
587                rest = &rest[close + 1..];
588                continue;
589            }
590            if let Some(query) = rest[..open].trim().strip_prefix("@media") {
591                let close = block_end(rest, open)?;
592                if env.matches(query) {
593                    sheet.parse_into(&rest[open + 1..close], env)?;
594                }
595                rest = &rest[close + 1..];
596                continue;
597            }
598            let close = rest[open..].find('}').map(|c| open + c).ok_or_else(|| StyleError("missing `}`".into()))?;
599            let sels = &rest[..open];
600            let decls: Vec<(String, String)> = rest[open + 1..close]
601                .split(';')
602                .filter(|d| !d.trim().is_empty())
603                .map(|d| {
604                    let (k, v) = d.split_once(':').ok_or_else(|| StyleError(format!("bad declaration `{}`", d.trim())))?;
605                    Ok((k.trim().to_ascii_lowercase(), env.units(&env.substitute(v.trim()))))
606                })
607                .collect::<Result<_, StyleError>>()?;
608            for s in sels.split(',') {
609                if s.trim() == ":root" {
610                    for (k, v) in &decls {
611                        if k.starts_with("--") {
612                            sheet.vars.insert(k.clone(), v.clone());
613                        }
614                    }
615                    continue;
616                }
617                let order = sheet.rules.len();
618                sheet.rules.push(Rule { sel: Selector::parse(s)?, src: s.trim().to_string(), order, decls: decls.clone() });
619            }
620            rest = &rest[close + 1..];
621        }
622        if !rest.trim().is_empty() {
623            return Err(StyleError(format!("trailing text `{}`", rest.trim())));
624        }
625        Ok(())
626    }
627
628    /// The `@keyframes` rule called `name`.
629    pub fn keyframes(&self, name: &str) -> Option<&super::motion::Keyframes> {
630        self.keyframes.get(name)
631    }
632
633    /// A custom property (`--name`) with `var()` references resolved.
634    pub fn var(&self, name: &str) -> Option<String> {
635        self.vars.get(name).map(|v| self.subst(v, 0))
636    }
637
638    /// [`Sheet::var`] interned for `&'static str` style fields; `fallback` when unset.
639    pub fn var_static(&self, name: &str, fallback: &'static str) -> &'static str {
640        self.var(name).map(|v| intern(&v)).unwrap_or(fallback)
641    }
642
643    /// The style of a parentless element given as a spec (`span.tq-pill.ok`), cached.
644    pub fn el(&self, spec: &str) -> Style {
645        if let Some(s) = self.cache.lock().unwrap_or_else(|e| e.into_inner()).get(spec) {
646            return s.clone();
647        }
648        let s = self.resolve(&Node::parse(spec), None);
649        self.cache.lock().unwrap_or_else(|e| e.into_inner()).insert(spec.to_string(), s.clone());
650        s
651    }
652
653    /// [`Sheet::resolve`] for a registered widget: with the `inspector` feature the
654    /// matched declarations are kept under `widget` for the inspector panel.
655    pub fn resolve_for(&self, widget: &str, n: &Node<'_>, parent: Option<&Style>) -> Style {
656        #[cfg(feature = "inspector")]
657        {
658            let (s, tr) = self.resolve_traced(n, parent);
659            trace::record(widget, tr);
660            s
661        }
662        #[cfg(not(feature = "inspector"))]
663        {
664            let _ = widget;
665            self.resolve(n, parent)
666        }
667    }
668
669    /// [`Sheet::el`] for a registered widget (see [`Sheet::resolve_for`]).
670    pub fn el_for(&self, widget: &str, spec: &str) -> Style {
671        #[cfg(feature = "inspector")]
672        trace::record(widget, self.resolve_traced(&Node::parse(spec), None).1);
673        #[cfg(not(feature = "inspector"))]
674        let _ = widget;
675        self.el(spec)
676    }
677
678    /// `v` with `var()` resolved against an element's custom properties, then the sheet's.
679    pub(crate) fn subst_with(&self, v: &str, local: &std::collections::BTreeMap<String, String>) -> String {
680        self.subst_in(v, 0, Some(local))
681    }
682
683    fn subst(&self, v: &str, depth: u32) -> String {
684        self.subst_in(v, depth, None)
685    }
686
687    fn subst_in(&self, v: &str, depth: u32, local: Option<&std::collections::BTreeMap<String, String>>) -> String {
688        let Some(i) = v.find("var(") else { return v.to_string() };
689        let Some(j) = v[i..].find(')').map(|j| i + j) else { return v.to_string() };
690        let inner = &v[i + 4..j];
691        let (name, fb) = inner.split_once(',').map(|(a, b)| (a.trim(), Some(b.trim()))).unwrap_or((inner.trim(), None));
692        let found = local.and_then(|l| l.get(name)).or_else(|| self.vars.get(name));
693        let val = if depth > 8 { None } else { found.map(|x| self.subst_in(x, depth + 1, local)) };
694        let val = val.or(fb.map(str::to_string)).unwrap_or_default();
695        format!("{}{}{}", &v[..i], val, self.subst_in(&v[j + 1..], depth, local))
696    }
697
698    /// Cascade every matching rule (specificity, then source order) over the inherited
699    /// properties of `parent`.
700    pub fn resolve(&self, n: &Node<'_>, parent: Option<&Style>) -> Style {
701        self.resolve_traced(n, parent).0
702    }
703
704    /// [`Sheet::resolve`] plus, per applied declaration in cascade order, the property, its
705    /// substituted value and the selector of the rule it came from (what an inspector shows).
706    pub fn resolve_traced(&self, n: &Node<'_>, parent: Option<&Style>) -> (Style, Vec<Applied>) {
707        self.resolve_traced_in(n, &[], parent)
708    }
709
710    /// [`Sheet::resolve`] for an element whose ancestors are `up` (root first, parent last),
711    /// so descendant (`.a .b`) and child (`.a > .b`) selectors can match. Without
712    /// ancestors (`resolve`, `el`) only one-compound selectors apply.
713    pub fn resolve_in(&self, n: &Node<'_>, up: &[Node<'_>], parent: Option<&Style>) -> Style {
714        self.resolve_traced_in(n, up, parent).0
715    }
716
717    /// The sheet has a selector with a combinator (descendant / child), so callers that
718    /// do not track ancestors may want to.
719    pub fn has_complex(&self) -> bool {
720        self.rules.iter().any(|r| r.sel.parts.len() > 1)
721    }
722
723    /// [`Sheet::resolve_traced`] with ancestors (see [`Sheet::resolve_in`]).
724    pub fn resolve_traced_in(&self, n: &Node<'_>, up: &[Node<'_>], parent: Option<&Style>) -> (Style, Vec<Applied>) {
725        self.resolve_full(n, up, parent, &[])
726    }
727
728    /// [`Sheet::resolve_in`] for an element with inline custom properties (`--name`,
729    /// from a `style` attribute): they override the sheet's for the element, so its own
730    /// sheet declarations (`color: var(--fg)`) already see them, like the browser.
731    pub fn resolve_with_inline(&self, n: &Node<'_>, up: &[Node<'_>], parent: Option<&Style>, inline: &[(&str, &str)]) -> Style {
732        self.resolve_full(n, up, parent, inline).0
733    }
734
735    fn resolve_full(&self, n: &Node<'_>, up: &[Node<'_>], parent: Option<&Style>, inline: &[(&str, &str)]) -> (Style, Vec<Applied>) {
736        let mut trace = Vec::new();
737        let mut s = Style::default();
738        if let Some(p) = parent {
739            s.color = p.color.clone();
740            s.font_size = p.font_size;
741            s.font_weight = p.font_weight;
742            s.font_family = p.font_family.clone();
743            s.font_metrics = p.font_metrics.clone();
744            s.line_height = p.line_height;
745            s.text_align = p.text_align.clone();
746            s.white_space = p.white_space.clone();
747            s.font_style = p.font_style.clone();
748            s.overflow_wrap = p.overflow_wrap.clone();
749            s.shape_rendering = p.shape_rendering.clone();
750            s.custom = p.custom.clone();
751        }
752        let mut hits: Vec<&Rule> = self.rules.iter().filter(|r| if up.is_empty() { r.sel.matches(n) } else { r.sel.matches_in(n, up) }).collect();
753        crate::sort::sort_by_key(&mut hits, |r| (r.sel.specificity(), r.order));
754        // Custom properties first (they cascade, then every var() sees the element's values).
755        for r in &hits {
756            for (k, v) in &r.decls {
757                if k.starts_with("--") {
758                    s.custom.insert(k.clone(), v.clone());
759                }
760            }
761        }
762        for (k, v) in inline {
763            if k.starts_with("--") {
764                s.custom.insert(k.to_string(), v.to_string());
765            }
766        }
767        let local = std::mem::take(&mut s.custom);
768        // Inserts, not `collect`: a bulk-built map pulls in a whole stable sort of `(String, String)`.
769        for (k, v) in &local {
770            s.custom.insert(k.clone(), self.subst_in(v, 0, Some(&local)));
771        }
772        let mut lh_raw: Option<String> = None;
773        for r in hits {
774            for (k, v) in &r.decls {
775                let v = self.subst_in(v, 0, Some(&s.custom));
776                if k.starts_with("--") {
777                    trace.push(Applied { property: k.clone(), value: v, selector: r.src.clone() });
778                    continue;
779                }
780                if k == "line-height" {
781                    lh_raw = Some(v.clone());
782                }
783                apply(&mut s, k, &v);
784                trace.push(Applied { property: k.clone(), value: v, selector: r.src.clone() });
785            }
786        }
787        // A unitless line-height multiplies the final font size.
788        if let Some(raw) = lh_raw {
789            if let Ok(m) = raw.trim().parse::<f64>() {
790                s.line_height = Some(m * s.font_size.unwrap_or(16.0));
791            }
792        }
793        (s, trace)
794    }
795}
796
797/// The `border-style` keywords the `border` shorthands recognise.
798const BORDER_STYLES: [&str; 9] = ["solid", "dashed", "dotted", "none", "hidden", "double", "groove", "ridge", "inset"];
799
800/// A length that may be a percentage: `(px, fraction)`, at most one set (`auto` → neither).
801fn len(v: &str) -> (Option<f64>, Option<f64>) {
802    match v.trim().strip_suffix('%') {
803        Some(p) => (None, p.trim().parse::<f64>().ok().map(|p| p / 100.0)),
804        None => (px(v), None),
805    }
806}
807
808/// `aspect-ratio`: `w / h`, a single number, or `auto` (optionally with a ratio, which wins).
809fn ratio(v: &str) -> Option<f64> {
810    let v = v.trim().trim_start_matches("auto").trim();
811    let r = match v.split_once('/') {
812        Some((w, h)) => w.trim().parse::<f64>().ok()? / h.trim().parse::<f64>().ok()?,
813        None => v.parse().ok()?,
814    };
815    (r.is_finite() && r > 0.0).then_some(r)
816}
817
818fn px(v: &str) -> Option<f64> {
819    let v = v.trim();
820    v.strip_suffix("px").unwrap_or(v).trim().parse().ok()
821}
822
823fn edges(v: &str) -> Option<[f64; 4]> {
824    let n: Vec<f64> = v.split_whitespace().map(px).collect::<Option<_>>()?;
825    Some(match n[..] {
826        [a] => [a, a, a, a],
827        [a, b] => [a, b, a, b],
828        [a, b, c] => [a, b, c, b],
829        [a, b, c, d] => [a, b, c, d],
830        _ => return None,
831    })
832}
833
834/// Values split at top-level whitespace (a colour function's inner spaces stay).
835fn split_values(v: &str) -> Vec<String> {
836    let (mut out, mut cur, mut depth) = (Vec::new(), String::new(), 0i32);
837    for ch in v.trim().chars() {
838        match ch {
839            '(' => depth += 1,
840            ')' => depth -= 1,
841            _ => {}
842        }
843        if ch.is_whitespace() && depth <= 0 {
844            if !cur.is_empty() {
845                out.push(std::mem::take(&mut cur));
846            }
847        } else {
848            cur.push(ch);
849        }
850    }
851    if !cur.is_empty() {
852        out.push(cur);
853    }
854    out
855}
856
857/// One to four values expanded to top, right, bottom, left (as `padding`).
858fn edges4<T: Clone>(n: &[T]) -> Option<[T; 4]> {
859    Some(match n {
860        [a] => [a.clone(), a.clone(), a.clone(), a.clone()],
861        [a, b] => [a.clone(), b.clone(), a.clone(), b.clone()],
862        [a, b, c] => [a.clone(), b.clone(), c.clone(), b.clone()],
863        [a, b, c, d] => [a.clone(), b.clone(), c.clone(), d.clone()],
864        _ => return None,
865    })
866}
867
868/// `border-radius: 1-4 values [/ 1-4 values]` as `[h, v]` per corner (top-left,
869/// top-right, bottom-right, bottom-left; the value order is the same as `padding`'s
870/// with corners for sides).
871fn radius_list(v: &str) -> Option<[[f64; 2]; 4]> {
872    let (h, vv) = match v.split_once('/') {
873        Some((a, b)) => (a, Some(b)),
874        None => (v, None),
875    };
876    let side = |t: &str| -> Option<[f64; 4]> {
877        let n: Vec<f64> = t.split_whitespace().map(px).collect::<Option<_>>()?;
878        edges4(&n)
879    };
880    let hs = side(h)?;
881    let vs = match vv {
882        Some(t) => side(t)?,
883        None => hs,
884    };
885    Some([[hs[0], vs[0]], [hs[1], vs[1]], [hs[2], vs[2]], [hs[3], vs[3]]])
886}
887
888/// Apply one declaration (`k` lower-case) to `s`.
889pub(crate) fn apply_decl(s: &mut Style, k: &str, v: &str) {
890    apply(s, k, v)
891}
892
893fn apply(s: &mut Style, k: &str, v: &str) {
894    match k {
895        "color" => s.color = Some(v.into()),
896        "background" | "background-color" => s.background = Some(v.into()),
897        "border-color" => {
898            let parts = split_values(v);
899            if parts.len() <= 1 {
900                s.border_color = Some(v.into());
901                s.border_colors = None;
902            } else if let Some(e) = edges4(&parts) {
903                s.border_color = Some(e[0].to_string());
904                s.border_colors = Some(e.map(|c| Some(c.to_string())));
905            }
906        }
907        "border-width" => {
908            if let Some(e) = edges(v) {
909                if e.iter().all(|w| *w == e[0]) {
910                    s.border_width = Some(e[0]);
911                    s.border_widths = None;
912                } else {
913                    s.border_width = None;
914                    s.border_widths = Some(e);
915                }
916            } else {
917                s.border_width = None;
918                s.border_widths = None;
919            }
920        }
921        "border" => {
922            // `1px solid #333`
923            for part in split_values(v) {
924                if let Some(w) = px(&part).filter(|_| part.ends_with("px") || part == "0") {
925                    s.border_width = Some(w);
926                    s.border_widths = None;
927                } else if BORDER_STYLES.contains(&part.as_str()) {
928                    s.border_style = Some(part);
929                } else {
930                    s.border_color = Some(part);
931                    s.border_colors = None;
932                }
933            }
934        }
935        "border-top" | "border-right" | "border-bottom" | "border-left" | "border-top-width" | "border-right-width" | "border-bottom-width"
936        | "border-left-width" | "border-top-color" | "border-right-color" | "border-bottom-color" | "border-left-color" => {
937            let mut it = k["border-".len()..].splitn(2, '-');
938            let side = it.next().unwrap_or_default();
939            let what = it.next();
940            let Some(i) = ["top", "right", "bottom", "left"].iter().position(|x| *x == side) else { return };
941            let set_w = |s: &mut Style, w: f64| {
942                let mut e = s.border_edges();
943                e[i] = w;
944                s.border_widths = Some(e);
945            };
946            let set_c = |s: &mut Style, c: String| {
947                let base = s.border_color.clone();
948                s.border_colors.get_or_insert_with(|| [base.clone(), base.clone(), base.clone(), base])[i] = Some(c);
949            };
950            match what {
951                Some("width") => {
952                    if let Some(w) = px(v) {
953                        set_w(s, w)
954                    }
955                }
956                Some(_) => set_c(s, v.trim().to_string()),
957                None => {
958                    for part in split_values(v) {
959                        if let Some(w) = px(&part).filter(|_| part.ends_with("px") || part == "0") {
960                            set_w(s, w);
961                        } else if part == "none" {
962                            set_w(s, 0.0);
963                        } else if BORDER_STYLES.contains(&part.as_str()) {
964                            s.border_style = Some(part);
965                        } else {
966                            set_c(s, part);
967                        }
968                    }
969                }
970            }
971        }
972        "border-style" => s.border_style = Some(v.trim().into()),
973        "aspect-ratio" => s.aspect_ratio = ratio(v),
974        "padding" => s.padding = edges(v),
975        "margin" => s.margin = edges(v),
976        _ if k.starts_with("padding-") || k.starts_with("margin-") => {
977            let (box_, side) = k.split_once('-').unwrap_or_default();
978            let i = ["top", "right", "bottom", "left"].iter().position(|x| *x == side);
979            let e = if box_ == "padding" { &mut s.padding } else { &mut s.margin };
980            if let (Some(i), Some(n)) = (i, px(v)) {
981                e.get_or_insert([0.0; 4])[i] = n;
982            }
983        }
984        "border-radius" => match radius_list(v) {
985            Some(r) if r.iter().all(|c| c[0] == r[0][0] && c[1] == r[0][0]) => {
986                s.border_radius = Some(r[0][0]);
987                s.border_radii = None;
988            }
989            Some(r) => {
990                s.border_radius = Some(r[0][0]);
991                s.border_radii = Some(r);
992            }
993            None => {
994                s.border_radius = None;
995                s.border_radii = None;
996            }
997        },
998        "border-top-left-radius" | "border-top-right-radius" | "border-bottom-right-radius" | "border-bottom-left-radius" => {
999            let i = ["border-top-left-radius", "border-top-right-radius", "border-bottom-right-radius", "border-bottom-left-radius"]
1000                .iter()
1001                .position(|x| *x == k)
1002                .unwrap_or(0);
1003            let n: Option<Vec<f64>> = v.split_whitespace().map(px).collect();
1004            let c = match n.as_deref() {
1005                Some([a]) => [*a, *a],
1006                Some([a, b]) => [*a, *b],
1007                _ => return,
1008            };
1009            let mut r = s.radii();
1010            r[i] = c;
1011            s.border_radii = Some(r);
1012        }
1013        "position" => s.position = Some(v.trim().into()),
1014        "top" => s.top = px(v),
1015        "right" => s.right = px(v),
1016        "bottom" => s.bottom = px(v),
1017        "left" => s.left = px(v),
1018        "inset" => {
1019            let e = edges(v);
1020            [s.top, s.right, s.bottom, s.left] = e.map_or([None; 4], |e| e.map(Some));
1021        }
1022        "z-index" => s.z_index = v.trim().parse().ok(),
1023        "font-style" => s.font_style = Some(v.trim().into()),
1024        "overflow-wrap" | "word-wrap" => s.overflow_wrap = Some(v.trim().into()),
1025        "overflow" | "overflow-x" | "overflow-y" => s.overflow = Some(v.split_whitespace().next().unwrap_or("visible").into()),
1026        "shape-rendering" => s.shape_rendering = Some(v.trim().into()),
1027        "scrollbar-width" => s.scrollbar_width = Some(v.trim().into()),
1028        "font-size" => s.font_size = px(v),
1029        "font-weight" => {
1030            s.font_weight = match v {
1031                "normal" => Some(400),
1032                "bold" => Some(700),
1033                n => n.parse().ok(),
1034            }
1035        }
1036        "line-height" => s.line_height = if v.ends_with("px") { px(v) } else { None },
1037        "font-family" => s.font_family = Some(v.into()),
1038        "font-metrics" => s.font_metrics = Some(v.into()),
1039        "opacity" => s.opacity = v.parse().ok(),
1040        "width" => (s.width, s.width_pct) = len(v),
1041        "height" => (s.height, s.height_pct) = len(v),
1042        "gap" => {
1043            let parts: Vec<f64> = v.split_whitespace().filter_map(px).collect();
1044            match parts[..] {
1045                [g] => {
1046                    s.gap = Some(g);
1047                    s.row_gap = Some(g);
1048                }
1049                [r, c] => {
1050                    s.row_gap = Some(r);
1051                    s.gap = Some(c);
1052                }
1053                _ => {}
1054            }
1055        }
1056        "column-gap" => s.gap = px(v),
1057        "row-gap" => s.row_gap = px(v),
1058        "min-width" => (s.min_width, s.min_width_pct) = len(v),
1059        "max-width" => (s.max_width, s.max_width_pct) = len(v),
1060        "min-height" => s.min_height = px(v),
1061        "max-height" => s.max_height = px(v),
1062        "display" => s.display = Some(v.into()),
1063        "flex-direction" => s.flex_direction = Some(v.into()),
1064        "flex-wrap" => s.flex_wrap = Some(v.into()),
1065        "justify-content" => s.justify_content = Some(v.into()),
1066        "align-items" => s.align_items = Some(v.into()),
1067        "align-self" => s.align_self = Some(v.into()),
1068        "flex-grow" => s.flex_grow = v.parse().ok(),
1069        "flex-shrink" => s.flex_shrink = v.parse().ok(),
1070        "flex-basis" => s.flex_basis = px(v),
1071        "flex" => {
1072            let p: Vec<&str> = v.split_whitespace().collect();
1073            let (g, sh, b) = match p[..] {
1074                ["none"] => (Some(0.0), Some(0.0), None),
1075                ["auto"] => (Some(1.0), Some(1.0), None),
1076                [g] if g.parse::<f64>().is_ok() => (g.parse().ok(), Some(1.0), Some(0.0)),
1077                [b] => (Some(1.0), Some(1.0), px(b)),
1078                [g, sh] => (g.parse().ok(), sh.parse().ok(), Some(0.0)),
1079                [g, sh, b] => (g.parse().ok(), sh.parse().ok(), if b == "auto" { None } else { px(b) }),
1080                _ => (None, None, None),
1081            };
1082            s.flex_grow = g;
1083            s.flex_shrink = sh;
1084            s.flex_basis = b;
1085        }
1086        "grid-template-columns" => s.grid_template_columns = Some(v.into()),
1087        "box-shadow" => s.box_shadow = Some(v.into()),
1088        "background-clip" | "-webkit-background-clip" => s.background_clip = Some(v.trim().to_ascii_lowercase()),
1089        "backdrop-filter" | "-webkit-backdrop-filter" => s.backdrop_blur = backdrop_blur(v),
1090        "cursor" => s.cursor = Some(v.into()),
1091        "touch-action" => s.touch_action = Some(v.trim().to_ascii_lowercase()),
1092        "object-fit" => s.object_fit = Some(v.trim().to_ascii_lowercase()),
1093        "text-align" => s.text_align = Some(v.into()),
1094        "white-space" => s.white_space = Some(v.into()),
1095        "line-clamp" | "-webkit-line-clamp" => s.line_clamp = v.parse::<f64>().ok().filter(|n| *n >= 1.0).map(|n| n.min(999.0) as u16),
1096        "transition" => s.transitions = super::motion::parse_transitions(v),
1097        "animation" => s.animations = super::motion::parse_animations(v),
1098        _ => {}
1099    }
1100}
1101
1102/// Per-widget traces of matched declarations, read by the inspector.
1103#[cfg(feature = "inspector")]
1104pub mod trace {
1105    use super::Applied;
1106    use std::cell::RefCell;
1107    use std::collections::HashMap;
1108
1109    thread_local! {
1110        static TRACES: RefCell<HashMap<String, Vec<Applied>>> = RefCell::new(HashMap::new());
1111    }
1112
1113    /// Keep `tr` as the style trace of `widget` (replacing the previous frame's).
1114    pub fn record(widget: &str, tr: Vec<Applied>) {
1115        TRACES.with(|t| {
1116            t.borrow_mut().insert(widget.to_string(), tr);
1117        });
1118    }
1119
1120    /// The last recorded trace of `widget`.
1121    pub fn of(widget: &str) -> Option<Vec<Applied>> {
1122        TRACES.with(|t| t.borrow().get(widget).cloned())
1123    }
1124
1125    /// Forget every trace (an app that re-registers its widgets each frame rebuilds them).
1126    pub fn clear() {
1127        TRACES.with(|t| t.borrow_mut().clear());
1128    }
1129}
1130
1131/// A widget style struct that a style sheet can configure. Each field is reachable as a
1132/// custom property named after it (`them_bg` → `--them-bg`); common fields also answer
1133/// to the standard CSS property (`bg` ← `background`, `radius` ← `border-radius`, ...).
1134pub trait Styled {
1135    /// Override the fields the resolved style sets; untouched fields keep their value.
1136    fn apply_style(&mut self, s: &Style);
1137
1138    /// `self` overridden by the element `spec` of `sheet`.
1139    fn styled(mut self, sheet: &Sheet, spec: &str) -> Self
1140    where
1141        Self: Sized,
1142    {
1143        self.apply_style(&sheet.el(spec));
1144        self
1145    }
1146
1147    /// `Default` overridden by the element `spec` of `sheet`.
1148    fn from_sheet(sheet: &Sheet, spec: &str) -> Self
1149    where
1150        Self: Default + Sized,
1151    {
1152        let mut v = Self::default();
1153        v.apply_style(&sheet.el(spec));
1154        v
1155    }
1156}
1157
1158/// Field conversion used by [`styled!`].
1159/// One [`styled!`] field: standard properties `aliases` in order, then the
1160/// field's own `--custom` property; the last one present and parsable wins.
1161#[doc(hidden)]
1162#[inline(never)]
1163pub fn set_field<T: StyleField>(dst: &mut T, s: &Style, aliases: &[&str], field: &str) {
1164    for a in aliases {
1165        if let Some(v) = standard(s, a).and_then(|v| T::from_css(&v)) {
1166            *dst = v;
1167        }
1168    }
1169    if let Some(v) = s.field_css(field).and_then(T::from_css) {
1170        *dst = v;
1171    }
1172}
1173
1174pub trait StyleField: Sized {
1175    fn from_css(v: &str) -> Option<Self>;
1176}
1177
1178impl StyleField for &'static str {
1179    fn from_css(v: &str) -> Option<Self> {
1180        Some(intern(v.trim()))
1181    }
1182}
1183
1184impl StyleField for Option<&'static str> {
1185    fn from_css(v: &str) -> Option<Self> {
1186        Some(if v.trim() == "none" { None } else { Some(intern(v.trim())) })
1187    }
1188}
1189
1190impl StyleField for f64 {
1191    fn from_css(v: &str) -> Option<Self> {
1192        px(v)
1193    }
1194}
1195
1196impl StyleField for u32 {
1197    fn from_css(v: &str) -> Option<Self> {
1198        match v.trim() {
1199            "normal" => Some(400),
1200            "bold" => Some(700),
1201            n => n.parse().ok(),
1202        }
1203    }
1204}
1205
1206impl StyleField for bool {
1207    fn from_css(v: &str) -> Option<Self> {
1208        match v.trim() {
1209            "true" | "1" | "yes" => Some(true),
1210            "false" | "0" | "no" => Some(false),
1211            _ => None,
1212        }
1213    }
1214}
1215
1216/// The CSS text of a standard property in a resolved [`Style`].
1217pub fn standard(s: &Style, prop: &str) -> Option<String> {
1218    let n = |v: Option<f64>| v.map(|x| x.to_string());
1219    match prop {
1220        "color" => s.color.clone(),
1221        "background" => s.background.clone(),
1222        "border-color" => s.border_color.clone(),
1223        "border-width" => n(s.border_width),
1224        "border-radius" => n(s.border_radius),
1225        "font-size" => n(s.font_size),
1226        "font-weight" => s.font_weight.map(|w| w.to_string()),
1227        "line-height" => n(s.line_height),
1228        "font-family" => s.font_family.clone(),
1229        "font-metrics" => s.font_metrics.clone(),
1230        "width" => n(s.width),
1231        "height" => n(s.height),
1232        "gap" => n(s.gap),
1233        "padding-top" => n(s.padding.map(|p| p[0])),
1234        "padding-right" => n(s.padding.map(|p| p[1])),
1235        "padding-bottom" => n(s.padding.map(|p| p[2])),
1236        "padding-left" => n(s.padding.map(|p| p[3])),
1237        "box-shadow" => s.box_shadow.clone(),
1238        "background-clip" => s.background_clip.clone(),
1239        _ => None,
1240    }
1241}
1242
1243/// Implement [`Styled`] for a style struct: `styled!(T { field [= "css-prop", ...], ... })`.
1244/// The custom property `--field-name` always applies, after (and so over) the aliases.
1245#[macro_export]
1246macro_rules! styled {
1247    ($t:ty { $($f:ident $(= $($alias:literal),+)?),* $(,)? }) => {
1248        impl $crate::ui::style::Styled for $t {
1249            fn apply_style(&mut self, s: &$crate::ui::style::Style) {
1250                $(
1251                    $crate::ui::style::set_field(&mut self.$f, s, &[$($($alias),+)?], stringify!($f));
1252                )*
1253            }
1254        }
1255    };
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use super::*;
1261
1262    const CSS: &str = r#"
1263        :root { --txt: #f5f5f5; --acc: #3b82f6; --btn-bg: var(--el, #1f1f1f) }
1264        /* the base */
1265        button { color: var(--txt); font-size: 13px; line-height: 1.5; padding: 5px 14px }
1266        .seg button, .x { gap: 1px }
1267    "#;
1268
1269    #[test]
1270    fn descendant_and_child_selectors() {
1271        let sh = Sheet::parse(CSS).unwrap();
1272        let seg = [Node::parse("div.seg")];
1273        // `.seg button` needs the ancestor; without one only `button` applies.
1274        assert_eq!(sh.resolve_in(&Node::new("button"), &seg, None).gap, Some(1.0));
1275        assert_eq!(sh.resolve(&Node::new("button"), None).gap, None);
1276        let sh = Sheet::parse(
1277            ".a > .b { width: 10px } .a .b { height: 5px } .a .c > .b { width: 20px } .x { width: 3px } .bad >  { }",
1278        );
1279        assert!(sh.is_err(), "a dangling combinator is rejected");
1280        let sh = Sheet::parse(".a > .b { width: 10px } .a .b { height: 5px } .a .c > .b { width: 20px }").unwrap();
1281        assert!(sh.has_complex());
1282        let b = Node::parse("div.b");
1283        // child of .a
1284        let s = sh.resolve_in(&b, &[Node::parse("div.a")], None);
1285        assert_eq!((s.width, s.height), (Some(10.0), Some(5.0)));
1286        // grandchild of .a through .c: descendant + the more specific `.a .c > .b`
1287        let s = sh.resolve_in(&b, &[Node::parse("div.a"), Node::parse("div.c")], None);
1288        assert_eq!((s.width, s.height), (Some(20.0), Some(5.0)));
1289        // grandchild through a plain div: descendant only
1290        let s = sh.resolve_in(&b, &[Node::parse("div.a"), Node::parse("div")], None);
1291        assert_eq!((s.width, s.height), (None, Some(5.0)));
1292        // backtracking: `.a .c > .b` with .c the parent and .a further up
1293        let s = sh.resolve_in(&b, &[Node::parse("div.a"), Node::parse("div"), Node::parse("div.c")], None);
1294        assert_eq!(s.width, Some(20.0));
1295    }
1296
1297    #[test]
1298    fn percent_lengths_aspect_ratio_and_border_style() {
1299        let s = inline("width: 50%; height: 25%; max-width: 80%; aspect-ratio: 16 / 9; border: 1px dashed #333");
1300        assert_eq!((s.width, s.width_pct, s.height_pct, s.max_width_pct), (None, Some(0.5), Some(0.25), Some(0.8)));
1301        assert!((s.aspect_ratio.unwrap() - 16.0 / 9.0).abs() < 1e-9);
1302        assert_eq!((s.border_style.as_deref(), s.border_color.as_deref(), s.border_width), (Some("dashed"), Some("#333"), Some(1.0)));
1303        assert_eq!(s.border_dash(1.0), Some([3.0, 3.0]));
1304        assert!(!inline("border-style: none").border_drawn());
1305        assert_eq!(inline("aspect-ratio: 1.5").aspect_ratio, Some(1.5));
1306        assert_eq!(inline("aspect-ratio: auto").aspect_ratio, None);
1307    }
1308
1309    #[test]
1310    fn cascade_specificity_then_order() {
1311        let sh = Sheet::parse(
1312            "button{background:#111} .on{background:#222} button{background:#333} #send{background:var(--acc)} :root{--acc:#3b82f6}",
1313        )
1314        .unwrap();
1315        assert_eq!(sh.resolve(&Node::new("button"), None).background.as_deref(), Some("#333"));
1316        assert_eq!(sh.resolve(&Node::new("button").class("on"), None).background.as_deref(), Some("#222"));
1317        assert_eq!(sh.resolve(&Node::new("button").class("on").id("send"), None).background.as_deref(), Some("#3b82f6"));
1318    }
1319
1320    #[test]
1321    fn state_precedence() {
1322        let sh = Sheet::parse(".b{color:#aaa} .b:hover{color:#bbb} .b:focus-visible{color:#ccc} .b:disabled{opacity:0.5}").unwrap();
1323        let n = |s| Node::new("button").class("b").state(s);
1324        assert_eq!(sh.resolve(&n(State::NONE), None).color.as_deref(), Some("#aaa"));
1325        assert_eq!(sh.resolve(&n(State::HOVER), None).color.as_deref(), Some("#bbb"));
1326        // equal specificity: the later rule wins
1327        assert_eq!(sh.resolve(&n(State::HOVER | State::FOCUS_VISIBLE), None).color.as_deref(), Some("#ccc"));
1328        assert_eq!(sh.resolve(&n(State::DISABLED), None).opacity, Some(0.5));
1329        assert!(Selector::parse("a:nth-child").is_err());
1330    }
1331
1332    #[test]
1333    fn variables_fallbacks_and_inheritance() {
1334        let sh = Sheet::parse(
1335            ":root{--txt:#f5f5f5;--btn-bg:var(--el, #1f1f1f)} .card{color:var(--txt);font-size:14px;line-height:1.5;background:var(--btn-bg)} .pill{font-size:11.5px;padding:0 8px}",
1336        )
1337        .unwrap();
1338        assert_eq!(sh.var("--btn-bg").as_deref(), Some("#1f1f1f"));
1339        let card = sh.resolve(&Node::new("div").class("card"), None);
1340        assert_eq!((card.color.as_deref(), card.line_height, card.background.as_deref()), (Some("#f5f5f5"), Some(21.0), Some("#1f1f1f")));
1341        let pill = sh.resolve(&Node::new("span").class("pill"), Some(&card));
1342        // colour and line-height inherit (a computed px line-height, as in CSS); background does not
1343        assert_eq!((pill.color.as_deref(), pill.font_size, pill.line_height, pill.background), (Some("#f5f5f5"), Some(11.5), Some(21.0), None));
1344        assert_eq!(pill.padding, Some([0.0, 8.0, 0.0, 8.0]));
1345    }
1346
1347    #[test]
1348    fn trace_reports_rule_sources_in_cascade_order() {
1349        let sh = Sheet::parse(":root{--a:#111} #x{color:var(--a)} .b, button{color:#222;gap:2px}").unwrap();
1350        let (s, tr) = sh.resolve_traced(&Node::new("button").class("b").id("x"), None);
1351        assert_eq!(s.color.as_deref(), Some("#111"));
1352        let sel: Vec<_> = tr.iter().map(|a| (a.property.as_str(), a.selector.as_str())).collect();
1353        assert_eq!(sel, [("color", "button"), ("gap", "button"), ("color", ".b"), ("gap", ".b"), ("color", "#x")]);
1354        assert_eq!(tr.last().unwrap().value, "#111");
1355    }
1356
1357    #[test]
1358    fn media_blocks_and_env_follow_the_environment() {
1359        use crate::ui::media::{Edges, MediaEnv};
1360        let css = ".bar{height:44px;padding-bottom:env(safe-area-inset-bottom, 0px)} @media (pointer: coarse) { .btn{padding:12px 16px} } .btn{color:#fff} @media (max-width: 600px) and (orientation: portrait) { .side{display:none} }";
1361        let phone = MediaEnv::touch(390.0, 844.0, Edges::new(47.0, 0.0, 34.0, 0.0));
1362        let ph = Sheet::parse_with(css, &phone).unwrap();
1363        assert_eq!(ph.el("div.bar").padding.map(|p| p[2]), Some(34.0));
1364        assert_eq!(ph.el("button.btn").padding, Some([12.0, 16.0, 12.0, 16.0]));
1365        assert_eq!(ph.el("button.btn").color.as_deref(), Some("#fff"), "rules after the block still apply");
1366        assert_eq!(ph.el("div.side").display.as_deref(), Some("none"));
1367        let desk = Sheet::parse_with(css, &MediaEnv::desktop(1440.0, 900.0)).unwrap();
1368        assert_eq!(desk.el("div.bar").padding.map(|p| p[2]), Some(0.0));
1369        assert_eq!(desk.el("button.btn").padding, None);
1370        assert_eq!(desk.el("div.side").display, None);
1371    }
1372
1373    #[test]
1374    fn custom_properties_cascade_inherit_and_feed_var() {
1375        let sh = Sheet::parse(":root{--acc:#3b82f6} .t{--me-bg:var(--acc);--pad:4px} .t.dim{--pad:2px;padding:var(--pad)} .c{color:var(--me-bg)}").unwrap();
1376        let t = sh.resolve(&Node::parse("div.t.dim"), None);
1377        assert_eq!((t.custom("--me-bg"), t.custom("--pad"), t.padding), (Some("#3b82f6"), Some("2px"), Some([2.0; 4])));
1378        let c = sh.resolve(&Node::parse("span.c"), Some(&t));
1379        assert_eq!(c.color.as_deref(), Some("#3b82f6"), "inherited custom property feeds var()");
1380        assert_eq!(sh.el("div.t").custom("--pad"), Some("4px"));
1381        assert_eq!(sh.var_static("--acc", "#000"), "#3b82f6");
1382        assert_eq!(sh.var_static("--nope", "#000"), "#000");
1383    }
1384
1385    #[derive(Default, Debug, PartialEq)]
1386    struct Demo {
1387        bg: &'static str,
1388        border: Option<&'static str>,
1389        radius: f64,
1390        hdr_weight: u32,
1391        chevron_on_hover: bool,
1392    }
1393    crate::styled!(Demo { bg = "background", border = "border-color", radius = "border-radius", hdr_weight, chevron_on_hover });
1394
1395    #[test]
1396    fn styled_structs_read_standard_and_custom_properties() {
1397        let sh = Sheet::parse(".pill{background:#111;border-radius:9px;--hdr-weight:600;--chevron-on-hover:true} .pill.flat{--border:none} .pill.edge{border:1px solid #222;--bg:#333}").unwrap();
1398        let d = Demo::from_sheet(&sh, "div.pill");
1399        assert_eq!(d, Demo { bg: "#111", border: None, radius: 9.0, hdr_weight: 600, chevron_on_hover: true });
1400        let e = Demo::from_sheet(&sh, "div.pill.edge");
1401        assert_eq!((e.bg, e.border), ("#333", Some("#222")), "the custom property wins over the alias");
1402        assert_eq!(Demo::from_sheet(&sh, "div.pill.flat").border, None);
1403        let n = Node::parse("button.a.b#x:hover");
1404        assert_eq!((n.kind, n.id, n.classes.clone(), n.state), ("button", Some("x"), vec!["a", "b"], State::HOVER));
1405    }
1406
1407    #[test]
1408    fn dialog_card_style_reads_the_sheet() {
1409        let sh = Sheet::parse(":root{--el:#1b1b1b} .dlg{background:var(--el);border:1px solid #2c2c2c;border-radius:14px;box-shadow:0 30px 80px rgba(0,0,0,0.8)} .flat{box-shadow:none;--border:none}").unwrap();
1410        let base = crate::ui::widgets::composite::dialog::CardStyle { bg: "a", border: None, radius: 0.0, shadow: None };
1411        let c = base.styled(&sh, "div.dlg");
1412        assert_eq!(c, crate::ui::widgets::composite::dialog::CardStyle { bg: "#1b1b1b", border: Some("#2c2c2c"), radius: 14.0, shadow: Some(crate::ui::widgets::composite::dialog::Shadow { dy: 30.0, blur: 80.0, color: "rgba(0,0,0,0.8)" }) });
1413        let f = base.styled(&sh, "div.dlg.flat");
1414        assert_eq!((f.shadow, f.border), (None, None));
1415    }
1416    #[test]
1417    fn border_shorthand_and_comments() {
1418        let sh = Sheet::parse("/* x */ .c{border:1px solid #1b1b1b;border-radius:12px;margin:0 0 8px}").unwrap();
1419        let s = sh.resolve(&Node::new("div").class("c"), None);
1420        assert_eq!((s.border_width, s.border_color.as_deref(), s.border_radius, s.margin), (Some(1.0), Some("#1b1b1b"), Some(12.0), Some([0.0, 0.0, 8.0, 0.0])));
1421        assert!(Sheet::parse(".a{color:#fff").is_err());
1422        assert!(Sheet::parse(".a{color}").is_err());
1423    }
1424
1425    #[test]
1426    fn margin_and_padding_longhands_set_one_side() {
1427        let sh = Sheet::parse(".a{margin-top:18px}.b{padding:4px;padding-right:50px;margin-left:3px}").unwrap();
1428        let a = sh.resolve(&Node::new("div").class("a"), None);
1429        assert_eq!(a.margin, Some([18.0, 0.0, 0.0, 0.0]));
1430        let b = sh.resolve(&Node::new("div").class("b"), None);
1431        assert_eq!((b.padding, b.margin), (Some([4.0, 50.0, 4.0, 4.0]), Some([0.0, 0.0, 0.0, 3.0])));
1432    }
1433
1434    #[test]
1435    fn corners_sides_and_positions_parse() {
1436        let s = inline("border-radius: 1px 2px 3px / 4px 5px; border-top-right-radius: 7px 8px");
1437        assert_eq!(s.radii(), [[1.0, 4.0], [7.0, 8.0], [3.0, 4.0], [2.0, 5.0]]);
1438        assert_eq!(s.border_radius, Some(1.0), "the first corner stays readable as the radius");
1439        // A later uniform radius resets the corners.
1440        assert_eq!(inline("border-radius: 2px 0; border-radius: 6px").border_radii, None);
1441        let b = inline("border: 1px solid rgba(0, 0, 0, 0.5); border-bottom-width: 3px; border-right: none");
1442        assert_eq!(b.border_color.as_deref(), Some("rgba(0, 0, 0, 0.5)"));
1443        assert_eq!(b.border_edges(), [1.0, 0.0, 3.0, 1.0]);
1444        let c = inline("border-color: red green; border-width: 2px");
1445        assert_eq!((c.border_side_color(0), c.border_side_color(1)), (Some("red"), Some("green")));
1446        assert_eq!((c.border_width, c.border_widths), (Some(2.0), None));
1447        let p = inline("position: absolute; inset: 1px 2px; z-index: 3; font-style: italic; overflow-wrap: anywhere; shape-rendering: geometricPrecision");
1448        assert!(p.positioned() && p.out_of_flow());
1449        assert_eq!([p.top, p.right, p.bottom, p.left], [Some(1.0), Some(2.0), Some(1.0), Some(2.0)]);
1450        assert_eq!((p.z_index, p.font_style.as_deref()), (Some(3), Some("italic")));
1451        // font-style, overflow-wrap and shape-rendering inherit.
1452        let sh = Sheet::parse("div { font-style: italic; overflow-wrap: anywhere; shape-rendering: geometricPrecision }").unwrap();
1453        let parent = sh.el("div");
1454        let kid = sh.resolve(&Node::parse("span"), Some(&parent));
1455        assert_eq!((kid.font_style, kid.overflow_wrap, kid.shape_rendering), (parent.font_style.clone(), parent.overflow_wrap.clone(), parent.shape_rendering.clone()));
1456    }
1457}