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