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