Skip to main content

nsh_core/
style.rs

1use std::{rc::Rc, sync::Arc};
2
3use ordered_float::OrderedFloat;
4use taffy::{
5    AlignContent, AlignItems, Dimension, Display, FlexDirection, FlexWrap, LengthPercentage,
6    LengthPercentageAuto, Position,
7};
8
9use crate::{
10    css,
11    effects::{
12        BackdropMaterial, BlendMode, BoxShadow, ClipInset, Cursor, Effects, Filter, GlassEffect,
13        Gradient, KeyframeAnimation, Keyframes, MacOsBackdrop, Outline, Transition,
14        TransitionProps,
15    },
16    element::PropEnum,
17    geometry::{
18        AbsoluteLength, Corners, DefiniteLength, Edges, Percentage, Point, Points, REM_SIZE, Size,
19        percentage, point, px,
20    },
21    grid,
22    transform::{Transform, TransformKind},
23};
24
25/// An sRGB color packed as `0xRRGGBBAA`.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub struct Color(pub u32);
28
29impl Color {
30    /// Fully transparent.
31    pub const TRANSPARENT: Color = Color(0);
32    /// Opaque black.
33    pub const BLACK: Color = Color(0x0000_00ff);
34
35    /// Creates a color from 8-bit components.
36    #[inline]
37    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
38        Color((r as u32) << 24 | (g as u32) << 16 | (b as u32) << 8 | a as u32)
39    }
40
41    /// Returns `(r, g, b, a)` in `0.0..=1.0`.
42    #[inline]
43    pub fn to_f64(self) -> (f64, f64, f64, f64) {
44        let c = self.0;
45        (
46            (c >> 24) as f64 / 255.0,
47            ((c >> 16) & 0xff) as f64 / 255.0,
48            ((c >> 8) & 0xff) as f64 / 255.0,
49            (c & 0xff) as f64 / 255.0,
50        )
51    }
52
53    /// Returns true if the alpha component is zero.
54    #[inline]
55    pub const fn is_transparent(self) -> bool {
56        self.0 & 0xff == 0
57    }
58
59    /// Parses a CSS color: hex, `rgb()` / `rgba()`, `hsl()` / `hsla()`,
60    /// `oklch()`, `oklab()` or a CSS named color.
61    pub fn parse(s: &str) -> Option<Color> {
62        crate::css::color(s)
63    }
64}
65
66/// Horizontal alignment of a text block.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
68pub enum TextAlign {
69    /// Natural alignment for the writing direction.
70    #[default]
71    Auto,
72    /// Left aligned.
73    Left,
74    /// Centered.
75    Center,
76    /// Right aligned.
77    Right,
78    /// Justified.
79    Justify,
80}
81
82/// `verticalAlign`: where an element inside a `<Text>` (an inline
83/// attachment) sits in its line, as CSS's `vertical-align` places a
84/// replaced inline box. The font it is measured against is the text's
85/// around the attachment; the line grows to hold the attachment wherever
86/// it reaches past that font (`TextAttachment::extent`).
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
88pub enum VerticalAlign {
89    /// `baseline`: its bottom on the baseline.
90    #[default]
91    Baseline,
92    /// `text-top`: its top at the top of the font (its ascent).
93    TextTop,
94    /// `text-bottom`: its bottom at the bottom of the font (its descent).
95    TextBottom,
96    /// `middle`: its middle half the font's x height above the baseline.
97    Middle,
98}
99
100impl VerticalAlign {
101    /// The value named by CSS keyword `name`.
102    pub fn parse(name: &str) -> Option<Self> {
103        Some(match name {
104            "baseline" => Self::Baseline,
105            "text-top" => Self::TextTop,
106            "text-bottom" => Self::TextBottom,
107            "middle" => Self::Middle,
108            _ => return None,
109        })
110    }
111}
112
113/// A font family name, interned: copying and comparing one is free, so
114/// resolved text styles stay `Copy` and cheap to hash.
115#[derive(Clone, Copy, PartialEq, Eq, Hash)]
116pub struct FontFamily(u32);
117
118static FAMILIES: std::sync::Mutex<Vec<std::sync::Arc<str>>> = std::sync::Mutex::new(Vec::new());
119
120impl FontFamily {
121    /// Interns `name`. Apps use a handful of families, so the table is a
122    /// small vector scanned linearly.
123    pub fn new(name: &str) -> FontFamily {
124        let mut families = FAMILIES.lock().unwrap_or_else(|e| e.into_inner());
125        if let Some(i) = families.iter().position(|f| &**f == name) {
126            return FontFamily(i as u32);
127        }
128        families.push(name.into());
129        FontFamily(families.len() as u32 - 1)
130    }
131
132    /// The family name.
133    pub fn name(self) -> std::sync::Arc<str> {
134        FAMILIES.lock().unwrap_or_else(|e| e.into_inner())[self.0 as usize].clone()
135    }
136}
137
138impl std::fmt::Debug for FontFamily {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        write!(f, "FontFamily({:?})", self.name())
141    }
142}
143
144/// A family of a `fontFamily` list ([`font_families`]). More generic
145/// families (`cursive`, `fantasy`) may be added: match with a `_` arm.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147#[non_exhaustive]
148pub enum FamilyName<'a> {
149    /// The system font: `system-ui`, `sans-serif`, `ui-sans-serif`,
150    /// `-apple-system`, `BlinkMacSystemFont`.
151    System,
152    /// The system's serif: `serif`, `ui-serif`.
153    Serif,
154    /// The system's monospace font: `monospace`, `ui-monospace`.
155    Monospace,
156    /// The system's rounded font (`ui-rounded`), where it has one.
157    Rounded,
158    /// A family installed on the device or registered by the app.
159    Named(&'a str),
160}
161
162/// Scans a quoted `fontFamily` item after its opening `quote`: returns the
163/// unescaped, trimmed family name (borrowing when no `\` escape appears) and
164/// the slice after the closing quote (or `""` if unclosed).
165fn unquote_family(body: &str, quote: char) -> (std::borrow::Cow<'_, str>, &str) {
166    let mut escaped = false;
167    let mut has_escapes = false;
168    let mut end = body.len();
169    let mut after = "";
170    for (i, c) in body.char_indices() {
171        if escaped {
172            escaped = false;
173            continue;
174        }
175        if c == '\\' {
176            escaped = true;
177            has_escapes = true;
178        } else if c == quote {
179            end = i;
180            after = &body[i + c.len_utf8()..];
181            break;
182        }
183    }
184    let raw = &body[..end];
185    if !has_escapes {
186        return (std::borrow::Cow::Borrowed(raw.trim()), after);
187    }
188    let mut decoded = String::with_capacity(raw.len());
189    let mut chars = raw.chars();
190    while let Some(c) = chars.next() {
191        if c == '\\' {
192            match chars.next() {
193                Some(next) => decoded.push(next),
194                None => decoded.push('\\'),
195            }
196        } else {
197            decoded.push(c);
198        }
199    }
200    let trimmed = decoded.trim();
201    if trimmed.len() == decoded.len() {
202        (std::borrow::Cow::Owned(decoded), after)
203    } else {
204        (std::borrow::Cow::Owned(trimmed.to_owned()), after)
205    }
206}
207
208/// The families of a `fontFamily` value, most preferred first, as CSS lists
209/// them: names separated by commas, each trimmed and unquoted
210/// (`"Inter, \"Noto Sans SC\", sans-serif"`), the generic families as
211/// [`FamilyName`]'s. A quoted name runs to its closing quote, commas and all
212/// (`'ACME, Inc'`), and is always a family's name: a quoted `"serif"` names a
213/// family called serif, as in CSS. Text is set in the first family a
214/// platform has, and a character that family lacks in the next that has it.
215/// This borrowed iterator preserves the input slices; platform lookup uses
216/// [`for_each_font_family`] to decode escapes into temporary storage.
217#[inline]
218pub fn font_families(value: &str) -> impl Iterator<Item = FamilyName<'_>> {
219    let mut rest = value;
220    std::iter::from_fn(
221        #[inline(always)]
222        move || {
223            loop {
224                rest = rest.trim_start();
225                if rest.is_empty() {
226                    return None;
227                }
228                let (family, quoted) = if let Some(q @ ('"' | '\'')) = rest.chars().next() {
229                    // To the closing quote (or the end, unclosed); what follows it
230                    // up to the next comma is not part of the name.
231                    let body = &rest[1..];
232                    let end = body.find(q).unwrap_or(body.len());
233                    let after = body.get(end + 1..).unwrap_or("");
234                    rest = after.find(',').map_or("", |i| &after[i + 1..]);
235                    (body[..end].trim(), true)
236                } else {
237                    let end = rest.find(',').unwrap_or(rest.len());
238                    let name = rest[..end].trim_end();
239                    rest = rest.get(end + 1..).unwrap_or("");
240                    (name, false)
241                };
242                if family.is_empty() {
243                    continue;
244                }
245                return Some(match family {
246                    name if quoted => FamilyName::Named(name),
247                    "system-ui" | "sans-serif" | "ui-sans-serif" | "-apple-system"
248                    | "BlinkMacSystemFont" => FamilyName::System,
249                    "serif" | "ui-serif" => FamilyName::Serif,
250                    "monospace" | "ui-monospace" => FamilyName::Monospace,
251                    "ui-rounded" => FamilyName::Rounded,
252                    name => FamilyName::Named(name),
253                });
254            }
255        },
256    )
257}
258
259/// Resolves font names while temporary decoded storage is alive. Intended
260/// for platform font lookup; only quoted backslash escapes allocate.
261#[doc(hidden)]
262#[inline]
263pub fn for_each_font_family(value: &str, mut resolve: impl FnMut(FamilyName<'_>)) {
264    if value.is_empty() {
265        return;
266    }
267    let mut rest = value;
268    loop {
269        rest = trim_family_start(rest);
270        if rest.is_empty() {
271            return;
272        }
273        let (family, quoted) = if let Some(q @ ('"' | '\'')) = rest.chars().next() {
274            let body = &rest[1..];
275            let end = body.find(q).unwrap_or(body.len());
276            if body.as_bytes()[..end].contains(&b'\\') {
277                rest = resolve_escaped_family(body, q, &mut resolve);
278                continue;
279            }
280            let after = body.get(end + 1..).unwrap_or("");
281            rest = after.find(',').map_or("", |i| &after[i + 1..]);
282            (trim_family_start(trim_family_end(&body[..end])), true)
283        } else {
284            let end = rest.find(',').unwrap_or(rest.len());
285            let name = trim_family_end(&rest[..end]);
286            rest = rest.get(end + 1..).unwrap_or("");
287            (name, false)
288        };
289        if !family.is_empty() {
290            resolve(match family {
291                name if quoted => FamilyName::Named(name),
292                "system-ui" | "sans-serif" | "ui-sans-serif" | "-apple-system"
293                | "BlinkMacSystemFont" => FamilyName::System,
294                "serif" | "ui-serif" => FamilyName::Serif,
295                "monospace" | "ui-monospace" => FamilyName::Monospace,
296                "ui-rounded" => FamilyName::Rounded,
297                name => FamilyName::Named(name),
298            });
299        }
300    }
301}
302
303// Font names are normally ASCII; preserve Unicode whitespace at either edge.
304#[inline]
305fn trim_family_start(value: &str) -> &str {
306    let value = value.trim_ascii_start();
307    if value
308        .as_bytes()
309        .first()
310        .is_some_and(|b| !b.is_ascii() || *b == 0x0b)
311    {
312        value.trim_start()
313    } else {
314        value
315    }
316}
317
318#[inline]
319fn trim_family_end(value: &str) -> &str {
320    let value = value.trim_ascii_end();
321    if value
322        .as_bytes()
323        .last()
324        .is_some_and(|b| !b.is_ascii() || *b == 0x0b)
325    {
326        value.trim_end()
327    } else {
328        value
329    }
330}
331
332#[cold]
333fn resolve_escaped_family<'a>(
334    body: &'a str,
335    quote: char,
336    resolve: &mut impl FnMut(FamilyName<'_>),
337) -> &'a str {
338    let (name, after) = unquote_family(body, quote);
339    if !name.is_empty() {
340        resolve(FamilyName::Named(&name));
341    }
342    after.find(',').map_or("", |i| &after[i + 1..])
343}
344
345/// Whether `name` is a CSS generic family (CSS Fonts 4) or system font keyword
346/// that stays bare unless originally quoted.
347pub(crate) fn is_css_generic_keyword(name: &str) -> bool {
348    const KEYWORDS: [&str; 15] = [
349        "serif",
350        "sans-serif",
351        "monospace",
352        "cursive",
353        "fantasy",
354        "system-ui",
355        "ui-serif",
356        "ui-sans-serif",
357        "ui-monospace",
358        "ui-rounded",
359        "math",
360        "emoji",
361        "fangsong",
362        "-apple-system",
363        "BlinkMacSystemFont",
364    ];
365    KEYWORDS.iter().any(|k| k.eq_ignore_ascii_case(name))
366}
367
368/// Formats a `fontFamily` value as a CSS family list: generic keywords stay
369/// bare and named families are quoted and CSS-escaped (`"SF Mono", "Menlo",
370/// monospace`, or `""` when `value` names no family), so a list embedded in a
371/// CSS `font` shorthand round-trips through [`for_each_font_family`] and
372/// [`crate::canvas::CanvasFont::parse`] with commas, quotes and backslashes
373/// intact (`'ACME, Inc'`, `'A"B'`).
374pub fn css_font_families(value: &str) -> String {
375    let mut out = String::with_capacity(value.len() + 2);
376    let mut rest = value;
377    loop {
378        rest = rest.trim_start();
379        if rest.is_empty() {
380            break;
381        }
382        let (family, quoted) = if let Some(q @ ('"' | '\'')) = rest.chars().next() {
383            let (name, after) = unquote_family(&rest[q.len_utf8()..], q);
384            rest = after.find(',').map_or("", |i| &after[i + 1..]);
385            (name, true)
386        } else {
387            let end = rest.find(',').unwrap_or(rest.len());
388            let name = rest[..end].trim_end();
389            rest = rest.get(end + 1..).unwrap_or("");
390            (std::borrow::Cow::Borrowed(name), false)
391        };
392        if family.is_empty() {
393            continue;
394        }
395        if !out.is_empty() {
396            out.push_str(", ");
397        }
398        if !quoted && is_css_generic_keyword(&family) {
399            out.push_str(&family);
400        } else {
401            out.push('"');
402            for c in family.chars().filter(|c| !c.is_control()) {
403                if c == '"' || c == '\\' {
404                    out.push('\\');
405                }
406                out.push(c);
407            }
408            out.push('"');
409        }
410    }
411    out
412}
413
414/// Lines drawn through or under text (`textDecorationLine`).
415#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
416pub struct TextDecoration {
417    /// Underline.
418    pub underline: bool,
419    /// Strikethrough.
420    pub line_through: bool,
421}
422
423impl TextDecoration {
424    /// True if no line is drawn.
425    #[inline]
426    pub const fn is_none(self) -> bool {
427        !self.underline && !self.line_through
428    }
429}
430
431/// How decoration lines are drawn (`textDecorationStyle`).
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
433pub enum DecorationStyle {
434    /// One solid line (default).
435    #[default]
436    Solid,
437    /// Two lines.
438    Double,
439    /// Dots.
440    Dotted,
441    /// Dashes.
442    Dashed,
443    /// A wavy line.
444    Wavy,
445}
446
447/// Case changes applied to text (`textTransform`).
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
449pub enum TextTransform {
450    /// As written.
451    #[default]
452    None,
453    /// UPPER CASE.
454    Uppercase,
455    /// lower case.
456    Lowercase,
457    /// First Letter Of Each Word.
458    Capitalize,
459}
460
461impl TextTransform {
462    /// Applies the transform to `s`.
463    pub fn apply<'a>(self, s: &'a str) -> std::borrow::Cow<'a, str> {
464        match self {
465            TextTransform::None => s.into(),
466            TextTransform::Uppercase => s.to_uppercase().into(),
467            TextTransform::Lowercase => s.to_lowercase().into(),
468            TextTransform::Capitalize => {
469                let mut out = String::with_capacity(s.len());
470                let mut start = true;
471                for c in s.chars() {
472                    if start && c.is_alphanumeric() {
473                        out.extend(c.to_uppercase());
474                        start = false;
475                    } else {
476                        out.push(c);
477                        start |= c.is_whitespace();
478                    }
479                }
480                out.into()
481            }
482        }
483    }
484}
485
486/// Where text that does not fit `numberOfLines` is cut (`textOverflow`).
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
488pub enum EllipsizeMode {
489    /// "Lorem ips…" (default).
490    #[default]
491    Tail,
492    /// "…sum dolor".
493    Head,
494    /// "Lorem…dolor".
495    Middle,
496    /// Cut without an ellipsis.
497    Clip,
498}
499
500/// The corner radii of a view, clockwise from the top left: a
501/// [`Corners<Points>`] with the curve they are drawn with.
502#[derive(Debug, Clone, Copy, PartialEq, Default)]
503pub struct CornerRadii {
504    /// Top left.
505    pub top_left: Points,
506    /// Top right.
507    pub top_right: Points,
508    /// Bottom right.
509    pub bottom_right: Points,
510    /// Bottom left.
511    pub bottom_left: Points,
512    /// `borderCurve: "continuous"`: corners whose curvature grows from the
513    /// edges (iOS app icons) instead of circular arcs; see [`crate::shape`].
514    pub continuous: bool,
515}
516
517impl CornerRadii {
518    /// The same circular radius on every corner.
519    pub const fn all(r: Points) -> Self {
520        Self {
521            top_left: r,
522            top_right: r,
523            bottom_right: r,
524            bottom_left: r,
525            continuous: false,
526        }
527    }
528
529    /// Circular corners with these radii.
530    pub const fn circular(corners: Corners<Points>) -> Self {
531        Self {
532            top_left: corners.top_left,
533            top_right: corners.top_right,
534            bottom_right: corners.bottom_right,
535            bottom_left: corners.bottom_left,
536            continuous: false,
537        }
538    }
539
540    /// The radii, without the curve.
541    #[inline]
542    pub const fn corners(self) -> Corners<Points> {
543        Corners {
544            top_left: self.top_left,
545            top_right: self.top_right,
546            bottom_right: self.bottom_right,
547            bottom_left: self.bottom_left,
548        }
549    }
550
551    /// `[top_left, top_right, bottom_right, bottom_left]`.
552    #[inline]
553    pub const fn to_array(self) -> [Points; 4] {
554        [
555            self.top_left,
556            self.top_right,
557            self.bottom_right,
558            self.bottom_left,
559        ]
560    }
561
562    /// True if no corner is rounded.
563    #[inline]
564    pub fn is_zero(&self) -> bool {
565        self.to_array().iter().all(|&r| r <= Points::ZERO)
566    }
567
568    /// The radius shared by every rounded corner, if they all share one.
569    /// Platforms render such shapes with a single radius plus a mask of
570    /// the rounded corners (no paths).
571    pub fn shared(&self) -> Option<Points> {
572        let mut shared = Points::ZERO;
573        for r in self.to_array() {
574            if r > Points::ZERO {
575                if shared > Points::ZERO && r != shared {
576                    return None;
577                }
578                shared = r;
579            }
580        }
581        Some(shared)
582    }
583
584    /// Scales the radii down so adjacent corners do not overlap on a box
585    /// of `size` (CSS rule).
586    pub fn fit(self, size: Size<Points>) -> Self {
587        let ratio = |side: Points, a: Points, b: Points| {
588            if a + b > side { side / (a + b) } else { 1.0 }
589        };
590        let (width, height) = (size.width, size.height);
591        let f = ratio(width, self.top_left, self.top_right)
592            .min(ratio(width, self.bottom_left, self.bottom_right))
593            .min(ratio(height, self.top_left, self.bottom_left))
594            .min(ratio(height, self.top_right, self.bottom_right))
595            .max(0.0);
596        if f >= 1.0 {
597            return self;
598        }
599        Self {
600            top_left: self.top_left * f,
601            top_right: self.top_right * f,
602            bottom_right: self.bottom_right * f,
603            bottom_left: self.bottom_left * f,
604            ..self
605        }
606    }
607
608    /// The radii of a curve `d` inside this one (e.g. the inner edge of a
609    /// border).
610    pub fn inset(self, d: Points) -> Self {
611        Self {
612            top_left: (self.top_left - d).max(Points::ZERO),
613            top_right: (self.top_right - d).max(Points::ZERO),
614            bottom_right: (self.bottom_right - d).max(Points::ZERO),
615            bottom_left: (self.bottom_left - d).max(Points::ZERO),
616            ..self
617        }
618    }
619}
620
621impl From<CornerRadii> for Corners<Points> {
622    fn from(radii: CornerRadii) -> Self {
623        radii.corners()
624    }
625}
626
627/// How borders are drawn (`borderStyle`).
628#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
629pub enum BorderStyle {
630    /// A solid line (default).
631    #[default]
632    Solid,
633    /// Dashes.
634    Dashed,
635    /// Dots.
636    Dotted,
637}
638
639/// Border widths and colors, per side.
640#[derive(Debug, Clone, Copy, PartialEq)]
641pub struct Borders {
642    /// Widths.
643    pub widths: Edges<Points>,
644    /// Colors: top, right, bottom, left.
645    pub colors: [Color; 4],
646    /// Line style.
647    pub style: BorderStyle,
648}
649
650impl Borders {
651    /// No border.
652    pub const NONE: Borders = Borders {
653        widths: Edges {
654            top: Points::ZERO,
655            right: Points::ZERO,
656            bottom: Points::ZERO,
657            left: Points::ZERO,
658        },
659        colors: [Color::BLACK; 4],
660        style: BorderStyle::Solid,
661    };
662
663    /// True if some side draws something.
664    pub fn is_visible(&self) -> bool {
665        let widths = self.widths.to_array();
666        (0..4).any(|i| widths[i] > Points::ZERO && !self.colors[i].is_transparent())
667    }
668
669    /// `(width, color)` when every side is the same.
670    pub fn uniform(&self) -> Option<(Points, Color)> {
671        let widths = self.widths.to_array();
672        let [w, ..] = widths;
673        let [c, ..] = self.colors;
674        (widths.iter().all(|&x| x == w) && self.colors.iter().all(|&x| x == c)).then_some((w, c))
675    }
676
677    /// The width of side `side`: 0 top, 1 right, 2 bottom, 3 left (the
678    /// order of `colors`).
679    pub fn width(&self, side: usize) -> Points {
680        match side {
681            0 => self.widths.top,
682            1 => self.widths.right,
683            2 => self.widths.bottom,
684            _ => self.widths.left,
685        }
686    }
687
688    fn width_mut(&mut self, side: usize) -> &mut Points {
689        match side {
690            0 => &mut self.widths.top,
691            1 => &mut self.widths.right,
692            2 => &mut self.widths.bottom,
693            _ => &mut self.widths.left,
694        }
695    }
696}
697
698impl Default for Borders {
699    fn default() -> Self {
700        Self::NONE
701    }
702}
703
704/// Visual (non-layout) properties of a native view.
705#[derive(Debug, Clone, PartialEq)]
706pub struct ViewStyle {
707    /// Background fill.
708    pub background_color: Color,
709    /// `borderRadius`: the radius of corners without their own.
710    pub border_radius: Points,
711    /// `borderTopLeftRadius` etc.; they override `border_radius`.
712    pub corner_radius: Corners<Option<Points>>,
713    /// `borderCurve: "continuous"`.
714    pub continuous_corners: bool,
715    /// Borders (their widths also affect layout).
716    pub borders: Borders,
717    /// Opacity in `0.0..=1.0`.
718    pub opacity: f32,
719    /// Clip children to the (rounded) bounds.
720    pub overflow_hidden: bool,
721    /// Static transform, around the view's center.
722    pub transform: Transform,
723    /// `tintColor`: recolors an image's opaque pixels.
724    pub tint_color: Option<Color>,
725    /// `accentColor`: the color a system control shows its state in, which
726    /// a native component gets as its `accentColor` prop (a system switch's
727    /// track when on, for example); the control's own when `None`.
728    pub accent_color: Option<Color>,
729    /// Android's material shadow: the node's `android={{ elevation }}` prop,
730    /// not a style.
731    pub elevation: Points,
732    /// `transformOrigin`: the point transforms act around.
733    pub transform_origin: TransformOrigin,
734    /// `objectPosition`: where an image sits in its box (image views; the
735    /// platforms take it from [`crate::mount::ImageOptions::position`]).
736    pub object_position: ObjectPosition,
737    /// `backfaceVisibility: "hidden"`: invisible when turned away.
738    pub backface_hidden: bool,
739    /// Layered / inset shadows, gradients and filters.
740    pub effects: Option<Arc<Effects>>,
741    /// `mixBlendMode`.
742    pub blend_mode: BlendMode,
743    /// The iOS material from `ios={{ backdropMaterial }}`, projected at mount time.
744    pub backdrop_material: BackdropMaterial,
745    /// `glassEffect`.
746    pub glass_effect: GlassEffect,
747    /// `glassTintColor`: the tint of `glassEffect`'s native material.
748    pub glass_tint_color: Option<Color>,
749    /// The macOS backdrop from `macos={{ backdrop }}`, projected at mount time.
750    pub macos_backdrop: Option<MacOsBackdrop>,
751    /// The Windows backdrop from `windows={{ backdrop }}`, projected at
752    /// mount time.
753    pub windows_backdrop: Option<crate::WindowsBackdrop>,
754    /// `outline*`.
755    pub outline: Outline,
756    /// `visibility: "hidden"`: not drawn and not touchable, still laid out.
757    pub hidden: bool,
758    /// `cursor`.
759    pub cursor: Cursor,
760    /// `transition*`: style changes animate.
761    pub transition: Option<Transition>,
762    /// `animation*`: a keyframe animation runs.
763    pub animation: Option<KeyframeAnimation>,
764    /// In a terminal, the layout gave the view one row of its
765    /// accessibility label in place of its content (an icon button whose
766    /// icon a terminal leaves out): the platform draws the label there, and
767    /// on no other view. Not a style: the core sets it at mount time,
768    /// always `false` off a terminal.
769    pub shows_label: bool,
770    /// In a terminal, the label the layout gave the view
771    /// ([`Self::shows_label`]) is a popup trigger's arrow alone (`▾`): the
772    /// words it is flush against (a split button's main action) say what
773    /// it opens. Another popup trigger's label is its name and the arrow.
774    /// Not a style: the core sets it at mount time, always `false` off a
775    /// terminal.
776    pub label_arrow_only: bool,
777}
778
779/// `transformOrigin`: the point transforms rotate and scale around.
780#[derive(Debug, Clone, Copy, PartialEq)]
781pub struct TransformOrigin {
782    /// Horizontal position: from the left edge, or a fraction of the width.
783    pub x: DefiniteLength,
784    /// Vertical position: from the top edge, or a fraction of the height.
785    pub y: DefiniteLength,
786    /// Depth.
787    pub z: Points,
788}
789
790impl Default for TransformOrigin {
791    fn default() -> Self {
792        Self::CENTER
793    }
794}
795
796impl TransformOrigin {
797    /// The center (the default).
798    pub const CENTER: Self = Self {
799        x: DefiniteLength::Fraction(Percentage(0.5)),
800        y: DefiniteLength::Fraction(Percentage(0.5)),
801        z: Points::ZERO,
802    };
803
804    /// Offset of the origin from the center of a box of `size`, in the
805    /// plane, and its depth.
806    pub fn offset(&self, size: Size<Points>) -> (Point<Points>, Points) {
807        let at = |len: DefiniteLength, side: Points| {
808            len.to_points(AbsoluteLength::Points(side), REM_SIZE) - side / 2.0
809        };
810        (
811            point(at(self.x, size.width), at(self.y, size.height)),
812            self.z,
813        )
814    }
815
816    /// Parses CSS's syntax: one to three of keywords (`left`, `center`,
817    /// `right`, `top`, `bottom`), percentages and lengths (`10px` or a
818    /// bare number), the third being a depth.
819    pub fn parse(s: &str) -> Option<Self> {
820        let parts: Vec<&str> = s.split_whitespace().collect();
821        if parts.is_empty() || parts.len() > 3 {
822            return None;
823        }
824        let fraction = |f: f32| DefiniteLength::Fraction(percentage(f));
825        let len = |p: &str| -> Option<DefiniteLength> {
826            if let Some(pct) = p.strip_suffix('%') {
827                return pct.trim().parse::<f32>().ok().map(|v| fraction(v / 100.0));
828            }
829            p.strip_suffix("px")
830                .unwrap_or(p)
831                .parse::<f32>()
832                .ok()
833                .map(|v| px(v).into())
834        };
835        let mut x = None;
836        let mut y = None;
837        let mut free = Vec::new();
838        for &p in parts.iter().take(2) {
839            match p {
840                "left" => x = Some(fraction(0.0)),
841                "right" => x = Some(fraction(1.0)),
842                "top" => y = Some(fraction(0.0)),
843                "bottom" => y = Some(fraction(1.0)),
844                "center" => free.push(fraction(0.5)),
845                p => free.push(len(p)?),
846            }
847        }
848        // Unnamed values fill x, then y.
849        for v in free {
850            if x.is_none() {
851                x = Some(v);
852            } else if y.is_none() {
853                y = Some(v);
854            } else {
855                return None;
856            }
857        }
858        let z = match parts.get(2) {
859            Some(p) => px(p.strip_suffix("px").unwrap_or(p).parse::<f32>().ok()?),
860            None => Points::ZERO,
861        };
862        Some(Self {
863            x: x.unwrap_or(fraction(0.5)),
864            y: y.unwrap_or(fraction(0.5)),
865            z,
866        })
867    }
868}
869
870/// One axis of a CSS `<position>`: a distance from the start edge (left,
871/// top) or the end edge (right, bottom). Percentages are fractions of the
872/// free space: the box's size less the content's (negative when the
873/// content overflows), as CSS's `object-position` resolves them.
874#[derive(Debug, Clone, Copy, PartialEq)]
875#[non_exhaustive]
876pub struct PositionAxis {
877    /// Measured from the end edge (right, bottom) instead of the start.
878    pub from_end: bool,
879    /// The distance from that edge.
880    pub offset: DefiniteLength,
881}
882
883impl Default for PositionAxis {
884    /// The center.
885    fn default() -> Self {
886        Self::CENTER
887    }
888}
889
890impl PositionAxis {
891    /// The start edge (`left`, `top`, `0%`).
892    pub const START: Self = Self::start(DefiniteLength::Fraction(Percentage(0.0)));
893    /// The center (`center`, `50%`).
894    pub const CENTER: Self = Self::start(DefiniteLength::Fraction(Percentage(0.5)));
895    /// The end edge (`right`, `bottom`, `100%`).
896    pub const END: Self = Self::start(DefiniteLength::Fraction(Percentage(1.0)));
897
898    /// `offset` from the start edge.
899    pub const fn start(offset: DefiniteLength) -> Self {
900        Self {
901            from_end: false,
902            offset,
903        }
904    }
905
906    /// `offset` from the end edge.
907    pub const fn end(offset: DefiniteLength) -> Self {
908        Self {
909            from_end: true,
910            offset,
911        }
912    }
913
914    /// Where content starts along this axis, from the box's start edge,
915    /// given the `free` space (the box's size less the content's).
916    pub fn resolve(&self, free: Points) -> Points {
917        let d = self
918            .offset
919            .to_points(AbsoluteLength::Points(free), REM_SIZE);
920        if self.from_end { free - d } else { d }
921    }
922}
923
924/// `objectPosition`: where an image sits in its box once
925/// `objectFit` / `object-*` has sized it, as CSS's `object-position`
926/// places it (the center by default). The parts of a covering image
927/// outside the box are cropped.
928#[derive(Debug, Clone, Copy, PartialEq, Default)]
929#[non_exhaustive]
930pub struct ObjectPosition {
931    /// Horizontal.
932    pub x: PositionAxis,
933    /// Vertical.
934    pub y: PositionAxis,
935}
936
937impl ObjectPosition {
938    /// The center (the default).
939    pub const CENTER: Self = Self {
940        x: PositionAxis::CENTER,
941        y: PositionAxis::CENTER,
942    };
943
944    /// A position of two axes.
945    pub const fn new(x: PositionAxis, y: PositionAxis) -> Self {
946        Self { x, y }
947    }
948
949    /// Parses CSS's `<position>` as `object-position` takes it: one or two
950    /// keywords, percentages or lengths (`top`, `left bottom`, `25% 75%`,
951    /// `10px 0`), or edges with offsets (`right 10px bottom 20%`).
952    pub fn parse(s: &str) -> Option<Self> {
953        css::object_position(s)
954    }
955
956    /// The top left corner of content of `content` size placed in a box of
957    /// `size`.
958    pub fn place(&self, size: Size<Points>, content: Size<Points>) -> Point<Points> {
959        point(
960            self.x.resolve(size.width - content.width),
961            self.y.resolve(size.height - content.height),
962        )
963    }
964}
965
966impl std::fmt::Display for ObjectPosition {
967    /// CSS's four-value form (`left 50% top 10px`), which every position
968    /// can be written in.
969    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
970        let length = |l: DefiniteLength| match l {
971            DefiniteLength::Absolute(a) => format!("{}px", a.to_points(REM_SIZE).0),
972            DefiniteLength::Fraction(p) => format!("{}%", p.0 * 100.0),
973        };
974        write!(
975            f,
976            "{} {} {} {}",
977            if self.x.from_end { "right" } else { "left" },
978            length(self.x.offset),
979            if self.y.from_end { "bottom" } else { "top" },
980            length(self.y.offset),
981        )
982    }
983}
984
985/// `fontVariant`: OpenType features, as bits.
986#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
987pub struct FontVariant(pub u8);
988
989impl FontVariant {
990    /// `small-caps`.
991    pub const SMALL_CAPS: u8 = 1;
992    /// `oldstyle-nums`.
993    pub const OLDSTYLE_NUMS: u8 = 2;
994    /// `lining-nums`.
995    pub const LINING_NUMS: u8 = 4;
996    /// `tabular-nums`.
997    pub const TABULAR_NUMS: u8 = 8;
998    /// `proportional-nums`.
999    pub const PROPORTIONAL_NUMS: u8 = 16;
1000
1001    /// Parses space-separated variant names.
1002    pub fn parse(s: &str) -> Option<Self> {
1003        let mut bits = 0;
1004        for word in s.split_whitespace() {
1005            bits |= match word {
1006                "small-caps" => Self::SMALL_CAPS,
1007                "oldstyle-nums" => Self::OLDSTYLE_NUMS,
1008                "lining-nums" => Self::LINING_NUMS,
1009                "tabular-nums" => Self::TABULAR_NUMS,
1010                "proportional-nums" => Self::PROPORTIONAL_NUMS,
1011                "normal" => 0,
1012                _ => return None,
1013            };
1014        }
1015        Some(Self(bits))
1016    }
1017
1018    /// Whether `bit` is set.
1019    pub fn has(self, bit: u8) -> bool {
1020        self.0 & bit != 0
1021    }
1022
1023    /// The OpenType feature tags.
1024    pub fn tags(self) -> impl Iterator<Item = &'static str> {
1025        [
1026            (Self::SMALL_CAPS, "smcp"),
1027            (Self::OLDSTYLE_NUMS, "onum"),
1028            (Self::LINING_NUMS, "lnum"),
1029            (Self::TABULAR_NUMS, "tnum"),
1030            (Self::PROPORTIONAL_NUMS, "pnum"),
1031        ]
1032        .into_iter()
1033        .filter(move |&(bit, _)| self.has(bit))
1034        .map(|(_, tag)| tag)
1035    }
1036}
1037
1038impl ViewStyle {
1039    /// Drops the gradient backgrounds, so the background color shows: what
1040    /// press feedback and animated background colors do (a gradient is
1041    /// drawn over the color and would hide them).
1042    pub(crate) fn clear_background_images(&mut self) {
1043        if let Some(e) = self
1044            .effects
1045            .as_deref()
1046            .filter(|e| !e.background_images.is_empty())
1047        {
1048            let mut effects = e.clone();
1049            effects.background_images.clear();
1050            self.effects = crate::effects::shared(effects);
1051        }
1052    }
1053
1054    /// `clipPath`: the shape everything the view draws is clipped to.
1055    #[inline]
1056    pub fn clip_path(&self) -> Option<&ClipInset> {
1057        self.effects.as_deref().and_then(|e| e.clip_path.as_ref())
1058    }
1059
1060    /// The radius of each corner (before fitting them to a size with
1061    /// [`CornerRadii::fit`]).
1062    pub fn radii(&self) -> CornerRadii {
1063        let radii = self
1064            .corner_radius
1065            .map(|r| r.unwrap_or(self.border_radius).max(Points::ZERO));
1066        CornerRadii {
1067            continuous: self.continuous_corners,
1068            ..CornerRadii::circular(radii)
1069        }
1070    }
1071}
1072
1073impl Default for ViewStyle {
1074    fn default() -> Self {
1075        Self::DEFAULT
1076    }
1077}
1078
1079impl ViewStyle {
1080    /// [`Default::default`], as a constant.
1081    pub(crate) const DEFAULT: Self = Self {
1082        background_color: Color::TRANSPARENT,
1083        border_radius: Points::ZERO,
1084        corner_radius: Corners {
1085            top_left: None,
1086            top_right: None,
1087            bottom_right: None,
1088            bottom_left: None,
1089        },
1090        continuous_corners: false,
1091        borders: Borders::NONE,
1092        opacity: 1.0,
1093        overflow_hidden: false,
1094        transform: Transform::IDENTITY,
1095        tint_color: None,
1096        accent_color: None,
1097        elevation: Points::ZERO,
1098        transform_origin: TransformOrigin::CENTER,
1099        object_position: ObjectPosition::CENTER,
1100        backface_hidden: false,
1101        effects: None,
1102        blend_mode: BlendMode::Normal,
1103        backdrop_material: BackdropMaterial::UltraThin,
1104        glass_effect: GlassEffect::None,
1105        glass_tint_color: None,
1106        macos_backdrop: None,
1107        windows_backdrop: None,
1108        outline: Outline::NONE,
1109        hidden: false,
1110        cursor: Cursor::Auto,
1111        transition: None,
1112        animation: None,
1113        shows_label: false,
1114        label_arrow_only: false,
1115    };
1116}
1117
1118/// A shadow behind text (`textShadow`, `text-shadow-*`).
1119#[derive(Debug, Clone, Copy, PartialEq, Default)]
1120pub struct TextShadow {
1121    /// Color.
1122    pub color: Color,
1123    /// Horizontal offset.
1124    pub offset_x: Points,
1125    /// Vertical offset.
1126    pub offset_y: Points,
1127    /// Blur radius.
1128    pub radius: Points,
1129}
1130
1131/// Text properties as written on a node; unset values are inherited from
1132/// the enclosing text.
1133#[derive(Debug, Clone, Copy, PartialEq, Default)]
1134pub struct TextStyle {
1135    /// Foreground color.
1136    pub color: Option<Color>,
1137    /// Font size.
1138    pub font_size: Option<Points>,
1139    /// Font weight, `100..=900`.
1140    pub font_weight: Option<u16>,
1141    /// Line height.
1142    pub line_height: Option<Points>,
1143    /// Block alignment (only meaningful on a text block).
1144    pub text_align: Option<TextAlign>,
1145    /// Whether `text_align`'s left or right is a side (`left`, `right`),
1146    /// kept right to left, rather than the start or the end (`start`,
1147    /// `end`), which right to left is the other side.
1148    pub text_align_physical: bool,
1149    /// How far the first line of each paragraph starts from the leading
1150    /// edge (`textIndent`); `None` inherits. A negative value is 0: the
1151    /// first line does not hang into the margin.
1152    pub text_indent: Option<Points>,
1153    /// The same in ems of this node's font size (`"2em"`); overrides
1154    /// `text_indent` when set after it.
1155    pub text_indent_em: Option<f32>,
1156    /// Font family; `None` inherits (the system font at the root).
1157    pub font_family: Option<FontFamily>,
1158    /// Italic (`fontStyle`).
1159    pub italic: Option<bool>,
1160    /// Extra space between characters.
1161    pub letter_spacing: Option<Points>,
1162    /// Extra space between characters in ems of this node's font size
1163    /// (`"0.05em"`); overrides `letter_spacing` when set after it.
1164    pub letter_spacing_em: Option<f32>,
1165    /// A line-height length relative to this node's font size (`em` or
1166    /// a percentage), resolved before inheritance.
1167    pub line_height_em: Option<f32>,
1168    /// The font size relative to the inherited font size (`"0.875em"`,
1169    /// `"87.5%"`), resolved before inheritance; overrides `font_size`.
1170    pub font_size_em: Option<f32>,
1171    /// Line height as a multiple of the font size (`"1.5"`),
1172    /// inherited as a multiple.
1173    pub line_height_multiple: Option<f32>,
1174    /// Underline / strikethrough.
1175    pub decoration: Option<TextDecoration>,
1176    /// `textDecorationStyle`.
1177    pub decoration_style: Option<DecorationStyle>,
1178    /// `textDecorationThickness`.
1179    pub decoration_thickness: Option<Points>,
1180    /// `textUnderlineOffset`: below the baseline.
1181    pub underline_offset: Option<Points>,
1182    /// Color of the decoration lines; the text color by default.
1183    pub decoration_color: Option<Color>,
1184    /// Case transform.
1185    pub transform: Option<TextTransform>,
1186    /// The text shadow's color (`textShadow`, `text-shadow-*`: its widest
1187    /// layer's).
1188    pub shadow_color: Option<Color>,
1189    /// The text shadow's offset.
1190    pub shadow_offset: Option<Point<Points>>,
1191    /// The text shadow's blur radius.
1192    pub shadow_radius: Option<Points>,
1193    /// `fontVariant`.
1194    pub font_variant: Option<FontVariant>,
1195    /// `writingDirection`: right to left (`Some(true)`), left to right, or
1196    /// from the content (`None`, `auto`).
1197    pub writing_direction: Option<bool>,
1198    /// `textAlignVertical`: where text shorter than its box sits, 0% top
1199    /// (`auto`, `top`), 50% `center`, 100% `bottom`.
1200    pub align_vertical: Option<Percentage>,
1201    /// `placeholderColor`: an input's placeholder (not inherited).
1202    pub placeholder_color: Option<Color>,
1203    /// `selectionColor`: an input's or a selectable text's selection
1204    /// highlight (not inherited).
1205    pub selection_color: Option<Color>,
1206    /// `caretColor`: an input's caret (not inherited).
1207    pub caret_color: Option<Color>,
1208}
1209
1210impl TextStyle {
1211    /// [`Default::default`], as a constant.
1212    pub(crate) const DEFAULT: Self = Self {
1213        color: None,
1214        font_size: None,
1215        font_weight: None,
1216        line_height: None,
1217        text_align: None,
1218        text_align_physical: false,
1219        text_indent: None,
1220        text_indent_em: None,
1221        font_family: None,
1222        italic: None,
1223        letter_spacing: None,
1224        letter_spacing_em: None,
1225        line_height_em: None,
1226        font_size_em: None,
1227        line_height_multiple: None,
1228        decoration: None,
1229        decoration_style: None,
1230        decoration_thickness: None,
1231        underline_offset: None,
1232        decoration_color: None,
1233        transform: None,
1234        shadow_color: None,
1235        shadow_offset: None,
1236        shadow_radius: None,
1237        font_variant: None,
1238        writing_direction: None,
1239        align_vertical: None,
1240        placeholder_color: None,
1241        selection_color: None,
1242        caret_color: None,
1243    };
1244}
1245
1246impl TextStyle {
1247    /// The text shadow these properties describe, if any. Like NSShadow, an
1248    /// offset or radius without a color uses black at a third of opacity.
1249    pub fn shadow(&self) -> Option<TextShadow> {
1250        if self.shadow_color.is_none()
1251            && self.shadow_offset.is_none()
1252            && self.shadow_radius.is_none()
1253        {
1254            return None;
1255        }
1256        let color = self.shadow_color.unwrap_or(Color(0x0000_0055));
1257        if color.is_transparent() {
1258            return None;
1259        }
1260        let offset = self.shadow_offset.unwrap_or_default();
1261        Some(TextShadow {
1262            color,
1263            offset_x: offset.x,
1264            offset_y: offset.y,
1265            radius: self.shadow_radius.unwrap_or_default().max(Points::ZERO),
1266        })
1267    }
1268}
1269
1270/// What `fill` or `stroke` paints with (CSS's and SVG's `<paint>`).
1271#[derive(Debug, Clone, Copy, PartialEq)]
1272pub enum SvgPaint {
1273    /// `none`: nothing.
1274    None,
1275    /// `currentColor`: the element's text color (`color`, inherited).
1276    CurrentColor,
1277    /// A color.
1278    Color(Color),
1279}
1280
1281/// SVG's paint properties, as CSS has them on any element and inherits
1282/// them (`fill`, `stroke`, `strokeWidth`, `strokeDasharray`; `fill-*` /
1283/// `stroke-*`): what the shapes a Rust component draws paint with (the
1284/// marks of `nsh/base/plot`), read through a drawing's
1285/// [`crate::canvas::ViewPaint`]s. Unset values inherit; at the root they
1286/// are CSS's initial values, which the drawing names.
1287#[derive(Debug, Clone, PartialEq, Default)]
1288#[non_exhaustive]
1289pub struct PaintStyle {
1290    /// `fill`.
1291    pub fill: Option<SvgPaint>,
1292    /// `stroke`.
1293    pub stroke: Option<SvgPaint>,
1294    /// `strokeWidth`.
1295    pub stroke_width: Option<Points>,
1296    /// `strokeDasharray`: the dashes and gaps, empty for `none`.
1297    pub stroke_dasharray: Option<Arc<[Points]>>,
1298}
1299
1300impl PaintStyle {
1301    /// These properties where set, `parent`'s (the inherited ones) where
1302    /// not.
1303    pub fn inherit(&self, parent: &PaintStyle) -> PaintStyle {
1304        PaintStyle {
1305            fill: self.fill.or(parent.fill),
1306            stroke: self.stroke.or(parent.stroke),
1307            stroke_width: self.stroke_width.or(parent.stroke_width),
1308            stroke_dasharray: self
1309                .stroke_dasharray
1310                .clone()
1311                .or_else(|| parent.stroke_dasharray.clone()),
1312        }
1313    }
1314}
1315
1316/// A complete node style, split by consumer.
1317#[derive(Debug, Clone)]
1318pub struct Style {
1319    /// Layout properties, consumed by taffy.
1320    pub layout: taffy::Style,
1321    /// Visual properties of the native view.
1322    pub view: ViewStyle,
1323    /// Text properties.
1324    pub text: TextStyle,
1325    /// SVG's paint properties (inherited, as text properties are).
1326    pub paint: PaintStyle,
1327    /// Visual properties driven by native animation nodes; they override
1328    /// the static values while bound.
1329    pub animated: Vec<(crate::animation::AnimationProp, crate::animation::NodeId)>,
1330    /// `zIndex`: stacking order among siblings (higher on top).
1331    pub z_index: i32,
1332    /// `verticalAlign`: where the element sits in its line when it is
1333    /// inside a `<Text>`.
1334    pub vertical_align: VerticalAlign,
1335    /// `direction`: right to left (`Some(true)`), left to right, or
1336    /// inherited (`None`).
1337    pub direction: Option<bool>,
1338    /// Start / end properties, placed by the resolved direction.
1339    pub logical: Logical,
1340    /// Values that only show together with another property.
1341    pub(crate) pending: Pending,
1342    /// CSS's `perspective` (`perspective-*`, `Styled::perspective`): the
1343    /// depth the view gives its children's 3D transforms, seen from its
1344    /// center; the core composes it into their transforms.
1345    pub perspective: Option<Points>,
1346}
1347
1348/// Values of properties that take effect only together with another one,
1349/// kept so that the result does not depend on the order they are set in:
1350/// `outlineWidth` under `outlineStyle: "none"` and the border widths under
1351/// `borderStyle: "none"` (no outline, no border, as in CSS),
1352/// `animationDuration` and the other `animation*` keys before
1353/// `animationName`.
1354#[derive(Clone, Default)]
1355pub(crate) struct Pending {
1356    /// `outlineWidth` as set.
1357    outline_width: Points,
1358    /// `outlineStyle: "none"` / `"hidden"`.
1359    outline_hidden: bool,
1360    /// The border widths as set: top, right, bottom, left.
1361    border_widths: [Points; 4],
1362    /// `borderStartWidth`, `borderEndWidth` as set.
1363    border_logical: [Option<Points>; 2],
1364    /// `borderStyle: "none"` / `"hidden"`: every used width is 0.
1365    border_hidden: bool,
1366    /// `position: "fixed"`: laid out and mounted in its root view's box.
1367    pub(crate) fixed_position: bool,
1368    /// `position: "sticky"`: laid out as `relative`, its insets where it
1369    /// sticks in the viewport of the scroll view around it.
1370    pub(crate) sticky_position: bool,
1371    /// `animationDuration`.
1372    animation_duration: Option<f32>,
1373    /// `animationDelay`.
1374    animation_delay: Option<f32>,
1375    /// `animationTimingFunction`.
1376    animation_easing: Option<[f32; 4]>,
1377    /// `animationIterationCount` (`None` inside: forever).
1378    animation_iterations: Option<Option<u32>>,
1379    /// `animationFrameRate` (`None` inside: the screen's highest).
1380    animation_frame_rate: Option<Option<f32>>,
1381    /// The `env()` terms of the padding and margin, added by the core to
1382    /// the lengths their declarations set.
1383    pub(crate) env: EnvEdges,
1384    /// `objectFit`: how an image or a video fits its box (`None`: the
1385    /// element's default).
1386    pub(crate) object_fit: Option<crate::ResizeMode>,
1387    /// `numberOfLines`: the most lines of a text (`Some(0)`, `none`: no clamp
1388    /// over a class's).
1389    pub(crate) number_of_lines: Option<u32>,
1390    /// `textOverflow`: where a clamped text is cut.
1391    pub(crate) text_overflow: Option<EllipsizeMode>,
1392    /// `userSelect`: whether a text can be selected (`None`, `auto`: the
1393    /// view's around it, else the platform's).
1394    pub(crate) user_select: Option<bool>,
1395    /// `pointerEvents`: which touches the view and the views in it take.
1396    pub(crate) pointer_events: Option<crate::props::PointerEvents>,
1397    /// The `boxShadow` layers (by index) that name no color: CSS's
1398    /// `currentColor`, filled in by [`Style::apply_current_color`].
1399    current_shadows: u64,
1400    /// The `textShadow` names no color.
1401    current_text_shadow: bool,
1402    /// The color properties set to `currentColor` last ([`current_bits`]),
1403    /// filled in by [`Style::apply_current_color`].
1404    current_colors: u16,
1405    /// The `filter` list's `drop-shadow()`s (by index) that name no color:
1406    /// CSS's `currentColor`.
1407    current_drop_shadows: u64,
1408    /// Values that write `currentColor` inside them (a gradient's stop, a
1409    /// `color-mix()`, a shadow's color), by property: parsed again with
1410    /// the color by [`Style::apply_current_color`].
1411    current_values: Vec<(StyleKey, Box<str>)>,
1412    /// How many entries of the transform list each [`TransformProperty`]
1413    /// holds, in their order, then the steps Rust components bind after
1414    /// them ([`StyleDecl::Transform`]).
1415    transform_counts: [u8; TRANSFORM_PARTS],
1416}
1417
1418/// [`TransformProperty`]'s parts of a transform list, and the bound steps
1419/// after them.
1420const TRANSFORM_PARTS: usize = 5;
1421
1422/// The properties a view's transform is made of, in the order CSS
1423/// composes them: `translate`, `rotate`, `scale`, then `transform` (CSS's
1424/// string, or a list of steps whose amounts may be animated values).
1425#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1426pub enum TransformProperty {
1427    /// `translate`.
1428    Translate,
1429    /// `rotate`.
1430    Rotate,
1431    /// `scale`.
1432    Scale,
1433    /// `transform`.
1434    Transform,
1435}
1436
1437/// Bookkeeping, not what the style shows: styles that look the same print
1438/// the same (tests compare typed styles and classes so).
1439impl std::fmt::Debug for Pending {
1440    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1441        f.write_str("Pending")
1442    }
1443}
1444
1445impl Pending {
1446    /// `animation` with the `animation*` values set.
1447    fn animation(&self, mut animation: KeyframeAnimation) -> KeyframeAnimation {
1448        if let Some(ms) = self.animation_duration {
1449            animation.duration = ms;
1450        }
1451        if let Some(ms) = self.animation_delay {
1452            animation.delay = ms;
1453        }
1454        if let Some(easing) = self.animation_easing {
1455            animation.easing = easing;
1456        }
1457        if let Some(count) = self.animation_iterations {
1458            animation.iterations = count;
1459        }
1460        if let Some(hz) = self.animation_frame_rate {
1461            animation.frame_rate = hz;
1462        }
1463        animation
1464    }
1465}
1466
1467/// A CSS environment variable (`env()`) a padding or margin may use.
1468#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1469pub enum EnvVar {
1470    /// `safe-area-inset-top`: the top inset of the root view the node
1471    /// renders in.
1472    SafeAreaInsetTop,
1473    /// `safe-area-inset-right`.
1474    SafeAreaInsetRight,
1475    /// `safe-area-inset-bottom`.
1476    SafeAreaInsetBottom,
1477    /// `safe-area-inset-left`.
1478    SafeAreaInsetLeft,
1479    /// `keyboard-inset-height` (the VirtualKeyboard API's): the software
1480    /// keyboard's height over the surface, 0 while it is hidden.
1481    KeyboardInsetHeight,
1482}
1483
1484impl EnvVar {
1485    /// The variable named `name`, if NSH has it.
1486    pub(crate) fn parse(name: &str) -> Option<Self> {
1487        Some(match name {
1488            "safe-area-inset-top" => Self::SafeAreaInsetTop,
1489            "safe-area-inset-right" => Self::SafeAreaInsetRight,
1490            "safe-area-inset-bottom" => Self::SafeAreaInsetBottom,
1491            "safe-area-inset-left" => Self::SafeAreaInsetLeft,
1492            "keyboard-inset-height" => Self::KeyboardInsetHeight,
1493            _ => return None,
1494        })
1495    }
1496}
1497
1498/// The `env()` terms of a node's padding and margin by physical edge (top,
1499/// right, bottom, left).
1500#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1501pub(crate) struct EnvEdges {
1502    /// The padding's.
1503    pub(crate) padding: [Option<EnvVar>; 4],
1504    /// The margin's.
1505    pub(crate) margin: [Option<EnvVar>; 4],
1506}
1507
1508impl EnvEdges {
1509    /// Whether no edge has a term.
1510    pub(crate) fn is_empty(&self) -> bool {
1511        *self == Self::default()
1512    }
1513}
1514
1515/// A padding or margin value using `env()`: `env(name)`, `env(name,
1516/// <length>)`, `calc(env(name) + <length>)` or `calc(<length> +
1517/// env(name))`. `None` when `s` uses no `env()`; else the length part (in
1518/// points) and the variable (none when an unknown name's fallback stands
1519/// in for it), or an error for anything else.
1520pub(crate) fn env_length(s: &str) -> Option<Result<(f32, Option<EnvVar>), StyleError>> {
1521    if !s.contains("env(") {
1522        return None;
1523    }
1524    // One term: `env(...)` or a length.
1525    fn term(s: &str) -> Option<(f32, Option<EnvVar>)> {
1526        let Some(args) = s.strip_prefix("env(").and_then(|r| r.strip_suffix(')')) else {
1527            return Some((css::length(s)?, None));
1528        };
1529        let (name, fallback) = match args.split_once(',') {
1530            Some((name, fallback)) => (name.trim(), Some(fallback.trim())),
1531            None => (args.trim(), None),
1532        };
1533        match EnvVar::parse(name) {
1534            Some(var) => Some((0.0, Some(var))),
1535            // CSS: an unknown variable is its fallback.
1536            None => Some((css::length(fallback?)?, None)),
1537        }
1538    }
1539    let parse = |s: &str| {
1540        let s = s.trim();
1541        let Some(inner) = s.strip_prefix("calc(").and_then(|r| r.strip_suffix(')')) else {
1542            return term(s);
1543        };
1544        // `a + b`, the `+` outside parentheses and between white space, as
1545        // CSS requires.
1546        let mut depth = 0i32;
1547        let mut plus = None;
1548        for (i, c) in inner.char_indices() {
1549            match c {
1550                '(' => depth += 1,
1551                ')' => depth -= 1,
1552                '+' if depth == 0 => {
1553                    let spaced = inner[..i].ends_with(char::is_whitespace)
1554                        && inner[i + 1..].starts_with(char::is_whitespace);
1555                    if !spaced || plus.is_some() {
1556                        return None;
1557                    }
1558                    plus = Some(i);
1559                }
1560                _ => {}
1561            }
1562        }
1563        let at = plus?;
1564        let (a, b) = (term(inner[..at].trim())?, term(inner[at + 1..].trim())?);
1565        if a.1.is_some() && b.1.is_some() {
1566            return None;
1567        }
1568        Some((a.0 + b.0, a.1.or(b.1)))
1569    };
1570    Some(parse(s).ok_or(StyleError::InvalidValue))
1571}
1572
1573/// The physical edges (top, right, bottom, left) a margin or padding key
1574/// sets.
1575fn edges(key: StyleKey) -> &'static [usize] {
1576    use StyleKey as K;
1577    match key {
1578        K::Margin | K::Padding => &[0, 1, 2, 3],
1579        K::MarginHorizontal | K::PaddingHorizontal => &[1, 3],
1580        K::MarginVertical | K::PaddingVertical => &[0, 2],
1581        K::MarginTop | K::PaddingTop => &[0],
1582        K::MarginRight | K::PaddingRight => &[1],
1583        K::MarginBottom | K::PaddingBottom => &[2],
1584        _ => &[3],
1585    }
1586}
1587
1588/// The length part of an `env()` value, in points ([`env_length`]).
1589fn env_points(v: StyleValue<'_>) -> Points {
1590    match v {
1591        StyleValue::Str(s) => px(env_length(s).and_then(Result::ok).map_or(0.0, |(l, _)| l)),
1592        _ => Points::ZERO,
1593    }
1594}
1595
1596/// A padding edge: its length and its `env()` term.
1597fn padding_edge(v: StyleValue<'_>) -> Result<(LengthPercentage, Option<EnvVar>), StyleError> {
1598    if let StyleValue::Str(s) = v
1599        && let Some(env) = env_length(s)
1600    {
1601        let (length, var) = env?;
1602        // Padding is never negative.
1603        if length < 0.0 {
1604            return Err(StyleError::InvalidValue);
1605        }
1606        return Ok((LengthPercentage::length(length), var));
1607    }
1608    Ok((lp_or_zero(v)?, None))
1609}
1610
1611/// A margin edge: its length and its `env()` term.
1612fn margin_edge(v: StyleValue<'_>) -> Result<(LengthPercentageAuto, Option<EnvVar>), StyleError> {
1613    if let StyleValue::Str(s) = v
1614        && let Some(env) = env_length(s)
1615    {
1616        let (length, var) = env?;
1617        return Ok((LengthPercentageAuto::length(length), var));
1618    }
1619    Ok((lpa_or_zero(v)?, None))
1620}
1621
1622/// Properties named by start and end (`marginStart`, `borderTopEndRadius`
1623/// ...): left and right in left-to-right layouts, the other way around in
1624/// right-to-left ones.
1625#[derive(Debug, Clone, Copy, PartialEq, Default)]
1626pub struct Logical {
1627    /// `marginStart`, `marginEnd`.
1628    pub margin: [Option<LengthPercentageAuto>; 2],
1629    /// `paddingStart`, `paddingEnd`.
1630    pub padding: [Option<LengthPercentage>; 2],
1631    /// `start`, `end`.
1632    pub inset: [Option<LengthPercentageAuto>; 2],
1633    /// `borderStartWidth`, `borderEndWidth`.
1634    pub border_width: [Option<Points>; 2],
1635    /// `borderStartColor`, `borderEndColor`.
1636    pub border_color: [Option<Color>; 2],
1637    /// `borderTopStartRadius`, `borderTopEndRadius`,
1638    /// `borderBottomEndRadius`, `borderBottomStartRadius`.
1639    pub radius: [Option<Points>; 4],
1640}
1641
1642impl Logical {
1643    /// Whether no start / end property is set.
1644    pub fn is_empty(&self) -> bool {
1645        *self == Self::default()
1646    }
1647}
1648
1649fn set_side<T>(rect: &mut taffy::Rect<T>, left: bool, value: T) {
1650    if left {
1651        rect.left = value;
1652    } else {
1653        rect.right = value;
1654    }
1655}
1656
1657/// Gives an unset `alignContent` (taffy's `normal`) its meaning for the
1658/// node's display: React Native's `flex-start` for flex (and block)
1659/// containers, where taffy's `normal` would stretch wrapped lines, and
1660/// CSS's `normal` for grids, whose auto tracks then stretch to fill the
1661/// container. (`justifyContent`'s `normal` is already `flex-start` in
1662/// flex containers.)
1663pub(crate) fn resolve_normal_alignment(layout: &mut taffy::Style) {
1664    if layout.display != Display::Grid && layout.align_content == AlignContent::NORMAL {
1665        layout.align_content = AlignContent::FLEX_START;
1666    }
1667}
1668
1669/// The layout style of a view that nothing styles: React Native's defaults
1670/// ([`Style::default`]'s) with `alignContent` resolved.
1671pub(crate) fn unstyled_layout() -> taffy::Style {
1672    let mut layout = Style::default().layout;
1673    resolve_normal_alignment(&mut layout);
1674    layout
1675}
1676
1677/// Lays a node out in direction `rtl`: its left and right properties keep
1678/// their sides, as in CSS, and its start / end ones take the sides the
1679/// direction gives them.
1680pub(crate) fn apply_direction(
1681    layout: &mut taffy::Style,
1682    view: &mut ViewStyle,
1683    logical: &Logical,
1684    rtl: bool,
1685) {
1686    layout.direction = if rtl {
1687        taffy::Direction::Rtl
1688    } else {
1689        taffy::Direction::Ltr
1690    };
1691    if logical.is_empty() {
1692        return;
1693    }
1694    // Start is the left side left to right.
1695    for (i, left) in [!rtl, rtl].into_iter().enumerate() {
1696        if let Some(v) = logical.margin[i] {
1697            set_side(&mut layout.margin, left, v);
1698        }
1699        if let Some(v) = logical.padding[i] {
1700            set_side(&mut layout.padding, left, v);
1701        }
1702        if let Some(v) = logical.inset[i] {
1703            set_side(&mut layout.inset, left, v);
1704        }
1705        let side = if left { 3 } else { 1 };
1706        if let Some(w) = logical.border_width[i] {
1707            set_side(&mut layout.border, left, LengthPercentage::length(w.0));
1708            *view.borders.width_mut(side) = w;
1709        }
1710        if let Some(c) = logical.border_color[i] {
1711            view.borders.colors[side] = c;
1712        }
1713    }
1714    // Corners: top start, top end, bottom end, bottom start.
1715    let [top_start, top_end, bottom_end, bottom_start] = logical.radius;
1716    let c = &mut view.corner_radius;
1717    let (top_left, top_right, bottom_right, bottom_left) = if rtl {
1718        (top_end, top_start, bottom_start, bottom_end)
1719    } else {
1720        (top_start, top_end, bottom_end, bottom_start)
1721    };
1722    for (corner, r) in [
1723        (&mut c.top_left, top_left),
1724        (&mut c.top_right, top_right),
1725        (&mut c.bottom_right, bottom_right),
1726        (&mut c.bottom_left, bottom_left),
1727    ] {
1728        if r.is_some() {
1729            *corner = r;
1730        }
1731    }
1732}
1733
1734impl Default for Style {
1735    /// React Native defaults, which differ from CSS (and taffy) defaults.
1736    fn default() -> Self {
1737        let layout = taffy::Style {
1738            display: Display::Flex,
1739            position: Position::Relative,
1740            flex_direction: FlexDirection::Column,
1741            flex_shrink: 0.0,
1742            // Unset: `flex-start` (React Native) outside grids, CSS's
1743            // `normal` in grids (`resolve_normal_alignment`).
1744            align_content: AlignContent::NORMAL,
1745            // Unset: 0, as in Yoga (`min_len`).
1746            min_size: taffy::Size {
1747                width: LengthPercentageAuto::length(0.0),
1748                height: LengthPercentageAuto::length(0.0),
1749            },
1750            ..taffy::Style::DEFAULT
1751        };
1752        Self {
1753            layout,
1754            view: ViewStyle::default(),
1755            text: TextStyle::default(),
1756            paint: PaintStyle::default(),
1757            animated: Vec::new(),
1758            z_index: 0,
1759            vertical_align: VerticalAlign::Baseline,
1760            direction: None,
1761            logical: Logical::default(),
1762            pending: Pending::default(),
1763            perspective: None,
1764        }
1765    }
1766}
1767
1768/// Which TypeScript style interface a property belongs to (each extends
1769/// the one before: layout, then views, then text or images).
1770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1771pub(crate) enum StyleGroup {
1772    Layout,
1773    View,
1774    Text,
1775    Image,
1776    Input,
1777}
1778
1779/// A style property's TypeScript declaration (`js::style`).
1780#[derive(Debug, Clone, Copy)]
1781pub(crate) struct StyleType {
1782    pub(crate) name: &'static str,
1783    pub(crate) group: StyleGroup,
1784    pub(crate) ts: &'static str,
1785    pub(crate) doc: Option<&'static str>,
1786}
1787
1788/// The style properties the JS bridge decodes itself (objects and lists,
1789/// `crates/nsh-js/src/protocol.rs`), for the TypeScript declarations.
1790pub(crate) const OBJECT_STYLE_TYPES: &[StyleType] = &[];
1791
1792macro_rules! style_keys {
1793    ($($key:ident = $name:literal: $group:ident $ts:literal $($doc:literal)?),* $(,)?) => {
1794        /// The style properties' TypeScript declarations, in order.
1795        pub(crate) const STYLE_TYPES: &[StyleType] = &[$(StyleType {
1796            name: $name,
1797            group: StyleGroup::$group,
1798            ts: $ts,
1799            doc: style_keys!(@doc $($doc)?),
1800        }),*];
1801
1802        /// A style property, by its React Native name.
1803        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1804        pub enum StyleKey {
1805            $(
1806                #[doc = concat!("`", $name, "`")]
1807                $key,
1808            )*
1809        }
1810
1811        impl StyleKey {
1812            /// The key named `name` (React Native's camel case).
1813            pub fn parse(name: &str) -> Option<StyleKey> {
1814                Some(match name {
1815                    $($name => StyleKey::$key,)*
1816                    _ => return None,
1817                })
1818            }
1819
1820            /// The React Native name.
1821            pub fn name(self) -> &'static str {
1822                match self {
1823                    $(StyleKey::$key => $name,)*
1824                }
1825            }
1826        }
1827    };
1828    (@doc) => { None };
1829    (@doc $doc:literal) => { Some($doc) };
1830}
1831
1832style_keys! {
1833    Display = "display": Layout "\"flex\" | \"grid\" | \"block\" | \"flow-root\" | \"none\"" "`flex` lays the children out in a row unless `flexDirection` (or a class) sets a direction, as in CSS; a view that sets no display lays them out in a column.",
1834    BoxSizing = "boxSizing": Layout "\"border-box\" | \"content-box\"" "The box that width and height include.",
1835    Position = "position": Layout "\"relative\" | \"absolute\" | \"static\" | \"fixed\" | \"sticky\"" "`static` stays in flow and lets absolute descendants use the nearest positioned ancestor as their containing block. `fixed` lays an element out in its root view and mounts it above that root view's children. `sticky`: in the flow, and while its parent shows it stays `top` (in a horizontal scroll view `left`) from the start of the viewport of the scroll view around it, as far as the end of its parent's content box, or with `bottom` (`right`) at the viewport's end less the inset while its normal place is past it; it draws above its siblings of the same `zIndex`.",
1836    FlexDirection = "flexDirection": Layout "\"row\" | \"column\" | \"row-reverse\" | \"column-reverse\"",
1837    FlexWrap = "flexWrap": Layout "\"wrap\" | \"nowrap\" | \"wrap-reverse\"",
1838    Flex = "flex": Layout "number | \"none\" | \"auto\" | \"initial\" | (string & {})" "CSS's shorthand: `1` is `1 1 0`, `\"none\"` is `0 0 auto`, `\"auto\"` is `1 1 auto`, or grow, shrink and basis written out (`\"2 0 50%\"`).",
1839    FlexGrow = "flexGrow": Layout "number",
1840    FlexShrink = "flexShrink": Layout "number",
1841    FlexBasis = "flexBasis": Layout "DimensionValue | \"min-content\" | \"max-content\" | \"fit-content\"",
1842    JustifyContent = "justifyContent": Layout "Exclude<Distribute, \"stretch\"> | \"stretch\"",
1843    AlignItems = "alignItems": Layout "ItemAlign",
1844    AlignSelf = "alignSelf": Layout "ItemAlign | \"auto\"",
1845    AlignContent = "alignContent": Layout "Distribute",
1846    Width = "width": Layout "DimensionValue | \"min-content\" | \"max-content\" | \"fit-content\"",
1847    Height = "height": Layout "DimensionValue | \"min-content\" | \"max-content\" | \"fit-content\"",
1848    MinWidth = "minWidth": Layout "LengthValue",
1849    MinHeight = "minHeight": Layout "LengthValue",
1850    MaxWidth = "maxWidth": Layout "LengthValue",
1851    MaxHeight = "maxHeight": Layout "LengthValue",
1852    AspectRatio = "aspectRatio": Layout "number | \"auto\" | `${number}/${number}` | `${number} / ${number}`" "Width over height: a number (`1.5`) or CSS's ratio (`\"16 / 9\"`); `\"auto\"` is none.",
1853    Top = "top": Layout "DimensionValue | AnimatedNode" "An animated value only for a `position: \"sticky\"` view: how far from the top of the scroll view's viewport it sticks, following the value (below a header that moves).",
1854    Right = "right": Layout "DimensionValue",
1855    Bottom = "bottom": Layout "DimensionValue",
1856    Left = "left": Layout "DimensionValue | AnimatedNode" "An animated value only for a `position: \"sticky\"` view in a horizontal scroll view, as `top`.",
1857    Margin = "margin": Layout "DimensionValue | EnvValue",
1858    MarginHorizontal = "marginHorizontal": Layout "DimensionValue | EnvValue",
1859    MarginVertical = "marginVertical": Layout "DimensionValue | EnvValue",
1860    MarginTop = "marginTop": Layout "DimensionValue | EnvValue",
1861    MarginRight = "marginRight": Layout "DimensionValue | EnvValue",
1862    MarginBottom = "marginBottom": Layout "DimensionValue | EnvValue",
1863    MarginLeft = "marginLeft": Layout "DimensionValue | EnvValue",
1864    Padding = "padding": Layout "LengthValue | EnvValue",
1865    PaddingHorizontal = "paddingHorizontal": Layout "LengthValue | EnvValue",
1866    PaddingVertical = "paddingVertical": Layout "LengthValue | EnvValue",
1867    PaddingTop = "paddingTop": Layout "LengthValue | EnvValue",
1868    PaddingRight = "paddingRight": Layout "LengthValue | EnvValue",
1869    PaddingBottom = "paddingBottom": Layout "LengthValue | EnvValue",
1870    PaddingLeft = "paddingLeft": Layout "LengthValue | EnvValue",
1871    Gap = "gap": Layout "LengthValue",
1872    RowGap = "rowGap": Layout "LengthValue",
1873    ColumnGap = "columnGap": Layout "LengthValue",
1874    BorderWidth = "borderWidth": View "number",
1875    BorderTopWidth = "borderTopWidth": View "number",
1876    BorderRightWidth = "borderRightWidth": View "number",
1877    BorderBottomWidth = "borderBottomWidth": View "number",
1878    BorderLeftWidth = "borderLeftWidth": View "number",
1879    ZIndex = "zIndex": Layout "number" "Order among siblings (stable); also the native stacking order.",
1880    BoxShadow = "boxShadow": View "string | BoxShadowLayer[]" "CSS `box-shadow`: offsets, blur, spread and color, several separated by commas, `inset` for inner shadows; or its layers (`[{ x: 0, y: 6, blur: 18, color: \"#0000004d\" }]`), which take numbers, not strings. A layer without a color is the text color (CSS's `currentColor`).",
1881    BackgroundImage = "backgroundImage": View "string" "CSS gradients drawn over the background color: `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`, several separated by commas.",
1882    Filter = "filter": View "string" "CSS filters of the view and its content: `brightness()`, `contrast()`, `grayscale()`, `hue-rotate()`, `invert()`, `saturate()`, `sepia()`, `opacity()`, `blur()`, `drop-shadow()`.",
1883    BackdropFilter = "backdropFilter": View "string" "CSS filters of what is behind the view (`blur(10px)`).",
1884    MaskImage = "maskImage": View "string" "A CSS gradient whose alpha decides how much of the view is drawn, fully where opaque and not at all where transparent: `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`. Masks everything the view draws, its backdrop filter included, whose blur then draws without the system material's tint. It transitions (`transitionProperty: \"mask-image\"`, or `all`) between gradients of the same kind and number of stops, each stop's color and position on its own, so a fade can grow in from an edge; any other change, and to or from `none`, applies at once, as in CSS. Not drawn on Windows and GPUI.",
1885    ClipPath = "clipPath": View "string" "CSS's `clip-path` with an `inset()` shape: `\"inset(8px 0 0 50% round 12px)\"` moves each edge in (one to four lengths or percentages of the width or height, as `margin`) and rounds the corners (`round`, one to four radii in points), or `\"none\"`. Everything the view draws, the views in it included, shows only inside the shape, and only there does a press reach the view or the views in it. It transitions (`transitionProperty: \"clip-path\"`, or `all`), each edge and radius on its own, so a panel can open out of a corner; to or from `none` it changes at once, as in CSS.",
1886    GlassEffect = "glassEffect": View "\"none\" | \"regular\" | \"clear\"" "A glass material behind the view's content (Apple's Liquid Glass). Drawn on iOS 26 and macOS 26 and later; elsewhere the view's `backdropFilter` is drawn as before, so give a glass view a blur to fall back to.",
1887    GlassTintColor = "glassTintColor": View "ColorValue" "A tint of the glass material (`glassEffect`; iOS 26 and macOS 26 and later): the color the native glass takes on, or `null` for the system default. A transparent color is an explicit tint, not a reset. Has no effect without glass; the blur fallback on earlier systems stays unchanged.",
1888    MixBlendMode = "mixBlendMode": View "\"normal\" | \"multiply\" | \"screen\" | \"overlay\" | \"darken\" | \"lighten\" | \"color-dodge\" | \"color-burn\" | \"hard-light\" | \"soft-light\" | \"difference\" | \"exclusion\" | \"hue\" | \"saturation\" | \"color\" | \"luminosity\" | \"plus-darker\" | \"plus-lighter\"" "How the view blends with what is behind it.",
1889    OutlineWidth = "outlineWidth": View "number" "A line outside the border that takes no space.",
1890    OutlineColor = "outlineColor": View "ColorValue",
1891    OutlineStyle = "outlineStyle": View "\"solid\" | \"dashed\" | \"dotted\" | \"none\" | \"hidden\"",
1892    OutlineOffset = "outlineOffset": View "number" "Distance from the border edge (negative: inside).",
1893    Visibility = "visibility": View "\"visible\" | \"hidden\" | \"collapse\"" "Hidden views keep their space. On a nested text (a span), its characters keep their place, are not drawn, and are left out of copies and screen readers.",
1894    Cursor = "cursor": View "\"auto\" | \"default\" | \"context-menu\" | \"alias\" | \"copy\" | \"cell\" | \"pointer\" | \"text\" | \"vertical-text\" | \"wait\" | \"progress\" | \"help\" | \"crosshair\" | \"move\" | \"all-scroll\" | \"grab\" | \"grabbing\" | \"not-allowed\" | \"no-drop\" | \"zoom-in\" | \"zoom-out\" | \"col-resize\" | \"e-resize\" | \"w-resize\" | \"ew-resize\" | \"row-resize\" | \"n-resize\" | \"s-resize\" | \"ns-resize\" | \"ne-resize\" | \"nw-resize\" | \"se-resize\" | \"sw-resize\" | \"nesw-resize\" | \"nwse-resize\" | \"none\"" "The pointer over the view (pointers and desktops).",
1895    TransitionProperty = "transitionProperty": View "string" "The properties that animate when they change (`\"opacity, transform\"`, `\"all\"`, `\"colors\"`, `\"clip-path\"`, `\"mask-image\"`).",
1896    TransitionDuration = "transitionDuration": View "number | `${number}ms` | `${number}s`" "Milliseconds as a number, or `\"150ms\"` / `\"0.2s\"`.",
1897    TransitionDelay = "transitionDelay": View "number | `${number}ms` | `${number}s`",
1898    TransitionTimingFunction = "transitionTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})` | `spring(${string})`" "CSS's keywords and `cubic-bezier(x1, y1, x2, y2)` (a `y` outside 0..1 overshoots), or NSH's `spring(stiffness, damping)` / `spring(stiffness, damping, mass)`: a spring's physics (a mass of 1 by default) that times itself, lasting until it settles, so `transitionDuration` is not used.",
1899    AnimationName = "animationName": View "\"none\" | \"spin\" | \"ping\" | \"pulse\" | \"bounce\"" "A built-in keyframe animation, run natively.",
1900    AnimationDuration = "animationDuration": View "number | `${number}ms` | `${number}s`",
1901    AnimationDelay = "animationDelay": View "number | `${number}ms` | `${number}s`",
1902    AnimationTimingFunction = "animationTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
1903    AnimationIterationCount = "animationIterationCount": View "number | \"infinite\"",
1904    AnimationFrameRate = "animationFrameRate": View "number" "The highest frame rate the keyframe animation needs, in Hz (a slow spinner: 30); unset, the screen's highest. Platforms that can lower their frame rate honor it.",
1905    TextDecorationStyle = "textDecorationStyle": Text "\"solid\" | \"double\" | \"dotted\" | \"dashed\" | \"wavy\"",
1906    TextDecorationThickness = "textDecorationThickness": Text "number | \"auto\" | \"from-font\"",
1907    TextUnderlineOffset = "textUnderlineOffset": Text "number | \"auto\"",
1908    GridTemplateColumns = "gridTemplateColumns": Layout "string" "CSS grid tracks: `\"repeat(3, 1fr)\"`, `\"200px 1fr\"`, `minmax()`, `auto-fill` / `auto-fit`, line names (`\"[full-start] 1fr [content-start] 2fr [content-end full-end]\"`).",
1909    GridTemplateRows = "gridTemplateRows": Layout "string",
1910    GridAutoColumns = "gridAutoColumns": Layout "string" "Tracks of implicitly created columns.",
1911    GridAutoRows = "gridAutoRows": Layout "string",
1912    GridAutoFlow = "gridAutoFlow": Layout "\"row\" | \"column\" | \"dense\" | \"row dense\" | \"column dense\"",
1913    GridColumn = "gridColumn": Layout "number | string" "`\"1 / 3\"`, `\"span 2\"`, a line number or name (`\"content-start / full-end\"`, `\"span col\"`).",
1914    GridColumnStart = "gridColumnStart": Layout "number | string",
1915    GridColumnEnd = "gridColumnEnd": Layout "number | string",
1916    GridRow = "gridRow": Layout "number | string",
1917    GridRowStart = "gridRowStart": Layout "number | string",
1918    GridRowEnd = "gridRowEnd": Layout "number | string",
1919    JustifyItems = "justifyItems": Layout "ItemAlign" "How grid items sit in their areas along the row.",
1920    JustifySelf = "justifySelf": Layout "ItemAlign | \"auto\"",
1921    Direction = "direction": Layout "\"inherit\" | \"ltr\" | \"rtl\"" "Layout direction; inherited by default. As in CSS, `left` and `right` properties keep their sides right to left, while the `inlineStart` / `inlineEnd` ones (`marginStart`, `end`, ...) take the sides the direction gives them.",
1922    MarginStart = "marginStart": Layout "DimensionValue",
1923    MarginEnd = "marginEnd": Layout "DimensionValue",
1924    PaddingStart = "paddingStart": Layout "LengthValue",
1925    PaddingEnd = "paddingEnd": Layout "LengthValue",
1926    Start = "start": Layout "DimensionValue" "Left in left-to-right layouts, right in right-to-left ones.",
1927    End = "end": Layout "DimensionValue",
1928    BorderStartWidth = "borderStartWidth": View "number",
1929    BorderEndWidth = "borderEndWidth": View "number",
1930    BorderStartColor = "borderStartColor": View "ColorValue",
1931    BorderEndColor = "borderEndColor": View "ColorValue",
1932    BorderTopStartRadius = "borderTopStartRadius": View "number",
1933    BorderTopEndRadius = "borderTopEndRadius": View "number",
1934    BorderBottomEndRadius = "borderBottomEndRadius": View "number",
1935    BorderBottomStartRadius = "borderBottomStartRadius": View "number",
1936    BackgroundColor = "backgroundColor": View "ColorValue | AnimatedNode",
1937    BorderRadius = "borderRadius": View "number",
1938    BorderTopLeftRadius = "borderTopLeftRadius": View "number",
1939    BorderTopRightRadius = "borderTopRightRadius": View "number",
1940    BorderBottomRightRadius = "borderBottomRightRadius": View "number",
1941    BorderBottomLeftRadius = "borderBottomLeftRadius": View "number",
1942    BorderColor = "borderColor": View "ColorValue | AnimatedNode",
1943    BorderTopColor = "borderTopColor": View "ColorValue",
1944    BorderRightColor = "borderRightColor": View "ColorValue",
1945    BorderBottomColor = "borderBottomColor": View "ColorValue",
1946    BorderLeftColor = "borderLeftColor": View "ColorValue",
1947    BorderStyle = "borderStyle": View "\"solid\" | \"dashed\" | \"dotted\" | \"none\" | \"hidden\"" "`none` and `hidden`: no border whatever the widths (they take no space).",
1948    BorderCurve = "borderCurve": View "\"circular\" | \"continuous\"" "`continuous`: corners whose curvature eases into the edges (iOS app icons).",
1949    TintColor = "tintColor": Image "ColorValue" "Recolors a template image.",
1950    AccentColor = "accentColor": View "ColorValue" "CSS's `accent-color`: the color a system control shows its state in (`accent-*`), which a native component gets as its `accentColor` prop, such as a system switch's track when on; the control's own color when unset. Set on the control itself (not inherited).",
1951    ObjectFit = "objectFit": View "\"fill\" | \"contain\" | \"cover\" | \"none\" | \"scale-down\"" "CSS's `object-fit`: how an image or a video fits its box. Images cover it by default, videos are contained in it.",
1952    ObjectPosition = "objectPosition": Image "string" "Where the image sits in its box once `objectFit` has sized it, as CSS's `object-position`: keywords, percentages and lengths (`\"top\"`, `\"left bottom\"`, `\"25% 75%\"`, `\"right 10px bottom 20%\"`). A covering image is cropped around it. Default the center.",
1953    BackfaceVisibility = "backfaceVisibility": View "\"visible\" | \"hidden\"" "`\"hidden\"`: invisible while turned away (3D rotations).",
1954    Translate = "translate": View "string | number | AnimatedNode | [x: number | string | AnimatedNode, y?: number | string | AnimatedNode]" "CSS's `translate`: x, then y (`\"10px 20px\"`; percentages of the view's size, `\"-50% 0\"`); a number is points. An animated value moves it natively, along x (along both, each its own, in the `[x, y]` form).",
1955    Rotate = "rotate": View "string | number | AnimatedNode" "CSS's `rotate`: `\"45deg\"`, or about an axis, `\"x 90deg\"`; a number, and an animated value, is degrees about z.",
1956    Scale = "scale": View "string | number | AnimatedNode | [x: number | AnimatedNode, y: number | AnimatedNode]" "CSS's `scale`: `1.5`, `\"150%\"`, x and y (`\"1 2\"`, `[x, y]`).",
1957    Transform = "transform": View "string | TransformStep[]" "CSS's `transform`: `\"translateX(10px) rotate(45deg) scale(1.5)\"` (`translate()`, `scale()`, `rotate()` on any axis, `skew()` and `perspective()` functions), or `\"none\"`; or a list of steps whose amounts may be animated values (`[{ perspective: 800 }, { rotateY: angle }]`, a motion's `transform`). Applies after `translate`, `rotate` and `scale`, as in CSS.",
1958    TransformOrigin = "transformOrigin": View "string | (number | string)[]" "The point `transform` acts around: keywords, percentages and lengths (\"top left\", \"50% 0\", `[10, 20]`). Default the center.",
1959    Opacity = "opacity": View "number | AnimatedNode",
1960    Overflow = "overflow": View "\"visible\" | \"hidden\"",
1961    Color = "color": Text "ColorValue | AnimatedNode",
1962    FontSize = "fontSize": Text "number | `${number}em` | `${number}%`" "Points, or relative to the inherited font size as CSS's `em` and percentages (`\"0.875em\"`, `\"87.5%\"`), so a span scales with its paragraph.",
1963    FontWeight = "fontWeight": Text "\"normal\" | \"bold\" | number | `${number}`" "`\"normal\"` (400), `\"bold\"` (700) or 100–900.",
1964    LineHeight = "lineHeight": Text "number",
1965    FontFamily = "fontFamily": Text "string" "A system family or the name an imported font (`import Inter from \"./Inter.ttf\"`) evaluates to, or a list of them as CSS writes it, most preferred first (`\"Brand, 'Noto Sans SC', sans-serif\"`): characters the first lacks come from the next that has them.",
1966    FontStyle = "fontStyle": Text "\"normal\" | \"italic\"",
1967    LetterSpacing = "letterSpacing": Text "number",
1968    TextDecorationLine = "textDecorationLine": Text "\"none\" | \"underline\" | \"line-through\" | \"underline line-through\"",
1969    TextDecorationColor = "textDecorationColor": Text "ColorValue",
1970    WritingDirection = "writingDirection": Text "\"auto\" | \"ltr\" | \"rtl\"" "Base direction of the text; `auto` takes it from the content.",
1971    TextAlignVertical = "textAlignVertical": Text "\"auto\" | \"top\" | \"center\" | \"bottom\"" "Where text shorter than its box sits (`<Text>` with a height).",
1972    FontVariant = "fontVariant": Text "FontVariantName[] | (string & {})" "OpenType number and letter forms: a list (`[\"tabular-nums\"]`), or CSS's names separated by spaces (`\"tabular-nums small-caps\"`).",
1973    TextShadow = "textShadow": Text "string | TextShadowLayer[]" "CSS's `text-shadow`: offsets, blur and color (`\"0 1px 2px rgb(0 0 0 / 0.3)\"`), several separated by commas, drawn as the widest one; or its layers (`[{ x: 0, y: 1, blur: 2, color: \"#0000004d\" }]`); a layer without a color is the text color; `\"none\"`.",
1974    TextTransform = "textTransform": Text "\"none\" | \"uppercase\" | \"lowercase\" | \"capitalize\"",
1975    TextAlign = "textAlign": Text "\"auto\" | \"left\" | \"center\" | \"right\" | \"justify\" | \"start\" | \"end\"" "`left` and `right` keep their sides in right-to-left layouts; `start` and `end` follow the direction.",
1976    TextIndent = "textIndent": Text "number | `${number}em`" "CSS's `text-indent`: how far the first line of every paragraph starts from the block's leading edge, in points or in `em` of the font size; a negative value is 0 (the first line does not hang into the margin on every platform the same way). Default 0.",
1977    PlaceholderColor = "placeholderColor": Input "ColorValue" "An input's placeholder (`placeholder:text-*`).",
1978    SelectionColor = "selectionColor": Text "ColorValue" "An input's or a selectable text's selection highlight (`selection:bg-*`); iOS draws an input's caret in it too, unless `caretColor` is set (UIKit tints both with one color).",
1979    CaretColor = "caretColor": Input "ColorValue" "CSS's `caret-color`: an input's caret (`caret-*`); on iOS also its selection highlight (UIKit tints both with one color).",
1980    Fill = "fill": View "\"none\" | \"currentColor\" | ColorValue" "What the shapes a component draws are filled with (CSS's and SVG's `fill`, inherited; `fill-*`): a chart's areas.",
1981    Stroke = "stroke": View "\"none\" | \"currentColor\" | ColorValue" "What the outlines of the shapes a component draws are painted with (CSS's and SVG's `stroke`, inherited; `stroke-<color>`): a chart's lines and grid lines.",
1982    StrokeWidth = "strokeWidth": View "number | string" "The width of those outlines, a length (CSS's and SVG's `stroke-width`, inherited, 1 by default; `stroke-<number>`).",
1983    StrokeDasharray = "strokeDasharray": View "number | string" "The dashes and gaps of those outlines, lengths separated by spaces or commas, an odd list repeated, or `none` (CSS's and SVG's `stroke-dasharray`, inherited).",
1984    NumberOfLines = "numberOfLines": Text "number" "The most lines a `<Text>` shows (CSS's `line-clamp`, class `line-clamp-*`); 0 shows them all.",
1985    TextOverflow = "textOverflow": Text "\"ellipsis\" | \"clip\" | \"ellipsis-start\" | \"ellipsis-middle\"" "CSS's `text-overflow`: how a clamped `<Text>` is cut, with an ellipsis at its end (the default), clipped, or with the ellipsis at its start or in its middle.",
1986    UserSelect = "userSelect": View "\"auto\" | \"none\" | \"text\"" "CSS's `user-select`: whether a `<Text>` can be selected (`\"text\"`) or not (`\"none\"`); a view's reaches the texts in it; `\"auto\"` leaves it to the view around it, else to the platform.",
1987    PointerEvents = "pointerEvents": View "\"auto\" | \"none\" | \"box-none\" | \"box-only\"" "CSS's `pointer-events`: `\"none\"` takes no touches, for the view and the views in it unless one says `\"auto\"`; `\"box-none\"` takes none on the view itself, only on the views in it; `\"box-only\"` takes them on the view itself, never on the views in it.",
1988    VerticalAlign = "verticalAlign": View "\"baseline\" | \"text-top\" | \"text-bottom\" | \"middle\"" "Where a view or image inside a `<Text>` sits in its line (CSS `vertical-align`, `align-*`): on the baseline (the default; a view with text in it by the baseline of its first line of text, as an `inline-flex` box, else by its bottom edge, as an image), its top or bottom at the top or bottom of the text's font, or its middle half the font's x height above the baseline. The line grows to hold it.",
1989}
1990
1991/// A style property value as read from JS.
1992#[derive(Debug, Clone, Copy)]
1993pub enum StyleValue<'a> {
1994    /// A number.
1995    Number(f32),
1996    /// A string.
1997    Str(&'a str),
1998    /// `null` / `undefined`: resets the property to its default.
1999    Null,
2000}
2001
2002/// CSS's `line-height` (`lineHeight`).
2003#[derive(Debug, Clone, Copy, PartialEq, Default)]
2004pub enum LineHeight {
2005    /// The font's own (`normal`).
2006    #[default]
2007    Normal,
2008    /// Points (`"20px"`).
2009    Points(Points),
2010    /// A multiple of the font size, which nested texts take with their own
2011    /// size (a number: `1.5`).
2012    Multiple(f32),
2013    /// A multiple of the element's own font size, which nested texts take
2014    /// as points (`"1.5em"`, `"150%"`).
2015    Em(f32),
2016}
2017
2018impl From<Points> for LineHeight {
2019    fn from(points: Points) -> Self {
2020        LineHeight::Points(points)
2021    }
2022}
2023
2024impl From<crate::geometry::Rems> for LineHeight {
2025    fn from(rems: crate::geometry::Rems) -> Self {
2026        LineHeight::Points(rems.to_points(crate::geometry::REM_SIZE))
2027    }
2028}
2029
2030impl From<crate::geometry::AbsoluteLength> for LineHeight {
2031    fn from(length: crate::geometry::AbsoluteLength) -> Self {
2032        LineHeight::Points(length.to_points(crate::geometry::REM_SIZE))
2033    }
2034}
2035
2036/// A grid template as a style holds it (`gridTemplateColumns`).
2037#[derive(Debug, Clone, PartialEq)]
2038pub struct GridTemplateValue(Rc<grid::Template>);
2039
2040/// A style property's value, parsed ([`StyleKey::parse_value`]): what
2041/// [`Style::apply_value`] sets without parsing. TSX styles are parsed into
2042/// it once; classes and Rust's typed styles make it directly.
2043#[derive(Debug, Clone, PartialEq)]
2044pub enum PropertyValue {
2045    /// The property's default (`null`).
2046    Default,
2047    /// `display`.
2048    Display(Display),
2049    /// `boxSizing`.
2050    BoxSizing(taffy::BoxSizing),
2051    /// `position`: Taffy's, then whether it is `fixed` and `sticky`.
2052    Position(Position, bool, bool),
2053    /// `flexDirection`.
2054    FlexDirection(FlexDirection),
2055    /// `flexWrap`.
2056    FlexWrap(FlexWrap),
2057    /// `flex`: grow, shrink and basis.
2058    Flex(OrderedFloat<f32>, OrderedFloat<f32>, Dimension),
2059    /// A number (`flexGrow`, `zIndex`, `opacity`).
2060    Number(OrderedFloat<f32>),
2061    /// A number or none (`aspectRatio`).
2062    OptNumber(Option<OrderedFloat<f32>>),
2063    /// A size (`width`, `flexBasis`).
2064    Dimension(Dimension),
2065    /// A length, a percentage or `auto` (`margin`, `top`, `minWidth`).
2066    Lpa(LengthPercentageAuto),
2067    /// A length or a percentage (`padding`, `gap`).
2068    Lp(LengthPercentage),
2069    /// [`PropertyValue::Lpa`] or unset (`marginStart`).
2070    OptLpa(Option<LengthPercentageAuto>),
2071    /// [`PropertyValue::Lp`] or unset (`paddingStart`).
2072    OptLp(Option<LengthPercentage>),
2073    /// Points (`borderWidth`, `borderRadius`, `outlineWidth`).
2074    Points(Points),
2075    /// Points or unset (`fontSize`, a corner's radius).
2076    OptPoints(Option<Points>),
2077    /// `alignContent`, `justifyContent`.
2078    AlignContent(AlignContent),
2079    /// `alignItems`, `alignSelf` (`None`: `auto`), `justifyItems`.
2080    AlignItems(Option<AlignItems>),
2081    /// `verticalAlign`.
2082    VerticalAlign(VerticalAlign),
2083    /// Right to left (`Some(true)`), left to right, or unset (`direction`,
2084    /// `writingDirection`, `fontStyle`'s italic).
2085    OptBool(Option<bool>),
2086    /// A flag (`overflow: hidden`, `visibility: hidden`, `borderCurve:
2087    /// continuous`, `backfaceVisibility: hidden`).
2088    Bool(bool),
2089    /// A color or unset.
2090    Color(Option<Color>),
2091    /// CSS's `currentColor`, written out: the node's text color.
2092    CurrentColor,
2093    /// A value that writes `currentColor` inside it, parsed with a
2094    /// stand-in color, and its text, parsed again with the node's color.
2095    Deferred(Box<str>, Box<PropertyValue>),
2096    /// `borderStyle`, `outlineStyle`: the style and whether it hides the
2097    /// line (`none`).
2098    BorderStyle(BorderStyle, bool),
2099    /// `objectFit` (`None`: the element's default).
2100    ObjectFit(Option<crate::ResizeMode>),
2101    /// `objectPosition`.
2102    ObjectPosition(ObjectPosition),
2103    /// A transform property's steps, each with its animated value if any.
2104    Transform(Box<[(TransformKind, f32, Option<crate::animation::NodeId>)]>),
2105    /// `transformOrigin`.
2106    TransformOrigin(TransformOrigin),
2107    /// `fontWeight`.
2108    FontWeight(Option<u16>),
2109    /// `lineHeight`.
2110    LineHeight(LineHeight),
2111    /// `fontFamily`.
2112    FontFamily(Option<FontFamily>),
2113    /// `letterSpacing`: points, or ems of the font size.
2114    LetterSpacing(Option<Points>, Option<OrderedFloat<f32>>),
2115    /// `textIndent`: points, or ems of the font size.
2116    TextIndent(Option<Points>, Option<OrderedFloat<f32>>),
2117    /// `fontSize`: points, or a multiple of the inherited font size.
2118    FontSize(Option<Points>, Option<OrderedFloat<f32>>),
2119    /// `textDecorationLine`.
2120    TextDecoration(Option<TextDecoration>),
2121    /// `fontVariant`.
2122    FontVariant(Option<FontVariant>),
2123    /// `textShadow`: the widest layer and whether it names its color.
2124    TextShadow(Option<(TextShadow, bool)>),
2125    /// `textTransform`.
2126    TextTransform(Option<TextTransform>),
2127    /// `textAlign`, and whether it is physical (`left` / `right`).
2128    TextAlign(Option<TextAlign>, bool),
2129    /// `boxShadow`'s layers, each with whether it names its color.
2130    Shadows(Rc<[(BoxShadow, bool)]>),
2131    /// `backgroundImage`, `maskImage`.
2132    Gradients(Rc<[Gradient]>),
2133    /// `clipPath` (`None`: `none`).
2134    ClipPath(Option<ClipInset>),
2135    /// `filter`, `backdropFilter`, each with whether a `drop-shadow()`
2136    /// names its color.
2137    Filters(Rc<[(Filter, bool)]>),
2138    /// `glassEffect`.
2139    GlassEffect(GlassEffect),
2140    /// `mixBlendMode`.
2141    BlendMode(BlendMode),
2142    /// `cursor`.
2143    Cursor(Cursor),
2144    /// `transitionProperty`.
2145    TransitionProps(TransitionProps),
2146    /// Milliseconds (durations, delays).
2147    Ms(OrderedFloat<f32>),
2148    /// A timing function's cubic Bézier control points.
2149    Easing([OrderedFloat<f32>; 4]),
2150    /// `transitionTimingFunction`'s `spring(stiffness, damping, mass)`.
2151    Spring(crate::element::Spring),
2152    /// `animationName`.
2153    Keyframes(Option<Keyframes>),
2154    /// `animationIterationCount` (`None`: forever).
2155    Iterations(Option<u32>),
2156    /// `fill`, `stroke` (`None`: unset, inherited).
2157    Paint(Option<SvgPaint>),
2158    /// `strokeDasharray` (empty: `none`).
2159    Dashes(Option<Arc<[Points]>>),
2160    /// A margin or padding of a length (points) plus an environment
2161    /// variable (`calc(env(safe-area-inset-top) + 8px)`).
2162    EnvLength(Points, EnvVar),
2163    /// `textAlignVertical`: 0% the top, 50% the middle, 100% the bottom.
2164    AlignVertical(Option<Percentage>),
2165    /// `numberOfLines` (`Some(0)`: no clamp).
2166    NumberOfLines(Option<u32>),
2167    /// `textOverflow`.
2168    TextOverflow(Option<EllipsizeMode>),
2169    /// `pointerEvents`.
2170    PointerEvents(Option<crate::props::PointerEvents>),
2171    /// `textDecorationStyle`.
2172    DecorationStyle(Option<DecorationStyle>),
2173    /// `gridTemplateColumns`, `gridTemplateRows`.
2174    GridTemplate(GridTemplateValue),
2175    /// `gridAutoColumns`, `gridAutoRows`.
2176    GridTracks(Rc<[taffy::TrackSizingFunction]>),
2177    /// `gridAutoFlow`.
2178    GridAutoFlow(taffy::GridAutoFlow),
2179    /// `gridColumn`, `gridRow`.
2180    GridLine(taffy::Line<taffy::GridPlacement<String>>),
2181    /// `gridColumnStart` and the other lines.
2182    GridPlacement(taffy::GridPlacement<String>),
2183}
2184
2185impl PropertyValue {
2186    /// A grid template's value.
2187    pub(crate) fn grid_template(template: grid::Template) -> Self {
2188        PropertyValue::GridTemplate(GridTemplateValue(Rc::new(template)))
2189    }
2190}
2191
2192impl Eq for PropertyValue {}
2193
2194impl std::hash::Hash for PropertyValue {
2195    /// The variant and its payload: values that compare equal hash alike,
2196    /// and values that differ (a width's points, a padding's) hash apart,
2197    /// as the styles of Rust elements key their lowered rules by their
2198    /// declarations, which differ in little else. Floats hash as
2199    /// `OrderedFloat`s (`f32`'s `==` has `0.0 == -0.0`), taffy's lengths by
2200    /// the bits they compare by, lists by their length (their items are
2201    /// only compared). Every variant is matched, so a new one says how it
2202    /// hashes.
2203    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2204        use std::mem::discriminant;
2205
2206        use PropertyValue as V;
2207        /// A taffy length as it compares: its tag and its value's bits.
2208        fn raw(length: taffy::CompactLength) -> (usize, u32) {
2209            (length.tag(), length.value().to_bits())
2210        }
2211        discriminant(self).hash(state);
2212        match self {
2213            V::Default | V::CurrentColor => {}
2214            V::Display(d) => discriminant(d).hash(state),
2215            V::BoxSizing(b) => discriminant(b).hash(state),
2216            V::Position(p, a, b) => (discriminant(p), a, b).hash(state),
2217            V::FlexDirection(d) => discriminant(d).hash(state),
2218            V::FlexWrap(w) => discriminant(w).hash(state),
2219            V::Flex(grow, shrink, basis) => (grow, shrink, raw(basis.into_raw())).hash(state),
2220            V::Number(n) | V::Ms(n) => n.hash(state),
2221            V::OptNumber(n) => n.hash(state),
2222            V::Dimension(d) => raw(d.into_raw()).hash(state),
2223            V::Lpa(l) => raw(l.into_raw()).hash(state),
2224            V::Lp(l) => raw(l.into_raw()).hash(state),
2225            V::OptLpa(l) => l.map(|l| raw(l.into_raw())).hash(state),
2226            V::OptLp(l) => l.map(|l| raw(l.into_raw())).hash(state),
2227            V::Points(p) => p.hash(state),
2228            V::OptPoints(p) => p.hash(state),
2229            V::AlignContent(a) => (discriminant(&a.keyword), discriminant(&a.safety)).hash(state),
2230            V::AlignItems(a) => a
2231                .map(|a| (discriminant(&a.keyword), discriminant(&a.safety)))
2232                .hash(state),
2233            V::VerticalAlign(v) => v.hash(state),
2234            V::OptBool(b) => b.hash(state),
2235            V::Bool(b) => b.hash(state),
2236            V::Color(c) => c.hash(state),
2237            V::Deferred(s, _) => s.hash(state),
2238            V::BorderStyle(s, b) => (discriminant(s), b).hash(state),
2239            V::ObjectFit(f) => f.as_ref().map(discriminant).hash(state),
2240            V::ObjectPosition(p) => {
2241                (p.x.from_end, p.x.offset, p.y.from_end, p.y.offset).hash(state)
2242            }
2243            V::Transform(steps) => steps.len().hash(state),
2244            V::TransformOrigin(o) => (o.x, o.y, o.z).hash(state),
2245            V::FontWeight(w) => w.hash(state),
2246            V::LineHeight(l) => {
2247                discriminant(l).hash(state);
2248                if let LineHeight::Points(Points(v)) | LineHeight::Multiple(v) | LineHeight::Em(v) =
2249                    l
2250                {
2251                    OrderedFloat(*v).hash(state);
2252                }
2253            }
2254            V::FontFamily(f) => f.hash(state),
2255            V::LetterSpacing(p, n) | V::FontSize(p, n) | V::TextIndent(p, n) => (p, n).hash(state),
2256            V::TextDecoration(d) => d.hash(state),
2257            V::FontVariant(v) => v.hash(state),
2258            V::TextShadow(s) => s
2259                .map(|(s, b)| (s.color, s.offset_x, s.offset_y, s.radius, b))
2260                .hash(state),
2261            V::TextTransform(t) => t.hash(state),
2262            V::TextAlign(a, b) => (a.as_ref().map(discriminant), b).hash(state),
2263            V::Shadows(l) => l.len().hash(state),
2264            V::Gradients(l) => l.len().hash(state),
2265            V::ClipPath(c) => c.map(|c| (c.offsets, c.fractions, c.radii)).hash(state),
2266            V::Filters(l) => l.len().hash(state),
2267            V::GlassEffect(g) => discriminant(g).hash(state),
2268            V::BlendMode(m) => discriminant(m).hash(state),
2269            V::Cursor(c) => discriminant(c).hash(state),
2270            V::TransitionProps(p) => p.0.hash(state),
2271            V::Easing(e) => e.hash(state),
2272            V::Spring(s) => [s.stiffness, s.damping, s.mass]
2273                .map(OrderedFloat)
2274                .hash(state),
2275            V::Keyframes(k) => k.as_ref().map(discriminant).hash(state),
2276            V::Iterations(n) | V::NumberOfLines(n) => n.hash(state),
2277            V::Paint(p) => {
2278                p.as_ref().map(discriminant).hash(state);
2279                if let Some(SvgPaint::Color(c)) = p {
2280                    c.hash(state);
2281                }
2282            }
2283            V::Dashes(d) => d.as_deref().hash(state),
2284            V::EnvLength(p, var) => (p, discriminant(var)).hash(state),
2285            V::AlignVertical(p) => p.hash(state),
2286            V::TextOverflow(m) => m.hash(state),
2287            V::PointerEvents(p) => p.as_ref().map(discriminant).hash(state),
2288            V::DecorationStyle(s) => s.hash(state),
2289            V::GridTemplate(t) => t.0.0.len().hash(state),
2290            V::GridTracks(l) => l.len().hash(state),
2291            V::GridAutoFlow(f) => discriminant(f).hash(state),
2292            V::GridLine(l) => (discriminant(&l.start), discriminant(&l.end)).hash(state),
2293            V::GridPlacement(p) => discriminant(p).hash(state),
2294        }
2295    }
2296}
2297
2298/// One declaration of a [`StylePatch`].
2299#[derive(Debug, Clone, PartialEq)]
2300pub enum StyleDecl {
2301    /// A property.
2302    Set(StyleKey, PropertyValue),
2303    /// Sets a transform property to its steps, each driven by an animated
2304    /// value when it has one (the amount is then the identity until it is
2305    /// bound): the steps of other properties stay.
2306    SetTransform(
2307        TransformProperty,
2308        Box<[(TransformKind, f32, Option<crate::animation::NodeId>)]>,
2309    ),
2310    /// Appends a transform step after every property's, driven by an
2311    /// animated value when given (a Rust component's `bind_transform`).
2312    Transform(TransformKind, f32, Option<crate::animation::NodeId>),
2313    /// A property driven by a native animation node.
2314    Animated(crate::animation::AnimationProp, crate::animation::NodeId),
2315    /// A value the property takes unless a class or the style itself sets
2316    /// it (`display: "flex"`'s row, as CSS's): applied before the classes
2317    /// ([`StylePatch::apply_defaults`]), never by [`StyleDecl::apply`].
2318    Default(StyleKey, PropertyValue),
2319    /// The color property is the node's text color unless a class or the
2320    /// style sets it: CSS's `currentColor`, the color of a border or an
2321    /// outline whose width the style sets. Applied before the classes, as
2322    /// [`StyleDecl::Default`].
2323    CurrentColor(StyleKey),
2324}
2325
2326impl StyleDecl {
2327    /// Applies the declaration to `style`.
2328    pub fn apply(&self, style: &mut Style) -> Result<(), StyleError> {
2329        match self {
2330            StyleDecl::Set(key, value) => style.apply_value(*key, value),
2331            StyleDecl::SetTransform(property, steps) => style.set_transform(*property, steps),
2332            StyleDecl::Transform(kind, amount, node) => {
2333                // The bound steps are the list's last part: they go at its end.
2334                let index = style
2335                    .view
2336                    .transform
2337                    .push(*kind, *amount)
2338                    .ok_or(StyleError::InvalidValue)?;
2339                style.pending.transform_counts[TRANSFORM_PARTS - 1] += 1;
2340                if let Some(node) = node {
2341                    style
2342                        .animated
2343                        .push((crate::animation::AnimationProp::Transform(index), *node));
2344                }
2345                Ok(())
2346            }
2347            StyleDecl::Animated(prop, node) => {
2348                style.animated.push((*prop, *node));
2349                Ok(())
2350            }
2351            StyleDecl::Default(..) | StyleDecl::CurrentColor(_) => Ok(()),
2352        }
2353    }
2354}
2355
2356/// A style as written (`style={...}`): its declarations in order (the
2357/// shorthands of [`StylePatch::set`] before their longhands), kept so the
2358/// core can apply them again over class styles when those change.
2359#[derive(Debug, Clone, Default, PartialEq)]
2360pub struct StylePatch {
2361    decls: Vec<StyleDecl>,
2362}
2363
2364impl StylePatch {
2365    /// Applies `decl` to `style` and records it if it applied. A default
2366    /// ([`StyleDecl::Default`]) applies unless the patch sets the property.
2367    pub fn push(&mut self, style: &mut Style, decl: StyleDecl) -> Result<(), StyleError> {
2368        match &decl {
2369            StyleDecl::Default(key, value) if !self.sets(*key) => {
2370                style.apply_value(*key, value)?;
2371            }
2372            decl => decl.apply(style)?,
2373        }
2374        self.decls.push(decl);
2375        Ok(())
2376    }
2377
2378    /// Sets property `key` of the style object this patch records on
2379    /// `style`, and records it. As in React Native, a longhand
2380    /// (`borderTopWidth`, `marginHorizontal`, `flexGrow`, ...) wins over
2381    /// its shorthand (`borderWidth`, `margin`, `flex`) in one object
2382    /// whatever their order: a shorthand set after its longhands is
2383    /// recorded before them, and they apply again; a `null` longhand is
2384    /// unset, so its shorthand shows.
2385    pub fn set(
2386        &mut self,
2387        style: &mut Style,
2388        key: &str,
2389        value: StyleValue<'_>,
2390    ) -> Result<(), StyleError> {
2391        let key = StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?;
2392        if matches!(value, StyleValue::Null) && self.has_shorthand_of(key) {
2393            return Ok(());
2394        }
2395        let parsed = key.parse_value(value)?;
2396        style.apply_value(key, &parsed)?;
2397        if key == StyleKey::Display && matches!(value, StyleValue::Str("flex")) {
2398            // A CSS flex container is a row unless a direction is set
2399            // (by a class or this style, before or after).
2400            let row = PropertyValue::FlexDirection(FlexDirection::Row);
2401            if !self.sets(StyleKey::FlexDirection) {
2402                let _ = style.apply_value(StyleKey::FlexDirection, &row);
2403            }
2404            self.decls
2405                .push(StyleDecl::Default(StyleKey::FlexDirection, row));
2406        }
2407        if matches!(
2408            key,
2409            StyleKey::BoxShadow | StyleKey::TextShadow | StyleKey::Filter
2410        ) {
2411            // Its layers (`drop-shadow()`s) without a color are the text
2412            // color's: as a width's.
2413            let colorless = match key {
2414                StyleKey::BoxShadow => style.pending.current_shadows != 0,
2415                StyleKey::Filter => style.pending.current_drop_shadows != 0,
2416                _ => style.pending.current_text_shadow,
2417            };
2418            if colorless {
2419                self.insert_current_color(key);
2420            } else {
2421                self.decls.retain(|d| *d != StyleDecl::CurrentColor(key));
2422            }
2423        }
2424        if let Some(color) = key.current_color()
2425            && !matches!(value, StyleValue::Null)
2426        {
2427            self.insert_current_color(color);
2428        }
2429        let decl = StyleDecl::Set(key, parsed);
2430        let longhands = key.longhands();
2431        let Some(at) = self
2432            .decls
2433            .iter()
2434            .position(|d| matches!(d, StyleDecl::Set(k, _) if longhands.contains(k)))
2435        else {
2436            self.decls.push(decl);
2437            return Ok(());
2438        };
2439        // Nulls set before are dropped (the shorthand shows); the others
2440        // apply again over it.
2441        self.decls.retain(
2442            |d| !matches!(d, StyleDecl::Set(k, PropertyValue::Default) if longhands.contains(k)),
2443        );
2444        let at = at.min(self.decls.len());
2445        self.decls.insert(at, decl);
2446        for d in &self.decls[at + 1..] {
2447            if let StyleDecl::Set(k, v) = d
2448                && longhands.contains(k)
2449            {
2450                let _ = style.apply_value(*k, v);
2451            }
2452        }
2453        Ok(())
2454    }
2455
2456    /// Whether a shorthand of `key` is recorded.
2457    fn has_shorthand_of(&self, key: StyleKey) -> bool {
2458        self.decls
2459            .iter()
2460            .any(|d| matches!(d, StyleDecl::Set(k, _) if k.longhands().contains(&key)))
2461    }
2462
2463    /// Records that `key` is the node's text color where nothing sets it
2464    /// ([`StyleDecl::CurrentColor`]), once. These are kept first and in key
2465    /// order: they apply before the classes in any order, so styles that
2466    /// set the same keys compare equal.
2467    fn insert_current_color(&mut self, key: StyleKey) {
2468        let decl = StyleDecl::CurrentColor(key);
2469        if self.decls.contains(&decl) {
2470            return;
2471        }
2472        let at = self
2473            .decls
2474            .iter()
2475            .take_while(
2476                |d| matches!(d, StyleDecl::CurrentColor(k) if (*k as usize) < (key as usize)),
2477            )
2478            .count();
2479        self.decls.insert(at, decl);
2480    }
2481
2482    /// Whether a declaration sets `key`.
2483    fn sets(&self, key: StyleKey) -> bool {
2484        self.decls
2485            .iter()
2486            .any(|d| matches!(d, StyleDecl::Set(k, _) if *k == key))
2487    }
2488
2489    /// Applies every declaration to `style`, in order.
2490    pub fn apply(&self, style: &mut Style) {
2491        for decl in &self.decls {
2492            // Declarations were checked when they were recorded.
2493            let _ = decl.apply(style);
2494        }
2495    }
2496
2497    /// Applies the values the style gives properties that nothing sets
2498    /// ([`StyleDecl::Default`], [`StyleDecl::CurrentColor`] with `current`,
2499    /// the node's text color): to the style before its classes, which
2500    /// [`StylePatch::apply`] then follows.
2501    pub fn apply_defaults(&self, style: &mut Style, current: Color) {
2502        for decl in &self.decls {
2503            match decl {
2504                StyleDecl::Default(key, value) => {
2505                    let _ = style.apply_value(*key, value);
2506                }
2507                // A shadow's colorless layers take the color once the
2508                // style is in place ([`Style::apply_current_color`]).
2509                StyleDecl::CurrentColor(
2510                    StyleKey::BoxShadow | StyleKey::TextShadow | StyleKey::Filter,
2511                ) => {}
2512                StyleDecl::CurrentColor(key) => style.set_color(*key, current),
2513                _ => {}
2514            }
2515        }
2516    }
2517
2518    /// Whether a color of the style is the node's text color
2519    /// ([`StyleDecl::CurrentColor`]): it is styled again when the color
2520    /// it inherits changes.
2521    pub fn reads_current_color(&self) -> bool {
2522        // A side's color is set by its own key or by `borderColor`.
2523        let set = |k: StyleKey| match k {
2524            // A colorless shadow layer reads it for as long as it is there.
2525            StyleKey::BoxShadow | StyleKey::TextShadow | StyleKey::Filter => false,
2526            StyleKey::OutlineColor | StyleKey::BorderColor => self.sets(k),
2527            _ => self.sets(k) || self.sets(StyleKey::BorderColor),
2528        };
2529        self.decls.iter().any(|d| match d {
2530            StyleDecl::CurrentColor(k) => !set(*k),
2531            // `currentColor` written out, or inside a value.
2532            StyleDecl::Set(_, PropertyValue::CurrentColor | PropertyValue::Deferred(..)) => true,
2533            _ => false,
2534        })
2535    }
2536
2537    /// Whether there are no declarations.
2538    pub fn is_empty(&self) -> bool {
2539        self.decls.is_empty()
2540    }
2541
2542    /// The declarations.
2543    pub fn decls(&self) -> &[StyleDecl] {
2544        &self.decls
2545    }
2546}
2547
2548impl StyleKey {
2549    /// The color a width property draws in, CSS's `currentColor` unless
2550    /// something sets it.
2551    fn current_color(self) -> Option<StyleKey> {
2552        use StyleKey as K;
2553        Some(match self {
2554            K::BorderWidth => K::BorderColor,
2555            K::BorderTopWidth => K::BorderTopColor,
2556            K::BorderRightWidth => K::BorderRightColor,
2557            K::BorderBottomWidth => K::BorderBottomColor,
2558            K::BorderLeftWidth => K::BorderLeftColor,
2559            K::BorderStartWidth => K::BorderStartColor,
2560            K::BorderEndWidth => K::BorderEndColor,
2561            K::OutlineWidth => K::OutlineColor,
2562            _ => return None,
2563        })
2564    }
2565
2566    /// The properties that override this shorthand in a style object
2567    /// whatever their order (Yoga takes an edge's own value before its
2568    /// axis' and that of all edges, `flexGrow` before `flex`).
2569    fn longhands(self) -> &'static [StyleKey] {
2570        use StyleKey as K;
2571        match self {
2572            K::Margin => &[
2573                K::MarginHorizontal,
2574                K::MarginVertical,
2575                K::MarginTop,
2576                K::MarginRight,
2577                K::MarginBottom,
2578                K::MarginLeft,
2579            ],
2580            K::MarginHorizontal => &[K::MarginLeft, K::MarginRight],
2581            K::MarginVertical => &[K::MarginTop, K::MarginBottom],
2582            K::Padding => &[
2583                K::PaddingHorizontal,
2584                K::PaddingVertical,
2585                K::PaddingTop,
2586                K::PaddingRight,
2587                K::PaddingBottom,
2588                K::PaddingLeft,
2589            ],
2590            K::PaddingHorizontal => &[K::PaddingLeft, K::PaddingRight],
2591            K::PaddingVertical => &[K::PaddingTop, K::PaddingBottom],
2592            K::BorderWidth => &[
2593                K::BorderTopWidth,
2594                K::BorderRightWidth,
2595                K::BorderBottomWidth,
2596                K::BorderLeftWidth,
2597            ],
2598            K::BorderColor => &[
2599                K::BorderTopColor,
2600                K::BorderRightColor,
2601                K::BorderBottomColor,
2602                K::BorderLeftColor,
2603            ],
2604            K::Gap => &[K::RowGap, K::ColumnGap],
2605            K::Flex => &[K::FlexGrow, K::FlexShrink, K::FlexBasis],
2606            K::GridColumn => &[K::GridColumnStart, K::GridColumnEnd],
2607            K::GridRow => &[K::GridRowStart, K::GridRowEnd],
2608            _ => &[],
2609        }
2610    }
2611}
2612
2613/// Why a style property was rejected.
2614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2615pub enum StyleError {
2616    /// The property name is not supported.
2617    UnknownProperty,
2618    /// The value has the wrong type or format.
2619    InvalidValue,
2620}
2621
2622enum Len {
2623    Px(f32),
2624    Pct(f32),
2625    Auto,
2626}
2627
2628impl Len {
2629    fn parse(v: StyleValue<'_>) -> Result<Len, StyleError> {
2630        match v {
2631            StyleValue::Number(n) => Ok(Len::Px(n)),
2632            StyleValue::Str("auto") => Ok(Len::Auto),
2633            StyleValue::Str(s) => s
2634                .strip_suffix('%')
2635                .and_then(|p| p.trim().parse::<f32>().ok())
2636                .map(|p| Len::Pct(p / 100.0))
2637                .ok_or(StyleError::InvalidValue),
2638            StyleValue::Null => Ok(Len::Auto),
2639        }
2640    }
2641
2642    fn dim(self) -> Dimension {
2643        match self {
2644            Len::Px(v) => Dimension::length(v),
2645            Len::Pct(v) => Dimension::percent(v),
2646            Len::Auto => Dimension::auto(),
2647        }
2648    }
2649
2650    fn lpa(self) -> LengthPercentageAuto {
2651        match self {
2652            Len::Px(v) => LengthPercentageAuto::length(v),
2653            Len::Pct(v) => LengthPercentageAuto::percent(v),
2654            Len::Auto => LengthPercentageAuto::auto(),
2655        }
2656    }
2657
2658    fn lp(self) -> Result<LengthPercentage, StyleError> {
2659        match self {
2660            Len::Px(v) => Ok(LengthPercentage::length(v)),
2661            Len::Pct(v) => Ok(LengthPercentage::percent(v)),
2662            Len::Auto => Err(StyleError::InvalidValue),
2663        }
2664    }
2665}
2666
2667/// Intrinsic sizes are delegated to Taffy's sizing algorithms.
2668fn dimension(value: StyleValue<'_>) -> Result<Dimension, StyleError> {
2669    Ok(match value {
2670        StyleValue::Str("min-content") => Dimension::min_content(),
2671        StyleValue::Str("max-content") => Dimension::max_content(),
2672        StyleValue::Str("fit-content") => Dimension::fit_content(),
2673        value => Len::parse(value)?.dim(),
2674    })
2675}
2676
2677/// A zero-default length: `null` resets to 0 rather than `auto`.
2678fn lp_or_zero(v: StyleValue<'_>) -> Result<LengthPercentage, StyleError> {
2679    match v {
2680        StyleValue::Null => Ok(LengthPercentage::length(0.0)),
2681        v => Len::parse(v)?.lp(),
2682    }
2683}
2684
2685fn opt_lpa(v: StyleValue<'_>) -> Result<Option<LengthPercentageAuto>, StyleError> {
2686    match v {
2687        StyleValue::Null => Ok(None),
2688        v => Ok(Some(Len::parse(v)?.lpa())),
2689    }
2690}
2691
2692fn opt_lp(v: StyleValue<'_>) -> Result<Option<LengthPercentage>, StyleError> {
2693    match v {
2694        StyleValue::Null => Ok(None),
2695        v => Ok(Some(Len::parse(v)?.lp()?)),
2696    }
2697}
2698
2699/// Whether a value of `key` may write `currentColor` inside it (CSS's
2700/// properties that take a color, alone or in a gradient, a shadow or a
2701/// filter; `color` itself takes it alone: the inherited color).
2702fn defers_current_color(key: StyleKey) -> bool {
2703    matches!(
2704        key,
2705        StyleKey::BackgroundImage
2706            | StyleKey::MaskImage
2707            | StyleKey::Filter
2708            | StyleKey::BackdropFilter
2709            | StyleKey::BoxShadow
2710            | StyleKey::TextShadow
2711    ) || current_bits(key).is_some()
2712}
2713
2714/// The color properties `currentColor` fills, by bit of
2715/// `Pending::current_colors` ([`current_bits`]).
2716const CURRENT_KEYS: [StyleKey; 10] = [
2717    StyleKey::BorderTopColor,
2718    StyleKey::BorderRightColor,
2719    StyleKey::BorderBottomColor,
2720    StyleKey::BorderLeftColor,
2721    StyleKey::BorderStartColor,
2722    StyleKey::BorderEndColor,
2723    StyleKey::OutlineColor,
2724    StyleKey::BackgroundColor,
2725    StyleKey::TextDecorationColor,
2726    StyleKey::CaretColor,
2727];
2728
2729/// The bits of [`CURRENT_KEYS`] color property `key` sets (`borderColor`:
2730/// every side's), if it takes `currentColor`.
2731fn current_bits(key: StyleKey) -> Option<u16> {
2732    if key == StyleKey::BorderColor {
2733        return Some(0b1111);
2734    }
2735    let bit = CURRENT_KEYS.iter().position(|k| *k == key)?;
2736    Some(1 << bit)
2737}
2738
2739/// A minimum size: unset is 0, as in Yoga, so that flex items shrink
2740/// without measuring their content (React Native's layout, NSH's
2741/// default); `auto` is CSS's automatic minimum, which keeps a flex item
2742/// from shrinking below its content's min-content size.
2743fn min_len(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
2744    match v {
2745        StyleValue::Null => Ok(LengthPercentageAuto::length(0.0)),
2746        v => Ok(Len::parse(v)?.lpa()),
2747    }
2748}
2749
2750fn lpa_or_zero(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
2751    match v {
2752        StyleValue::Null => Ok(LengthPercentageAuto::length(0.0)),
2753        v => Ok(Len::parse(v)?.lpa()),
2754    }
2755}
2756
2757fn number(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
2758    match v {
2759        StyleValue::Number(n) => Ok(n),
2760        StyleValue::Null => Ok(default),
2761        StyleValue::Str(_) => Err(StyleError::InvalidValue),
2762    }
2763}
2764
2765/// A frame rate in Hz as an animation asks for one: a positive, finite
2766/// number (anything else asks for none: the screen's highest).
2767pub(crate) fn frame_rate(hz: Option<f32>) -> Option<f32> {
2768    hz.filter(|hz| hz.is_finite() && *hz > 0.0)
2769}
2770
2771fn opt_number(v: StyleValue<'_>) -> Result<Option<f32>, StyleError> {
2772    match v {
2773        StyleValue::Number(n) => Ok(Some(n)),
2774        StyleValue::Null => Ok(None),
2775        StyleValue::Str(_) => Err(StyleError::InvalidValue),
2776    }
2777}
2778
2779fn opt_points(v: StyleValue<'_>) -> Result<Option<Points>, StyleError> {
2780    Ok(opt_number(v)?.map(px))
2781}
2782
2783fn color(v: StyleValue<'_>) -> Result<Option<Color>, StyleError> {
2784    match v {
2785        StyleValue::Str(s) => Color::parse(s).map(Some).ok_or(StyleError::InvalidValue),
2786        StyleValue::Null => Ok(None),
2787        StyleValue::Number(_) => Err(StyleError::InvalidValue),
2788    }
2789}
2790
2791/// A `fill` / `stroke` value; `inherit` is unset, since they inherit.
2792fn svg_paint(v: StyleValue<'_>) -> Result<Option<SvgPaint>, StyleError> {
2793    let StyleValue::Str(s) = v else {
2794        return match v {
2795            StyleValue::Null => Ok(None),
2796            _ => Err(StyleError::InvalidValue),
2797        };
2798    };
2799    let s = s.trim();
2800    Ok(if s.eq_ignore_ascii_case("none") {
2801        Some(SvgPaint::None)
2802    } else if s.eq_ignore_ascii_case("currentcolor") {
2803        Some(SvgPaint::CurrentColor)
2804    } else if s.eq_ignore_ascii_case("inherit") {
2805        None
2806    } else {
2807        Some(SvgPaint::Color(
2808            Color::parse(s).ok_or(StyleError::InvalidValue)?,
2809        ))
2810    })
2811}
2812
2813/// A `strokeDasharray` value: lengths (no negatives) separated by commas
2814/// and / or spaces, or `none` (empty); one whose lengths add up to zero is
2815/// a solid line, as in SVG.
2816fn dasharray(v: StyleValue<'_>) -> Result<Option<Arc<[Points]>>, StyleError> {
2817    let lengths: Vec<Points> = match v {
2818        StyleValue::Null => return Ok(None),
2819        StyleValue::Number(n) if n >= 0.0 => vec![px(n)],
2820        StyleValue::Number(_) => return Err(StyleError::InvalidValue),
2821        StyleValue::Str(s) if s.trim().eq_ignore_ascii_case("none") => Vec::new(),
2822        StyleValue::Str(s) => s
2823            .split(|c: char| c == ',' || c.is_whitespace())
2824            .filter(|part| !part.is_empty())
2825            .map(|part| match css::length(part) {
2826                Some(n) if n >= 0.0 => Ok(px(n)),
2827                _ => Err(StyleError::InvalidValue),
2828            })
2829            .collect::<Result<_, _>>()?,
2830    };
2831    if lengths.iter().all(|l| l.0 == 0.0) {
2832        return Ok(Some(Arc::from([])));
2833    }
2834    Ok(Some(lengths.into()))
2835}
2836
2837fn keyword<'a>(v: StyleValue<'a>) -> Result<Option<&'a str>, StyleError> {
2838    match v {
2839        StyleValue::Str(s) => Ok(Some(s)),
2840        StyleValue::Null => Ok(None),
2841        StyleValue::Number(_) => Err(StyleError::InvalidValue),
2842    }
2843}
2844
2845fn align_items(v: StyleValue<'_>) -> Result<Option<AlignItems>, StyleError> {
2846    Ok(match keyword(v)? {
2847        None => None,
2848        Some("flex-start") => Some(AlignItems::FLEX_START),
2849        Some("flex-end") => Some(AlignItems::FLEX_END),
2850        // CSS's logical keywords: the writing direction's start and end
2851        // (right to left, `start` is the right), not the flex direction's.
2852        Some("start") => Some(AlignItems::START),
2853        Some("end") => Some(AlignItems::END),
2854        Some("self-start") => Some(AlignItems::SELF_START),
2855        Some("self-end") => Some(AlignItems::SELF_END),
2856        Some("center") => Some(AlignItems::CENTER),
2857        Some("stretch") => Some(AlignItems::STRETCH),
2858        Some("baseline") => Some(AlignItems::BASELINE),
2859        // CSS's `normal`: `stretch` for items without an aspect ratio.
2860        Some("normal") => Some(AlignItems::NORMAL),
2861        Some(_) => return Err(StyleError::InvalidValue),
2862    })
2863}
2864
2865/// `alignContent` / `justifyContent`; unset (null, `normal`) is CSS's
2866/// `normal`, which [`resolve_normal_alignment`] makes React Native's
2867/// `flex-start` outside grids.
2868fn align_content(v: StyleValue<'_>) -> Result<AlignContent, StyleError> {
2869    Ok(match keyword(v)? {
2870        None | Some("normal") => AlignContent::NORMAL,
2871        Some("flex-start") => AlignContent::FLEX_START,
2872        Some("flex-end") => AlignContent::FLEX_END,
2873        Some("start") => AlignContent::START,
2874        Some("end") => AlignContent::END,
2875        Some("center") => AlignContent::CENTER,
2876        Some("stretch") => AlignContent::STRETCH,
2877        Some("space-between") => AlignContent::SPACE_BETWEEN,
2878        Some("space-around") => AlignContent::SPACE_AROUND,
2879        Some("space-evenly") => AlignContent::SPACE_EVENLY,
2880        Some(_) => return Err(StyleError::InvalidValue),
2881    })
2882}
2883
2884fn font_weight(v: StyleValue<'_>) -> Result<Option<u16>, StyleError> {
2885    Ok(match v {
2886        StyleValue::Null => None,
2887        StyleValue::Number(n) => Some((n as u16).clamp(100, 900)),
2888        StyleValue::Str("normal") => Some(400),
2889        StyleValue::Str("bold") => Some(700),
2890        StyleValue::Str(s) => Some(
2891            s.parse::<u16>()
2892                .map_err(|_| StyleError::InvalidValue)?
2893                .clamp(100, 900),
2894        ),
2895    })
2896}
2897
2898/// A length in points from a number or a string (`"2px"`, `"0.5rem"`).
2899fn length_value(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
2900    match v {
2901        StyleValue::Number(n) => Ok(n),
2902        StyleValue::Str(s) => css::length(s).ok_or(StyleError::InvalidValue),
2903        StyleValue::Null => Ok(default),
2904    }
2905}
2906
2907/// Milliseconds from a number or `"150ms"` / `"0.2s"`.
2908fn duration(v: StyleValue<'_>) -> Result<f32, StyleError> {
2909    match v {
2910        StyleValue::Number(n) => Ok(n.max(0.0)),
2911        StyleValue::Null => Ok(0.0),
2912        StyleValue::Str(s) => {
2913            let s = s.trim();
2914            let ms = if let Some(n) = s.strip_suffix("ms") {
2915                css::number(n)
2916            } else if let Some(n) = s.strip_suffix('s') {
2917                css::number(n).map(|n| n * 1000.0)
2918            } else {
2919                css::number(s)
2920            };
2921            ms.map(|n| n.max(0.0)).ok_or(StyleError::InvalidValue)
2922        }
2923    }
2924}
2925
2926/// A CSS timing function as cubic Bézier control points.
2927fn timing_function(v: StyleValue<'_>) -> Result<[f32; 4], StyleError> {
2928    let Some(s) = keyword(v)? else {
2929        return Ok(Transition::EASE);
2930    };
2931    Ok(match s.trim() {
2932        "linear" => [0.0, 0.0, 1.0, 1.0],
2933        "ease" => Transition::EASE,
2934        "ease-in" => [0.42, 0.0, 1.0, 1.0],
2935        "ease-out" => [0.0, 0.0, 0.58, 1.0],
2936        "ease-in-out" => [0.42, 0.0, 0.58, 1.0],
2937        s => {
2938            let args = s
2939                .strip_prefix("cubic-bezier(")
2940                .and_then(|a| a.strip_suffix(')'))
2941                .ok_or(StyleError::InvalidValue)?;
2942            let n: Vec<f32> = args.split(',').filter_map(css::number).collect();
2943            let [a, b, c, d] = n.as_slice() else {
2944                return Err(StyleError::InvalidValue);
2945            };
2946            [*a, *b, *c, *d]
2947        }
2948    })
2949}
2950
2951/// `spring(stiffness, damping)` or `spring(stiffness, damping, mass)`, NSH's
2952/// timing function past CSS's: `None` for any other value, an error for a
2953/// spring that cannot settle (a stiffness, damping or mass that is not
2954/// positive).
2955fn spring_function(s: &str) -> Option<Result<crate::element::Spring, StyleError>> {
2956    let args = s.trim().strip_prefix("spring(")?.strip_suffix(')')?;
2957    let n: Option<Vec<f32>> = args.split(',').map(css::number).collect();
2958    let spring = match n.as_deref() {
2959        Some(&[stiffness, damping]) => (stiffness, damping, 1.0),
2960        Some(&[stiffness, damping, mass]) => (stiffness, damping, mass),
2961        _ => return Some(Err(StyleError::InvalidValue)),
2962    };
2963    Some(spring_of(spring).ok_or(StyleError::InvalidValue))
2964}
2965
2966/// A spring of `(stiffness, damping, mass)` that settles: each positive
2967/// and finite.
2968pub(crate) fn spring_of(
2969    (stiffness, damping, mass): (f32, f32, f32),
2970) -> Option<crate::element::Spring> {
2971    [stiffness, damping, mass]
2972        .iter()
2973        .all(|v| v.is_finite() && *v > 0.0)
2974        .then(|| crate::element::Spring {
2975            stiffness,
2976            damping,
2977            mass,
2978            ..crate::element::Spring::default()
2979        })
2980}
2981
2982/// `transitionProperty`: CSS property names, mapped to the groups that
2983/// transition natively.
2984fn transition_properties(s: &str) -> Option<TransitionProps> {
2985    let mut bits = 0;
2986    for name in s.split(',').map(str::trim) {
2987        bits |= match name {
2988            "all" => TransitionProps::ALL,
2989            "none" => 0,
2990            "color"
2991            | "colors"
2992            | "background-color"
2993            | "backgroundColor"
2994            | "border-color"
2995            | "borderColor"
2996            | "outline-color"
2997            | "text-decoration-color"
2998            | "fill"
2999            | "stroke"
3000            | "--tw-gradient-from"
3001            | "--tw-gradient-via"
3002            | "--tw-gradient-to" => TransitionProps::COLORS,
3003            "opacity" => TransitionProps::OPACITY,
3004            "transform" | "translate" | "scale" | "rotate" => TransitionProps::TRANSFORM,
3005            "box-shadow" | "boxShadow" | "shadow" => TransitionProps::SHADOW,
3006            "border-radius" | "borderRadius" | "border-width" | "borderWidth" => {
3007                TransitionProps::SHAPE
3008            }
3009            "clip-path" | "clipPath" => TransitionProps::CLIP_PATH,
3010            "mask-image" | "maskImage" | "-webkit-mask-image" | "mask" => TransitionProps::MASK,
3011            // Properties that do not animate natively.
3012            "filter" | "backdrop-filter" | "display" | "visibility" | "content-visibility"
3013            | "overlay" | "pointer-events" => 0,
3014            _ => return None,
3015        };
3016    }
3017    Some(TransitionProps(bits))
3018}
3019
3020fn grid_value<T>(
3021    v: StyleValue<'_>,
3022    parse: impl Fn(&str) -> Option<Vec<T>>,
3023) -> Result<Vec<T>, StyleError> {
3024    match keyword(v)? {
3025        None => Ok(Vec::new()),
3026        Some(s) => parse(s).ok_or(StyleError::InvalidValue),
3027    }
3028}
3029
3030fn grid_template(v: StyleValue<'_>) -> Result<grid::Template, StyleError> {
3031    match keyword(v)? {
3032        None => Ok((Vec::new(), Vec::new())),
3033        Some(s) => grid::template(s).ok_or(StyleError::InvalidValue),
3034    }
3035}
3036
3037fn grid_placement(v: StyleValue<'_>) -> Result<taffy::GridPlacement<String>, StyleError> {
3038    match v {
3039        StyleValue::Null => Ok(taffy::GridPlacement::Auto),
3040        StyleValue::Number(n) => line_index(n),
3041        StyleValue::Str(s) => grid::placement(s).ok_or(StyleError::InvalidValue),
3042    }
3043}
3044
3045/// CSS's `aspect-ratio`: `16 / 9`, `1.5`, `auto` (none).
3046fn aspect_ratio(s: &str) -> Result<Option<f32>, StyleError> {
3047    let s = s.trim();
3048    if s == "auto" {
3049        return Ok(None);
3050    }
3051    let ratio = match s.split_once('/') {
3052        Some((w, h)) => css::number(w.trim())
3053            .zip(css::number(h.trim()))
3054            .map(|(w, h)| w / h),
3055        None => css::number(s),
3056    };
3057    match ratio {
3058        Some(r) if r.is_finite() && r > 0.0 => Ok(Some(r)),
3059        _ => Err(StyleError::InvalidValue),
3060    }
3061}
3062
3063/// A grid line by its number (CSS has no line 0).
3064fn line_index(n: f32) -> Result<taffy::GridPlacement<String>, StyleError> {
3065    match n as i16 {
3066        0 => Err(StyleError::InvalidValue),
3067        n => Ok(grid::line_number(n)),
3068    }
3069}
3070
3071fn grid_line(v: StyleValue<'_>) -> Result<taffy::Line<taffy::GridPlacement<String>>, StyleError> {
3072    match v {
3073        StyleValue::Null => Ok(taffy::Line {
3074            start: taffy::GridPlacement::Auto,
3075            end: taffy::GridPlacement::Auto,
3076        }),
3077        StyleValue::Number(n) => Ok(grid::line_from(line_index(n)?)),
3078        StyleValue::Str(s) => grid::line(s).ok_or(StyleError::InvalidValue),
3079    }
3080}
3081
3082impl StyleKey {
3083    /// Parses `value` for this property: what [`Style::apply_value`] sets.
3084    /// Only a TSX style's values (and class strings, once) come here.
3085    pub fn parse_value(self, value: StyleValue<'_>) -> Result<PropertyValue, StyleError> {
3086        if let StyleValue::Str(s) = value {
3087            if css::is_current_color(s) && (current_bits(self).is_some() || self == StyleKey::Color)
3088            {
3089                return Ok(PropertyValue::CurrentColor);
3090            }
3091            if defers_current_color(self) && css::mentions_current_color(s) {
3092                // Checked now with a stand-in color, parsed again with the
3093                // node's once the style is in place.
3094                let probe = css::with_current_color(s, Color::BLACK);
3095                let probe = self.parse_inner(StyleValue::Str(&probe))?;
3096                return Ok(PropertyValue::Deferred(s.into(), Box::new(probe)));
3097            }
3098        }
3099        match value {
3100            StyleValue::Null => Ok(PropertyValue::Default),
3101            value => self.parse_inner(value),
3102        }
3103    }
3104
3105    /// `n` as this property's value, as a number in a TSX style is
3106    /// (points for lengths, a multiple for `lineHeight`).
3107    pub fn number_value(self, n: f32) -> Result<PropertyValue, StyleError> {
3108        self.parse_inner(StyleValue::Number(n))
3109    }
3110
3111    /// `length` as this property's value: points, a fraction of the
3112    /// containing block or `auto`, where the property takes them.
3113    pub fn length_value(
3114        self,
3115        length: crate::geometry::Length,
3116    ) -> Result<PropertyValue, StyleError> {
3117        use StyleKey as K;
3118
3119        use crate::geometry::Length;
3120        let len = match length {
3121            Length::Definite(DefiniteLength::Absolute(a)) => Len::Px(a.to_points(REM_SIZE).0),
3122            Length::Definite(DefiniteLength::Fraction(f)) => Len::Pct(f.0),
3123            Length::Auto => Len::Auto,
3124        };
3125        Ok(match (self, len) {
3126            (K::FlexBasis | K::Width | K::Height, len) => PropertyValue::Dimension(len.dim()),
3127            (
3128                K::MinWidth
3129                | K::MinHeight
3130                | K::MaxWidth
3131                | K::MaxHeight
3132                | K::Top
3133                | K::Right
3134                | K::Bottom
3135                | K::Left
3136                | K::Margin
3137                | K::MarginHorizontal
3138                | K::MarginVertical
3139                | K::MarginTop
3140                | K::MarginRight
3141                | K::MarginBottom
3142                | K::MarginLeft,
3143                len,
3144            ) => PropertyValue::Lpa(len.lpa()),
3145            (
3146                K::Padding
3147                | K::PaddingHorizontal
3148                | K::PaddingVertical
3149                | K::PaddingTop
3150                | K::PaddingRight
3151                | K::PaddingBottom
3152                | K::PaddingLeft
3153                | K::Gap
3154                | K::RowGap
3155                | K::ColumnGap,
3156                len,
3157            ) => PropertyValue::Lp(len.lp()?),
3158            (K::MarginStart | K::MarginEnd | K::Start | K::End, len) => {
3159                PropertyValue::OptLpa(Some(len.lpa()))
3160            }
3161            (K::PaddingStart | K::PaddingEnd, len) => PropertyValue::OptLp(Some(len.lp()?)),
3162            (K::LineHeight, Len::Px(n)) => PropertyValue::LineHeight(LineHeight::Points(px(n))),
3163            (K::LineHeight, Len::Pct(f)) => PropertyValue::LineHeight(LineHeight::Em(f)),
3164            (K::FontSize, Len::Px(n)) => PropertyValue::FontSize(Some(px(n)), None),
3165            (K::FontSize, Len::Pct(f)) if f >= 0.0 => {
3166                PropertyValue::FontSize(None, Some(OrderedFloat(f)))
3167            }
3168            (key, Len::Px(n)) => key.number_value(n)?,
3169            _ => return Err(StyleError::InvalidValue),
3170        })
3171    }
3172
3173    /// The value `null` gives the property.
3174    fn default_value(self) -> PropertyValue {
3175        self.parse_inner(StyleValue::Null)
3176            .expect("every property takes null")
3177    }
3178
3179    fn parse_inner(self, value: StyleValue<'_>) -> Result<PropertyValue, StyleError> {
3180        use StyleKey as K;
3181        let of = OrderedFloat;
3182        Ok(match self {
3183            // Layout
3184            K::Display => PropertyValue::Display(match keyword(value)? {
3185                None | Some("flex") => Display::Flex,
3186                Some("grid") => Display::Grid,
3187                Some("block") => Display::Block,
3188                Some("flow-root") => Display::FlowRoot,
3189                Some("none") => Display::None,
3190                Some(_) => return Err(StyleError::InvalidValue),
3191            }),
3192            K::BoxSizing => PropertyValue::BoxSizing(match keyword(value)? {
3193                None | Some("border-box") => taffy::BoxSizing::BorderBox,
3194                Some("content-box") => taffy::BoxSizing::ContentBox,
3195                _ => return Err(StyleError::InvalidValue),
3196            }),
3197            K::Position => {
3198                let (position, fixed, sticky) = match keyword(value)? {
3199                    None | Some("relative") => (Position::Relative, false, false),
3200                    Some("absolute") => (Position::Absolute, false, false),
3201                    Some("fixed") => (Position::Fixed, true, false),
3202                    Some("static") => (Position::Static, false, false),
3203                    Some("sticky") => (Position::Relative, false, true),
3204                    Some(_) => return Err(StyleError::InvalidValue),
3205                };
3206                PropertyValue::Position(position, fixed, sticky)
3207            }
3208            K::FlexDirection => PropertyValue::FlexDirection(match keyword(value)? {
3209                None | Some("column") => FlexDirection::Column,
3210                Some("row") => FlexDirection::Row,
3211                Some("column-reverse") => FlexDirection::ColumnReverse,
3212                Some("row-reverse") => FlexDirection::RowReverse,
3213                Some(_) => return Err(StyleError::InvalidValue),
3214            }),
3215            K::FlexWrap => PropertyValue::FlexWrap(match keyword(value)? {
3216                None | Some("nowrap") => FlexWrap::NoWrap,
3217                Some("wrap") => FlexWrap::Wrap,
3218                Some("wrap-reverse") => FlexWrap::WrapReverse,
3219                Some(_) => return Err(StyleError::InvalidValue),
3220            }),
3221            K::Flex => {
3222                // CSS's shorthand. Unset: the defaults (React Native's
3223                // `flexShrink: 0`).
3224                let (grow, shrink, basis) = match value {
3225                    StyleValue::Null => (0.0, 0.0, Dimension::auto()),
3226                    StyleValue::Number(n) if n >= 0.0 => (n, 1.0, Dimension::length(0.0)),
3227                    StyleValue::Number(_) => return Err(StyleError::InvalidValue),
3228                    StyleValue::Str(s) => {
3229                        let (grow, shrink, basis) = css::flex(s).ok_or(StyleError::InvalidValue)?;
3230                        let basis = match basis.map(|b| (b, css::length_or_percent(b))) {
3231                            None => Dimension::length(0.0),
3232                            // A CSS length (`30px`, `2rem`) or a percentage.
3233                            Some((_, Some(DefiniteLength::Absolute(a)))) => {
3234                                Dimension::length(a.to_points(crate::geometry::REM_SIZE).0)
3235                            }
3236                            Some((_, Some(DefiniteLength::Fraction(f)))) => Dimension::percent(f.0),
3237                            // `auto`, `min-content`, ...
3238                            Some((b, None)) => dimension(StyleValue::Str(b))?,
3239                        };
3240                        (grow, shrink, basis)
3241                    }
3242                };
3243                PropertyValue::Flex(of(grow), of(shrink), basis)
3244            }
3245            K::FlexGrow | K::FlexShrink | K::ZIndex => {
3246                PropertyValue::Number(of(number(value, 0.0)?))
3247            }
3248            K::Opacity => PropertyValue::Number(of(number(value, 1.0)?.clamp(0.0, 1.0))),
3249            K::FlexBasis | K::Width | K::Height => PropertyValue::Dimension(dimension(value)?),
3250            K::JustifyContent | K::AlignContent => {
3251                PropertyValue::AlignContent(align_content(value)?)
3252            }
3253            K::AlignItems | K::JustifyItems => PropertyValue::AlignItems(align_items(value)?),
3254            K::AlignSelf | K::JustifySelf => PropertyValue::AlignItems(match value {
3255                StyleValue::Str("auto") => None,
3256                v => align_items(v)?,
3257            }),
3258            K::MinWidth | K::MinHeight => PropertyValue::Lpa(min_len(value)?),
3259            K::MaxWidth | K::MaxHeight | K::Top | K::Right | K::Bottom | K::Left => {
3260                PropertyValue::Lpa(Len::parse(value)?.lpa())
3261            }
3262            K::AspectRatio => PropertyValue::OptNumber(match value {
3263                StyleValue::Str(s) => aspect_ratio(s)?.map(of),
3264                v => opt_number(v)?.map(of),
3265            }),
3266            K::Margin
3267            | K::MarginHorizontal
3268            | K::MarginVertical
3269            | K::MarginTop
3270            | K::MarginRight
3271            | K::MarginBottom
3272            | K::MarginLeft => match margin_edge(value)? {
3273                (_, Some(var)) => PropertyValue::EnvLength(env_points(value), var),
3274                (v, None) => PropertyValue::Lpa(v),
3275            },
3276            K::Padding
3277            | K::PaddingHorizontal
3278            | K::PaddingVertical
3279            | K::PaddingTop
3280            | K::PaddingRight
3281            | K::PaddingBottom
3282            | K::PaddingLeft => match padding_edge(value)? {
3283                (_, Some(var)) => PropertyValue::EnvLength(env_points(value), var),
3284                (v, None) => PropertyValue::Lp(v),
3285            },
3286            K::Gap | K::RowGap | K::ColumnGap => PropertyValue::Lp(lp_or_zero(value)?),
3287            K::BorderWidth
3288            | K::BorderTopWidth
3289            | K::BorderRightWidth
3290            | K::BorderBottomWidth
3291            | K::BorderLeftWidth => PropertyValue::Points(px(number(value, 0.0)?.max(0.0))),
3292            K::VerticalAlign => PropertyValue::VerticalAlign(match keyword(value)? {
3293                None => VerticalAlign::Baseline,
3294                Some(k) => VerticalAlign::parse(k).ok_or(StyleError::InvalidValue)?,
3295            }),
3296            K::Direction => PropertyValue::OptBool(match keyword(value)? {
3297                None | Some("inherit") => None,
3298                Some("ltr") => Some(false),
3299                Some("rtl") => Some(true),
3300                Some(_) => return Err(StyleError::InvalidValue),
3301            }),
3302            K::MarginStart | K::MarginEnd | K::Start | K::End => {
3303                PropertyValue::OptLpa(opt_lpa(value)?)
3304            }
3305            K::PaddingStart | K::PaddingEnd => PropertyValue::OptLp(opt_lp(value)?),
3306            K::BorderStartWidth | K::BorderEndWidth => {
3307                PropertyValue::OptPoints(opt_points(value)?.map(|w| w.max(Points::ZERO)))
3308            }
3309            K::BorderStartColor
3310            | K::BorderEndColor
3311            | K::BackgroundColor
3312            | K::BorderColor
3313            | K::BorderTopColor
3314            | K::BorderRightColor
3315            | K::BorderBottomColor
3316            | K::BorderLeftColor
3317            | K::TintColor
3318            | K::AccentColor
3319            | K::GlassTintColor
3320            | K::OutlineColor
3321            | K::Color
3322            | K::TextDecorationColor
3323            | K::PlaceholderColor
3324            | K::SelectionColor
3325            | K::CaretColor => PropertyValue::Color(color(value)?),
3326            K::BorderTopStartRadius
3327            | K::BorderTopEndRadius
3328            | K::BorderBottomEndRadius
3329            | K::BorderBottomStartRadius
3330            | K::BorderTopLeftRadius
3331            | K::BorderTopRightRadius
3332            | K::BorderBottomRightRadius
3333            | K::BorderBottomLeftRadius => PropertyValue::OptPoints(opt_points(value)?),
3334            K::FontSize => {
3335                let (points, em) = font_size(value)?;
3336                PropertyValue::FontSize(points, em.map(of))
3337            }
3338            K::BorderRadius => PropertyValue::Points(px(number(value, 0.0)?)),
3339            K::BorderStyle | K::OutlineStyle => {
3340                // `none` (and `hidden`) draws and lays out no line whatever
3341                // the width, set before or after it (CSS).
3342                let (style, hidden) = match keyword(value)? {
3343                    None | Some("solid") => (BorderStyle::Solid, false),
3344                    Some("dashed") => (BorderStyle::Dashed, false),
3345                    Some("dotted") => (BorderStyle::Dotted, false),
3346                    Some("none") | Some("hidden") => (BorderStyle::Solid, true),
3347                    Some(_) => return Err(StyleError::InvalidValue),
3348                };
3349                PropertyValue::BorderStyle(style, hidden)
3350            }
3351            K::BorderCurve => PropertyValue::Bool(match keyword(value)? {
3352                None | Some("circular") => false,
3353                Some("continuous") => true,
3354                Some(_) => return Err(StyleError::InvalidValue),
3355            }),
3356            K::BackfaceVisibility | K::Overflow => PropertyValue::Bool(match keyword(value)? {
3357                None | Some("visible") => false,
3358                Some("hidden") => true,
3359                Some(_) => return Err(StyleError::InvalidValue),
3360            }),
3361            K::Visibility => PropertyValue::Bool(match keyword(value)? {
3362                None | Some("visible") => false,
3363                Some("hidden") | Some("collapse") => true,
3364                Some(_) => return Err(StyleError::InvalidValue),
3365            }),
3366            K::ObjectFit => PropertyValue::ObjectFit(match keyword(value)? {
3367                None => None,
3368                Some("fill") => Some(crate::ResizeMode::Stretch),
3369                Some("contain") => Some(crate::ResizeMode::Contain),
3370                Some("cover") => Some(crate::ResizeMode::Cover),
3371                Some("none") => Some(crate::ResizeMode::Center),
3372                Some("scale-down") => Some(crate::ResizeMode::ScaleDown),
3373                Some(_) => return Err(StyleError::InvalidValue),
3374            }),
3375            K::ObjectPosition => PropertyValue::ObjectPosition(match keyword(value)? {
3376                None => ObjectPosition::CENTER,
3377                Some(s) => ObjectPosition::parse(s).ok_or(StyleError::InvalidValue)?,
3378            }),
3379            K::Transform => transform_value(value, crate::transform::parse_css, None)?,
3380            K::Translate => transform_value(
3381                value,
3382                crate::transform::parse_translate,
3383                Some(TransformKind::TranslateX),
3384            )?,
3385            K::Rotate => transform_value(
3386                value,
3387                crate::transform::parse_rotate,
3388                Some(TransformKind::Rotate),
3389            )?,
3390            K::Scale => transform_value(
3391                value,
3392                crate::transform::parse_scale,
3393                Some(TransformKind::Scale),
3394            )?,
3395            K::TransformOrigin => PropertyValue::TransformOrigin(match keyword(value)? {
3396                None => TransformOrigin::CENTER,
3397                Some(s) => TransformOrigin::parse(s).ok_or(StyleError::InvalidValue)?,
3398            }),
3399
3400            // Text
3401            K::Fill | K::Stroke => PropertyValue::Paint(svg_paint(value)?),
3402            K::StrokeWidth => PropertyValue::OptPoints(match value {
3403                StyleValue::Null => None,
3404                StyleValue::Number(n) if n >= 0.0 => Some(px(n)),
3405                StyleValue::Str(s) => match css::length(s) {
3406                    Some(n) if n >= 0.0 => Some(px(n)),
3407                    _ => return Err(StyleError::InvalidValue),
3408                },
3409                StyleValue::Number(_) => return Err(StyleError::InvalidValue),
3410            }),
3411            K::StrokeDasharray => PropertyValue::Dashes(dasharray(value)?),
3412            K::FontWeight => PropertyValue::FontWeight(font_weight(value)?),
3413            K::LineHeight => PropertyValue::LineHeight(line_height(value)?),
3414            K::FontFamily => {
3415                PropertyValue::FontFamily(keyword(value)?.map(|name| FontFamily::new(name.trim())))
3416            }
3417            K::FontStyle => PropertyValue::OptBool(match keyword(value)? {
3418                None => None,
3419                Some("normal") => Some(false),
3420                Some("italic") => Some(true),
3421                Some(_) => return Err(StyleError::InvalidValue),
3422            }),
3423            K::LetterSpacing => {
3424                let (points, em) = match value {
3425                    StyleValue::Str(s) if s.ends_with("em") && !s.ends_with("rem") => {
3426                        let n = css::number(&s[..s.len() - 2]).ok_or(StyleError::InvalidValue)?;
3427                        (None, Some(of(n)))
3428                    }
3429                    StyleValue::Str(s) => (
3430                        Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
3431                        None,
3432                    ),
3433                    v => (opt_points(v)?, None),
3434                };
3435                PropertyValue::LetterSpacing(points, em)
3436            }
3437            K::TextIndent => {
3438                let (points, em) = match value {
3439                    StyleValue::Str(s) if s.ends_with("em") && !s.ends_with("rem") => {
3440                        let n = css::number(&s[..s.len() - 2]).ok_or(StyleError::InvalidValue)?;
3441                        (None, Some(of(n)))
3442                    }
3443                    StyleValue::Str(s) => (
3444                        Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
3445                        None,
3446                    ),
3447                    v => (opt_points(v)?, None),
3448                };
3449                PropertyValue::TextIndent(points, em)
3450            }
3451            K::TextDecorationLine => PropertyValue::TextDecoration(match keyword(value)? {
3452                None => None,
3453                Some(words) => {
3454                    let mut d = TextDecoration::default();
3455                    for word in words.split_whitespace() {
3456                        match word {
3457                            "none" => {}
3458                            "underline" => d.underline = true,
3459                            "line-through" => d.line_through = true,
3460                            _ => return Err(StyleError::InvalidValue),
3461                        }
3462                    }
3463                    Some(d)
3464                }
3465            }),
3466            K::WritingDirection => PropertyValue::OptBool(match keyword(value)? {
3467                None | Some("auto") => None,
3468                Some("ltr") => Some(false),
3469                Some("rtl") => Some(true),
3470                Some(_) => return Err(StyleError::InvalidValue),
3471            }),
3472            K::FontVariant => PropertyValue::FontVariant(match keyword(value)? {
3473                None => None,
3474                Some(s) => Some(FontVariant::parse(s).ok_or(StyleError::InvalidValue)?),
3475            }),
3476            K::TextShadow => {
3477                let layers = match keyword(value)? {
3478                    None => Vec::new(),
3479                    Some(s) => crate::css::text_shadows(s).ok_or(StyleError::InvalidValue)?,
3480                };
3481                // One text shadow natively: the widest layer stands for all,
3482                // as the classes' does.
3483                PropertyValue::TextShadow(
3484                    layers
3485                        .into_iter()
3486                        .max_by(|a, b| a.0.radius.0.total_cmp(&b.0.radius.0)),
3487                )
3488            }
3489            K::NumberOfLines => PropertyValue::NumberOfLines(match value {
3490                StyleValue::Null => None,
3491                StyleValue::Number(n) if n >= 0.0 => Some(n as u32),
3492                _ => return Err(StyleError::InvalidValue),
3493            }),
3494            K::TextOverflow => PropertyValue::TextOverflow(match keyword(value)? {
3495                None => None,
3496                Some("ellipsis") => Some(EllipsizeMode::Tail),
3497                Some("clip") => Some(EllipsizeMode::Clip),
3498                Some("ellipsis-start") => Some(EllipsizeMode::Head),
3499                Some("ellipsis-middle") => Some(EllipsizeMode::Middle),
3500                Some(_) => return Err(StyleError::InvalidValue),
3501            }),
3502            K::UserSelect => PropertyValue::OptBool(match keyword(value)? {
3503                None | Some("auto") => None,
3504                Some("none") => Some(false),
3505                Some("text") => Some(true),
3506                Some(_) => return Err(StyleError::InvalidValue),
3507            }),
3508            K::PointerEvents => {
3509                use crate::props::PointerEvents as P;
3510                PropertyValue::PointerEvents(match keyword(value)? {
3511                    None => None,
3512                    Some("auto") => Some(P::Auto),
3513                    Some("none") => Some(P::None),
3514                    Some("box-none") => Some(P::BoxNone),
3515                    Some("box-only") => Some(P::BoxOnly),
3516                    Some(_) => return Err(StyleError::InvalidValue),
3517                })
3518            }
3519            K::TextAlignVertical => PropertyValue::AlignVertical(match keyword(value)? {
3520                None => None,
3521                Some("auto" | "top") => Some(percentage(0.0)),
3522                Some("center") => Some(percentage(0.5)),
3523                Some("bottom") => Some(percentage(1.0)),
3524                Some(_) => return Err(StyleError::InvalidValue),
3525            }),
3526            K::TextTransform => PropertyValue::TextTransform(match keyword(value)? {
3527                None => None,
3528                Some("none") => Some(TextTransform::None),
3529                Some("uppercase") => Some(TextTransform::Uppercase),
3530                Some("lowercase") => Some(TextTransform::Lowercase),
3531                Some("capitalize") => Some(TextTransform::Capitalize),
3532                Some(_) => return Err(StyleError::InvalidValue),
3533            }),
3534            K::TextAlign => {
3535                // `left` and `right` keep their sides right to left, as in
3536                // CSS; `start` and `end` are left and right there.
3537                let (align, physical) = match keyword(value)? {
3538                    None => (None, false),
3539                    Some("auto") => (Some(TextAlign::Auto), false),
3540                    Some("left") => (Some(TextAlign::Left), true),
3541                    Some("center") => (Some(TextAlign::Center), false),
3542                    Some("right") => (Some(TextAlign::Right), true),
3543                    Some("justify") => (Some(TextAlign::Justify), false),
3544                    Some("start") => (Some(TextAlign::Left), false),
3545                    Some("end") => (Some(TextAlign::Right), false),
3546                    Some(_) => return Err(StyleError::InvalidValue),
3547                };
3548                PropertyValue::TextAlign(align, physical)
3549            }
3550
3551            // Effects
3552            K::BoxShadow => PropertyValue::Shadows(match keyword(value)? {
3553                None => Rc::from([]),
3554                Some(s) => css::shadow_layers(s)
3555                    .ok_or(StyleError::InvalidValue)?
3556                    .into(),
3557            }),
3558            K::BackgroundImage => PropertyValue::Gradients(match keyword(value)? {
3559                None => Rc::from([]),
3560                Some(s) => css::gradients(s).ok_or(StyleError::InvalidValue)?.into(),
3561            }),
3562            K::MaskImage => PropertyValue::Gradients(match keyword(value)? {
3563                None | Some("none") => Rc::from([]),
3564                Some(s) => css::gradients(s).ok_or(StyleError::InvalidValue)?.into(),
3565            }),
3566            K::ClipPath => PropertyValue::ClipPath(match keyword(value)? {
3567                None | Some("none") => None,
3568                Some(s) => Some(css::clip_inset(s).ok_or(StyleError::InvalidValue)?),
3569            }),
3570            K::Filter => PropertyValue::Filters(match keyword(value)? {
3571                None => Rc::from([]),
3572                Some(s) => css::filter_list(s).ok_or(StyleError::InvalidValue)?.into(),
3573            }),
3574            K::BackdropFilter => PropertyValue::Filters(match keyword(value)? {
3575                None => Rc::from([]),
3576                Some(s) => css::filters(s)
3577                    .ok_or(StyleError::InvalidValue)?
3578                    .into_iter()
3579                    .map(|f| (f, true))
3580                    .collect(),
3581            }),
3582            K::GlassEffect => PropertyValue::GlassEffect(match keyword(value)? {
3583                None => GlassEffect::None,
3584                Some(s) => GlassEffect::parse(s).ok_or(StyleError::InvalidValue)?,
3585            }),
3586            K::MixBlendMode => PropertyValue::BlendMode(match keyword(value)? {
3587                None => BlendMode::Normal,
3588                Some(s) => BlendMode::parse(s).ok_or(StyleError::InvalidValue)?,
3589            }),
3590            K::OutlineWidth => PropertyValue::Points(px(length_value(value, 0.0)?.max(0.0))),
3591            K::OutlineOffset => PropertyValue::Points(px(length_value(value, 0.0)?)),
3592            K::Cursor => PropertyValue::Cursor(match keyword(value)? {
3593                None => Cursor::Auto,
3594                Some(s) => Cursor::parse(s).ok_or(StyleError::InvalidValue)?,
3595            }),
3596            K::TransitionProperty => PropertyValue::TransitionProps(match keyword(value)? {
3597                None => TransitionProps(TransitionProps::ALL),
3598                Some(s) => transition_properties(s).ok_or(StyleError::InvalidValue)?,
3599            }),
3600            K::TransitionDuration
3601            | K::TransitionDelay
3602            | K::AnimationDuration
3603            | K::AnimationDelay => PropertyValue::Ms(of(duration(value)?)),
3604            K::TransitionTimingFunction => match keyword(value)?.and_then(spring_function) {
3605                Some(spring) => PropertyValue::Spring(spring?),
3606                None => PropertyValue::Easing(timing_function(value)?.map(of)),
3607            },
3608            K::AnimationTimingFunction => PropertyValue::Easing(timing_function(value)?.map(of)),
3609            K::AnimationName => PropertyValue::Keyframes(match keyword(value)? {
3610                None | Some("none") => None,
3611                Some("spin") => Some(Keyframes::Spin),
3612                Some("ping") => Some(Keyframes::Ping),
3613                Some("pulse") => Some(Keyframes::Pulse),
3614                Some("bounce") => Some(Keyframes::Bounce),
3615                Some(_) => return Err(StyleError::InvalidValue),
3616            }),
3617            K::AnimationIterationCount => PropertyValue::Iterations(match value {
3618                StyleValue::Str("infinite") | StyleValue::Null => None,
3619                v => Some(number(v, 1.0)?.max(0.0) as u32),
3620            }),
3621            K::AnimationFrameRate => {
3622                PropertyValue::OptNumber(frame_rate(opt_number(value)?).map(of))
3623            }
3624            K::TextDecorationStyle => PropertyValue::DecorationStyle(match keyword(value)? {
3625                None => None,
3626                Some("solid") => Some(DecorationStyle::Solid),
3627                Some("double") => Some(DecorationStyle::Double),
3628                Some("dotted") => Some(DecorationStyle::Dotted),
3629                Some("dashed") => Some(DecorationStyle::Dashed),
3630                Some("wavy") => Some(DecorationStyle::Wavy),
3631                Some(_) => return Err(StyleError::InvalidValue),
3632            }),
3633            K::TextDecorationThickness => PropertyValue::OptPoints(match value {
3634                StyleValue::Null | StyleValue::Str("auto") | StyleValue::Str("from-font") => None,
3635                v => Some(px(length_value(v, 1.0)?.max(0.0))),
3636            }),
3637            K::TextUnderlineOffset => PropertyValue::OptPoints(match value {
3638                StyleValue::Null | StyleValue::Str("auto") => None,
3639                v => Some(px(length_value(v, 0.0)?)),
3640            }),
3641
3642            // Grid
3643            K::GridTemplateColumns | K::GridTemplateRows => {
3644                PropertyValue::GridTemplate(GridTemplateValue(Rc::new(grid_template(value)?)))
3645            }
3646            K::GridAutoColumns | K::GridAutoRows => {
3647                PropertyValue::GridTracks(grid_value(value, grid::auto_tracks)?.into())
3648            }
3649            K::GridAutoFlow => PropertyValue::GridAutoFlow(match keyword(value)? {
3650                None => taffy::GridAutoFlow::Row,
3651                Some(s) => grid::auto_flow(s).ok_or(StyleError::InvalidValue)?,
3652            }),
3653            K::GridColumn | K::GridRow => PropertyValue::GridLine(grid_line(value)?),
3654            K::GridColumnStart | K::GridColumnEnd | K::GridRowStart | K::GridRowEnd => {
3655                PropertyValue::GridPlacement(grid_placement(value)?)
3656            }
3657        })
3658    }
3659}
3660
3661/// A transform property's value: CSS's syntax as `parse` reads it, a
3662/// number as one `number` step, `null` as none.
3663fn transform_value(
3664    value: StyleValue<'_>,
3665    parse: fn(&str) -> Option<Vec<crate::TransformOp>>,
3666    number: Option<TransformKind>,
3667) -> Result<PropertyValue, StyleError> {
3668    let ops = match value {
3669        StyleValue::Null => Vec::new(),
3670        StyleValue::Number(n) => {
3671            let kind = number.ok_or(StyleError::InvalidValue)?;
3672            vec![crate::TransformOp { kind, value: n }]
3673        }
3674        StyleValue::Str(s) => parse(s).ok_or(StyleError::InvalidValue)?,
3675    };
3676    Ok(PropertyValue::Transform(
3677        ops.iter().map(|op| (op.kind, op.value, None)).collect(),
3678    ))
3679}
3680
3681/// `lineHeight`: a number is points (React Native); strings, which
3682/// classes write, are a multiple of the font size (`"1.5"`), a multiple
3683/// of the element's own font size (`"1.5em"`, `"150%"`), points
3684/// (`"20px"`) or the font's own (`"normal"`).
3685/// `fontSize`: points (a number or a length), or ems / a percentage of
3686/// the inherited font size.
3687fn font_size(value: StyleValue<'_>) -> Result<(Option<Points>, Option<f32>), StyleError> {
3688    Ok(match value {
3689        StyleValue::Str(s) if s.ends_with('%') || (s.ends_with("em") && !s.ends_with("rem")) => {
3690            let n = if let Some(n) = s.strip_suffix('%') {
3691                css::number(n).map(|n| n / 100.0)
3692            } else {
3693                css::number(&s[..s.len() - 2])
3694            }
3695            .filter(|n| *n >= 0.0)
3696            .ok_or(StyleError::InvalidValue)?;
3697            (None, Some(n))
3698        }
3699        StyleValue::Str(s) => (
3700            Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
3701            None,
3702        ),
3703        v => (opt_points(v)?, None),
3704    })
3705}
3706
3707fn line_height(value: StyleValue<'_>) -> Result<LineHeight, StyleError> {
3708    Ok(match value {
3709        StyleValue::Null | StyleValue::Str("normal") => LineHeight::Normal,
3710        StyleValue::Number(n) => LineHeight::Points(px(n)),
3711        StyleValue::Str(s) if s.ends_with("px") || s.ends_with("pt") || s.ends_with("rem") => {
3712            LineHeight::Points(px(css::length(s).ok_or(StyleError::InvalidValue)?))
3713        }
3714        StyleValue::Str(s) if s.ends_with('%') || s.ends_with("em") => {
3715            let n = if let Some(n) = s.strip_suffix('%') {
3716                css::number(n).map(|n| n / 100.0)
3717            } else {
3718                css::number(s.strip_suffix("em").unwrap_or(s))
3719            }
3720            .filter(|n| *n >= 0.0)
3721            .ok_or(StyleError::InvalidValue)?;
3722            LineHeight::Em(n)
3723        }
3724        StyleValue::Str(s) => LineHeight::Multiple(
3725            css::number(s)
3726                .filter(|n| *n >= 0.0)
3727                .ok_or(StyleError::InvalidValue)?,
3728        ),
3729    })
3730}
3731
3732impl Style {
3733    /// Gives the shadow layers a style wrote without a color the node's
3734    /// text color, `current` (CSS's `currentColor`).
3735    pub(crate) fn apply_current_color(&mut self, current: Color) {
3736        if !self.pending.current_values.is_empty() {
3737            // Taken out while they apply: setting a key drops its entry.
3738            let values = std::mem::take(&mut self.pending.current_values);
3739            for (key, value) in &values {
3740                let value = css::with_current_color(value, current);
3741                let _ = self.set_key(*key, StyleValue::Str(&value));
3742            }
3743            self.pending.current_values = values;
3744        }
3745        let mask = self.pending.current_drop_shadows;
3746        if mask != 0 {
3747            self.edit_effects(|e| {
3748                for (i, filter) in e.filters.iter_mut().enumerate().take(64) {
3749                    if mask & 1 << i != 0
3750                        && let Filter::DropShadow { color, .. } = filter
3751                    {
3752                        *color = current;
3753                    }
3754                }
3755            });
3756        }
3757        let mask = self.pending.current_shadows;
3758        if mask != 0 {
3759            self.edit_effects(|e| {
3760                for (i, layer) in e.box_shadows.iter_mut().enumerate().take(64) {
3761                    if mask & 1 << i != 0 {
3762                        layer.color = current;
3763                    }
3764                }
3765            });
3766        }
3767        if self.pending.current_text_shadow {
3768            self.text.shadow_color = Some(current);
3769        }
3770        let colors = self.pending.current_colors;
3771        for (bit, key) in CURRENT_KEYS.iter().enumerate() {
3772            if colors & 1 << bit != 0 {
3773                self.put_color(*key, current);
3774            }
3775        }
3776    }
3777
3778    /// What the style says of the node's own props: `numberOfLines`,
3779    /// `textOverflow`, `userSelect` and `pointerEvents`, into `props`.
3780    pub(crate) fn node_props(&self, props: &mut crate::tailwind::ClassProps) {
3781        let p = &self.pending;
3782        props.number_of_lines = p.number_of_lines;
3783        props.ellipsize = p.text_overflow;
3784        props.selectable = p.user_select;
3785        props.pointer_events = p.pointer_events;
3786    }
3787
3788    /// `objectFit` (the `object-*` classes set it too): how an image or a
3789    /// video fits its box; `None` leaves the element's default.
3790    pub fn object_fit(&self) -> Option<crate::ResizeMode> {
3791        self.pending.object_fit
3792    }
3793
3794    /// Sets transform property `property` to `steps` in its place in the
3795    /// transform list, the other properties' steps around it; a step with
3796    /// an animated value is bound to it.
3797    pub fn set_transform(
3798        &mut self,
3799        property: TransformProperty,
3800        steps: &[(TransformKind, f32, Option<crate::animation::NodeId>)],
3801    ) -> Result<(), StyleError> {
3802        use crate::animation::AnimationProp;
3803        let part = property as usize;
3804        let counts = self.pending.transform_counts;
3805        let start: usize = counts[..part].iter().map(|&c| usize::from(c)).sum();
3806        let old = usize::from(counts[part]);
3807        let ops = self.view.transform.ops();
3808        if ops.len() - old + steps.len() > crate::MAX_TRANSFORMS {
3809            return Err(StyleError::InvalidValue);
3810        }
3811        let mut list = Transform::IDENTITY;
3812        let kept = ops[..start].iter().map(|op| (op.kind, op.value));
3813        let after = ops[start + old..].iter().map(|op| (op.kind, op.value));
3814        for (kind, value) in kept
3815            .chain(steps.iter().map(|&(kind, value, _)| (kind, value)))
3816            .chain(after)
3817        {
3818            let _ = list.push(kind, value);
3819        }
3820        self.view.transform = list;
3821        // The bindings of the steps after it move with them.
3822        let moved = steps.len() as isize - old as isize;
3823        self.animated.retain_mut(|(prop, _)| match prop {
3824            AnimationProp::Transform(i) if usize::from(*i) >= start + old => {
3825                *i = (*i as isize + moved) as u8;
3826                true
3827            }
3828            AnimationProp::Transform(i) => usize::from(*i) < start,
3829            _ => true,
3830        });
3831        for (k, &(_, _, node)) in steps.iter().enumerate() {
3832            if let Some(node) = node {
3833                self.animated
3834                    .push((AnimationProp::Transform((start + k) as u8), node));
3835            }
3836        }
3837        self.pending.transform_counts[part] = steps.len() as u8;
3838        Ok(())
3839    }
3840
3841    /// Changes the effects lists (copying them if shared).
3842    pub fn edit_effects(&mut self, f: impl FnOnce(&mut Effects)) {
3843        let mut effects = self
3844            .view
3845            .effects
3846            .take()
3847            .map(|e| (*e).clone())
3848            .unwrap_or_default();
3849        f(&mut effects);
3850        self.view.effects = crate::effects::shared(effects);
3851    }
3852
3853    /// Sets the box shadows (top layer first).
3854    pub fn set_box_shadows(&mut self, shadows: Vec<BoxShadow>) {
3855        self.edit_effects(|e| e.box_shadows = shadows);
3856    }
3857
3858    /// Sets the gradient backgrounds (top layer first).
3859    pub fn set_background_images(&mut self, images: Vec<Gradient>) {
3860        self.edit_effects(|e| e.background_images = images);
3861    }
3862
3863    /// Sets the filters.
3864    pub fn set_filters(&mut self, filters: Vec<Filter>, backdrop: bool) {
3865        self.edit_effects(|e| {
3866            if backdrop {
3867                e.backdrop_filters = filters;
3868            } else {
3869                e.filters = filters;
3870            }
3871        });
3872    }
3873
3874    fn transition_mut(&mut self) -> &mut Transition {
3875        self.view.transition.get_or_insert(Transition {
3876            properties: TransitionProps(TransitionProps::ALL),
3877            duration: 0.0,
3878            delay: 0.0,
3879            easing: Transition::EASE,
3880            spring: None,
3881        })
3882    }
3883
3884    fn set_border_width(&mut self, sides: &[usize], w: Points) {
3885        for &side in sides {
3886            self.pending.border_widths[side] = w;
3887            if !self.pending.border_hidden {
3888                self.set_used_border_width(side, w);
3889            }
3890        }
3891    }
3892
3893    /// The width side `side` lays out and draws with.
3894    fn set_used_border_width(&mut self, side: usize, w: Points) {
3895        *self.view.borders.width_mut(side) = w;
3896        let v = LengthPercentage::length(w.0);
3897        let b = &mut self.layout.border;
3898        match side {
3899            0 => b.top = v,
3900            1 => b.right = v,
3901            2 => b.bottom = v,
3902            _ => b.left = v,
3903        }
3904    }
3905
3906    fn set_logical_border_width(&mut self, i: usize, w: Option<Points>) {
3907        self.pending.border_logical[i] = w;
3908        if !self.pending.border_hidden {
3909            self.logical.border_width[i] = w;
3910        }
3911    }
3912
3913    fn set_border_color(&mut self, sides: &[usize], c: Option<Color>) {
3914        let c = c.unwrap_or(Color::BLACK);
3915        for &side in sides {
3916            self.view.borders.colors[side] = c;
3917        }
3918    }
3919
3920    /// Sets color property `key` (`borderColor`, `outlineColor`) to `color`;
3921    /// other keys are left as they are.
3922    pub(crate) fn set_color(&mut self, key: StyleKey, color: Color) {
3923        if let Some(bits) = current_bits(key) {
3924            self.pending.current_colors &= !bits;
3925        }
3926        self.put_color(key, color);
3927    }
3928
3929    /// [`Style::set_color`], leaving what `currentColor` fills alone.
3930    fn put_color(&mut self, key: StyleKey, color: Color) {
3931        match key {
3932            StyleKey::BorderColor => self.view.borders.colors = [color; 4],
3933            StyleKey::OutlineColor => self.view.outline.color = color,
3934            StyleKey::BackgroundColor => self.view.background_color = color,
3935            StyleKey::BorderTopColor => self.view.borders.colors[0] = color,
3936            StyleKey::BorderRightColor => self.view.borders.colors[1] = color,
3937            StyleKey::BorderBottomColor => self.view.borders.colors[2] = color,
3938            StyleKey::BorderLeftColor => self.view.borders.colors[3] = color,
3939            StyleKey::BorderStartColor => self.logical.border_color[0] = Some(color),
3940            StyleKey::BorderEndColor => self.logical.border_color[1] = Some(color),
3941            StyleKey::TextDecorationColor => self.text.decoration_color = Some(color),
3942            StyleKey::CaretColor => self.text.caret_color = Some(color),
3943            _ => debug_assert!(false, "set_color({key:?})"),
3944        }
3945    }
3946
3947    /// Sets one property using its React Native name.
3948    pub fn set(&mut self, key: &str, value: StyleValue<'_>) -> Result<(), StyleError> {
3949        self.set_key(
3950            StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?,
3951            value,
3952        )
3953    }
3954
3955    /// Sets one property.
3956    pub fn set_key(&mut self, key: StyleKey, value: StyleValue<'_>) -> Result<(), StyleError> {
3957        let value = key.parse_value(value)?;
3958        self.apply_value(key, &value)
3959    }
3960
3961    /// Sets property `key` to `value`, parsed before ([`StyleKey::parse_value`])
3962    /// or made typed (classes, Rust's styles). A value of another property's
3963    /// kind is rejected.
3964    pub fn apply_value(&mut self, key: StyleKey, value: &PropertyValue) -> Result<(), StyleError> {
3965        use PropertyValue as V;
3966        use StyleKey as K;
3967        if !self.pending.current_values.is_empty() {
3968            self.pending.current_values.retain(|(k, _)| *k != key);
3969        }
3970        match value {
3971            V::Default => return self.apply_value(key, &key.default_value()),
3972            V::Deferred(text, probe) => {
3973                self.apply_value(key, probe)?;
3974                self.pending.current_values.push((key, text.clone()));
3975                return Ok(());
3976            }
3977            _ => {}
3978        }
3979        let current = matches!(value, V::CurrentColor);
3980        if let Some(bits) = current_bits(key) {
3981            // The last value wins: `currentColor` is filled in once the
3982            // style is in place, another value takes its place.
3983            if current {
3984                self.pending.current_colors |= bits;
3985                return Ok(());
3986            }
3987            self.pending.current_colors &= !bits;
3988        } else if current {
3989            if key != K::Color {
3990                return Err(StyleError::InvalidValue);
3991            }
3992            // CSS: `color: currentColor` is the inherited color.
3993            self.text.color = None;
3994            return Ok(());
3995        }
3996        let l = &mut self.layout;
3997        match (key, value) {
3998            // Layout
3999            (K::Display, V::Display(v)) => l.display = *v,
4000            (K::BoxSizing, V::BoxSizing(v)) => l.box_sizing = *v,
4001            (K::Position, V::Position(position, fixed, sticky)) => {
4002                l.position = *position;
4003                self.pending.fixed_position = *fixed;
4004                self.pending.sticky_position = *sticky;
4005            }
4006            (K::FlexDirection, V::FlexDirection(v)) => l.flex_direction = *v,
4007            (K::FlexWrap, V::FlexWrap(v)) => l.flex_wrap = *v,
4008            (K::Flex, V::Flex(grow, shrink, basis)) => {
4009                (l.flex_grow, l.flex_shrink, l.flex_basis) = (grow.0, shrink.0, *basis);
4010            }
4011            (K::FlexGrow, V::Number(n)) => l.flex_grow = n.0,
4012            (K::FlexShrink, V::Number(n)) => l.flex_shrink = n.0,
4013            (K::FlexBasis, V::Dimension(v)) => l.flex_basis = *v,
4014            (K::JustifyContent, V::AlignContent(v)) => l.justify_content = *v,
4015            (K::AlignItems, V::AlignItems(v)) => l.align_items = v.unwrap_or(AlignItems::STRETCH),
4016            (K::AlignSelf, V::AlignItems(v)) => l.align_self = *v,
4017            (K::AlignContent, V::AlignContent(v)) => l.align_content = *v,
4018            (K::Width, V::Dimension(v)) => l.size.width = *v,
4019            (K::Height, V::Dimension(v)) => l.size.height = *v,
4020            (K::MinWidth, V::Lpa(v)) => l.min_size.width = *v,
4021            (K::MinHeight, V::Lpa(v)) => l.min_size.height = *v,
4022            (K::MaxWidth, V::Lpa(v)) => l.max_size.width = *v,
4023            (K::MaxHeight, V::Lpa(v)) => l.max_size.height = *v,
4024            (K::AspectRatio, V::OptNumber(v)) => l.aspect_ratio = v.map(|n| n.0),
4025            (K::Top, V::Lpa(v)) => l.inset.top = *v,
4026            (K::Right, V::Lpa(v)) => l.inset.right = *v,
4027            (K::Bottom, V::Lpa(v)) => l.inset.bottom = *v,
4028            (K::Left, V::Lpa(v)) => l.inset.left = *v,
4029            (
4030                K::Margin
4031                | K::MarginHorizontal
4032                | K::MarginVertical
4033                | K::MarginTop
4034                | K::MarginRight
4035                | K::MarginBottom
4036                | K::MarginLeft,
4037                v,
4038            ) => {
4039                let (length, var) = match v {
4040                    V::Lpa(v) => (*v, None),
4041                    V::EnvLength(p, var) => (LengthPercentageAuto::length(p.0), Some(*var)),
4042                    _ => return Err(StyleError::InvalidValue),
4043                };
4044                let m = &mut l.margin;
4045                for &side in edges(key) {
4046                    *[&mut m.top, &mut m.right, &mut m.bottom, &mut m.left][side] = length;
4047                    self.pending.env.margin[side] = var;
4048                }
4049            }
4050            (
4051                K::Padding
4052                | K::PaddingHorizontal
4053                | K::PaddingVertical
4054                | K::PaddingTop
4055                | K::PaddingRight
4056                | K::PaddingBottom
4057                | K::PaddingLeft,
4058                v,
4059            ) => {
4060                let (length, var) = match v {
4061                    V::Lp(v) => (*v, None),
4062                    V::EnvLength(p, var) => (LengthPercentage::length(p.0), Some(*var)),
4063                    _ => return Err(StyleError::InvalidValue),
4064                };
4065                let p = &mut l.padding;
4066                for &side in edges(key) {
4067                    *[&mut p.top, &mut p.right, &mut p.bottom, &mut p.left][side] = length;
4068                    self.pending.env.padding[side] = var;
4069                }
4070            }
4071            (K::Gap, V::Lp(v)) => {
4072                l.gap = taffy::Size {
4073                    width: *v,
4074                    height: *v,
4075                };
4076            }
4077            (K::RowGap, V::Lp(v)) => l.gap.height = *v,
4078            (K::ColumnGap, V::Lp(v)) => l.gap.width = *v,
4079            (K::BorderWidth, V::Points(w)) => self.set_border_width(&[0, 1, 2, 3], *w),
4080            (K::BorderTopWidth, V::Points(w)) => self.set_border_width(&[0], *w),
4081            (K::BorderRightWidth, V::Points(w)) => self.set_border_width(&[1], *w),
4082            (K::BorderBottomWidth, V::Points(w)) => self.set_border_width(&[2], *w),
4083            (K::BorderLeftWidth, V::Points(w)) => self.set_border_width(&[3], *w),
4084            (K::ZIndex, V::Number(n)) => self.z_index = n.0 as i32,
4085            (K::VerticalAlign, V::VerticalAlign(v)) => self.vertical_align = *v,
4086            (K::Direction, V::OptBool(v)) => self.direction = *v,
4087            (K::MarginStart, V::OptLpa(v)) => self.logical.margin[0] = *v,
4088            (K::MarginEnd, V::OptLpa(v)) => self.logical.margin[1] = *v,
4089            (K::PaddingStart, V::OptLp(v)) => self.logical.padding[0] = *v,
4090            (K::PaddingEnd, V::OptLp(v)) => self.logical.padding[1] = *v,
4091            (K::Start, V::OptLpa(v)) => self.logical.inset[0] = *v,
4092            (K::End, V::OptLpa(v)) => self.logical.inset[1] = *v,
4093            (K::BorderStartWidth, V::OptPoints(w)) => self.set_logical_border_width(0, *w),
4094            (K::BorderEndWidth, V::OptPoints(w)) => self.set_logical_border_width(1, *w),
4095            (K::BorderStartColor, V::Color(c)) => self.logical.border_color[0] = *c,
4096            (K::BorderEndColor, V::Color(c)) => self.logical.border_color[1] = *c,
4097            (K::BorderTopStartRadius, V::OptPoints(r)) => self.logical.radius[0] = *r,
4098            (K::BorderTopEndRadius, V::OptPoints(r)) => self.logical.radius[1] = *r,
4099            (K::BorderBottomEndRadius, V::OptPoints(r)) => self.logical.radius[2] = *r,
4100            (K::BorderBottomStartRadius, V::OptPoints(r)) => self.logical.radius[3] = *r,
4101
4102            // View
4103            (K::BackgroundColor, V::Color(c)) => {
4104                self.view.background_color = c.unwrap_or(Color::TRANSPARENT)
4105            }
4106            (K::BorderRadius, V::Points(r)) => self.view.border_radius = *r,
4107            (K::BorderTopLeftRadius, V::OptPoints(r)) => self.view.corner_radius.top_left = *r,
4108            (K::BorderTopRightRadius, V::OptPoints(r)) => self.view.corner_radius.top_right = *r,
4109            (K::BorderBottomRightRadius, V::OptPoints(r)) => {
4110                self.view.corner_radius.bottom_right = *r
4111            }
4112            (K::BorderBottomLeftRadius, V::OptPoints(r)) => {
4113                self.view.corner_radius.bottom_left = *r
4114            }
4115            (K::BorderColor, V::Color(c)) => self.set_border_color(&[0, 1, 2, 3], *c),
4116            (K::BorderTopColor, V::Color(c)) => self.set_border_color(&[0], *c),
4117            (K::BorderRightColor, V::Color(c)) => self.set_border_color(&[1], *c),
4118            (K::BorderBottomColor, V::Color(c)) => self.set_border_color(&[2], *c),
4119            (K::BorderLeftColor, V::Color(c)) => self.set_border_color(&[3], *c),
4120            (K::BorderStyle, V::BorderStyle(style, hidden)) => {
4121                // `none` (and `hidden`, the same outside tables) draws and
4122                // lays out no border whatever the widths, set before or
4123                // after it (CSS).
4124                let hidden = *hidden;
4125                self.view.borders.style = *style;
4126                if hidden != self.pending.border_hidden {
4127                    self.pending.border_hidden = hidden;
4128                    for side in 0..4 {
4129                        let w = if hidden {
4130                            Points::ZERO
4131                        } else {
4132                            self.pending.border_widths[side]
4133                        };
4134                        self.set_used_border_width(side, w);
4135                    }
4136                    self.logical.border_width = if hidden {
4137                        [None; 2]
4138                    } else {
4139                        self.pending.border_logical
4140                    };
4141                }
4142            }
4143            (K::BorderCurve, V::Bool(v)) => self.view.continuous_corners = *v,
4144            (K::TintColor, V::Color(c)) => self.view.tint_color = *c,
4145            (K::AccentColor, V::Color(c)) => self.view.accent_color = *c,
4146            (K::GlassTintColor, V::Color(c)) => self.view.glass_tint_color = *c,
4147            (K::ObjectFit, V::ObjectFit(v)) => self.pending.object_fit = *v,
4148            (K::ObjectPosition, V::ObjectPosition(v)) => self.view.object_position = *v,
4149            (K::BackfaceVisibility, V::Bool(v)) => self.view.backface_hidden = *v,
4150            (K::Transform, V::Transform(steps)) => {
4151                self.set_transform(TransformProperty::Transform, steps)?
4152            }
4153            (K::Translate, V::Transform(steps)) => {
4154                self.set_transform(TransformProperty::Translate, steps)?
4155            }
4156            (K::Rotate, V::Transform(steps)) => {
4157                self.set_transform(TransformProperty::Rotate, steps)?
4158            }
4159            (K::Scale, V::Transform(steps)) => {
4160                self.set_transform(TransformProperty::Scale, steps)?
4161            }
4162            (K::TransformOrigin, V::TransformOrigin(v)) => self.view.transform_origin = *v,
4163            (K::Opacity, V::Number(n)) => self.view.opacity = n.0.clamp(0.0, 1.0),
4164            (K::Overflow, V::Bool(v)) => self.view.overflow_hidden = *v,
4165
4166            // Text
4167            (K::Color, V::Color(c)) => self.text.color = *c,
4168            (K::Fill, V::Paint(v)) => self.paint.fill = *v,
4169            (K::Stroke, V::Paint(v)) => self.paint.stroke = *v,
4170            (K::StrokeWidth, V::OptPoints(v)) => self.paint.stroke_width = *v,
4171            (K::StrokeDasharray, V::Dashes(v)) => self.paint.stroke_dasharray = v.clone(),
4172            (K::FontSize, V::FontSize(points, em)) => {
4173                self.text.font_size = *points;
4174                self.text.font_size_em = em.map(|n| n.0);
4175            }
4176            (K::FontWeight, V::FontWeight(v)) => self.text.font_weight = *v,
4177            (K::LineHeight, V::LineHeight(v)) => {
4178                let t = &mut self.text;
4179                (t.line_height, t.line_height_multiple, t.line_height_em) = match *v {
4180                    LineHeight::Normal => (None, None, None),
4181                    LineHeight::Points(p) => (Some(p), None, None),
4182                    LineHeight::Multiple(n) => (None, Some(n), None),
4183                    LineHeight::Em(n) => (None, None, Some(n)),
4184                };
4185            }
4186            (K::FontFamily, V::FontFamily(v)) => self.text.font_family = *v,
4187            (K::FontStyle, V::OptBool(v)) => self.text.italic = *v,
4188            (K::LetterSpacing, V::LetterSpacing(points, em)) => {
4189                self.text.letter_spacing = *points;
4190                self.text.letter_spacing_em = em.map(|n| n.0);
4191            }
4192            (K::TextDecorationLine, V::TextDecoration(v)) => self.text.decoration = *v,
4193            (K::TextDecorationColor, V::Color(c)) => self.text.decoration_color = *c,
4194            (K::PlaceholderColor, V::Color(c)) => self.text.placeholder_color = *c,
4195            (K::SelectionColor, V::Color(c)) => self.text.selection_color = *c,
4196            (K::CaretColor, V::Color(c)) => self.text.caret_color = *c,
4197            (K::WritingDirection, V::OptBool(v)) => self.text.writing_direction = *v,
4198            (K::TextAlignVertical, V::AlignVertical(v)) => self.text.align_vertical = *v,
4199            (K::NumberOfLines, V::NumberOfLines(v)) => self.pending.number_of_lines = *v,
4200            (K::TextOverflow, V::TextOverflow(v)) => self.pending.text_overflow = *v,
4201            (K::UserSelect, V::OptBool(v)) => self.pending.user_select = *v,
4202            (K::PointerEvents, V::PointerEvents(v)) => self.pending.pointer_events = *v,
4203            (K::FontVariant, V::FontVariant(v)) => self.text.font_variant = *v,
4204            (K::TextShadow, V::TextShadow(v)) => {
4205                self.pending.current_text_shadow = v.is_some_and(|(_, colored)| !colored);
4206                let widest = v.map(|(s, _)| s);
4207                self.text.shadow_color = widest.map(|s| s.color);
4208                self.text.shadow_offset = widest.map(|s| point(s.offset_x, s.offset_y));
4209                self.text.shadow_radius = widest.map(|s| s.radius);
4210            }
4211            (K::TextTransform, V::TextTransform(v)) => self.text.transform = *v,
4212            (K::TextAlign, V::TextAlign(align, physical)) => {
4213                self.text.text_align = *align;
4214                self.text.text_align_physical = *physical;
4215            }
4216            (K::TextIndent, V::TextIndent(points, em)) => {
4217                self.text.text_indent = *points;
4218                self.text.text_indent_em = em.map(|n| n.0);
4219            }
4220
4221            // Effects
4222            (K::BoxShadow, V::Shadows(layers)) => {
4223                self.pending.current_shadows = layers
4224                    .iter()
4225                    .enumerate()
4226                    .filter(|(i, (_, colored))| *i < 64 && !colored)
4227                    .fold(0, |mask, (i, _)| mask | 1 << i);
4228                let list = layers.iter().map(|(l, _)| *l).collect();
4229                self.edit_effects(|e| e.box_shadows = list);
4230            }
4231            (K::BackgroundImage, V::Gradients(list)) => {
4232                let list = list.to_vec();
4233                self.edit_effects(|e| e.background_images = list);
4234            }
4235            (K::MaskImage, V::Gradients(list)) => {
4236                let list = list.to_vec();
4237                self.edit_effects(|e| e.mask_images = list);
4238            }
4239            (K::ClipPath, V::ClipPath(clip)) => {
4240                let clip = *clip;
4241                self.edit_effects(|e| e.clip_path = clip);
4242            }
4243            (K::Filter, V::Filters(list)) => {
4244                // A `drop-shadow()` without a color is the text color's.
4245                self.pending.current_drop_shadows = list
4246                    .iter()
4247                    .take(64)
4248                    .enumerate()
4249                    .filter(|(_, (_, named))| !named)
4250                    .fold(0, |m, (i, _)| m | 1 << i);
4251                let list = list.iter().map(|(f, _)| *f).collect();
4252                self.edit_effects(|e| e.filters = list);
4253            }
4254            (K::BackdropFilter, V::Filters(list)) => {
4255                let list = list.iter().map(|(f, _)| *f).collect();
4256                self.edit_effects(|e| e.backdrop_filters = list);
4257            }
4258            (K::GlassEffect, V::GlassEffect(v)) => self.view.glass_effect = *v,
4259            (K::MixBlendMode, V::BlendMode(v)) => self.view.blend_mode = *v,
4260            (K::OutlineWidth, V::Points(width)) => {
4261                self.pending.outline_width = *width;
4262                if !self.pending.outline_hidden {
4263                    self.view.outline.width = *width;
4264                }
4265            }
4266            (K::OutlineColor, V::Color(c)) => {
4267                self.view.outline.color = c.unwrap_or(Outline::NONE.color)
4268            }
4269            (K::OutlineOffset, V::Points(v)) => self.view.outline.offset = *v,
4270            (K::OutlineStyle, V::BorderStyle(style, hidden)) => {
4271                // `none` draws no outline whatever the width, set before
4272                // or after it (CSS).
4273                self.view.outline.style = *style;
4274                self.pending.outline_hidden = *hidden;
4275                self.view.outline.width = if *hidden {
4276                    Points::ZERO
4277                } else {
4278                    self.pending.outline_width
4279                };
4280            }
4281            (K::Visibility, V::Bool(v)) => self.view.hidden = *v,
4282            (K::Cursor, V::Cursor(v)) => self.view.cursor = *v,
4283            (K::TransitionProperty, V::TransitionProps(v)) => self.transition_mut().properties = *v,
4284            (K::TransitionDuration, V::Ms(ms)) => self.transition_mut().duration = ms.0,
4285            (K::TransitionDelay, V::Ms(ms)) => self.transition_mut().delay = ms.0,
4286            (K::TransitionTimingFunction, V::Easing(e)) => {
4287                let t = self.transition_mut();
4288                t.easing = e.map(|n| n.0);
4289                t.spring = None;
4290            }
4291            (K::TransitionTimingFunction, V::Spring(spring)) => {
4292                self.transition_mut().spring = Some(*spring)
4293            }
4294            (K::AnimationName, V::Keyframes(keyframes)) => {
4295                // An animation already running (a class's) keeps its
4296                // values; a new one takes those set before its name.
4297                let pending = &self.pending;
4298                self.view.animation = keyframes.map(|keyframes| {
4299                    let base = self
4300                        .view
4301                        .animation
4302                        .unwrap_or_else(|| pending.animation(KeyframeAnimation::new(keyframes)));
4303                    KeyframeAnimation { keyframes, ..base }
4304                });
4305            }
4306            (K::AnimationDuration, V::Ms(ms)) => {
4307                self.pending.animation_duration = Some(ms.0);
4308                if let Some(a) = self.view.animation.as_mut() {
4309                    a.duration = ms.0;
4310                }
4311            }
4312            (K::AnimationDelay, V::Ms(ms)) => {
4313                self.pending.animation_delay = Some(ms.0);
4314                if let Some(a) = self.view.animation.as_mut() {
4315                    a.delay = ms.0;
4316                }
4317            }
4318            (K::AnimationTimingFunction, V::Easing(e)) => {
4319                let easing = e.map(|n| n.0);
4320                self.pending.animation_easing = Some(easing);
4321                if let Some(a) = self.view.animation.as_mut() {
4322                    a.easing = easing;
4323                }
4324            }
4325            (K::AnimationIterationCount, V::Iterations(count)) => {
4326                self.pending.animation_iterations = Some(*count);
4327                if let Some(a) = self.view.animation.as_mut() {
4328                    a.iterations = *count;
4329                }
4330            }
4331            (K::AnimationFrameRate, V::OptNumber(hz)) => {
4332                let hz = hz.map(|n| n.0);
4333                self.pending.animation_frame_rate = Some(hz);
4334                if let Some(a) = self.view.animation.as_mut() {
4335                    a.frame_rate = hz;
4336                }
4337            }
4338            (K::TextDecorationStyle, V::DecorationStyle(v)) => self.text.decoration_style = *v,
4339            (K::TextDecorationThickness, V::OptPoints(v)) => self.text.decoration_thickness = *v,
4340            (K::TextUnderlineOffset, V::OptPoints(v)) => self.text.underline_offset = *v,
4341
4342            // Grid
4343            (K::GridTemplateColumns, V::GridTemplate(t)) => {
4344                (l.grid_template_columns, l.grid_template_column_names) = (*t.0).clone();
4345            }
4346            (K::GridTemplateRows, V::GridTemplate(t)) => {
4347                (l.grid_template_rows, l.grid_template_row_names) = (*t.0).clone();
4348            }
4349            (K::GridAutoColumns, V::GridTracks(v)) => l.grid_auto_columns = v.to_vec(),
4350            (K::GridAutoRows, V::GridTracks(v)) => l.grid_auto_rows = v.to_vec(),
4351            (K::GridAutoFlow, V::GridAutoFlow(v)) => l.grid_auto_flow = *v,
4352            (K::GridColumn, V::GridLine(v)) => l.grid_column = v.clone(),
4353            (K::GridRow, V::GridLine(v)) => l.grid_row = v.clone(),
4354            (K::GridColumnStart, V::GridPlacement(v)) => l.grid_column.start = v.clone(),
4355            (K::GridColumnEnd, V::GridPlacement(v)) => l.grid_column.end = v.clone(),
4356            (K::GridRowStart, V::GridPlacement(v)) => l.grid_row.start = v.clone(),
4357            (K::GridRowEnd, V::GridPlacement(v)) => l.grid_row.end = v.clone(),
4358            (K::JustifyItems, V::AlignItems(v)) => {
4359                l.justify_items = v.unwrap_or(AlignItems::STRETCH)
4360            }
4361            (K::JustifySelf, V::AlignItems(v)) => l.justify_self = *v,
4362            _ => return Err(StyleError::InvalidValue),
4363        }
4364        Ok(())
4365    }
4366}
4367
4368#[cfg(test)]
4369mod tests {
4370    #[test]
4371    fn font_family_lists_name_their_families_in_order() {
4372        use super::{FamilyName, font_families};
4373        let list: Vec<_> =
4374            font_families(" Inter , \"Noto Sans SC\",'Brand Mono', ui-monospace, sans-serif,")
4375                .collect();
4376        assert_eq!(
4377            list,
4378            [
4379                FamilyName::Named("Inter"),
4380                FamilyName::Named("Noto Sans SC"),
4381                FamilyName::Named("Brand Mono"),
4382                FamilyName::Monospace,
4383                FamilyName::System,
4384            ]
4385        );
4386        assert_eq!(
4387            font_families("serif").collect::<Vec<_>>(),
4388            [FamilyName::Serif]
4389        );
4390        assert_eq!(
4391            font_families("ui-rounded").collect::<Vec<_>>(),
4392            [FamilyName::Rounded]
4393        );
4394        assert_eq!(font_families(" , ").count(), 0);
4395    }
4396
4397    #[test]
4398    fn family_names_remain_copy_and_borrowed() {
4399        fn is_copy<T: Copy>() {}
4400        is_copy::<FamilyName<'_>>();
4401        let name = String::from("Inter");
4402        let FamilyName::Named(borrowed) = font_families(&name).next().unwrap() else {
4403            panic!("expected named family");
4404        };
4405        assert_eq!(borrowed.as_ptr(), name.as_ptr());
4406    }
4407
4408    #[test]
4409    fn decoded_families_keep_whitespace_semantics() {
4410        for input in [
4411            "\u{2003}Inter\u{2003}, serif",
4412            "\u{000b}Inter\u{000b}, serif",
4413            "'\u{2003}Inter\u{000b}', serif",
4414        ] {
4415            assert_eq!(decoded_families(input), decoded_families("Inter, serif"));
4416        }
4417    }
4418
4419    fn decoded_families(value: &str) -> Vec<String> {
4420        let mut out = Vec::new();
4421        for_each_font_family(value, |family| out.push(format!("{family:?}")));
4422        out
4423    }
4424
4425    #[test]
4426    fn quoted_family_names_keep_their_commas() {
4427        use super::{FamilyName, css_font_families, font_families};
4428        assert_eq!(
4429            font_families("'ACME, Inc', serif").collect::<Vec<_>>(),
4430            [FamilyName::Named("ACME, Inc"), FamilyName::Serif]
4431        );
4432        assert_eq!(
4433            font_families("\"Brand, Display\" , 'monospace', ui-monospace").collect::<Vec<_>>(),
4434            [
4435                FamilyName::Named("Brand, Display"),
4436                FamilyName::Named("monospace"),
4437                FamilyName::Monospace,
4438            ]
4439        );
4440        // An unclosed quote runs to the end.
4441        assert_eq!(
4442            font_families("Inter, 'Noto, Sans").collect::<Vec<_>>(),
4443            [FamilyName::Named("Inter"), FamilyName::Named("Noto, Sans"),]
4444        );
4445        assert_eq!(
4446            css_font_families("SF Mono, Menlo, PingFang SC, monospace"),
4447            "\"SF Mono\", \"Menlo\", \"PingFang SC\", monospace"
4448        );
4449        assert_eq!(
4450            css_font_families("'ACME, Inc', serif"),
4451            "\"ACME, Inc\", serif"
4452        );
4453        assert_eq!(css_font_families(" , "), "");
4454
4455        assert_eq!(
4456            decoded_families(r#"'A\\B', monospace"#),
4457            [r#"Named("A\\B")"#, "Monospace"]
4458        );
4459        assert_eq!(
4460            decoded_families(r#""A\"B", serif"#),
4461            [r#"Named("A\"B")"#, "Serif"]
4462        );
4463
4464        // Quotes and backslashes inside family names round-trip identically
4465        // through css_font_families -> CanvasFont::parse -> text_style -> for_each_font_family.
4466        for raw in [
4467            "'A\"B', serif",
4468            "\"A\\\"B\", serif",
4469            "'A\\\\B', monospace",
4470            "a\\b, sans-serif",
4471            "'Quote\\'s, Back\\\\slash', ui-rounded",
4472        ] {
4473            let expected = decoded_families(raw);
4474            let css_list = css_font_families(raw);
4475            assert_eq!(decoded_families(&css_list), expected, "{raw}");
4476            let shorthand = format!("13px {css_list}");
4477            let parsed = crate::canvas::CanvasFont::parse(&shorthand).expect("valid CSS font");
4478            let text_family = parsed.text_style().font_family.expect("has font_family");
4479            assert_eq!(decoded_families(&text_family.name()), expected, "{raw}");
4480        }
4481        assert_eq!(
4482            font_families("'A\"B', serif").collect::<Vec<_>>(),
4483            [FamilyName::Named("A\"B"), FamilyName::Serif]
4484        );
4485        assert_eq!(
4486            font_families("'A\\\\B', monospace").collect::<Vec<_>>(),
4487            [FamilyName::Named("A\\\\B"), FamilyName::Monospace]
4488        );
4489    }
4490
4491    use super::*;
4492    use crate::geometry::{relative, size};
4493
4494    /// `fill`, `stroke`, `strokeWidth` and `strokeDasharray` take what CSS
4495    /// takes for them.
4496    #[test]
4497    fn svg_paint_properties() {
4498        let mut s = Style::default();
4499        s.set("fill", StyleValue::Str("#ff0000")).unwrap();
4500        s.set("stroke", StyleValue::Str("currentColor")).unwrap();
4501        s.set("strokeWidth", StyleValue::Str("2px")).unwrap();
4502        s.set("strokeDasharray", StyleValue::Str("4, 2 1")).unwrap();
4503        assert_eq!(s.paint.fill, Some(SvgPaint::Color(Color(0xff00_00ff))));
4504        assert_eq!(s.paint.stroke, Some(SvgPaint::CurrentColor));
4505        assert_eq!(s.paint.stroke_width, Some(px(2.0)));
4506        assert_eq!(
4507            s.paint.stroke_dasharray.as_deref(),
4508            Some(&[px(4.0), px(2.0), px(1.0)][..])
4509        );
4510        s.set("strokeDasharray", StyleValue::Number(3.0)).unwrap();
4511        assert_eq!(s.paint.stroke_dasharray.as_deref(), Some(&[px(3.0)][..]));
4512        // `none`, and dashes that add up to nothing: a solid line.
4513        for none in ["none", "0 0"] {
4514            s.set("strokeDasharray", StyleValue::Str(none)).unwrap();
4515            assert_eq!(s.paint.stroke_dasharray.as_deref(), Some(&[][..]));
4516        }
4517        s.set("fill", StyleValue::Str("none")).unwrap();
4518        assert_eq!(s.paint.fill, Some(SvgPaint::None));
4519        // Negative lengths are invalid, as in CSS.
4520        assert!(s.set("strokeWidth", StyleValue::Number(-1.0)).is_err());
4521        assert!(s.set("strokeDasharray", StyleValue::Str("4 -2")).is_err());
4522        assert!(s.set("fill", StyleValue::Str("nope")).is_err());
4523        s.set("stroke", StyleValue::Null).unwrap();
4524        assert_eq!(s.paint.stroke, None);
4525    }
4526
4527    #[test]
4528    fn transform_properties_keep_css_order_and_their_bindings() {
4529        use TransformKind::*;
4530
4531        use crate::animation::AnimationProp::Transform as Step;
4532        let kinds = |s: &Style| {
4533            s.view
4534                .transform
4535                .ops()
4536                .iter()
4537                .map(|o| o.kind)
4538                .collect::<Vec<_>>()
4539        };
4540        let mut s = Style::default();
4541        s.set_transform(TransformProperty::Scale, &[(Scale, 1.0, Some(7))])
4542            .unwrap();
4543        // A `transform` list with an animated step.
4544        s.set_transform(TransformProperty::Transform, &[(RotateY, 0.0, Some(9))])
4545            .unwrap();
4546        assert_eq!(s.animated, vec![(Step(0), 7), (Step(1), 9)]);
4547        // `translate` goes before them, moving their bindings.
4548        s.set_key(StyleKey::Translate, StyleValue::Str("10px 20px"))
4549            .unwrap();
4550        assert_eq!(kinds(&s), [TranslateX, TranslateY, Scale, RotateY]);
4551        assert_eq!(s.animated, vec![(Step(2), 7), (Step(3), 9)]);
4552        // Unset, a property's steps and bindings go.
4553        s.set_key(StyleKey::Scale, StyleValue::Null).unwrap();
4554        assert_eq!(kinds(&s), [TranslateX, TranslateY, RotateY]);
4555        assert_eq!(s.animated, vec![(Step(2), 9)]);
4556        // A Rust component's bound step goes after them all.
4557        StyleDecl::Transform(Rotate, 0.0, Some(11))
4558            .apply(&mut s)
4559            .unwrap();
4560        s.set_key(StyleKey::Rotate, StyleValue::Number(30.0))
4561            .unwrap();
4562        assert_eq!(kinds(&s), [TranslateX, TranslateY, Rotate, RotateY, Rotate]);
4563        assert_eq!(s.animated, vec![(Step(3), 9), (Step(4), 11)]);
4564        // CSS's string replaces the list, its binding with it.
4565        s.set_key(StyleKey::Transform, StyleValue::Str("skewX(5deg)"))
4566            .unwrap();
4567        assert_eq!(kinds(&s), [TranslateX, TranslateY, Rotate, SkewX, Rotate]);
4568        assert_eq!(s.animated, vec![(Step(4), 11)]);
4569        assert_eq!(
4570            s.set_key(StyleKey::Transform, StyleValue::Str("rotate(45)")),
4571            Err(StyleError::InvalidValue)
4572        );
4573    }
4574
4575    #[test]
4576    fn aspect_ratios_and_font_variants_take_css_strings() {
4577        let ratio = |v| {
4578            let mut s = Style::default();
4579            s.set("aspectRatio", v).map(|_| s.layout.aspect_ratio)
4580        };
4581        assert_eq!(ratio(StyleValue::Str("16 / 9")), Ok(Some(16.0 / 9.0)));
4582        assert_eq!(ratio(StyleValue::Str("2/1")), Ok(Some(2.0)));
4583        assert_eq!(ratio(StyleValue::Str("1.5")), Ok(Some(1.5)));
4584        assert_eq!(ratio(StyleValue::Number(1.5)), Ok(Some(1.5)));
4585        assert_eq!(ratio(StyleValue::Str("auto")), Ok(None));
4586        assert_eq!(
4587            ratio(StyleValue::Str("1 / 0")),
4588            Err(StyleError::InvalidValue)
4589        );
4590        let mut s = Style::default();
4591        s.set("fontVariant", StyleValue::Str("tabular-nums small-caps"))
4592            .unwrap();
4593        let v = s.text.font_variant.unwrap();
4594        assert!(v.has(FontVariant::TABULAR_NUMS) && v.has(FontVariant::SMALL_CAPS));
4595    }
4596
4597    #[test]
4598    fn line_height_numbers_are_points() {
4599        let mut s = Style::default();
4600        s.set("lineHeight", StyleValue::Number(20.0)).unwrap();
4601        assert_eq!(s.text.line_height, Some(px(20.0)));
4602        // Strings are what classes write: a multiple, or a length.
4603        s.set("lineHeight", StyleValue::Str("1.5")).unwrap();
4604        assert_eq!(
4605            (s.text.line_height, s.text.line_height_multiple),
4606            (None, Some(1.5))
4607        );
4608        s.set("lineHeight", StyleValue::Str("150%")).unwrap();
4609        assert_eq!(s.text.line_height_em, Some(1.5));
4610        s.set("lineHeight", StyleValue::Str("20px")).unwrap();
4611        assert_eq!(s.text.line_height, Some(px(20.0)));
4612        s.set("lineHeight", StyleValue::Null).unwrap();
4613        assert_eq!(
4614            (
4615                s.text.line_height,
4616                s.text.line_height_multiple,
4617                s.text.line_height_em
4618            ),
4619            (None, None, None)
4620        );
4621    }
4622
4623    #[test]
4624    fn font_size_takes_ems_and_percentages() {
4625        let mut s = Style::default();
4626        s.set("fontSize", StyleValue::Number(16.0)).unwrap();
4627        assert_eq!(
4628            (s.text.font_size, s.text.font_size_em),
4629            (Some(px(16.0)), None)
4630        );
4631        s.set("fontSize", StyleValue::Str("0.875em")).unwrap();
4632        assert_eq!((s.text.font_size, s.text.font_size_em), (None, Some(0.875)));
4633        s.set("fontSize", StyleValue::Str("150%")).unwrap();
4634        assert_eq!(s.text.font_size_em, Some(1.5));
4635        s.set("fontSize", StyleValue::Str("20px")).unwrap();
4636        assert_eq!(
4637            (s.text.font_size, s.text.font_size_em),
4638            (Some(px(20.0)), None)
4639        );
4640        assert!(s.set("fontSize", StyleValue::Str("-1em")).is_err());
4641        // Rust's `text_size(relative(..))` writes the same value.
4642        let rel = StyleKey::FontSize
4643            .length_value(crate::geometry::relative(0.5).into())
4644            .unwrap();
4645        assert_eq!(rel, PropertyValue::FontSize(None, Some(OrderedFloat(0.5))));
4646        s.set("fontSize", StyleValue::Null).unwrap();
4647        assert_eq!((s.text.font_size, s.text.font_size_em), (None, None));
4648    }
4649
4650    #[test]
4651    fn values_parse_once_and_apply_typed() {
4652        let key = StyleKey::PaddingTop;
4653        let value = key.parse_value(StyleValue::Str("25%")).unwrap();
4654        assert_eq!(value, PropertyValue::Lp(LengthPercentage::percent(0.25)));
4655        let mut s = Style::default();
4656        s.apply_value(key, &value).unwrap();
4657        assert_eq!(s.layout.padding.top, LengthPercentage::percent(0.25));
4658        // A value of another property's kind is rejected.
4659        assert_eq!(
4660            s.apply_value(key, &PropertyValue::Color(None)),
4661            Err(StyleError::InvalidValue)
4662        );
4663        // `null` is the property's default.
4664        s.apply_value(key, &PropertyValue::Default).unwrap();
4665        assert_eq!(s.layout.padding.top, LengthPercentage::length(0.0));
4666        // Equal values hash alike, signed zeros included.
4667        let hash = |v: &PropertyValue| {
4668            use std::hash::{BuildHasher, BuildHasherDefault};
4669            BuildHasherDefault::<rustc_hash::FxHasher>::default().hash_one(v)
4670        };
4671        let (a, b) = (
4672            PropertyValue::Points(px(0.0)),
4673            PropertyValue::Points(px(-0.0)),
4674        );
4675        assert_eq!(a, b);
4676        assert_eq!(hash(&a), hash(&b));
4677    }
4678
4679    #[test]
4680    fn typed_lengths_are_the_numbers_and_percentages_of_styles() {
4681        use crate::geometry::{Length, percentage};
4682        for key in [
4683            StyleKey::Width,
4684            StyleKey::MarginLeft,
4685            StyleKey::Gap,
4686            StyleKey::LineHeight,
4687        ] {
4688            assert_eq!(
4689                key.length_value(px(12.0).into()),
4690                key.parse_value(StyleValue::Number(12.0))
4691            );
4692        }
4693        assert_eq!(
4694            StyleKey::Width.length_value(percentage(0.5).into()),
4695            StyleKey::Width.parse_value(StyleValue::Str("50%"))
4696        );
4697        assert_eq!(
4698            StyleKey::Top.length_value(Length::Auto),
4699            StyleKey::Top.parse_value(StyleValue::Str("auto"))
4700        );
4701        assert!(StyleKey::Padding.length_value(Length::Auto).is_err());
4702    }
4703
4704    #[test]
4705    fn parse_colors() {
4706        assert_eq!(Color::parse("#fff"), Some(Color(0xffff_ffff)));
4707        assert_eq!(Color::parse("#f008"), Some(Color(0xff00_0088)));
4708        assert_eq!(Color::parse("#123456"), Some(Color(0x1234_56ff)));
4709        assert_eq!(Color::parse("#12345678"), Some(Color(0x1234_5678)));
4710        assert_eq!(Color::parse("rgb(255, 0, 10)"), Some(Color(0xff00_0aff)));
4711        assert_eq!(Color::parse("rgba(0,0,0,0.5)"), Some(Color(0x0000_0080)));
4712        assert_eq!(Color::parse("white"), Some(Color(0xffff_ffff)));
4713        assert_eq!(Color::parse("#12"), None);
4714        assert_eq!(Color::parse("nope"), None);
4715    }
4716
4717    #[test]
4718    fn env_on_padding_and_margin() {
4719        use EnvVar::*;
4720        let mut s = Style::default();
4721        let k = StyleValue::Str;
4722        s.set("paddingBottom", k("env(keyboard-inset-height)"))
4723            .unwrap();
4724        assert_eq!(
4725            s.pending.env.padding,
4726            [None, None, Some(KeyboardInsetHeight), None]
4727        );
4728        assert_eq!(s.layout.padding.bottom, LengthPercentage::length(0.0));
4729        // `calc()` adds a length, on either side.
4730        s.set("paddingTop", k("calc(env(safe-area-inset-top) + 8px)"))
4731            .unwrap();
4732        assert_eq!(s.pending.env.padding[0], Some(SafeAreaInsetTop));
4733        assert_eq!(s.layout.padding.top, LengthPercentage::length(8.0));
4734        s.set("marginLeft", k("calc(0.5rem + env(safe-area-inset-left))"))
4735            .unwrap();
4736        assert_eq!(s.pending.env.margin[3], Some(SafeAreaInsetLeft));
4737        assert_eq!(s.layout.margin.left, LengthPercentageAuto::length(8.0));
4738        // Margins may go below zero.
4739        s.set("marginBottom", k("calc(env(keyboard-inset-height) + -4px)"))
4740            .unwrap();
4741        assert_eq!(s.layout.margin.bottom, LengthPercentageAuto::length(-4.0));
4742        // Shorthands set every edge they cover.
4743        s.set("paddingHorizontal", k("env(safe-area-inset-right)"))
4744            .unwrap();
4745        assert_eq!(s.pending.env.padding[1], Some(SafeAreaInsetRight));
4746        assert_eq!(s.pending.env.padding[3], Some(SafeAreaInsetRight));
4747        s.set("margin", k("env(safe-area-inset-top)")).unwrap();
4748        assert_eq!(s.pending.env.margin, [Some(SafeAreaInsetTop); 4]);
4749        // An unknown variable is its fallback.
4750        s.set("paddingRight", k("env(titlebar-area-x, 12px)"))
4751            .unwrap();
4752        assert_eq!(s.pending.env.padding[1], None);
4753        assert_eq!(s.layout.padding.right, LengthPercentage::length(12.0));
4754        // A known one ignores its fallback.
4755        s.set("paddingRight", k("env(safe-area-inset-right, 12px)"))
4756            .unwrap();
4757        assert_eq!(s.pending.env.padding[1], Some(SafeAreaInsetRight));
4758        assert_eq!(s.layout.padding.right, LengthPercentage::length(0.0));
4759        // A plain value or a reset drops the term.
4760        s.set("paddingTop", StyleValue::Number(4.0)).unwrap();
4761        s.set("paddingBottom", StyleValue::Null).unwrap();
4762        s.set("margin", StyleValue::Null).unwrap();
4763        assert_eq!(s.pending.env.padding[0], None);
4764        assert_eq!(s.pending.env.padding[2], None);
4765        assert_eq!(s.pending.env.margin, [None; 4]);
4766        // Anything else is rejected.
4767        for v in [
4768            "env(titlebar-area-x)",
4769            "env(safe-area-inset-top) + 8px",
4770            "calc(env(safe-area-inset-top)+8px)",
4771            "calc(env(safe-area-inset-top) - 8px)",
4772            "calc(env(safe-area-inset-top) + env(keyboard-inset-height))",
4773            "calc(env(safe-area-inset-top) + 10%)",
4774            "calc(env(safe-area-inset-top) + 1px + 2px)",
4775            "max(env(safe-area-inset-top), 8px)",
4776        ] {
4777            assert_eq!(
4778                s.set("paddingTop", k(v)),
4779                Err(StyleError::InvalidValue),
4780                "{v}"
4781            );
4782        }
4783        // Padding is never negative.
4784        assert_eq!(
4785            s.set("paddingTop", k("calc(env(safe-area-inset-top) + -8px)")),
4786            Err(StyleError::InvalidValue)
4787        );
4788        // Only padding and margin's physical edges take `env()`.
4789        for key in ["paddingStart", "marginEnd", "top", "width", "gap"] {
4790            assert!(s.set(key, k("env(safe-area-inset-top)")).is_err(), "{key}");
4791        }
4792    }
4793
4794    #[test]
4795    fn react_native_defaults() {
4796        let s = Style::default();
4797        assert_eq!(s.layout.flex_direction, FlexDirection::Column);
4798        assert_eq!(s.layout.flex_shrink, 0.0);
4799        assert_eq!(s.layout.position, Position::Relative);
4800        // Unset: `flex-start` once laid out outside grids.
4801        assert_eq!(s.layout.align_content, AlignContent::NORMAL);
4802        let mut layout = s.layout.clone();
4803        resolve_normal_alignment(&mut layout);
4804        assert_eq!(layout.align_content, AlignContent::FLEX_START);
4805        assert_eq!(s.layout.min_size.width, LengthPercentageAuto::length(0.0));
4806    }
4807
4808    #[test]
4809    fn auto_minimum_sizes_are_css_automatic_minimums() {
4810        let mut s = Style::default();
4811        s.set("minWidth", StyleValue::Str("auto")).unwrap();
4812        s.set("minHeight", StyleValue::Str("auto")).unwrap();
4813        assert_eq!(s.layout.min_size.width, LengthPercentageAuto::auto());
4814        assert_eq!(s.layout.min_size.height, LengthPercentageAuto::auto());
4815        // Unset again: back to Yoga's 0.
4816        s.set("minWidth", StyleValue::Null).unwrap();
4817        assert_eq!(s.layout.min_size.width, LengthPercentageAuto::length(0.0));
4818    }
4819
4820    #[test]
4821    fn css_alignment_keywords() {
4822        let mut s = Style::default();
4823        let k = StyleValue::Str;
4824        for key in ["alignItems", "alignSelf", "justifyItems", "justifySelf"] {
4825            for v in ["start", "end", "self-start", "self-end"] {
4826                s.set(key, k(v)).unwrap();
4827            }
4828        }
4829        assert_eq!(s.layout.justify_self, Some(AlignItems::SELF_END));
4830        for key in ["alignContent", "justifyContent"] {
4831            s.set(key, k("end")).unwrap();
4832            assert_eq!(s.set(key, k("self-end")), Err(StyleError::InvalidValue));
4833        }
4834        assert_eq!(s.layout.align_content, AlignContent::END);
4835        s.set("alignContent", k("normal")).unwrap();
4836        assert_eq!(s.layout.align_content, AlignContent::NORMAL);
4837        s.set("justifyContent", StyleValue::Null).unwrap();
4838        assert_eq!(s.layout.justify_content, AlignContent::NORMAL);
4839        // A grid keeps CSS's `normal`; other containers take `flex-start`.
4840        s.set("display", k("grid")).unwrap();
4841        let mut grid = s.layout.clone();
4842        resolve_normal_alignment(&mut grid);
4843        assert_eq!(grid.align_content, AlignContent::NORMAL);
4844        assert_eq!(
4845            s.set("gridTemplateColumns", k("[a] 40px [b")),
4846            Err(StyleError::InvalidValue)
4847        );
4848        s.set("gridTemplateRows", k("[a] 40px [b] 1fr")).unwrap();
4849        assert_eq!(s.layout.grid_template_row_names.len(), 3);
4850        s.set("gridTemplateRows", StyleValue::Null).unwrap();
4851        assert!(s.layout.grid_template_row_names.is_empty());
4852    }
4853
4854    #[test]
4855    fn transform_origins() {
4856        let p = |s| TransformOrigin::parse(s).unwrap();
4857        assert_eq!(p("top left").x, relative(0.0));
4858        assert_eq!(p("top left").y, relative(0.0));
4859        assert_eq!(p("bottom").y, relative(1.0));
4860        assert_eq!(p("bottom").x, relative(0.5));
4861        assert_eq!(p("10px 25%").x, DefiniteLength::from(px(10.0)));
4862        assert_eq!(p("10px 25%").y, relative(0.25));
4863        assert_eq!(p("right 5 3").z, px(3.0));
4864        assert_eq!(p("center top").y, relative(0.0));
4865        assert_eq!(
4866            p("0 0").offset(size(px(100.0), px(50.0))),
4867            (point(px(-50.0), px(-25.0)), Points::ZERO)
4868        );
4869        assert!(TransformOrigin::parse("sideways").is_none());
4870    }
4871
4872    #[test]
4873    fn font_variants() {
4874        let v = FontVariant::parse("small-caps tabular-nums").unwrap();
4875        assert_eq!(v.tags().collect::<Vec<_>>(), ["smcp", "tnum"]);
4876        assert!(FontVariant::parse("wide").is_none());
4877    }
4878
4879    #[test]
4880    fn text_align_vertical_places_text_down_its_box() {
4881        let at = |v: &str| {
4882            let mut s = Style::default();
4883            s.set("textAlignVertical", StyleValue::Str(v)).unwrap();
4884            s.text.align_vertical
4885        };
4886        assert_eq!(at("top"), Some(percentage(0.0)));
4887        assert_eq!(at("center"), Some(percentage(0.5)));
4888        assert_eq!(at("bottom"), Some(percentage(1.0)));
4889        // `alignContent` is layout only.
4890        let mut s = Style::default();
4891        s.set("alignContent", StyleValue::Str("center")).unwrap();
4892        assert_eq!(s.text.align_vertical, None);
4893    }
4894
4895    #[test]
4896    fn flex_shorthand() {
4897        // CSS's: grow, shrink and basis.
4898        let flex = |v: StyleValue<'_>| {
4899            let mut s = Style::default();
4900            s.set("flex", v).map(|()| {
4901                (
4902                    s.layout.flex_grow,
4903                    s.layout.flex_shrink,
4904                    s.layout.flex_basis,
4905                )
4906            })
4907        };
4908        let (n, t) = (StyleValue::Number, StyleValue::Str);
4909        let (zero, auto) = (Dimension::length(0.0), Dimension::auto());
4910        assert_eq!(flex(n(2.0)), Ok((2.0, 1.0, zero)));
4911        // `0` shrinks as CSS's does (React Native's did not).
4912        assert_eq!(flex(n(0.0)), Ok((0.0, 1.0, zero)));
4913        assert_eq!(flex(t("none")), Ok((0.0, 0.0, auto)));
4914        assert_eq!(flex(t("auto")), Ok((1.0, 1.0, auto)));
4915        assert_eq!(flex(t("initial")), Ok((0.0, 1.0, auto)));
4916        assert_eq!(flex(t("2 0 50%")), Ok((2.0, 0.0, Dimension::percent(0.5))));
4917        assert_eq!(flex(t("30px 2")), Ok((2.0, 1.0, Dimension::length(30.0))));
4918        assert_eq!(flex(t("1 0")), Ok((1.0, 0.0, zero)));
4919        assert_eq!(flex(t("0 0 0")), Ok((0.0, 0.0, zero)));
4920        assert_eq!(flex(StyleValue::Null), Ok((0.0, 0.0, auto)));
4921        // Negative factors (React Native's `flex: -1`) are no CSS.
4922        for v in [n(-1.0), t("-1"), t("1 -1"), t("1 2 3 4"), t("nope")] {
4923            assert_eq!(flex(v), Err(StyleError::InvalidValue), "{v:?}");
4924        }
4925    }
4926
4927    /// Every order of `decls`.
4928    fn permutations<T: Clone>(decls: &[T]) -> Vec<Vec<T>> {
4929        if decls.len() <= 1 {
4930            return vec![decls.to_vec()];
4931        }
4932        let mut out = Vec::new();
4933        for i in 0..decls.len() {
4934            let mut rest = decls.to_vec();
4935            let first = rest.remove(i);
4936            for mut tail in permutations(&rest) {
4937                tail.insert(0, first.clone());
4938                out.push(tail);
4939            }
4940        }
4941        out
4942    }
4943
4944    /// Checks the style of one style object with `decls` in every order:
4945    /// as recorded, and replayed from the patch (over classes).
4946    fn in_any_order(decls: &[(&str, StyleValue<'_>)], check: impl Fn(&Style)) {
4947        for order in permutations(decls) {
4948            let mut style = Style::default();
4949            let mut patch = StylePatch::default();
4950            for &(key, value) in &order {
4951                patch.set(&mut style, key, value).unwrap();
4952            }
4953            let keys: Vec<_> = order.iter().map(|(k, _)| *k).collect();
4954            println!("{keys:?}");
4955            check(&style);
4956            let mut replayed = Style::default();
4957            patch.apply(&mut replayed);
4958            check(&replayed);
4959        }
4960    }
4961
4962    #[test]
4963    fn border_longhands_override_the_shorthand_in_any_order() {
4964        use StyleValue::{Null, Number, Str};
4965        in_any_order(
4966            &[
4967                ("borderTopWidth", Number(5.0)),
4968                ("borderWidth", Number(2.0)),
4969                ("borderLeftColor", Str("red")),
4970                ("borderColor", Str("blue")),
4971            ],
4972            |s| {
4973                assert_eq!(
4974                    s.view.borders.widths.to_array().map(|w| w.0),
4975                    [5.0, 2.0, 2.0, 2.0]
4976                );
4977                assert_eq!(s.layout.border.top, LengthPercentage::length(5.0));
4978                assert_eq!(s.layout.border.left, LengthPercentage::length(2.0));
4979                let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
4980                assert_eq!(s.view.borders.colors, [blue, blue, blue, red]);
4981            },
4982        );
4983        // A null longhand is unset: the shorthand shows.
4984        in_any_order(
4985            &[("borderTopWidth", Null), ("borderWidth", Number(2.0))],
4986            |s| assert_eq!(s.view.borders.widths.to_array().map(|w| w.0), [2.0; 4]),
4987        );
4988        // Without its shorthand, null still resets the longhand (a class's).
4989        let mut s = Style::default();
4990        s.set("borderTopWidth", Number(4.0)).unwrap();
4991        StylePatch::default()
4992            .set(&mut s, "borderTopWidth", Null)
4993            .unwrap();
4994        assert_eq!(s.view.borders.widths.top, Points::ZERO);
4995    }
4996
4997    #[test]
4998    fn edge_longhands_override_their_shorthands_in_any_order() {
4999        use StyleValue::Number;
5000        let len = LengthPercentageAuto::length;
5001        in_any_order(
5002            &[
5003                ("marginTop", Number(1.0)),
5004                ("marginVertical", Number(2.0)),
5005                ("margin", Number(3.0)),
5006                ("marginLeft", Number(4.0)),
5007                ("marginHorizontal", Number(5.0)),
5008            ],
5009            |s| {
5010                let m = s.layout.margin;
5011                assert_eq!(
5012                    [m.top, m.bottom, m.left, m.right],
5013                    [len(1.0), len(2.0), len(4.0), len(5.0)]
5014                );
5015            },
5016        );
5017        let len = LengthPercentage::length;
5018        in_any_order(
5019            &[
5020                ("paddingRight", Number(1.0)),
5021                ("padding", Number(3.0)),
5022                ("paddingVertical", Number(2.0)),
5023            ],
5024            |s| {
5025                let p = s.layout.padding;
5026                assert_eq!(
5027                    [p.top, p.bottom, p.left, p.right],
5028                    [len(2.0), len(2.0), len(3.0), len(1.0)]
5029                );
5030            },
5031        );
5032        in_any_order(&[("rowGap", Number(4.0)), ("gap", Number(8.0))], |s| {
5033            assert_eq!(s.layout.gap.height, len(4.0));
5034            assert_eq!(s.layout.gap.width, len(8.0));
5035        });
5036    }
5037
5038    #[test]
5039    fn flex_and_grid_longhands_override_their_shorthands_in_any_order() {
5040        use StyleValue::{Number, Str};
5041        in_any_order(&[("flexGrow", Number(2.0)), ("flex", Number(1.0))], |s| {
5042            assert_eq!(s.layout.flex_grow, 2.0);
5043            assert_eq!(s.layout.flex_shrink, 1.0);
5044            assert_eq!(s.layout.flex_basis, Dimension::length(0.0));
5045        });
5046        in_any_order(
5047            &[
5048                ("gridColumnStart", Number(2.0)),
5049                ("gridColumn", Str("1 / 4")),
5050            ],
5051            |s| {
5052                assert_eq!(
5053                    Some(&s.layout.grid_column.start),
5054                    grid::placement("2").as_ref()
5055                );
5056                assert_eq!(
5057                    Some(&s.layout.grid_column.end),
5058                    grid::placement("4").as_ref()
5059                );
5060            },
5061        );
5062    }
5063
5064    #[test]
5065    fn outline_style_none_hides_the_outline_in_any_order() {
5066        use StyleValue::{Null, Number, Str};
5067        in_any_order(
5068            &[("outlineStyle", Str("none")), ("outlineWidth", Number(3.0))],
5069            |s| assert!(!s.view.outline.is_visible()),
5070        );
5071        in_any_order(
5072            &[
5073                ("outlineStyle", Str("dashed")),
5074                ("outlineWidth", Number(3.0)),
5075            ],
5076            |s| {
5077                assert_eq!(s.view.outline.width, px(3.0));
5078                assert_eq!(s.view.outline.style, BorderStyle::Dashed);
5079            },
5080        );
5081        // A later style (inline over classes) showing it again gets the
5082        // width back.
5083        let mut s = Style::default();
5084        s.set("outlineWidth", Number(3.0)).unwrap();
5085        s.set("outlineStyle", Str("none")).unwrap();
5086        s.set("outlineStyle", Null).unwrap();
5087        assert_eq!(s.view.outline.width, px(3.0));
5088    }
5089
5090    #[test]
5091    fn border_style_none_hides_the_border_in_any_order() {
5092        use StyleValue::{Null, Number, Str};
5093        for none in ["none", "hidden"] {
5094            in_any_order(
5095                &[
5096                    ("borderStyle", Str(none)),
5097                    ("borderWidth", Number(3.0)),
5098                    ("borderTopWidth", Number(4.0)),
5099                    ("borderStartWidth", Number(5.0)),
5100                ],
5101                |s| {
5102                    assert!(!s.view.borders.is_visible());
5103                    assert_eq!(s.view.borders.widths.to_array(), [Points::ZERO; 4]);
5104                    assert_eq!(s.layout.border.top, LengthPercentage::length(0.0));
5105                    assert_eq!(s.layout.border.left, LengthPercentage::length(0.0));
5106                    assert_eq!(s.logical.border_width, [None; 2]);
5107                },
5108            );
5109        }
5110        // A later style showing it again gets the widths back.
5111        let mut s = Style::default();
5112        s.set("borderWidth", Number(3.0)).unwrap();
5113        s.set("borderEndWidth", Number(1.0)).unwrap();
5114        s.set("borderStyle", Str("none")).unwrap();
5115        s.set("borderStyle", Str("dashed")).unwrap();
5116        assert_eq!(s.view.borders.widths.to_array(), [px(3.0); 4]);
5117        assert_eq!(s.layout.border.right, LengthPercentage::length(3.0));
5118        assert_eq!(s.logical.border_width, [None, Some(px(1.0))]);
5119        assert_eq!(s.view.borders.style, BorderStyle::Dashed);
5120        s.set("borderStyle", Str("hidden")).unwrap();
5121        s.set("borderStyle", Null).unwrap();
5122        assert_eq!(s.view.borders.widths.to_array(), [px(3.0); 4]);
5123    }
5124
5125    #[test]
5126    fn animation_keys_apply_in_any_order() {
5127        use StyleValue::{Number, Str};
5128        in_any_order(
5129            &[
5130                ("animationDuration", Number(500.0)),
5131                ("animationIterationCount", Number(2.0)),
5132                ("animationName", Str("spin")),
5133                ("animationDelay", Str("0.1s")),
5134                ("animationTimingFunction", Str("ease-in")),
5135                ("animationFrameRate", Number(30.0)),
5136            ],
5137            |s| {
5138                let a = s.view.animation.unwrap();
5139                assert_eq!(a.keyframes, Keyframes::Spin);
5140                assert_eq!(a.duration, 500.0);
5141                assert_eq!(a.iterations, Some(2));
5142                assert_eq!(a.delay, 100.0);
5143                assert_eq!(a.easing, [0.42, 0.0, 1.0, 1.0]);
5144                assert_eq!(a.frame_rate, Some(30.0));
5145            },
5146        );
5147        // Without a name nothing runs.
5148        in_any_order(&[("animationDuration", Number(500.0))], |s| {
5149            assert_eq!(s.view.animation, None)
5150        });
5151        // Over a running (class) animation, the values change it.
5152        let mut s = Style::default();
5153        s.set("animationName", Str("ping")).unwrap();
5154        s.set("animationDuration", Number(300.0)).unwrap();
5155        s.set("animationName", Str("spin")).unwrap();
5156        assert_eq!(s.view.animation.unwrap().duration, 300.0);
5157    }
5158
5159    #[test]
5160    fn animation_frame_rate_asks_for_a_positive_rate() {
5161        use StyleValue::{Null, Number, Str};
5162        let mut s = Style::default();
5163        s.set("animationName", Str("spin")).unwrap();
5164        // Unset: the screen's highest.
5165        assert_eq!(s.view.animation.unwrap().frame_rate, None);
5166        s.set("animationFrameRate", Number(24.0)).unwrap();
5167        assert_eq!(s.view.animation.unwrap().frame_rate, Some(24.0));
5168        // Not a rate: none asked for.
5169        for hz in [0.0, -30.0, f32::INFINITY] {
5170            s.set("animationFrameRate", Number(hz)).unwrap();
5171            assert_eq!(s.view.animation.unwrap().frame_rate, None);
5172        }
5173        s.set("animationFrameRate", Number(30.0)).unwrap();
5174        s.set("animationFrameRate", Null).unwrap();
5175        assert_eq!(s.view.animation.unwrap().frame_rate, None);
5176        assert!(s.set("animationFrameRate", Str("30")).is_err());
5177    }
5178
5179    #[test]
5180    fn transition_keys_apply_in_any_order() {
5181        use StyleValue::{Number, Str};
5182        in_any_order(
5183            &[
5184                ("transitionDuration", Number(300.0)),
5185                ("transitionDelay", Number(50.0)),
5186                ("transitionTimingFunction", Str("linear")),
5187                ("transitionProperty", Str("opacity")),
5188            ],
5189            |s| {
5190                let t = s.view.transition.unwrap();
5191                assert_eq!(t.properties, TransitionProps(TransitionProps::OPACITY));
5192                assert_eq!(t.duration, 300.0);
5193                assert_eq!(t.delay, 50.0);
5194                assert_eq!(t.easing, [0.0, 0.0, 1.0, 1.0]);
5195                assert_eq!(t.spring, None);
5196            },
5197        );
5198    }
5199
5200    #[test]
5201    fn transitions_take_a_spring_and_curves_that_overshoot() {
5202        use StyleValue::Str;
5203        let mut s = Style::default();
5204        s.set("transitionTimingFunction", Str("spring(620, 36)"))
5205            .unwrap();
5206        let t = s.view.transition.unwrap();
5207        let spring = t.spring.expect("a spring");
5208        assert_eq!(
5209            (spring.stiffness, spring.damping, spring.mass),
5210            (620.0, 36.0, 1.0)
5211        );
5212        // It times itself: about 380 ms whatever the duration says.
5213        assert!((t.run_ms() - 383.8).abs() < 1.0, "{}", t.run_ms());
5214        s.set("transitionTimingFunction", Str("spring(992, 45, 2)"))
5215            .unwrap();
5216        assert_eq!(s.view.transition.unwrap().spring.unwrap().mass, 2.0);
5217        for bad in [
5218            "spring(620)",
5219            "spring(620, 0)",
5220            "spring(-1, 36)",
5221            "spring(a, b)",
5222        ] {
5223            assert!(
5224                s.set("transitionTimingFunction", Str(bad)).is_err(),
5225                "{bad}"
5226            );
5227        }
5228        // Keyframes have no spring.
5229        assert!(
5230            s.set("animationTimingFunction", Str("spring(620, 36)"))
5231                .is_err()
5232        );
5233        // A Bézier's y past 0..1 is kept: it overshoots.
5234        s.set(
5235            "transitionTimingFunction",
5236            Str("cubic-bezier(0.3, 1.25, 0.6, 1)"),
5237        )
5238        .unwrap();
5239        let t = s.view.transition.unwrap();
5240        assert_eq!((t.easing, t.spring), ([0.3, 1.25, 0.6, 1.0], None));
5241    }
5242
5243    #[test]
5244    fn corner_radii_override_the_shorthand_in_any_order() {
5245        let mut s = Style::default();
5246        s.set("borderTopLeftRadius", StyleValue::Number(4.0))
5247            .unwrap();
5248        s.set("borderRadius", StyleValue::Number(10.0)).unwrap();
5249        let r = s.view.radii();
5250        assert_eq!(r.to_array(), [px(4.0), px(10.0), px(10.0), px(10.0)]);
5251        assert_eq!(r.shared(), None);
5252        s.set("borderTopLeftRadius", StyleValue::Null).unwrap();
5253        assert_eq!(s.view.radii().shared(), Some(px(10.0)));
5254    }
5255
5256    #[test]
5257    fn shared_radius_ignores_square_corners() {
5258        let r = CornerRadii {
5259            top_left: px(12.0),
5260            top_right: px(12.0),
5261            ..CornerRadii::default()
5262        };
5263        assert_eq!(r.shared(), Some(px(12.0)));
5264        assert_eq!(CornerRadii::default().shared(), Some(px(0.0)));
5265        assert!(CornerRadii::default().is_zero());
5266    }
5267
5268    #[test]
5269    fn radii_fit_the_box() {
5270        // 100 + 300 on a 200 wide box: everything scales by 0.5.
5271        let r = CornerRadii {
5272            top_left: px(100.0),
5273            top_right: px(300.0),
5274            bottom_right: px(0.0),
5275            bottom_left: px(0.0),
5276            continuous: false,
5277        }
5278        .fit(size(px(200.0), px(1000.0)));
5279        assert_eq!(r.to_array(), [px(50.0), px(150.0), px(0.0), px(0.0)]);
5280        let fits = CornerRadii::all(px(10.0));
5281        assert_eq!(fits.fit(size(px(100.0), px(100.0))), fits);
5282        assert_eq!(fits.inset(px(4.0)), CornerRadii::all(px(6.0)));
5283        assert_eq!(fits.inset(px(40.0)), CornerRadii::all(px(0.0)));
5284    }
5285
5286    #[test]
5287    fn a_replayed_flex_display_keeps_its_row() {
5288        // A Rust component's host replays an app's style with `push`.
5289        let mut first = Style::default();
5290        let mut patch = StylePatch::default();
5291        patch
5292            .set(&mut first, "display", StyleValue::Str("flex"))
5293            .unwrap();
5294        let mut style = Style::default();
5295        let mut replayed = StylePatch::default();
5296        for decl in patch.decls() {
5297            replayed.push(&mut style, decl.clone()).unwrap();
5298        }
5299        assert_eq!(style.layout.flex_direction, FlexDirection::Row);
5300        // A width with its own side's color reads no text color.
5301        let mut patch = StylePatch::default();
5302        patch
5303            .set(&mut first, "borderBottomWidth", StyleValue::Number(1.0))
5304            .unwrap();
5305        assert!(patch.reads_current_color());
5306        patch
5307            .set(&mut first, "borderBottomColor", StyleValue::Str("#eee"))
5308            .unwrap();
5309        assert!(!patch.reads_current_color());
5310    }
5311
5312    #[test]
5313    fn current_color_written_out_is_the_text_color() {
5314        let text = Color(0x1234_56ff);
5315        let mut s = Style::default();
5316        let mut patch = StylePatch::default();
5317        for (key, value) in [
5318            ("backgroundColor", "currentColor"),
5319            ("borderColor", "CurrentColor"),
5320            // A later value wins over `currentColor`.
5321            ("borderTopColor", "red"),
5322            ("outlineColor", "currentcolor"),
5323            ("textDecorationColor", "currentColor"),
5324            ("boxShadow", "0 2px 4px currentColor"),
5325            ("textShadow", "0 1px 2px currentColor"),
5326        ] {
5327            patch.set(&mut s, key, StyleValue::Str(value)).unwrap();
5328        }
5329        assert!(patch.reads_current_color());
5330        s.apply_current_color(text);
5331        assert_eq!(s.view.background_color, text);
5332        assert_eq!(
5333            s.view.borders.colors,
5334            [Color(0xff00_00ff), text, text, text]
5335        );
5336        assert_eq!(s.view.outline.color, text);
5337        assert_eq!(s.text.decoration_color, Some(text));
5338        assert_eq!(s.view.effects.as_ref().unwrap().box_shadows[0].color, text);
5339        assert_eq!(s.text.shadow_color, Some(text));
5340        // And `currentColor` wins over an earlier value.
5341        let mut s = Style::default();
5342        s.set("backgroundColor", StyleValue::Str("red")).unwrap();
5343        s.set("backgroundColor", StyleValue::Str("currentColor"))
5344            .unwrap();
5345        s.apply_current_color(text);
5346        assert_eq!(s.view.background_color, text);
5347        // `color: currentColor` is the inherited color.
5348        s.set("color", StyleValue::Str("red")).unwrap();
5349        s.set("color", StyleValue::Str("currentColor")).unwrap();
5350        assert_eq!(s.text.color, None);
5351        // Where nothing fills it in, it is no color: rejected, never black.
5352        assert_eq!(
5353            s.set("tintColor", StyleValue::Str("currentColor")),
5354            Err(StyleError::InvalidValue)
5355        );
5356        assert_eq!(crate::css::box_shadows("0 2px 4px currentColor"), None);
5357    }
5358
5359    #[test]
5360    fn current_color_inside_values_is_the_text_color() {
5361        let text = Color(0x1234_56ff);
5362        let close = |a: Color, b: u32| {
5363            (0..4).all(|i| ((a.0 >> (i * 8)) & 0xff).abs_diff((b >> (i * 8)) & 0xff) <= 1)
5364        };
5365        let mut s = Style::default();
5366        let mut set = |key: &str, value: &str| s.set(key, StyleValue::Str(value));
5367        set("backgroundImage", "linear-gradient(currentColor, #ffffff)").unwrap();
5368        // CSS: a `drop-shadow()` without a color is the text color's too.
5369        set(
5370            "filter",
5371            "drop-shadow(0 1px 2px) drop-shadow(0 1px 2px CurrentColor) drop-shadow(0 1px 2px red)",
5372        )
5373        .unwrap();
5374        set(
5375            "boxShadow",
5376            "0 1px 2px color-mix(in srgb, currentColor 50%, transparent)",
5377        )
5378        .unwrap();
5379        set(
5380            "backgroundColor",
5381            "color-mix(in srgb, currentColor, #ffffff)",
5382        )
5383        .unwrap();
5384        // Checked with a stand-in color: a wrong value is rejected now.
5385        assert_eq!(
5386            set("maskImage", "linear-gradient(nope(currentColor), red)"),
5387            Err(StyleError::InvalidValue)
5388        );
5389        // `color` takes it alone only (the inherited color).
5390        assert_eq!(
5391            set("color", "color-mix(in srgb, currentColor, red)"),
5392            Err(StyleError::InvalidValue)
5393        );
5394        s.apply_current_color(text);
5395        let effects = s.view.effects.as_ref().unwrap();
5396        assert_eq!(effects.background_images[0].stops[0].color, text);
5397        let shadow_colors: Vec<Color> = effects
5398            .filters
5399            .iter()
5400            .map(|f| match f {
5401                Filter::DropShadow { color, .. } => *color,
5402                _ => Color::TRANSPARENT,
5403            })
5404            .collect();
5405        assert_eq!(shadow_colors, [text, text, Color(0xff00_00ff)]);
5406        assert!(close(effects.box_shadows[0].color, 0x1234_5680));
5407        assert!(
5408            close(s.view.background_color, 0x899a_abff),
5409            "{:x}",
5410            s.view.background_color.0
5411        );
5412        // A style with a `drop-shadow()` that names no color reads it.
5413        let mut patch = StylePatch::default();
5414        let mut styled = Style::default();
5415        patch
5416            .set(
5417                &mut styled,
5418                "filter",
5419                StyleValue::Str("drop-shadow(0 1px 2px)"),
5420            )
5421            .unwrap();
5422        assert!(patch.reads_current_color());
5423        // A later value replaces one that waits for the color.
5424        s.set("backgroundImage", StyleValue::Str("none")).unwrap();
5425        s.apply_current_color(text);
5426        assert!(
5427            s.view
5428                .effects
5429                .as_ref()
5430                .unwrap()
5431                .background_images
5432                .is_empty()
5433        );
5434    }
5435
5436    #[test]
5437    fn box_shadows_take_any_css_color() {
5438        // A color expression of the app's (`color-mix()`) is one word of the
5439        // layer.
5440        let mut s = Style::default();
5441        s.set(
5442            "boxShadow",
5443            StyleValue::Str("0 6px 18px color-mix(in srgb, #00ff00 50%, transparent)"),
5444        )
5445        .unwrap();
5446        let layer = s.view.effects.as_ref().unwrap().box_shadows[0];
5447        assert_eq!((layer.offset_y, layer.blur), (px(6.0), px(18.0)));
5448        assert_eq!(layer.color.0 >> 8, 0x00ff00);
5449        assert!(
5450            (0x7e..=0x81).contains(&(layer.color.0 & 0xff)),
5451            "{:x}",
5452            layer.color.0
5453        );
5454    }
5455
5456    #[test]
5457    fn text_shadows_are_css() {
5458        // The widest layer stands for all, as the classes' does.
5459        let mut s = Style::default();
5460        s.set(
5461            "textShadow",
5462            StyleValue::Str("0 1px 1px rgb(0 0 0 / 0.2), 2px 3px 6px red"),
5463        )
5464        .unwrap();
5465        assert_eq!(s.text.shadow_radius, Some(px(6.0)));
5466        assert_eq!(s.text.shadow_offset, Some(point(px(2.0), px(3.0))));
5467        assert_eq!(s.text.shadow_color, Color::parse("red"));
5468        // A layer without a color is the text color, filled in once known.
5469        s.set("textShadow", StyleValue::Str("0 1px 2px")).unwrap();
5470        s.apply_current_color(Color(0x1234_56ff));
5471        assert_eq!(s.text.shadow_color, Some(Color(0x1234_56ff)));
5472        assert_eq!(
5473            s.set("textShadow", StyleValue::Str("inset 0 1px red")),
5474            Err(StyleError::InvalidValue)
5475        );
5476        s.set("textShadow", StyleValue::Str("none")).unwrap();
5477        assert_eq!(s.text.shadow_radius, None);
5478    }
5479
5480    #[test]
5481    fn text_styles_parse() {
5482        let mut s = Style::default();
5483        s.set("fontFamily", StyleValue::Str("Inter")).unwrap();
5484        s.set("fontStyle", StyleValue::Str("italic")).unwrap();
5485        s.set(
5486            "textDecorationLine",
5487            StyleValue::Str("underline line-through"),
5488        )
5489        .unwrap();
5490        s.set("textTransform", StyleValue::Str("capitalize"))
5491            .unwrap();
5492        assert_eq!(s.text.font_family, Some(FontFamily::new("Inter")));
5493        assert_eq!(&*s.text.font_family.unwrap().name(), "Inter");
5494        assert_eq!(s.text.italic, Some(true));
5495        assert_eq!(
5496            s.text.decoration,
5497            Some(TextDecoration {
5498                underline: true,
5499                line_through: true
5500            })
5501        );
5502        assert_eq!(
5503            TextTransform::Capitalize.apply("hello wörld-x  ünd"),
5504            "Hello Wörld-x  Ünd"
5505        );
5506        assert_eq!(
5507            s.set("fontStyle", StyleValue::Str("oblique")),
5508            Err(StyleError::InvalidValue)
5509        );
5510    }
5511
5512    #[test]
5513    fn mask_image_parses() {
5514        let mut s = Style::default();
5515        assert!(s.view.effects.is_none());
5516        s.set(
5517            "maskImage",
5518            StyleValue::Str("linear-gradient(black 70%, transparent)"),
5519        )
5520        .unwrap();
5521        let masks = &s.view.effects.as_ref().unwrap().mask_images;
5522        assert_eq!(masks.len(), 1);
5523        // `none`, and the null of a style that was taken off, both clear it.
5524        s.set("maskImage", StyleValue::Str("none")).unwrap();
5525        assert!(
5526            s.view
5527                .effects
5528                .as_ref()
5529                .is_none_or(|e| e.mask_images.is_empty())
5530        );
5531        s.set(
5532            "maskImage",
5533            StyleValue::Str("linear-gradient(black, transparent)"),
5534        )
5535        .unwrap();
5536        s.set("maskImage", StyleValue::Null).unwrap();
5537        assert!(
5538            s.view
5539                .effects
5540                .as_ref()
5541                .is_none_or(|e| e.mask_images.is_empty())
5542        );
5543        assert_eq!(
5544            s.set("maskImage", StyleValue::Str("url(a.png)")),
5545            Err(StyleError::InvalidValue)
5546        );
5547    }
5548
5549    #[test]
5550    fn clip_path_parses_css_inset_shapes() {
5551        use crate::geometry::{Corners, Edges, px};
5552        let clip = |v: &str| {
5553            let mut s = Style::default();
5554            s.set("clipPath", StyleValue::Str(v))
5555                .map(|()| s.view.clip_path().copied())
5556        };
5557        let insets = |c: ClipInset| (c.offsets, c.fractions.map(|f| f.0), c.radii);
5558        // One to four edges as `margin` takes them, lengths and percentages.
5559        assert_eq!(
5560            insets(clip("inset(10px)").unwrap().unwrap()),
5561            (Edges::all(px(10.0)), Edges::all(0.0), Corners::all(px(0.0)))
5562        );
5563        assert_eq!(
5564            insets(clip("inset(1px 2px 3px 4px round 5px)").unwrap().unwrap()),
5565            (
5566                Edges::from([px(1.0), px(2.0), px(3.0), px(4.0)]),
5567                Edges::all(0.0),
5568                Corners::all(px(5.0))
5569            )
5570        );
5571        assert_eq!(
5572            insets(clip("inset(0 0 100% 100% round 12px)").unwrap().unwrap()),
5573            (
5574                Edges::all(px(0.0)),
5575                Edges::from([0.0, 0.0, 1.0, 1.0]),
5576                Corners::all(px(12.0))
5577            )
5578        );
5579        assert_eq!(
5580            insets(clip("inset(10% 4px)").unwrap().unwrap()),
5581            (
5582                Edges::from([px(0.0), px(4.0), px(0.0), px(4.0)]),
5583                Edges::from([0.1, 0.0, 0.1, 0.0]),
5584                Corners::all(px(0.0))
5585            )
5586        );
5587        assert_eq!(
5588            insets(clip("inset(1px 2px 3px)").unwrap().unwrap()).0,
5589            Edges::from([px(1.0), px(2.0), px(3.0), px(2.0)])
5590        );
5591        // Radii spread from the top left as `border-radius` spreads them.
5592        let radii = |v: &str| clip(v).unwrap().unwrap().radii.to_array();
5593        assert_eq!(
5594            radii("inset(0 round 1px 2px)"),
5595            [1.0, 2.0, 1.0, 2.0].map(px)
5596        );
5597        assert_eq!(
5598            radii("inset(0 round 1px 2px 3px)"),
5599            [1.0, 2.0, 3.0, 2.0].map(px)
5600        );
5601        assert_eq!(
5602            radii("inset(0 round 1px 2px 3px 4px)"),
5603            [1.0, 2.0, 3.0, 4.0].map(px)
5604        );
5605        // Negative edges reach outside the box.
5606        assert_eq!(clip("inset(-8px)").unwrap().unwrap().offsets.top, px(-8.0));
5607        // `none` and null clear it.
5608        assert_eq!(clip("none"), Ok(None));
5609        let mut s = Style::default();
5610        s.set("clipPath", StyleValue::Str("inset(4px)")).unwrap();
5611        s.set("clipPath", StyleValue::Null).unwrap();
5612        assert!(s.view.clip_path().is_none());
5613        assert!(s.view.effects.is_none());
5614        // Other shapes and forms NSH does not draw are rejected.
5615        for bad in [
5616            "inset()",
5617            "inset(1px 2px 3px 4px 5px)",
5618            "inset(1px round)",
5619            "inset(round 4px)",
5620            "inset(1px round 10%)",
5621            "inset(1px round -2px)",
5622            "inset(1px round 2px / 4px)",
5623            "inset(1px",
5624            "inset(red)",
5625            "circle(10px)",
5626            "polygon(0 0, 10px 0, 0 10px)",
5627            "url(#clip)",
5628        ] {
5629            assert_eq!(clip(bad), Err(StyleError::InvalidValue), "{bad}");
5630        }
5631    }
5632
5633    #[test]
5634    fn clip_path_and_mask_transition_as_their_own_properties() {
5635        let props = |v: &str| {
5636            let mut s = Style::default();
5637            s.set("transitionProperty", StyleValue::Str(v)).unwrap();
5638            s.view.transition.unwrap().properties
5639        };
5640        assert_eq!(props("clip-path").0, TransitionProps::CLIP_PATH);
5641        assert_eq!(props("clipPath").0, TransitionProps::CLIP_PATH);
5642        assert!(props("all").has(TransitionProps::CLIP_PATH));
5643        assert!(!props("border-radius").has(TransitionProps::CLIP_PATH));
5644        assert_eq!(props("mask-image").0, TransitionProps::MASK);
5645        assert_eq!(props("maskImage").0, TransitionProps::MASK);
5646        assert!(props("all").has(TransitionProps::MASK));
5647        assert!(!props("clip-path").has(TransitionProps::MASK));
5648    }
5649
5650    #[test]
5651    fn glass_tint_color_parses_and_clears() {
5652        let mut s = Style::default();
5653        assert_eq!(s.view.glass_tint_color, None);
5654        s.set("glassTintColor", StyleValue::Str("#ff0000")).unwrap();
5655        assert_eq!(s.view.glass_tint_color, Some(Color(0xff00_00ff)));
5656        s.set(
5657            "glassTintColor",
5658            StyleValue::Str("color-mix(in srgb, #00ff00 50%, transparent)"),
5659        )
5660        .unwrap();
5661        assert!(s.view.glass_tint_color.is_some());
5662        s.set("glassTintColor", StyleValue::Null).unwrap();
5663        assert_eq!(s.view.glass_tint_color, None);
5664        assert_eq!(
5665            s.set("glassTintColor", StyleValue::Number(1.0)),
5666            Err(StyleError::InvalidValue)
5667        );
5668    }
5669
5670    #[test]
5671    fn glass_effect_parses() {
5672        let mut s = Style::default();
5673        assert_eq!(s.view.glass_effect, GlassEffect::None);
5674        s.set("glassEffect", StyleValue::Str("regular")).unwrap();
5675        assert_eq!(s.view.glass_effect, GlassEffect::Regular);
5676        s.set("glassEffect", StyleValue::Str("clear")).unwrap();
5677        assert_eq!(s.view.glass_effect, GlassEffect::Clear);
5678        // `none`, and the null of a style that was taken off, both clear it.
5679        s.set("glassEffect", StyleValue::Str("none")).unwrap();
5680        assert_eq!(s.view.glass_effect, GlassEffect::None);
5681        s.set("glassEffect", StyleValue::Str("clear")).unwrap();
5682        s.set("glassEffect", StyleValue::Null).unwrap();
5683        assert_eq!(s.view.glass_effect, GlassEffect::None);
5684        assert_eq!(
5685            s.set("glassEffect", StyleValue::Str("frosted")),
5686            Err(StyleError::InvalidValue)
5687        );
5688        assert_eq!(
5689            s.set("glassEffect", StyleValue::Number(1.0)),
5690            Err(StyleError::InvalidValue)
5691        );
5692    }
5693
5694    #[test]
5695    fn rejects_bad_values() {
5696        let mut s = Style::default();
5697        assert_eq!(
5698            s.set("width", StyleValue::Str("wide")),
5699            Err(StyleError::InvalidValue)
5700        );
5701        assert_eq!(
5702            s.set("nope", StyleValue::Number(1.0)),
5703            Err(StyleError::UnknownProperty)
5704        );
5705        s.set("width", StyleValue::Str("50%")).unwrap();
5706        assert_eq!(s.layout.size.width, Dimension::percent(0.5));
5707    }
5708}