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