Skip to main content

nsh_core/
style.rs

1use std::sync::Arc;
2
3use taffy::{
4    AlignContent, AlignItems, Dimension, Display, FlexDirection, FlexWrap, LengthPercentage,
5    LengthPercentageAuto, Position,
6};
7
8use crate::{
9    css,
10    effects::{
11        BackdropMaterial, BlendMode, BoxShadow, Cursor, Effects, Filter, GlassEffect, Gradient,
12        KeyframeAnimation, Keyframes, Outline, Transition, TransitionProps,
13    },
14    element::PropEnum,
15    geometry::{
16        AbsoluteLength, Corners, DefiniteLength, Edges, Percentage, Point, Points, REM_SIZE, Size,
17        percentage, point, px,
18    },
19    grid,
20    transform::{Transform, TransformKind},
21};
22
23/// An sRGB color packed as `0xRRGGBBAA`.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
25pub struct Color(pub u32);
26
27impl Color {
28    /// Fully transparent.
29    pub const TRANSPARENT: Color = Color(0);
30    /// Opaque black.
31    pub const BLACK: Color = Color(0x0000_00ff);
32
33    /// Creates a color from 8-bit components.
34    #[inline]
35    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
36        Color((r as u32) << 24 | (g as u32) << 16 | (b as u32) << 8 | a as u32)
37    }
38
39    /// Returns `(r, g, b, a)` in `0.0..=1.0`.
40    #[inline]
41    pub fn to_f64(self) -> (f64, f64, f64, f64) {
42        let c = self.0;
43        (
44            (c >> 24) as f64 / 255.0,
45            ((c >> 16) & 0xff) as f64 / 255.0,
46            ((c >> 8) & 0xff) as f64 / 255.0,
47            (c & 0xff) as f64 / 255.0,
48        )
49    }
50
51    /// Returns true if the alpha component is zero.
52    #[inline]
53    pub const fn is_transparent(self) -> bool {
54        self.0 & 0xff == 0
55    }
56
57    /// Parses a CSS color: hex, `rgb()` / `rgba()`, `hsl()` / `hsla()`,
58    /// `oklch()`, `oklab()` or a CSS named color.
59    pub fn parse(s: &str) -> Option<Color> {
60        crate::css::color(s)
61    }
62}
63
64/// Horizontal alignment of a text block.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66pub enum TextAlign {
67    /// Natural alignment for the writing direction.
68    #[default]
69    Auto,
70    /// Left aligned.
71    Left,
72    /// Centered.
73    Center,
74    /// Right aligned.
75    Right,
76    /// Justified.
77    Justify,
78}
79
80/// `verticalAlign`: where an element inside a `<Text>` (an inline
81/// attachment) sits in its line, as CSS's `vertical-align` places a
82/// replaced inline box. The font it is measured against is the text's
83/// around the attachment; the line grows to hold the attachment wherever
84/// it reaches past that font (`TextAttachment::extent`).
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
86pub enum VerticalAlign {
87    /// `baseline`: its bottom on the baseline.
88    #[default]
89    Baseline,
90    /// `text-top`: its top at the top of the font (its ascent).
91    TextTop,
92    /// `text-bottom`: its bottom at the bottom of the font (its descent).
93    TextBottom,
94    /// `middle`: its middle half the font's x height above the baseline.
95    Middle,
96}
97
98impl VerticalAlign {
99    /// The value named by CSS keyword `name`.
100    pub fn parse(name: &str) -> Option<Self> {
101        Some(match name {
102            "baseline" => Self::Baseline,
103            "text-top" => Self::TextTop,
104            "text-bottom" => Self::TextBottom,
105            "middle" => Self::Middle,
106            _ => return None,
107        })
108    }
109}
110
111/// A font family name, interned: copying and comparing one is free, so
112/// resolved text styles stay `Copy` and cheap to hash.
113#[derive(Clone, Copy, PartialEq, Eq, Hash)]
114pub struct FontFamily(u32);
115
116static FAMILIES: std::sync::Mutex<Vec<std::sync::Arc<str>>> = std::sync::Mutex::new(Vec::new());
117
118impl FontFamily {
119    /// Interns `name`. Apps use a handful of families, so the table is a
120    /// small vector scanned linearly.
121    pub fn new(name: &str) -> FontFamily {
122        let mut families = FAMILIES.lock().unwrap_or_else(|e| e.into_inner());
123        if let Some(i) = families.iter().position(|f| &**f == name) {
124            return FontFamily(i as u32);
125        }
126        families.push(name.into());
127        FontFamily(families.len() as u32 - 1)
128    }
129
130    /// The family name.
131    pub fn name(self) -> std::sync::Arc<str> {
132        FAMILIES.lock().unwrap_or_else(|e| e.into_inner())[self.0 as usize].clone()
133    }
134}
135
136impl std::fmt::Debug for FontFamily {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        write!(f, "FontFamily({:?})", self.name())
139    }
140}
141
142/// Lines drawn through or under text (`textDecorationLine`).
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
144pub struct TextDecoration {
145    /// Underline.
146    pub underline: bool,
147    /// Strikethrough.
148    pub line_through: bool,
149}
150
151impl TextDecoration {
152    /// True if no line is drawn.
153    #[inline]
154    pub const fn is_none(self) -> bool {
155        !self.underline && !self.line_through
156    }
157}
158
159/// How decoration lines are drawn (`textDecorationStyle`).
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
161pub enum DecorationStyle {
162    /// One solid line (default).
163    #[default]
164    Solid,
165    /// Two lines.
166    Double,
167    /// Dots.
168    Dotted,
169    /// Dashes.
170    Dashed,
171    /// A wavy line.
172    Wavy,
173}
174
175/// Case changes applied to text (`textTransform`).
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
177pub enum TextTransform {
178    /// As written.
179    #[default]
180    None,
181    /// UPPER CASE.
182    Uppercase,
183    /// lower case.
184    Lowercase,
185    /// First Letter Of Each Word.
186    Capitalize,
187}
188
189impl TextTransform {
190    /// Applies the transform to `s`.
191    pub fn apply<'a>(self, s: &'a str) -> std::borrow::Cow<'a, str> {
192        match self {
193            TextTransform::None => s.into(),
194            TextTransform::Uppercase => s.to_uppercase().into(),
195            TextTransform::Lowercase => s.to_lowercase().into(),
196            TextTransform::Capitalize => {
197                let mut out = String::with_capacity(s.len());
198                let mut start = true;
199                for c in s.chars() {
200                    if start && c.is_alphanumeric() {
201                        out.extend(c.to_uppercase());
202                        start = false;
203                    } else {
204                        out.push(c);
205                        start |= c.is_whitespace();
206                    }
207                }
208                out.into()
209            }
210        }
211    }
212}
213
214/// Where text that does not fit `numberOfLines` is cut (`ellipsizeMode`).
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
216pub enum EllipsizeMode {
217    /// "Lorem ips…" (default).
218    #[default]
219    Tail,
220    /// "…sum dolor".
221    Head,
222    /// "Lorem…dolor".
223    Middle,
224    /// Cut without an ellipsis.
225    Clip,
226}
227
228/// The corner radii of a view, clockwise from the top left: a
229/// [`Corners<Points>`] with the curve they are drawn with.
230#[derive(Debug, Clone, Copy, PartialEq, Default)]
231pub struct CornerRadii {
232    /// Top left.
233    pub top_left: Points,
234    /// Top right.
235    pub top_right: Points,
236    /// Bottom right.
237    pub bottom_right: Points,
238    /// Bottom left.
239    pub bottom_left: Points,
240    /// `borderCurve: "continuous"`: corners whose curvature grows from the
241    /// edges (iOS app icons) instead of circular arcs; see [`crate::shape`].
242    pub continuous: bool,
243}
244
245impl CornerRadii {
246    /// The same circular radius on every corner.
247    pub const fn all(r: Points) -> Self {
248        Self {
249            top_left: r,
250            top_right: r,
251            bottom_right: r,
252            bottom_left: r,
253            continuous: false,
254        }
255    }
256
257    /// Circular corners with these radii.
258    pub const fn circular(corners: Corners<Points>) -> Self {
259        Self {
260            top_left: corners.top_left,
261            top_right: corners.top_right,
262            bottom_right: corners.bottom_right,
263            bottom_left: corners.bottom_left,
264            continuous: false,
265        }
266    }
267
268    /// The radii, without the curve.
269    #[inline]
270    pub const fn corners(self) -> Corners<Points> {
271        Corners {
272            top_left: self.top_left,
273            top_right: self.top_right,
274            bottom_right: self.bottom_right,
275            bottom_left: self.bottom_left,
276        }
277    }
278
279    /// `[top_left, top_right, bottom_right, bottom_left]`.
280    #[inline]
281    pub const fn to_array(self) -> [Points; 4] {
282        [
283            self.top_left,
284            self.top_right,
285            self.bottom_right,
286            self.bottom_left,
287        ]
288    }
289
290    /// True if no corner is rounded.
291    #[inline]
292    pub fn is_zero(&self) -> bool {
293        self.to_array().iter().all(|&r| r <= Points::ZERO)
294    }
295
296    /// The radius shared by every rounded corner, if they all share one.
297    /// Platforms render such shapes with a single radius plus a mask of
298    /// the rounded corners (no paths).
299    pub fn shared(&self) -> Option<Points> {
300        let mut shared = Points::ZERO;
301        for r in self.to_array() {
302            if r > Points::ZERO {
303                if shared > Points::ZERO && r != shared {
304                    return None;
305                }
306                shared = r;
307            }
308        }
309        Some(shared)
310    }
311
312    /// Scales the radii down so adjacent corners do not overlap on a box
313    /// of `size` (CSS rule).
314    pub fn fit(self, size: Size<Points>) -> Self {
315        let ratio = |side: Points, a: Points, b: Points| {
316            if a + b > side { side / (a + b) } else { 1.0 }
317        };
318        let (width, height) = (size.width, size.height);
319        let f = ratio(width, self.top_left, self.top_right)
320            .min(ratio(width, self.bottom_left, self.bottom_right))
321            .min(ratio(height, self.top_left, self.bottom_left))
322            .min(ratio(height, self.top_right, self.bottom_right))
323            .max(0.0);
324        if f >= 1.0 {
325            return self;
326        }
327        Self {
328            top_left: self.top_left * f,
329            top_right: self.top_right * f,
330            bottom_right: self.bottom_right * f,
331            bottom_left: self.bottom_left * f,
332            ..self
333        }
334    }
335
336    /// The radii of a curve `d` inside this one (e.g. the inner edge of a
337    /// border).
338    pub fn inset(self, d: Points) -> Self {
339        Self {
340            top_left: (self.top_left - d).max(Points::ZERO),
341            top_right: (self.top_right - d).max(Points::ZERO),
342            bottom_right: (self.bottom_right - d).max(Points::ZERO),
343            bottom_left: (self.bottom_left - d).max(Points::ZERO),
344            ..self
345        }
346    }
347}
348
349impl From<CornerRadii> for Corners<Points> {
350    fn from(radii: CornerRadii) -> Self {
351        radii.corners()
352    }
353}
354
355/// A drop shadow (React Native's `shadow*` properties).
356#[derive(Debug, Clone, Copy, PartialEq)]
357pub struct Shadow {
358    /// Shadow color; its alpha is multiplied by `opacity`.
359    pub color: Color,
360    /// Horizontal offset.
361    pub offset_x: Points,
362    /// Vertical offset.
363    pub offset_y: Points,
364    /// Opacity in `0.0..=1.0`; 0 (the default) means no shadow.
365    pub opacity: f32,
366    /// Blur radius.
367    pub radius: Points,
368}
369
370impl Shadow {
371    /// React Native's defaults: black, offset `(0, -3)`, radius 3, opacity 0.
372    pub const DEFAULT: Shadow = Shadow {
373        color: Color::BLACK,
374        offset_x: Points(0.0),
375        offset_y: Points(-3.0),
376        opacity: 0.0,
377        radius: Points(3.0),
378    };
379
380    /// True if the shadow draws anything.
381    #[inline]
382    pub fn is_visible(&self) -> bool {
383        self.opacity > 0.0 && !self.color.is_transparent()
384    }
385}
386
387impl Default for Shadow {
388    fn default() -> Self {
389        Self::DEFAULT
390    }
391}
392
393/// How borders are drawn (`borderStyle`).
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
395pub enum BorderStyle {
396    /// A solid line (default).
397    #[default]
398    Solid,
399    /// Dashes.
400    Dashed,
401    /// Dots.
402    Dotted,
403}
404
405/// Border widths and colors, per side.
406#[derive(Debug, Clone, Copy, PartialEq)]
407pub struct Borders {
408    /// Widths.
409    pub widths: Edges<Points>,
410    /// Colors: top, right, bottom, left.
411    pub colors: [Color; 4],
412    /// Line style.
413    pub style: BorderStyle,
414}
415
416impl Borders {
417    /// No border.
418    pub const NONE: Borders = Borders {
419        widths: Edges {
420            top: Points::ZERO,
421            right: Points::ZERO,
422            bottom: Points::ZERO,
423            left: Points::ZERO,
424        },
425        colors: [Color::BLACK; 4],
426        style: BorderStyle::Solid,
427    };
428
429    /// True if some side draws something.
430    pub fn is_visible(&self) -> bool {
431        let widths = self.widths.to_array();
432        (0..4).any(|i| widths[i] > Points::ZERO && !self.colors[i].is_transparent())
433    }
434
435    /// `(width, color)` when every side is the same.
436    pub fn uniform(&self) -> Option<(Points, Color)> {
437        let widths = self.widths.to_array();
438        let [w, ..] = widths;
439        let [c, ..] = self.colors;
440        (widths.iter().all(|&x| x == w) && self.colors.iter().all(|&x| x == c)).then_some((w, c))
441    }
442
443    /// The width of side `side`: 0 top, 1 right, 2 bottom, 3 left (the
444    /// order of `colors`).
445    pub fn width(&self, side: usize) -> Points {
446        match side {
447            0 => self.widths.top,
448            1 => self.widths.right,
449            2 => self.widths.bottom,
450            _ => self.widths.left,
451        }
452    }
453
454    fn width_mut(&mut self, side: usize) -> &mut Points {
455        match side {
456            0 => &mut self.widths.top,
457            1 => &mut self.widths.right,
458            2 => &mut self.widths.bottom,
459            _ => &mut self.widths.left,
460        }
461    }
462}
463
464impl Default for Borders {
465    fn default() -> Self {
466        Self::NONE
467    }
468}
469
470/// Visual (non-layout) properties of a native view.
471#[derive(Debug, Clone, PartialEq)]
472pub struct ViewStyle {
473    /// Background fill.
474    pub background_color: Color,
475    /// `borderRadius`: the radius of corners without their own.
476    pub border_radius: Points,
477    /// `borderTopLeftRadius` etc.; they override `border_radius`.
478    pub corner_radius: Corners<Option<Points>>,
479    /// `borderCurve: "continuous"`.
480    pub continuous_corners: bool,
481    /// Borders (their widths also affect layout).
482    pub borders: Borders,
483    /// Opacity in `0.0..=1.0`.
484    pub opacity: f32,
485    /// Clip children to the (rounded) bounds.
486    pub overflow_hidden: bool,
487    /// Drop shadow.
488    pub shadow: Shadow,
489    /// Static transform, around the view's center.
490    pub transform: Transform,
491    /// `tintColor`: recolors an image's opaque pixels.
492    pub tint_color: Option<Color>,
493    /// Android's material shadow: the node's `android={{ elevation }}` prop,
494    /// not a style.
495    pub elevation: Points,
496    /// `transformOrigin`: the point transforms act around.
497    pub transform_origin: TransformOrigin,
498    /// `objectPosition`: where an image sits in its box (image views; the
499    /// platforms take it from [`crate::mount::ImageOptions::position`]).
500    pub object_position: ObjectPosition,
501    /// `backfaceVisibility: "hidden"`: invisible when turned away.
502    pub backface_hidden: bool,
503    /// Layered / inset shadows, gradients and filters.
504    pub effects: Option<Arc<Effects>>,
505    /// `mixBlendMode`.
506    pub blend_mode: BlendMode,
507    /// The iOS material from `ios={{ backdropMaterial }}`, projected at mount time.
508    pub backdrop_material: BackdropMaterial,
509    /// `glassEffect`.
510    pub glass_effect: GlassEffect,
511    /// `outline*`.
512    pub outline: Outline,
513    /// `visibility: "hidden"`: not drawn and not touchable, still laid out.
514    pub hidden: bool,
515    /// `cursor`.
516    pub cursor: Cursor,
517    /// `transition*`: style changes animate.
518    pub transition: Option<Transition>,
519    /// `animation*`: a keyframe animation runs.
520    pub animation: Option<KeyframeAnimation>,
521}
522
523/// `transformOrigin`: the point transforms rotate and scale around.
524#[derive(Debug, Clone, Copy, PartialEq)]
525pub struct TransformOrigin {
526    /// Horizontal position: from the left edge, or a fraction of the width.
527    pub x: DefiniteLength,
528    /// Vertical position: from the top edge, or a fraction of the height.
529    pub y: DefiniteLength,
530    /// Depth.
531    pub z: Points,
532}
533
534impl Default for TransformOrigin {
535    fn default() -> Self {
536        Self::CENTER
537    }
538}
539
540impl TransformOrigin {
541    /// The center (the default).
542    pub const CENTER: Self = Self {
543        x: DefiniteLength::Fraction(Percentage(0.5)),
544        y: DefiniteLength::Fraction(Percentage(0.5)),
545        z: Points::ZERO,
546    };
547
548    /// Offset of the origin from the center of a box of `size`, in the
549    /// plane, and its depth.
550    pub fn offset(&self, size: Size<Points>) -> (Point<Points>, Points) {
551        let at = |len: DefiniteLength, side: Points| {
552            len.to_points(AbsoluteLength::Points(side), REM_SIZE) - side / 2.0
553        };
554        (
555            point(at(self.x, size.width), at(self.y, size.height)),
556            self.z,
557        )
558    }
559
560    /// Parses CSS's syntax: one to three of keywords (`left`, `center`,
561    /// `right`, `top`, `bottom`), percentages and lengths (`10px` or a
562    /// bare number), the third being a depth.
563    pub fn parse(s: &str) -> Option<Self> {
564        let parts: Vec<&str> = s.split_whitespace().collect();
565        if parts.is_empty() || parts.len() > 3 {
566            return None;
567        }
568        let fraction = |f: f32| DefiniteLength::Fraction(percentage(f));
569        let len = |p: &str| -> Option<DefiniteLength> {
570            if let Some(pct) = p.strip_suffix('%') {
571                return pct.trim().parse::<f32>().ok().map(|v| fraction(v / 100.0));
572            }
573            p.strip_suffix("px")
574                .unwrap_or(p)
575                .parse::<f32>()
576                .ok()
577                .map(|v| px(v).into())
578        };
579        let mut x = None;
580        let mut y = None;
581        let mut free = Vec::new();
582        for &p in parts.iter().take(2) {
583            match p {
584                "left" => x = Some(fraction(0.0)),
585                "right" => x = Some(fraction(1.0)),
586                "top" => y = Some(fraction(0.0)),
587                "bottom" => y = Some(fraction(1.0)),
588                "center" => free.push(fraction(0.5)),
589                p => free.push(len(p)?),
590            }
591        }
592        // Unnamed values fill x, then y.
593        for v in free {
594            if x.is_none() {
595                x = Some(v);
596            } else if y.is_none() {
597                y = Some(v);
598            } else {
599                return None;
600            }
601        }
602        let z = match parts.get(2) {
603            Some(p) => px(p.strip_suffix("px").unwrap_or(p).parse::<f32>().ok()?),
604            None => Points::ZERO,
605        };
606        Some(Self {
607            x: x.unwrap_or(fraction(0.5)),
608            y: y.unwrap_or(fraction(0.5)),
609            z,
610        })
611    }
612}
613
614/// One axis of a CSS `<position>`: a distance from the start edge (left,
615/// top) or the end edge (right, bottom). Percentages are fractions of the
616/// free space: the box's size less the content's (negative when the
617/// content overflows), as CSS's `object-position` resolves them.
618#[derive(Debug, Clone, Copy, PartialEq)]
619#[non_exhaustive]
620pub struct PositionAxis {
621    /// Measured from the end edge (right, bottom) instead of the start.
622    pub from_end: bool,
623    /// The distance from that edge.
624    pub offset: DefiniteLength,
625}
626
627impl Default for PositionAxis {
628    /// The center.
629    fn default() -> Self {
630        Self::CENTER
631    }
632}
633
634impl PositionAxis {
635    /// The start edge (`left`, `top`, `0%`).
636    pub const START: Self = Self::start(DefiniteLength::Fraction(Percentage(0.0)));
637    /// The center (`center`, `50%`).
638    pub const CENTER: Self = Self::start(DefiniteLength::Fraction(Percentage(0.5)));
639    /// The end edge (`right`, `bottom`, `100%`).
640    pub const END: Self = Self::start(DefiniteLength::Fraction(Percentage(1.0)));
641
642    /// `offset` from the start edge.
643    pub const fn start(offset: DefiniteLength) -> Self {
644        Self {
645            from_end: false,
646            offset,
647        }
648    }
649
650    /// `offset` from the end edge.
651    pub const fn end(offset: DefiniteLength) -> Self {
652        Self {
653            from_end: true,
654            offset,
655        }
656    }
657
658    /// Where content starts along this axis, from the box's start edge,
659    /// given the `free` space (the box's size less the content's).
660    pub fn resolve(&self, free: Points) -> Points {
661        let d = self
662            .offset
663            .to_points(AbsoluteLength::Points(free), REM_SIZE);
664        if self.from_end { free - d } else { d }
665    }
666}
667
668/// `objectPosition`: where an image sits in its box once
669/// `resizeMode` / `object-fit` has sized it, as CSS's `object-position`
670/// places it (the center by default). The parts of a covering image
671/// outside the box are cropped.
672#[derive(Debug, Clone, Copy, PartialEq, Default)]
673#[non_exhaustive]
674pub struct ObjectPosition {
675    /// Horizontal.
676    pub x: PositionAxis,
677    /// Vertical.
678    pub y: PositionAxis,
679}
680
681impl ObjectPosition {
682    /// The center (the default).
683    pub const CENTER: Self = Self {
684        x: PositionAxis::CENTER,
685        y: PositionAxis::CENTER,
686    };
687
688    /// A position of two axes.
689    pub const fn new(x: PositionAxis, y: PositionAxis) -> Self {
690        Self { x, y }
691    }
692
693    /// Parses CSS's `<position>` as `object-position` takes it: one or two
694    /// keywords, percentages or lengths (`top`, `left bottom`, `25% 75%`,
695    /// `10px 0`), or edges with offsets (`right 10px bottom 20%`).
696    pub fn parse(s: &str) -> Option<Self> {
697        css::object_position(s)
698    }
699
700    /// The top left corner of content of `content` size placed in a box of
701    /// `size`.
702    pub fn place(&self, size: Size<Points>, content: Size<Points>) -> Point<Points> {
703        point(
704            self.x.resolve(size.width - content.width),
705            self.y.resolve(size.height - content.height),
706        )
707    }
708}
709
710impl std::fmt::Display for ObjectPosition {
711    /// CSS's four-value form (`left 50% top 10px`), which every position
712    /// can be written in.
713    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
714        let length = |l: DefiniteLength| match l {
715            DefiniteLength::Absolute(a) => format!("{}px", a.to_points(REM_SIZE).0),
716            DefiniteLength::Fraction(p) => format!("{}%", p.0 * 100.0),
717        };
718        write!(
719            f,
720            "{} {} {} {}",
721            if self.x.from_end { "right" } else { "left" },
722            length(self.x.offset),
723            if self.y.from_end { "bottom" } else { "top" },
724            length(self.y.offset),
725        )
726    }
727}
728
729/// `fontVariant`: OpenType features, as bits.
730#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
731pub struct FontVariant(pub u8);
732
733impl FontVariant {
734    /// `small-caps`.
735    pub const SMALL_CAPS: u8 = 1;
736    /// `oldstyle-nums`.
737    pub const OLDSTYLE_NUMS: u8 = 2;
738    /// `lining-nums`.
739    pub const LINING_NUMS: u8 = 4;
740    /// `tabular-nums`.
741    pub const TABULAR_NUMS: u8 = 8;
742    /// `proportional-nums`.
743    pub const PROPORTIONAL_NUMS: u8 = 16;
744
745    /// Parses space-separated variant names.
746    pub fn parse(s: &str) -> Option<Self> {
747        let mut bits = 0;
748        for word in s.split_whitespace() {
749            bits |= match word {
750                "small-caps" => Self::SMALL_CAPS,
751                "oldstyle-nums" => Self::OLDSTYLE_NUMS,
752                "lining-nums" => Self::LINING_NUMS,
753                "tabular-nums" => Self::TABULAR_NUMS,
754                "proportional-nums" => Self::PROPORTIONAL_NUMS,
755                "normal" => 0,
756                _ => return None,
757            };
758        }
759        Some(Self(bits))
760    }
761
762    /// Whether `bit` is set.
763    pub fn has(self, bit: u8) -> bool {
764        self.0 & bit != 0
765    }
766
767    /// The OpenType feature tags.
768    pub fn tags(self) -> impl Iterator<Item = &'static str> {
769        [
770            (Self::SMALL_CAPS, "smcp"),
771            (Self::OLDSTYLE_NUMS, "onum"),
772            (Self::LINING_NUMS, "lnum"),
773            (Self::TABULAR_NUMS, "tnum"),
774            (Self::PROPORTIONAL_NUMS, "pnum"),
775        ]
776        .into_iter()
777        .filter(move |&(bit, _)| self.has(bit))
778        .map(|(_, tag)| tag)
779    }
780}
781
782impl ViewStyle {
783    /// Drops the gradient backgrounds, so the background color shows: what
784    /// press feedback and animated background colors do (a gradient is
785    /// drawn over the color and would hide them).
786    pub(crate) fn clear_background_images(&mut self) {
787        if let Some(e) = self
788            .effects
789            .as_deref()
790            .filter(|e| !e.background_images.is_empty())
791        {
792            let mut effects = e.clone();
793            effects.background_images.clear();
794            self.effects = crate::effects::shared(effects);
795        }
796    }
797
798    /// The radius of each corner (before fitting them to a size with
799    /// [`CornerRadii::fit`]).
800    pub fn radii(&self) -> CornerRadii {
801        let radii = self
802            .corner_radius
803            .map(|r| r.unwrap_or(self.border_radius).max(Points::ZERO));
804        CornerRadii {
805            continuous: self.continuous_corners,
806            ..CornerRadii::circular(radii)
807        }
808    }
809}
810
811impl Default for ViewStyle {
812    fn default() -> Self {
813        Self {
814            background_color: Color::TRANSPARENT,
815            border_radius: Points::ZERO,
816            corner_radius: Corners {
817                top_left: None,
818                top_right: None,
819                bottom_right: None,
820                bottom_left: None,
821            },
822            continuous_corners: false,
823            borders: Borders::NONE,
824            opacity: 1.0,
825            overflow_hidden: false,
826            shadow: Shadow::DEFAULT,
827            transform: Transform::IDENTITY,
828            tint_color: None,
829            elevation: Points::ZERO,
830            transform_origin: TransformOrigin::CENTER,
831            object_position: ObjectPosition::CENTER,
832            backface_hidden: false,
833            effects: None,
834            blend_mode: BlendMode::Normal,
835            backdrop_material: BackdropMaterial::UltraThin,
836            glass_effect: GlassEffect::None,
837            outline: Outline::NONE,
838            hidden: false,
839            cursor: Cursor::Auto,
840            transition: None,
841            animation: None,
842        }
843    }
844}
845
846/// A shadow behind text (`textShadow*`).
847#[derive(Debug, Clone, Copy, PartialEq)]
848pub struct TextShadow {
849    /// Color.
850    pub color: Color,
851    /// Horizontal offset.
852    pub offset_x: Points,
853    /// Vertical offset.
854    pub offset_y: Points,
855    /// Blur radius.
856    pub radius: Points,
857}
858
859/// Text properties as written on a node; unset values are inherited from
860/// the enclosing text.
861#[derive(Debug, Clone, Copy, PartialEq, Default)]
862pub struct TextStyle {
863    /// Foreground color.
864    pub color: Option<Color>,
865    /// Font size.
866    pub font_size: Option<Points>,
867    /// Font weight, `100..=900`.
868    pub font_weight: Option<u16>,
869    /// Line height.
870    pub line_height: Option<Points>,
871    /// Block alignment (only meaningful on a text block).
872    pub text_align: Option<TextAlign>,
873    /// Physical class alignment, preserved across direction changes in descendants.
874    pub text_align_physical: bool,
875    /// Font family; `None` inherits (the system font at the root).
876    pub font_family: Option<FontFamily>,
877    /// Italic (`fontStyle`).
878    pub italic: Option<bool>,
879    /// Extra space between characters.
880    pub letter_spacing: Option<Points>,
881    /// Extra space between characters in ems of this node's font size
882    /// (`"0.05em"`); overrides `letter_spacing` when set after it.
883    pub letter_spacing_em: Option<f32>,
884    /// A line-height length relative to this node's font size (`em` or
885    /// a percentage), resolved before inheritance.
886    pub line_height_em: Option<f32>,
887    /// Line height as a multiple of the font size (`"1.5"`),
888    /// inherited as a multiple.
889    pub line_height_multiple: Option<f32>,
890    /// Underline / strikethrough.
891    pub decoration: Option<TextDecoration>,
892    /// `textDecorationStyle`.
893    pub decoration_style: Option<DecorationStyle>,
894    /// `textDecorationThickness`.
895    pub decoration_thickness: Option<Points>,
896    /// `textUnderlineOffset`: below the baseline.
897    pub underline_offset: Option<Points>,
898    /// Color of the decoration lines; the text color by default.
899    pub decoration_color: Option<Color>,
900    /// Case transform.
901    pub transform: Option<TextTransform>,
902    /// `textShadowColor`.
903    pub shadow_color: Option<Color>,
904    /// `textShadowOffset`.
905    pub shadow_offset: Option<Point<Points>>,
906    /// `textShadowRadius`.
907    pub shadow_radius: Option<Points>,
908    /// `fontVariant`.
909    pub font_variant: Option<FontVariant>,
910    /// `writingDirection`: right to left (`Some(true)`), left to right, or
911    /// the layout's direction (`None`, `auto`).
912    pub writing_direction: Option<bool>,
913    /// `textAlignVertical`: where text shorter than its box sits, 0% top
914    /// (`auto`, `top`), 50% `center`, 100% `bottom`.
915    pub align_vertical: Option<Percentage>,
916    /// `placeholderColor`: an input's placeholder (not inherited).
917    pub placeholder_color: Option<Color>,
918    /// `selectionColor`: an input's caret and selection, a selectable
919    /// text's selection highlight (not inherited).
920    pub selection_color: Option<Color>,
921}
922
923impl TextStyle {
924    /// The text shadow these properties describe, if any. Like NSShadow, an
925    /// offset or radius without a color uses black at a third of opacity.
926    pub fn shadow(&self) -> Option<TextShadow> {
927        if self.shadow_color.is_none()
928            && self.shadow_offset.is_none()
929            && self.shadow_radius.is_none()
930        {
931            return None;
932        }
933        let color = self.shadow_color.unwrap_or(Color(0x0000_0055));
934        if color.is_transparent() {
935            return None;
936        }
937        let offset = self.shadow_offset.unwrap_or_default();
938        Some(TextShadow {
939            color,
940            offset_x: offset.x,
941            offset_y: offset.y,
942            radius: self.shadow_radius.unwrap_or_default().max(Points::ZERO),
943        })
944    }
945}
946
947/// What `fill` or `stroke` paints with (CSS's and SVG's `<paint>`).
948#[derive(Debug, Clone, Copy, PartialEq)]
949pub enum SvgPaint {
950    /// `none`: nothing.
951    None,
952    /// `currentColor`: the element's text color (`color`, inherited).
953    CurrentColor,
954    /// A color.
955    Color(Color),
956}
957
958/// SVG's paint properties, as CSS has them on any element and inherits
959/// them (`fill`, `stroke`, `strokeWidth`, `strokeDasharray`; `fill-*` /
960/// `stroke-*`): what the shapes a Rust component draws paint with (the
961/// marks of `nsh/base/plot`), read through a drawing's
962/// [`crate::canvas::ViewPaint`]s. Unset values inherit; at the root they
963/// are CSS's initial values, which the drawing names.
964#[derive(Debug, Clone, PartialEq, Default)]
965#[non_exhaustive]
966pub struct PaintStyle {
967    /// `fill`.
968    pub fill: Option<SvgPaint>,
969    /// `stroke`.
970    pub stroke: Option<SvgPaint>,
971    /// `strokeWidth`.
972    pub stroke_width: Option<Points>,
973    /// `strokeDasharray`: the dashes and gaps, empty for `none`.
974    pub stroke_dasharray: Option<Arc<[Points]>>,
975}
976
977impl PaintStyle {
978    /// These properties where set, `parent`'s (the inherited ones) where
979    /// not.
980    pub fn inherit(&self, parent: &PaintStyle) -> PaintStyle {
981        PaintStyle {
982            fill: self.fill.or(parent.fill),
983            stroke: self.stroke.or(parent.stroke),
984            stroke_width: self.stroke_width.or(parent.stroke_width),
985            stroke_dasharray: self
986                .stroke_dasharray
987                .clone()
988                .or_else(|| parent.stroke_dasharray.clone()),
989        }
990    }
991}
992
993/// A complete node style, split by consumer.
994#[derive(Debug, Clone)]
995pub struct Style {
996    /// Layout properties, consumed by taffy.
997    pub layout: taffy::Style,
998    /// Visual properties of the native view.
999    pub view: ViewStyle,
1000    /// Text properties.
1001    pub text: TextStyle,
1002    /// SVG's paint properties (inherited, as text properties are).
1003    pub paint: PaintStyle,
1004    /// Visual properties driven by native animation nodes; they override
1005    /// the static values while bound.
1006    pub animated: Vec<(crate::animation::AnimationProp, crate::animation::NodeId)>,
1007    /// `zIndex`: stacking order among siblings (higher on top).
1008    pub z_index: i32,
1009    /// `verticalAlign`: where the element sits in its line when it is
1010    /// inside a `<Text>`.
1011    pub vertical_align: VerticalAlign,
1012    /// `direction`: right to left (`Some(true)`), left to right, or
1013    /// inherited (`None`).
1014    pub direction: Option<bool>,
1015    /// Start / end properties, placed by the resolved direction.
1016    pub logical: Logical,
1017    /// Values that only show together with another property.
1018    pub(crate) pending: Pending,
1019    /// CSS's `perspective` (`perspective-*`, `Styled::perspective`): the
1020    /// depth the view gives its children's 3D transforms, seen from its
1021    /// center; the core composes it into their transforms.
1022    pub perspective: Option<Points>,
1023}
1024
1025/// Values of properties that take effect only together with another one,
1026/// kept so that the result does not depend on the order they are set in:
1027/// `outlineWidth` under `outlineStyle: "none"` and the border widths under
1028/// `borderStyle: "none"` (no outline, no border, as in CSS),
1029/// `animationDuration` and the other `animation*` keys before
1030/// `animationName`.
1031#[derive(Clone, Copy, Default)]
1032pub(crate) struct Pending {
1033    /// `outlineWidth` as set.
1034    outline_width: Points,
1035    /// `outlineStyle: "none"` / `"hidden"`.
1036    outline_hidden: bool,
1037    /// The border widths as set: top, right, bottom, left.
1038    border_widths: [Points; 4],
1039    /// `borderStartWidth`, `borderEndWidth` as set.
1040    border_logical: [Option<Points>; 2],
1041    /// `borderStyle: "none"` / `"hidden"`: every used width is 0.
1042    border_hidden: bool,
1043    /// `position: "fixed"`: laid out and mounted in its root view's box.
1044    pub(crate) fixed_position: bool,
1045    /// `position: "sticky"`: laid out as `relative`, its insets where it
1046    /// sticks in the viewport of the scroll view around it.
1047    pub(crate) sticky_position: bool,
1048    /// `animationDuration`.
1049    animation_duration: Option<f32>,
1050    /// `animationDelay`.
1051    animation_delay: Option<f32>,
1052    /// `animationTimingFunction`.
1053    animation_easing: Option<[f32; 4]>,
1054    /// `animationIterationCount` (`None` inside: forever).
1055    animation_iterations: Option<Option<u32>>,
1056    /// The `env()` terms of the padding and margin, added by the core to
1057    /// the lengths their declarations set.
1058    pub(crate) env: EnvEdges,
1059}
1060
1061/// Bookkeeping, not what the style shows: styles that look the same print
1062/// the same (tests compare typed styles and classes so).
1063impl std::fmt::Debug for Pending {
1064    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1065        f.write_str("Pending")
1066    }
1067}
1068
1069impl Pending {
1070    /// `animation` with the `animation*` values set.
1071    fn animation(&self, mut animation: KeyframeAnimation) -> KeyframeAnimation {
1072        if let Some(ms) = self.animation_duration {
1073            animation.duration = ms;
1074        }
1075        if let Some(ms) = self.animation_delay {
1076            animation.delay = ms;
1077        }
1078        if let Some(easing) = self.animation_easing {
1079            animation.easing = easing;
1080        }
1081        if let Some(count) = self.animation_iterations {
1082            animation.iterations = count;
1083        }
1084        animation
1085    }
1086}
1087
1088/// A CSS environment variable (`env()`) a padding or margin may use.
1089#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1090pub(crate) enum EnvVar {
1091    /// `safe-area-inset-top`: the top inset of the root view the node
1092    /// renders in.
1093    SafeAreaInsetTop,
1094    /// `safe-area-inset-right`.
1095    SafeAreaInsetRight,
1096    /// `safe-area-inset-bottom`.
1097    SafeAreaInsetBottom,
1098    /// `safe-area-inset-left`.
1099    SafeAreaInsetLeft,
1100    /// `keyboard-inset-height` (the VirtualKeyboard API's): the software
1101    /// keyboard's height over the surface, 0 while it is hidden.
1102    KeyboardInsetHeight,
1103}
1104
1105impl EnvVar {
1106    /// The variable named `name`, if NSH has it.
1107    pub(crate) fn parse(name: &str) -> Option<Self> {
1108        Some(match name {
1109            "safe-area-inset-top" => Self::SafeAreaInsetTop,
1110            "safe-area-inset-right" => Self::SafeAreaInsetRight,
1111            "safe-area-inset-bottom" => Self::SafeAreaInsetBottom,
1112            "safe-area-inset-left" => Self::SafeAreaInsetLeft,
1113            "keyboard-inset-height" => Self::KeyboardInsetHeight,
1114            _ => return None,
1115        })
1116    }
1117}
1118
1119/// The `env()` terms of a node's padding and margin by physical edge (top,
1120/// right, bottom, left).
1121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1122pub(crate) struct EnvEdges {
1123    /// The padding's.
1124    pub(crate) padding: [Option<EnvVar>; 4],
1125    /// The margin's.
1126    pub(crate) margin: [Option<EnvVar>; 4],
1127}
1128
1129impl EnvEdges {
1130    /// Whether no edge has a term.
1131    pub(crate) fn is_empty(&self) -> bool {
1132        *self == Self::default()
1133    }
1134
1135    /// Left and right swapped, as their declarations are in right-to-left
1136    /// layouts ([`swap_sides`]).
1137    pub(crate) fn swapped(mut self) -> Self {
1138        self.padding.swap(1, 3);
1139        self.margin.swap(1, 3);
1140        self
1141    }
1142}
1143
1144/// A padding or margin value using `env()`: `env(name)`, `env(name,
1145/// <length>)`, `calc(env(name) + <length>)` or `calc(<length> +
1146/// env(name))`. `None` when `s` uses no `env()`; else the length part (in
1147/// points) and the variable (none when an unknown name's fallback stands
1148/// in for it), or an error for anything else.
1149pub(crate) fn env_length(s: &str) -> Option<Result<(f32, Option<EnvVar>), StyleError>> {
1150    if !s.contains("env(") {
1151        return None;
1152    }
1153    // One term: `env(...)` or a length.
1154    fn term(s: &str) -> Option<(f32, Option<EnvVar>)> {
1155        let Some(args) = s.strip_prefix("env(").and_then(|r| r.strip_suffix(')')) else {
1156            return Some((css::length(s)?, None));
1157        };
1158        let (name, fallback) = match args.split_once(',') {
1159            Some((name, fallback)) => (name.trim(), Some(fallback.trim())),
1160            None => (args.trim(), None),
1161        };
1162        match EnvVar::parse(name) {
1163            Some(var) => Some((0.0, Some(var))),
1164            // CSS: an unknown variable is its fallback.
1165            None => Some((css::length(fallback?)?, None)),
1166        }
1167    }
1168    let parse = |s: &str| {
1169        let s = s.trim();
1170        let Some(inner) = s.strip_prefix("calc(").and_then(|r| r.strip_suffix(')')) else {
1171            return term(s);
1172        };
1173        // `a + b`, the `+` outside parentheses and between white space, as
1174        // CSS requires.
1175        let mut depth = 0i32;
1176        let mut plus = None;
1177        for (i, c) in inner.char_indices() {
1178            match c {
1179                '(' => depth += 1,
1180                ')' => depth -= 1,
1181                '+' if depth == 0 => {
1182                    let spaced = inner[..i].ends_with(char::is_whitespace)
1183                        && inner[i + 1..].starts_with(char::is_whitespace);
1184                    if !spaced || plus.is_some() {
1185                        return None;
1186                    }
1187                    plus = Some(i);
1188                }
1189                _ => {}
1190            }
1191        }
1192        let at = plus?;
1193        let (a, b) = (term(inner[..at].trim())?, term(inner[at + 1..].trim())?);
1194        if a.1.is_some() && b.1.is_some() {
1195            return None;
1196        }
1197        Some((a.0 + b.0, a.1.or(b.1)))
1198    };
1199    Some(parse(s).ok_or(StyleError::InvalidValue))
1200}
1201
1202/// A padding edge: its length and its `env()` term.
1203fn padding_edge(v: StyleValue<'_>) -> Result<(LengthPercentage, Option<EnvVar>), StyleError> {
1204    if let StyleValue::Str(s) = v
1205        && let Some(env) = env_length(s)
1206    {
1207        let (length, var) = env?;
1208        // Padding is never negative.
1209        if length < 0.0 {
1210            return Err(StyleError::InvalidValue);
1211        }
1212        return Ok((LengthPercentage::length(length), var));
1213    }
1214    Ok((lp_or_zero(v)?, None))
1215}
1216
1217/// A margin edge: its length and its `env()` term.
1218fn margin_edge(v: StyleValue<'_>) -> Result<(LengthPercentageAuto, Option<EnvVar>), StyleError> {
1219    if let StyleValue::Str(s) = v
1220        && let Some(env) = env_length(s)
1221    {
1222        let (length, var) = env?;
1223        return Ok((LengthPercentageAuto::length(length), var));
1224    }
1225    Ok((lpa_or_zero(v)?, None))
1226}
1227
1228/// Properties named by start and end (`marginStart`, `borderTopEndRadius`
1229/// ...): left and right in left-to-right layouts, the other way around in
1230/// right-to-left ones.
1231#[derive(Debug, Clone, Copy, PartialEq, Default)]
1232pub struct Logical {
1233    /// `marginStart`, `marginEnd`.
1234    pub margin: [Option<LengthPercentageAuto>; 2],
1235    /// `paddingStart`, `paddingEnd`.
1236    pub padding: [Option<LengthPercentage>; 2],
1237    /// `start`, `end`.
1238    pub inset: [Option<LengthPercentageAuto>; 2],
1239    /// `borderStartWidth`, `borderEndWidth`.
1240    pub border_width: [Option<Points>; 2],
1241    /// `borderStartColor`, `borderEndColor`.
1242    pub border_color: [Option<Color>; 2],
1243    /// `borderTopStartRadius`, `borderTopEndRadius`,
1244    /// `borderBottomEndRadius`, `borderBottomStartRadius`.
1245    pub radius: [Option<Points>; 4],
1246}
1247
1248impl Logical {
1249    /// Whether no start / end property is set.
1250    pub fn is_empty(&self) -> bool {
1251        *self == Self::default()
1252    }
1253}
1254
1255fn set_side<T>(rect: &mut taffy::Rect<T>, left: bool, value: T) {
1256    if left {
1257        rect.left = value;
1258    } else {
1259        rect.right = value;
1260    }
1261}
1262
1263/// Swaps the left and right properties: in right-to-left layouts they
1264/// mean start and end, as in React Native. An involution.
1265pub(crate) fn swap_sides(layout: &mut taffy::Style, view: &mut ViewStyle) {
1266    fn swap<T>(r: &mut taffy::Rect<T>) {
1267        std::mem::swap(&mut r.left, &mut r.right);
1268    }
1269    swap(&mut layout.margin);
1270    swap(&mut layout.padding);
1271    swap(&mut layout.inset);
1272    swap(&mut layout.border);
1273    let (w, r) = (&mut view.borders.widths, &mut view.corner_radius);
1274    std::mem::swap(&mut w.left, &mut w.right);
1275    view.borders.colors.swap(1, 3);
1276    std::mem::swap(&mut r.top_left, &mut r.top_right);
1277    std::mem::swap(&mut r.bottom_left, &mut r.bottom_right);
1278}
1279
1280/// Gives an unset `alignContent` (taffy's `normal`) its meaning for the
1281/// node's display: React Native's `flex-start` for flex (and block)
1282/// containers, where taffy's `normal` would stretch wrapped lines, and
1283/// CSS's `normal` for grids, whose auto tracks then stretch to fill the
1284/// container. (`justifyContent`'s `normal` is already `flex-start` in
1285/// flex containers.)
1286pub(crate) fn resolve_normal_alignment(layout: &mut taffy::Style) {
1287    if layout.display != Display::Grid && layout.align_content == AlignContent::NORMAL {
1288        layout.align_content = AlignContent::FLEX_START;
1289    }
1290}
1291
1292/// Lays a node out in direction `rtl`: swaps its left and right
1293/// properties when right to left, then places the start / end ones.
1294pub(crate) fn apply_direction(
1295    layout: &mut taffy::Style,
1296    view: &mut ViewStyle,
1297    logical: &Logical,
1298    rtl: bool,
1299) {
1300    layout.direction = if rtl {
1301        taffy::Direction::Rtl
1302    } else {
1303        taffy::Direction::Ltr
1304    };
1305    if rtl {
1306        swap_sides(layout, view);
1307    }
1308    if logical.is_empty() {
1309        return;
1310    }
1311    // Start is the left side left to right.
1312    for (i, left) in [!rtl, rtl].into_iter().enumerate() {
1313        if let Some(v) = logical.margin[i] {
1314            set_side(&mut layout.margin, left, v);
1315        }
1316        if let Some(v) = logical.padding[i] {
1317            set_side(&mut layout.padding, left, v);
1318        }
1319        if let Some(v) = logical.inset[i] {
1320            set_side(&mut layout.inset, left, v);
1321        }
1322        let side = if left { 3 } else { 1 };
1323        if let Some(w) = logical.border_width[i] {
1324            set_side(&mut layout.border, left, LengthPercentage::length(w.0));
1325            *view.borders.width_mut(side) = w;
1326        }
1327        if let Some(c) = logical.border_color[i] {
1328            view.borders.colors[side] = c;
1329        }
1330    }
1331    // Corners: top start, top end, bottom end, bottom start.
1332    let [top_start, top_end, bottom_end, bottom_start] = logical.radius;
1333    let c = &mut view.corner_radius;
1334    let (top_left, top_right, bottom_right, bottom_left) = if rtl {
1335        (top_end, top_start, bottom_start, bottom_end)
1336    } else {
1337        (top_start, top_end, bottom_end, bottom_start)
1338    };
1339    for (corner, r) in [
1340        (&mut c.top_left, top_left),
1341        (&mut c.top_right, top_right),
1342        (&mut c.bottom_right, bottom_right),
1343        (&mut c.bottom_left, bottom_left),
1344    ] {
1345        if r.is_some() {
1346            *corner = r;
1347        }
1348    }
1349}
1350
1351impl Default for Style {
1352    /// React Native defaults, which differ from CSS (and taffy) defaults.
1353    fn default() -> Self {
1354        let layout = taffy::Style {
1355            display: Display::Flex,
1356            position: Position::Relative,
1357            flex_direction: FlexDirection::Column,
1358            flex_shrink: 0.0,
1359            // Unset: `flex-start` (React Native) outside grids, CSS's
1360            // `normal` in grids (`resolve_normal_alignment`).
1361            align_content: AlignContent::NORMAL,
1362            // Yoga has no automatic minimum size (see `min_len`).
1363            min_size: taffy::Size {
1364                width: LengthPercentageAuto::length(0.0),
1365                height: LengthPercentageAuto::length(0.0),
1366            },
1367            ..taffy::Style::DEFAULT
1368        };
1369        Self {
1370            layout,
1371            view: ViewStyle::default(),
1372            text: TextStyle::default(),
1373            paint: PaintStyle::default(),
1374            animated: Vec::new(),
1375            z_index: 0,
1376            vertical_align: VerticalAlign::Baseline,
1377            direction: None,
1378            logical: Logical::default(),
1379            pending: Pending::default(),
1380            perspective: None,
1381        }
1382    }
1383}
1384
1385/// Which TypeScript style interface a property belongs to (each extends
1386/// the one before: layout, then views, then text or images).
1387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1388pub(crate) enum StyleGroup {
1389    Layout,
1390    View,
1391    Text,
1392    Image,
1393}
1394
1395/// A style property's TypeScript declaration (`js::style`).
1396#[derive(Debug, Clone, Copy)]
1397pub(crate) struct StyleType {
1398    pub(crate) name: &'static str,
1399    pub(crate) group: StyleGroup,
1400    pub(crate) ts: &'static str,
1401    pub(crate) doc: Option<&'static str>,
1402}
1403
1404/// The style properties the JS bridge decodes itself (objects and lists,
1405/// `crates/nsh-js/src/protocol.rs`), for the TypeScript declarations.
1406pub(crate) const OBJECT_STYLE_TYPES: &[StyleType] = &[
1407    StyleType {
1408        name: "transform",
1409        group: StyleGroup::View,
1410        ts: "TransformStep[]",
1411        doc: None,
1412    },
1413    StyleType {
1414        name: "shadowOffset",
1415        group: StyleGroup::View,
1416        ts: "{ width: number; height: number }",
1417        doc: Some("Default `{ width: 0, height: -3 }`, as in React Native."),
1418    },
1419    StyleType {
1420        name: "textShadowOffset",
1421        group: StyleGroup::Text,
1422        ts: "{ width: number; height: number }",
1423        doc: None,
1424    },
1425];
1426
1427macro_rules! style_keys {
1428    ($($key:ident = $name:literal: $group:ident $ts:literal $($doc:literal)?),* $(,)?) => {
1429        /// The style properties' TypeScript declarations, in order.
1430        pub(crate) const STYLE_TYPES: &[StyleType] = &[$(StyleType {
1431            name: $name,
1432            group: StyleGroup::$group,
1433            ts: $ts,
1434            doc: style_keys!(@doc $($doc)?),
1435        }),*];
1436
1437        /// A style property, by its React Native name.
1438        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1439        pub enum StyleKey {
1440            $(
1441                #[doc = concat!("`", $name, "`")]
1442                $key,
1443            )*
1444        }
1445
1446        impl StyleKey {
1447            /// The key named `name` (React Native's camel case).
1448            pub fn parse(name: &str) -> Option<StyleKey> {
1449                Some(match name {
1450                    $($name => StyleKey::$key,)*
1451                    _ => return None,
1452                })
1453            }
1454
1455            /// The React Native name.
1456            pub fn name(self) -> &'static str {
1457                match self {
1458                    $(StyleKey::$key => $name,)*
1459                }
1460            }
1461        }
1462    };
1463    (@doc) => { None };
1464    (@doc $doc:literal) => { Some($doc) };
1465}
1466
1467style_keys! {
1468    Display = "display": Layout "\"flex\" | \"grid\" | \"block\" | \"flow-root\" | \"none\"",
1469    BoxSizing = "boxSizing": Layout "\"border-box\" | \"content-box\"" "The box that width and height include.",
1470    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`.",
1471    FlexDirection = "flexDirection": Layout "\"row\" | \"column\" | \"row-reverse\" | \"column-reverse\"",
1472    FlexWrap = "flexWrap": Layout "\"wrap\" | \"nowrap\" | \"wrap-reverse\"",
1473    Flex = "flex": Layout "number",
1474    FlexGrow = "flexGrow": Layout "number",
1475    FlexShrink = "flexShrink": Layout "number",
1476    FlexBasis = "flexBasis": Layout "DimensionValue | \"min-content\" | \"max-content\" | \"fit-content\"",
1477    JustifyContent = "justifyContent": Layout "Exclude<Distribute, \"stretch\"> | \"stretch\"",
1478    AlignItems = "alignItems": Layout "Align",
1479    AlignSelf = "alignSelf": Layout "Align | \"auto\"",
1480    AlignContent = "alignContent": Layout "Distribute",
1481    Width = "width": Layout "DimensionValue | \"min-content\" | \"max-content\" | \"fit-content\"",
1482    Height = "height": Layout "DimensionValue | \"min-content\" | \"max-content\" | \"fit-content\"",
1483    MinWidth = "minWidth": Layout "LengthValue",
1484    MinHeight = "minHeight": Layout "LengthValue",
1485    MaxWidth = "maxWidth": Layout "LengthValue",
1486    MaxHeight = "maxHeight": Layout "LengthValue",
1487    AspectRatio = "aspectRatio": Layout "number",
1488    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).",
1489    Right = "right": Layout "DimensionValue",
1490    Bottom = "bottom": Layout "DimensionValue",
1491    Left = "left": Layout "DimensionValue | AnimatedNode" "An animated value only for a `position: \"sticky\"` view in a horizontal scroll view, as `top`.",
1492    Margin = "margin": Layout "DimensionValue | EnvValue",
1493    MarginHorizontal = "marginHorizontal": Layout "DimensionValue | EnvValue",
1494    MarginVertical = "marginVertical": Layout "DimensionValue | EnvValue",
1495    MarginTop = "marginTop": Layout "DimensionValue | EnvValue",
1496    MarginRight = "marginRight": Layout "DimensionValue | EnvValue",
1497    MarginBottom = "marginBottom": Layout "DimensionValue | EnvValue",
1498    MarginLeft = "marginLeft": Layout "DimensionValue | EnvValue",
1499    Padding = "padding": Layout "LengthValue | EnvValue",
1500    PaddingHorizontal = "paddingHorizontal": Layout "LengthValue | EnvValue",
1501    PaddingVertical = "paddingVertical": Layout "LengthValue | EnvValue",
1502    PaddingTop = "paddingTop": Layout "LengthValue | EnvValue",
1503    PaddingRight = "paddingRight": Layout "LengthValue | EnvValue",
1504    PaddingBottom = "paddingBottom": Layout "LengthValue | EnvValue",
1505    PaddingLeft = "paddingLeft": Layout "LengthValue | EnvValue",
1506    Gap = "gap": Layout "LengthValue",
1507    RowGap = "rowGap": Layout "LengthValue",
1508    ColumnGap = "columnGap": Layout "LengthValue",
1509    BorderWidth = "borderWidth": View "number",
1510    BorderTopWidth = "borderTopWidth": View "number",
1511    BorderRightWidth = "borderRightWidth": View "number",
1512    BorderBottomWidth = "borderBottomWidth": View "number",
1513    BorderLeftWidth = "borderLeftWidth": View "number",
1514    ZIndex = "zIndex": Layout "number" "Order among siblings (stable); also the native stacking order.",
1515    BoxShadow = "boxShadow": View "string" "CSS `box-shadow`: offsets, blur, spread and color, several separated by commas, `inset` for inner shadows.",
1516    BackgroundImage = "backgroundImage": View "string" "CSS gradients drawn over the background color: `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`, several separated by commas.",
1517    Filter = "filter": View "string" "CSS filters of the view and its content: `brightness()`, `contrast()`, `grayscale()`, `hue-rotate()`, `invert()`, `saturate()`, `sepia()`, `opacity()`, `blur()`, `drop-shadow()`.",
1518    BackdropFilter = "backdropFilter": View "string" "CSS filters of what is behind the view (`blur(10px)`).",
1519    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.",
1520    GlassEffect = "glassEffect": View "\"none\" | \"regular\" | \"clear\"" "A glass material behind the view's content (Apple's Liquid Glass). Drawn on iOS 26 and later; elsewhere the view's `backdropFilter` is drawn as before, so give a glass view a blur to fall back to.",
1521    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.",
1522    OutlineWidth = "outlineWidth": View "number" "A line outside the border that takes no space.",
1523    OutlineColor = "outlineColor": View "ColorValue",
1524    OutlineStyle = "outlineStyle": View "\"solid\" | \"dashed\" | \"dotted\" | \"none\" | \"hidden\"",
1525    OutlineOffset = "outlineOffset": View "number" "Distance from the border edge (negative: inside).",
1526    Visibility = "visibility": View "\"visible\" | \"hidden\" | \"collapse\"" "Hidden views keep their space.",
1527    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).",
1528    TransitionProperty = "transitionProperty": View "string" "The properties that animate when they change (`\"opacity, transform\"`, `\"all\"`, `\"colors\"`).",
1529    TransitionDuration = "transitionDuration": View "number | `${number}ms` | `${number}s`" "Milliseconds as a number, or `\"150ms\"` / `\"0.2s\"`.",
1530    TransitionDelay = "transitionDelay": View "number | `${number}ms` | `${number}s`",
1531    TransitionTimingFunction = "transitionTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
1532    AnimationName = "animationName": View "\"none\" | \"spin\" | \"ping\" | \"pulse\" | \"bounce\"" "A built-in keyframe animation, run natively.",
1533    AnimationDuration = "animationDuration": View "number | `${number}ms` | `${number}s`",
1534    AnimationDelay = "animationDelay": View "number | `${number}ms` | `${number}s`",
1535    AnimationTimingFunction = "animationTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
1536    AnimationIterationCount = "animationIterationCount": View "number | \"infinite\"",
1537    TextDecorationStyle = "textDecorationStyle": Text "\"solid\" | \"double\" | \"dotted\" | \"dashed\" | \"wavy\"",
1538    TextDecorationThickness = "textDecorationThickness": Text "number | \"auto\" | \"from-font\"",
1539    TextUnderlineOffset = "textUnderlineOffset": Text "number | \"auto\"",
1540    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]\"`).",
1541    GridTemplateRows = "gridTemplateRows": Layout "string",
1542    GridAutoColumns = "gridAutoColumns": Layout "string" "Tracks of implicitly created columns.",
1543    GridAutoRows = "gridAutoRows": Layout "string",
1544    GridAutoFlow = "gridAutoFlow": Layout "\"row\" | \"column\" | \"dense\" | \"row dense\" | \"column dense\"",
1545    GridColumn = "gridColumn": Layout "number | string" "`\"1 / 3\"`, `\"span 2\"`, a line number or name (`\"content-start / full-end\"`, `\"span col\"`).",
1546    GridColumnStart = "gridColumnStart": Layout "number | string",
1547    GridColumnEnd = "gridColumnEnd": Layout "number | string",
1548    GridRow = "gridRow": Layout "number | string",
1549    GridRowStart = "gridRowStart": Layout "number | string",
1550    GridRowEnd = "gridRowEnd": Layout "number | string",
1551    JustifyItems = "justifyItems": Layout "Align" "How grid items sit in their areas along the row.",
1552    JustifySelf = "justifySelf": Layout "Align | \"auto\"",
1553    Direction = "direction": Layout "\"inherit\" | \"ltr\" | \"rtl\"" "Layout direction; inherited by default. Right to left, `left` and `right` properties mean start and end (as in React Native).",
1554    MarginStart = "marginStart": Layout "DimensionValue",
1555    MarginEnd = "marginEnd": Layout "DimensionValue",
1556    PaddingStart = "paddingStart": Layout "LengthValue",
1557    PaddingEnd = "paddingEnd": Layout "LengthValue",
1558    Start = "start": Layout "DimensionValue" "Left in left-to-right layouts, right in right-to-left ones.",
1559    End = "end": Layout "DimensionValue",
1560    BorderStartWidth = "borderStartWidth": View "number",
1561    BorderEndWidth = "borderEndWidth": View "number",
1562    BorderStartColor = "borderStartColor": View "ColorValue",
1563    BorderEndColor = "borderEndColor": View "ColorValue",
1564    BorderTopStartRadius = "borderTopStartRadius": View "number",
1565    BorderTopEndRadius = "borderTopEndRadius": View "number",
1566    BorderBottomEndRadius = "borderBottomEndRadius": View "number",
1567    BorderBottomStartRadius = "borderBottomStartRadius": View "number",
1568    BackgroundColor = "backgroundColor": View "ColorValue | AnimatedNode",
1569    BorderRadius = "borderRadius": View "number",
1570    BorderTopLeftRadius = "borderTopLeftRadius": View "number",
1571    BorderTopRightRadius = "borderTopRightRadius": View "number",
1572    BorderBottomRightRadius = "borderBottomRightRadius": View "number",
1573    BorderBottomLeftRadius = "borderBottomLeftRadius": View "number",
1574    ShadowColor = "shadowColor": View "ColorValue | AnimatedNode",
1575    ShadowOpacity = "shadowOpacity": View "number | AnimatedNode",
1576    ShadowRadius = "shadowRadius": View "number | AnimatedNode",
1577    BorderColor = "borderColor": View "ColorValue | AnimatedNode",
1578    BorderTopColor = "borderTopColor": View "ColorValue",
1579    BorderRightColor = "borderRightColor": View "ColorValue",
1580    BorderBottomColor = "borderBottomColor": View "ColorValue",
1581    BorderLeftColor = "borderLeftColor": View "ColorValue",
1582    BorderStyle = "borderStyle": View "\"solid\" | \"dashed\" | \"dotted\" | \"none\" | \"hidden\"" "`none` and `hidden`: no border whatever the widths (they take no space).",
1583    BorderCurve = "borderCurve": View "\"circular\" | \"continuous\"" "`continuous`: corners whose curvature eases into the edges (iOS app icons).",
1584    TintColor = "tintColor": Image "ColorValue" "Recolors a template image.",
1585    ObjectPosition = "objectPosition": Image "string" "Where the image sits in its box once `resizeMode` 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.",
1586    BackfaceVisibility = "backfaceVisibility": View "\"visible\" | \"hidden\"" "`\"hidden\"`: invisible while turned away (3D rotations).",
1587    TransformOrigin = "transformOrigin": View "string | (number | string)[]" "The point `transform` acts around: keywords, percentages and lengths (\"top left\", \"50% 0\", `[10, 20]`). Default the center.",
1588    Opacity = "opacity": View "number | AnimatedNode",
1589    Overflow = "overflow": View "\"visible\" | \"hidden\"",
1590    Color = "color": Text "ColorValue | AnimatedNode",
1591    FontSize = "fontSize": Text "number",
1592    FontWeight = "fontWeight": Text "\"normal\" | \"bold\" | number | `${number}`" "`\"normal\"` (400), `\"bold\"` (700) or 100–900.",
1593    LineHeight = "lineHeight": Text "number",
1594    FontFamily = "fontFamily": Text "string" "A system family or the name an imported font (`import Inter from \"./Inter.ttf\"`) evaluates to.",
1595    FontStyle = "fontStyle": Text "\"normal\" | \"italic\"",
1596    LetterSpacing = "letterSpacing": Text "number",
1597    TextDecorationLine = "textDecorationLine": Text "\"none\" | \"underline\" | \"line-through\" | \"underline line-through\"",
1598    TextDecorationColor = "textDecorationColor": Text "ColorValue",
1599    WritingDirection = "writingDirection": Text "\"auto\" | \"ltr\" | \"rtl\"" "Base direction of the text; `auto` takes it from the content.",
1600    TextAlignVertical = "textAlignVertical": Text "\"auto\" | \"top\" | \"center\" | \"bottom\"" "Where text shorter than its box sits (`<Text>` with a height).",
1601    FontVariant = "fontVariant": Text "(\"small-caps\" | \"oldstyle-nums\" | \"lining-nums\" | \"tabular-nums\" | \"proportional-nums\")[]" "OpenType number and letter forms.",
1602    TextShadowColor = "textShadowColor": Text "ColorValue",
1603    TextShadowRadius = "textShadowRadius": Text "number",
1604    TextTransform = "textTransform": Text "\"none\" | \"uppercase\" | \"lowercase\" | \"capitalize\"",
1605    TextAlign = "textAlign": Text "\"auto\" | \"left\" | \"center\" | \"right\" | \"justify\"",
1606    PlaceholderColor = "placeholderColor": Text "ColorValue" "An input's placeholder (`placeholder:text-*`).",
1607    SelectionColor = "selectionColor": Text "ColorValue" "An input's caret and selection, a selectable text's selection highlight (`selection:bg-*`).",
1608    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.",
1609    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.",
1610    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>`).",
1611    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).",
1612    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-*`): its bottom on the baseline (the default), 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.",
1613}
1614
1615/// A style property value as read from JS.
1616#[derive(Debug, Clone, Copy)]
1617pub enum StyleValue<'a> {
1618    /// A number.
1619    Number(f32),
1620    /// A string.
1621    Str(&'a str),
1622    /// `null` / `undefined`: resets the property to its default.
1623    Null,
1624}
1625
1626/// A style property value owned by a [`StylePatch`].
1627#[derive(Debug, Clone, PartialEq)]
1628pub enum PatchValue {
1629    /// A number.
1630    Number(f32),
1631    /// A string.
1632    Str(Box<str>),
1633    /// Resets the property to its default.
1634    Null,
1635}
1636
1637impl PatchValue {
1638    /// The value as [`Style::set`] takes it.
1639    pub fn as_value(&self) -> StyleValue<'_> {
1640        match self {
1641            PatchValue::Number(n) => StyleValue::Number(*n),
1642            PatchValue::Str(s) => StyleValue::Str(s),
1643            PatchValue::Null => StyleValue::Null,
1644        }
1645    }
1646}
1647
1648impl From<StyleValue<'_>> for PatchValue {
1649    fn from(v: StyleValue<'_>) -> Self {
1650        match v {
1651            StyleValue::Number(n) => PatchValue::Number(n),
1652            StyleValue::Str(s) => PatchValue::Str(s.into()),
1653            StyleValue::Null => PatchValue::Null,
1654        }
1655    }
1656}
1657
1658/// One declaration of a [`StylePatch`].
1659#[derive(Debug, Clone, PartialEq)]
1660pub enum StyleDecl {
1661    /// A property.
1662    Set(StyleKey, PatchValue),
1663    /// Starts the `transform` list over: a `transform` replaces the
1664    /// transforms set before it (by classes).
1665    ClearTransform,
1666    /// Appends a `transform` entry, driven by an animated value when given
1667    /// (the amount is then the identity until it is bound).
1668    Transform(TransformKind, f32, Option<crate::animation::NodeId>),
1669    /// `shadowOffset`; `None` restores the default.
1670    ShadowOffset(Option<Point<Points>>),
1671    /// `textShadowOffset`.
1672    TextShadowOffset(Option<Point<Points>>),
1673    /// A property driven by a native animation node.
1674    Animated(crate::animation::AnimationProp, crate::animation::NodeId),
1675}
1676
1677impl StyleDecl {
1678    /// Applies the declaration to `style`.
1679    pub fn apply(&self, style: &mut Style) -> Result<(), StyleError> {
1680        match self {
1681            StyleDecl::Set(key, value) => style.set_key(*key, value.as_value()),
1682            StyleDecl::ClearTransform => {
1683                style.view.transform = Transform::IDENTITY;
1684                style.animated.retain(|(prop, _)| {
1685                    !matches!(prop, crate::animation::AnimationProp::Transform(_))
1686                });
1687                Ok(())
1688            }
1689            StyleDecl::Transform(kind, amount, node) => {
1690                let index = style
1691                    .view
1692                    .transform
1693                    .push(*kind, *amount)
1694                    .ok_or(StyleError::InvalidValue)?;
1695                if let Some(node) = node {
1696                    style
1697                        .animated
1698                        .push((crate::animation::AnimationProp::Transform(index), *node));
1699                }
1700                Ok(())
1701            }
1702            StyleDecl::ShadowOffset(offset) => {
1703                style.set_shadow_offset(*offset);
1704                Ok(())
1705            }
1706            StyleDecl::TextShadowOffset(offset) => {
1707                style.set_text_shadow_offset(*offset);
1708                Ok(())
1709            }
1710            StyleDecl::Animated(prop, node) => {
1711                style.animated.push((*prop, *node));
1712                Ok(())
1713            }
1714        }
1715    }
1716}
1717
1718/// A style as written (`style={...}`): its declarations in order (the
1719/// shorthands of [`StylePatch::set`] before their longhands), kept so the
1720/// core can apply them again over class styles when those change.
1721#[derive(Debug, Clone, Default, PartialEq)]
1722pub struct StylePatch {
1723    decls: Vec<StyleDecl>,
1724}
1725
1726impl StylePatch {
1727    /// Applies `decl` to `style` and records it if it applied.
1728    pub fn push(&mut self, style: &mut Style, decl: StyleDecl) -> Result<(), StyleError> {
1729        decl.apply(style)?;
1730        self.decls.push(decl);
1731        Ok(())
1732    }
1733
1734    /// Sets property `key` of the style object this patch records on
1735    /// `style`, and records it. As in React Native, a longhand
1736    /// (`borderTopWidth`, `marginHorizontal`, `flexGrow`, ...) wins over
1737    /// its shorthand (`borderWidth`, `margin`, `flex`) in one object
1738    /// whatever their order: a shorthand set after its longhands is
1739    /// recorded before them, and they apply again; a `null` longhand is
1740    /// unset, so its shorthand shows.
1741    pub fn set(
1742        &mut self,
1743        style: &mut Style,
1744        key: &str,
1745        value: StyleValue<'_>,
1746    ) -> Result<(), StyleError> {
1747        let key = StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?;
1748        if matches!(value, StyleValue::Null) && self.has_shorthand_of(key) {
1749            return Ok(());
1750        }
1751        style.set_key(key, value)?;
1752        let decl = StyleDecl::Set(key, value.into());
1753        let longhands = key.longhands();
1754        let Some(at) = self
1755            .decls
1756            .iter()
1757            .position(|d| matches!(d, StyleDecl::Set(k, _) if longhands.contains(k)))
1758        else {
1759            self.decls.push(decl);
1760            return Ok(());
1761        };
1762        // Nulls set before are dropped (the shorthand shows); the others
1763        // apply again over it.
1764        self.decls
1765            .retain(|d| !matches!(d, StyleDecl::Set(k, PatchValue::Null) if longhands.contains(k)));
1766        let at = at.min(self.decls.len());
1767        self.decls.insert(at, decl);
1768        for d in &self.decls[at + 1..] {
1769            if let StyleDecl::Set(k, v) = d
1770                && longhands.contains(k)
1771            {
1772                let _ = style.set_key(*k, v.as_value());
1773            }
1774        }
1775        Ok(())
1776    }
1777
1778    /// Whether a shorthand of `key` is recorded.
1779    fn has_shorthand_of(&self, key: StyleKey) -> bool {
1780        self.decls
1781            .iter()
1782            .any(|d| matches!(d, StyleDecl::Set(k, _) if k.longhands().contains(&key)))
1783    }
1784
1785    /// Applies every declaration to `style`, in order.
1786    pub fn apply(&self, style: &mut Style) {
1787        for decl in &self.decls {
1788            // Declarations were checked when they were recorded.
1789            let _ = decl.apply(style);
1790        }
1791    }
1792
1793    /// Whether there are no declarations.
1794    pub fn is_empty(&self) -> bool {
1795        self.decls.is_empty()
1796    }
1797
1798    /// The declarations.
1799    pub fn decls(&self) -> &[StyleDecl] {
1800        &self.decls
1801    }
1802}
1803
1804impl StyleKey {
1805    /// The properties that override this shorthand in a style object
1806    /// whatever their order (Yoga takes an edge's own value before its
1807    /// axis' and that of all edges, `flexGrow` before `flex`).
1808    fn longhands(self) -> &'static [StyleKey] {
1809        use StyleKey as K;
1810        match self {
1811            K::Margin => &[
1812                K::MarginHorizontal,
1813                K::MarginVertical,
1814                K::MarginTop,
1815                K::MarginRight,
1816                K::MarginBottom,
1817                K::MarginLeft,
1818            ],
1819            K::MarginHorizontal => &[K::MarginLeft, K::MarginRight],
1820            K::MarginVertical => &[K::MarginTop, K::MarginBottom],
1821            K::Padding => &[
1822                K::PaddingHorizontal,
1823                K::PaddingVertical,
1824                K::PaddingTop,
1825                K::PaddingRight,
1826                K::PaddingBottom,
1827                K::PaddingLeft,
1828            ],
1829            K::PaddingHorizontal => &[K::PaddingLeft, K::PaddingRight],
1830            K::PaddingVertical => &[K::PaddingTop, K::PaddingBottom],
1831            K::BorderWidth => &[
1832                K::BorderTopWidth,
1833                K::BorderRightWidth,
1834                K::BorderBottomWidth,
1835                K::BorderLeftWidth,
1836            ],
1837            K::BorderColor => &[
1838                K::BorderTopColor,
1839                K::BorderRightColor,
1840                K::BorderBottomColor,
1841                K::BorderLeftColor,
1842            ],
1843            K::Gap => &[K::RowGap, K::ColumnGap],
1844            K::Flex => &[K::FlexGrow, K::FlexShrink, K::FlexBasis],
1845            K::GridColumn => &[K::GridColumnStart, K::GridColumnEnd],
1846            K::GridRow => &[K::GridRowStart, K::GridRowEnd],
1847            _ => &[],
1848        }
1849    }
1850}
1851
1852/// Why a style property was rejected.
1853#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1854pub enum StyleError {
1855    /// The property name is not supported.
1856    UnknownProperty,
1857    /// The value has the wrong type or format.
1858    InvalidValue,
1859}
1860
1861enum Len {
1862    Px(f32),
1863    Pct(f32),
1864    Auto,
1865}
1866
1867impl Len {
1868    fn parse(v: StyleValue<'_>) -> Result<Len, StyleError> {
1869        match v {
1870            StyleValue::Number(n) => Ok(Len::Px(n)),
1871            StyleValue::Str("auto") => Ok(Len::Auto),
1872            StyleValue::Str(s) => s
1873                .strip_suffix('%')
1874                .and_then(|p| p.trim().parse::<f32>().ok())
1875                .map(|p| Len::Pct(p / 100.0))
1876                .ok_or(StyleError::InvalidValue),
1877            StyleValue::Null => Ok(Len::Auto),
1878        }
1879    }
1880
1881    fn dim(self) -> Dimension {
1882        match self {
1883            Len::Px(v) => Dimension::length(v),
1884            Len::Pct(v) => Dimension::percent(v),
1885            Len::Auto => Dimension::auto(),
1886        }
1887    }
1888
1889    fn lpa(self) -> LengthPercentageAuto {
1890        match self {
1891            Len::Px(v) => LengthPercentageAuto::length(v),
1892            Len::Pct(v) => LengthPercentageAuto::percent(v),
1893            Len::Auto => LengthPercentageAuto::auto(),
1894        }
1895    }
1896
1897    fn lp(self) -> Result<LengthPercentage, StyleError> {
1898        match self {
1899            Len::Px(v) => Ok(LengthPercentage::length(v)),
1900            Len::Pct(v) => Ok(LengthPercentage::percent(v)),
1901            Len::Auto => Err(StyleError::InvalidValue),
1902        }
1903    }
1904}
1905
1906/// Intrinsic sizes are delegated to Taffy's sizing algorithms.
1907fn dimension(value: StyleValue<'_>) -> Result<Dimension, StyleError> {
1908    Ok(match value {
1909        StyleValue::Str("min-content") => Dimension::min_content(),
1910        StyleValue::Str("max-content") => Dimension::max_content(),
1911        StyleValue::Str("fit-content") => Dimension::fit_content(),
1912        value => Len::parse(value)?.dim(),
1913    })
1914}
1915
1916/// A zero-default length: `null` resets to 0 rather than `auto`.
1917fn lp_or_zero(v: StyleValue<'_>) -> Result<LengthPercentage, StyleError> {
1918    match v {
1919        StyleValue::Null => Ok(LengthPercentage::length(0.0)),
1920        v => Len::parse(v)?.lp(),
1921    }
1922}
1923
1924fn opt_lpa(v: StyleValue<'_>) -> Result<Option<LengthPercentageAuto>, StyleError> {
1925    match v {
1926        StyleValue::Null => Ok(None),
1927        v => Ok(Some(Len::parse(v)?.lpa())),
1928    }
1929}
1930
1931fn opt_lp(v: StyleValue<'_>) -> Result<Option<LengthPercentage>, StyleError> {
1932    match v {
1933        StyleValue::Null => Ok(None),
1934        v => Ok(Some(Len::parse(v)?.lp()?)),
1935    }
1936}
1937
1938/// A minimum size: unset is 0, as in Yoga. Taffy's `auto` would be CSS's
1939/// automatic minimum (the min-content size), which keeps flex items from
1940/// shrinking below their content (`flex: 1` text in a row would overflow).
1941fn min_len(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
1942    Ok(match Len::parse(v)? {
1943        Len::Auto => LengthPercentageAuto::length(0.0),
1944        len => len.lpa(),
1945    })
1946}
1947
1948fn lpa_or_zero(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
1949    match v {
1950        StyleValue::Null => Ok(LengthPercentageAuto::length(0.0)),
1951        v => Ok(Len::parse(v)?.lpa()),
1952    }
1953}
1954
1955fn number(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
1956    match v {
1957        StyleValue::Number(n) => Ok(n),
1958        StyleValue::Null => Ok(default),
1959        StyleValue::Str(_) => Err(StyleError::InvalidValue),
1960    }
1961}
1962
1963fn opt_number(v: StyleValue<'_>) -> Result<Option<f32>, StyleError> {
1964    match v {
1965        StyleValue::Number(n) => Ok(Some(n)),
1966        StyleValue::Null => Ok(None),
1967        StyleValue::Str(_) => Err(StyleError::InvalidValue),
1968    }
1969}
1970
1971fn opt_points(v: StyleValue<'_>) -> Result<Option<Points>, StyleError> {
1972    Ok(opt_number(v)?.map(px))
1973}
1974
1975fn color(v: StyleValue<'_>) -> Result<Option<Color>, StyleError> {
1976    match v {
1977        StyleValue::Str(s) => Color::parse(s).map(Some).ok_or(StyleError::InvalidValue),
1978        StyleValue::Null => Ok(None),
1979        StyleValue::Number(_) => Err(StyleError::InvalidValue),
1980    }
1981}
1982
1983/// A `fill` / `stroke` value; `inherit` is unset, since they inherit.
1984fn svg_paint(v: StyleValue<'_>) -> Result<Option<SvgPaint>, StyleError> {
1985    let StyleValue::Str(s) = v else {
1986        return match v {
1987            StyleValue::Null => Ok(None),
1988            _ => Err(StyleError::InvalidValue),
1989        };
1990    };
1991    let s = s.trim();
1992    Ok(if s.eq_ignore_ascii_case("none") {
1993        Some(SvgPaint::None)
1994    } else if s.eq_ignore_ascii_case("currentcolor") {
1995        Some(SvgPaint::CurrentColor)
1996    } else if s.eq_ignore_ascii_case("inherit") {
1997        None
1998    } else {
1999        Some(SvgPaint::Color(
2000            Color::parse(s).ok_or(StyleError::InvalidValue)?,
2001        ))
2002    })
2003}
2004
2005/// A `strokeDasharray` value: lengths (no negatives) separated by commas
2006/// and / or spaces, or `none` (empty); one whose lengths add up to zero is
2007/// a solid line, as in SVG.
2008fn dasharray(v: StyleValue<'_>) -> Result<Option<Arc<[Points]>>, StyleError> {
2009    let lengths: Vec<Points> = match v {
2010        StyleValue::Null => return Ok(None),
2011        StyleValue::Number(n) if n >= 0.0 => vec![px(n)],
2012        StyleValue::Number(_) => return Err(StyleError::InvalidValue),
2013        StyleValue::Str(s) if s.trim().eq_ignore_ascii_case("none") => Vec::new(),
2014        StyleValue::Str(s) => s
2015            .split(|c: char| c == ',' || c.is_whitespace())
2016            .filter(|part| !part.is_empty())
2017            .map(|part| match css::length(part) {
2018                Some(n) if n >= 0.0 => Ok(px(n)),
2019                _ => Err(StyleError::InvalidValue),
2020            })
2021            .collect::<Result<_, _>>()?,
2022    };
2023    if lengths.iter().all(|l| l.0 == 0.0) {
2024        return Ok(Some(Arc::from([])));
2025    }
2026    Ok(Some(lengths.into()))
2027}
2028
2029fn keyword<'a>(v: StyleValue<'a>) -> Result<Option<&'a str>, StyleError> {
2030    match v {
2031        StyleValue::Str(s) => Ok(Some(s)),
2032        StyleValue::Null => Ok(None),
2033        StyleValue::Number(_) => Err(StyleError::InvalidValue),
2034    }
2035}
2036
2037fn align_items(v: StyleValue<'_>) -> Result<Option<AlignItems>, StyleError> {
2038    Ok(match keyword(v)? {
2039        None => None,
2040        Some("flex-start") => Some(AlignItems::FLEX_START),
2041        Some("flex-end") => Some(AlignItems::FLEX_END),
2042        // CSS's logical keywords: the writing direction's start and end
2043        // (right to left, `start` is the right), not the flex direction's.
2044        Some("start") => Some(AlignItems::START),
2045        Some("end") => Some(AlignItems::END),
2046        Some("self-start") => Some(AlignItems::SELF_START),
2047        Some("self-end") => Some(AlignItems::SELF_END),
2048        Some("center") => Some(AlignItems::CENTER),
2049        Some("stretch") => Some(AlignItems::STRETCH),
2050        Some("baseline") => Some(AlignItems::BASELINE),
2051        // CSS's `normal`: `stretch` for items without an aspect ratio.
2052        Some("normal") => Some(AlignItems::NORMAL),
2053        Some(_) => return Err(StyleError::InvalidValue),
2054    })
2055}
2056
2057/// `alignContent` / `justifyContent`; unset (null, `normal`) is CSS's
2058/// `normal`, which [`resolve_normal_alignment`] makes React Native's
2059/// `flex-start` outside grids.
2060fn align_content(v: StyleValue<'_>) -> Result<AlignContent, StyleError> {
2061    Ok(match keyword(v)? {
2062        None | Some("normal") => AlignContent::NORMAL,
2063        Some("flex-start") => AlignContent::FLEX_START,
2064        Some("flex-end") => AlignContent::FLEX_END,
2065        Some("start") => AlignContent::START,
2066        Some("end") => AlignContent::END,
2067        Some("center") => AlignContent::CENTER,
2068        Some("stretch") => AlignContent::STRETCH,
2069        Some("space-between") => AlignContent::SPACE_BETWEEN,
2070        Some("space-around") => AlignContent::SPACE_AROUND,
2071        Some("space-evenly") => AlignContent::SPACE_EVENLY,
2072        Some(_) => return Err(StyleError::InvalidValue),
2073    })
2074}
2075
2076fn font_weight(v: StyleValue<'_>) -> Result<Option<u16>, StyleError> {
2077    Ok(match v {
2078        StyleValue::Null => None,
2079        StyleValue::Number(n) => Some((n as u16).clamp(100, 900)),
2080        StyleValue::Str("normal") => Some(400),
2081        StyleValue::Str("bold") => Some(700),
2082        StyleValue::Str(s) => Some(
2083            s.parse::<u16>()
2084                .map_err(|_| StyleError::InvalidValue)?
2085                .clamp(100, 900),
2086        ),
2087    })
2088}
2089
2090/// A length in points from a number or a string (`"2px"`, `"0.5rem"`).
2091fn length_value(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
2092    match v {
2093        StyleValue::Number(n) => Ok(n),
2094        StyleValue::Str(s) => css::length(s).ok_or(StyleError::InvalidValue),
2095        StyleValue::Null => Ok(default),
2096    }
2097}
2098
2099/// Milliseconds from a number or `"150ms"` / `"0.2s"`.
2100fn duration(v: StyleValue<'_>) -> Result<f32, StyleError> {
2101    match v {
2102        StyleValue::Number(n) => Ok(n.max(0.0)),
2103        StyleValue::Null => Ok(0.0),
2104        StyleValue::Str(s) => {
2105            let s = s.trim();
2106            let ms = if let Some(n) = s.strip_suffix("ms") {
2107                css::number(n)
2108            } else if let Some(n) = s.strip_suffix('s') {
2109                css::number(n).map(|n| n * 1000.0)
2110            } else {
2111                css::number(s)
2112            };
2113            ms.map(|n| n.max(0.0)).ok_or(StyleError::InvalidValue)
2114        }
2115    }
2116}
2117
2118/// A CSS timing function as cubic Bézier control points.
2119fn timing_function(v: StyleValue<'_>) -> Result<[f32; 4], StyleError> {
2120    let Some(s) = keyword(v)? else {
2121        return Ok(Transition::EASE);
2122    };
2123    Ok(match s.trim() {
2124        "linear" => [0.0, 0.0, 1.0, 1.0],
2125        "ease" => Transition::EASE,
2126        "ease-in" => [0.42, 0.0, 1.0, 1.0],
2127        "ease-out" => [0.0, 0.0, 0.58, 1.0],
2128        "ease-in-out" => [0.42, 0.0, 0.58, 1.0],
2129        s => {
2130            let args = s
2131                .strip_prefix("cubic-bezier(")
2132                .and_then(|a| a.strip_suffix(')'))
2133                .ok_or(StyleError::InvalidValue)?;
2134            let n: Vec<f32> = args.split(',').filter_map(css::number).collect();
2135            let [a, b, c, d] = n.as_slice() else {
2136                return Err(StyleError::InvalidValue);
2137            };
2138            [*a, *b, *c, *d]
2139        }
2140    })
2141}
2142
2143/// `transitionProperty`: CSS property names, mapped to the groups that
2144/// transition natively.
2145fn transition_properties(s: &str) -> Option<TransitionProps> {
2146    let mut bits = 0;
2147    for name in s.split(',').map(str::trim) {
2148        bits |= match name {
2149            "all" => TransitionProps::ALL,
2150            "none" => 0,
2151            "color"
2152            | "colors"
2153            | "background-color"
2154            | "backgroundColor"
2155            | "border-color"
2156            | "borderColor"
2157            | "outline-color"
2158            | "text-decoration-color"
2159            | "fill"
2160            | "stroke"
2161            | "--tw-gradient-from"
2162            | "--tw-gradient-via"
2163            | "--tw-gradient-to" => TransitionProps::COLORS,
2164            "opacity" => TransitionProps::OPACITY,
2165            "transform" | "translate" | "scale" | "rotate" => TransitionProps::TRANSFORM,
2166            "box-shadow" | "boxShadow" | "shadow" => TransitionProps::SHADOW,
2167            "border-radius" | "borderRadius" | "border-width" | "borderWidth" => {
2168                TransitionProps::SHAPE
2169            }
2170            // Properties that do not animate natively.
2171            "filter" | "backdrop-filter" | "display" | "visibility" | "content-visibility"
2172            | "overlay" | "pointer-events" => 0,
2173            _ => return None,
2174        };
2175    }
2176    Some(TransitionProps(bits))
2177}
2178
2179fn grid_value<T>(
2180    v: StyleValue<'_>,
2181    parse: impl Fn(&str) -> Option<Vec<T>>,
2182) -> Result<Vec<T>, StyleError> {
2183    match keyword(v)? {
2184        None => Ok(Vec::new()),
2185        Some(s) => parse(s).ok_or(StyleError::InvalidValue),
2186    }
2187}
2188
2189fn grid_template(v: StyleValue<'_>) -> Result<grid::Template, StyleError> {
2190    match keyword(v)? {
2191        None => Ok((Vec::new(), Vec::new())),
2192        Some(s) => grid::template(s).ok_or(StyleError::InvalidValue),
2193    }
2194}
2195
2196fn grid_placement(v: StyleValue<'_>) -> Result<taffy::GridPlacement<String>, StyleError> {
2197    match v {
2198        StyleValue::Null => Ok(taffy::GridPlacement::Auto),
2199        StyleValue::Number(n) => {
2200            grid::placement(&(n as i32).to_string()).ok_or(StyleError::InvalidValue)
2201        }
2202        StyleValue::Str(s) => grid::placement(s).ok_or(StyleError::InvalidValue),
2203    }
2204}
2205
2206fn grid_line(v: StyleValue<'_>) -> Result<taffy::Line<taffy::GridPlacement<String>>, StyleError> {
2207    match v {
2208        StyleValue::Null => Ok(taffy::Line {
2209            start: taffy::GridPlacement::Auto,
2210            end: taffy::GridPlacement::Auto,
2211        }),
2212        StyleValue::Number(n) => {
2213            grid::line(&(n as i32).to_string()).ok_or(StyleError::InvalidValue)
2214        }
2215        StyleValue::Str(s) => grid::line(s).ok_or(StyleError::InvalidValue),
2216    }
2217}
2218
2219impl Style {
2220    /// Changes the effects lists (copying them if shared).
2221    pub fn edit_effects(&mut self, f: impl FnOnce(&mut Effects)) {
2222        let mut effects = self
2223            .view
2224            .effects
2225            .take()
2226            .map(|e| (*e).clone())
2227            .unwrap_or_default();
2228        f(&mut effects);
2229        self.view.effects = crate::effects::shared(effects);
2230    }
2231
2232    /// Sets the box shadows (top layer first).
2233    pub fn set_box_shadows(&mut self, shadows: Vec<BoxShadow>) {
2234        self.edit_effects(|e| e.box_shadows = shadows);
2235    }
2236
2237    /// Sets the gradient backgrounds (top layer first).
2238    pub fn set_background_images(&mut self, images: Vec<Gradient>) {
2239        self.edit_effects(|e| e.background_images = images);
2240    }
2241
2242    /// Sets the filters.
2243    pub fn set_filters(&mut self, filters: Vec<Filter>, backdrop: bool) {
2244        self.edit_effects(|e| {
2245            if backdrop {
2246                e.backdrop_filters = filters;
2247            } else {
2248                e.filters = filters;
2249            }
2250        });
2251    }
2252
2253    fn transition_mut(&mut self) -> &mut Transition {
2254        self.view.transition.get_or_insert(Transition {
2255            properties: TransitionProps(TransitionProps::ALL),
2256            duration: 0.0,
2257            delay: 0.0,
2258            easing: Transition::EASE,
2259        })
2260    }
2261
2262    /// Appends an entry to the `transform` list (`translateX`, `scale`,
2263    /// ...); rotations and skews are degrees (`"45deg"` strings are parsed
2264    /// by the caller). Returns the entry's index.
2265    pub fn push_transform(&mut self, key: &str, value: f32) -> Result<u8, StyleError> {
2266        let kind = TransformKind::parse(key).ok_or(StyleError::UnknownProperty)?;
2267        self.view
2268            .transform
2269            .push(kind, value)
2270            .ok_or(StyleError::InvalidValue)
2271    }
2272
2273    /// Sets `shadowOffset: { width, height }`; `None` restores the default.
2274    pub fn set_shadow_offset(&mut self, offset: Option<Point<Points>>) {
2275        let offset =
2276            offset.unwrap_or_else(|| point(Shadow::DEFAULT.offset_x, Shadow::DEFAULT.offset_y));
2277        self.view.shadow.offset_x = offset.x;
2278        self.view.shadow.offset_y = offset.y;
2279    }
2280
2281    /// Sets `textShadowOffset: { width, height }`.
2282    pub fn set_text_shadow_offset(&mut self, offset: Option<Point<Points>>) {
2283        self.text.shadow_offset = offset;
2284    }
2285
2286    fn set_border_width(
2287        &mut self,
2288        sides: &[usize],
2289        value: StyleValue<'_>,
2290    ) -> Result<(), StyleError> {
2291        let w = px(number(value, 0.0)?.max(0.0));
2292        for &side in sides {
2293            self.pending.border_widths[side] = w;
2294            if !self.pending.border_hidden {
2295                self.set_used_border_width(side, w);
2296            }
2297        }
2298        Ok(())
2299    }
2300
2301    /// The width side `side` lays out and draws with.
2302    fn set_used_border_width(&mut self, side: usize, w: Points) {
2303        *self.view.borders.width_mut(side) = w;
2304        let v = LengthPercentage::length(w.0);
2305        let b = &mut self.layout.border;
2306        match side {
2307            0 => b.top = v,
2308            1 => b.right = v,
2309            2 => b.bottom = v,
2310            _ => b.left = v,
2311        }
2312    }
2313
2314    fn set_logical_border_width(
2315        &mut self,
2316        i: usize,
2317        value: StyleValue<'_>,
2318    ) -> Result<(), StyleError> {
2319        let w = opt_points(value)?.map(|w| w.max(Points::ZERO));
2320        self.pending.border_logical[i] = w;
2321        if !self.pending.border_hidden {
2322            self.logical.border_width[i] = w;
2323        }
2324        Ok(())
2325    }
2326
2327    fn set_border_color(
2328        &mut self,
2329        sides: &[usize],
2330        value: StyleValue<'_>,
2331    ) -> Result<(), StyleError> {
2332        let c = color(value)?.unwrap_or(Color::BLACK);
2333        for &side in sides {
2334            self.view.borders.colors[side] = c;
2335        }
2336        Ok(())
2337    }
2338
2339    /// Sets color property `key` (`borderColor`, `outlineColor`) to `color`;
2340    /// other keys are left as they are.
2341    pub(crate) fn set_color(&mut self, key: StyleKey, color: Color) {
2342        match key {
2343            StyleKey::BorderColor => self.view.borders.colors = [color; 4],
2344            StyleKey::OutlineColor => self.view.outline.color = color,
2345            StyleKey::BackgroundColor => self.view.background_color = color,
2346            StyleKey::BorderTopColor => self.view.borders.colors[0] = color,
2347            StyleKey::BorderRightColor => self.view.borders.colors[1] = color,
2348            StyleKey::BorderBottomColor => self.view.borders.colors[2] = color,
2349            StyleKey::BorderLeftColor => self.view.borders.colors[3] = color,
2350            StyleKey::BorderStartColor => self.logical.border_color[0] = Some(color),
2351            StyleKey::BorderEndColor => self.logical.border_color[1] = Some(color),
2352            StyleKey::TextDecorationColor => self.text.decoration_color = Some(color),
2353            _ => debug_assert!(false, "set_color({key:?})"),
2354        }
2355    }
2356
2357    /// Sets one property using its React Native name.
2358    pub fn set(&mut self, key: &str, value: StyleValue<'_>) -> Result<(), StyleError> {
2359        self.set_key(
2360            StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?,
2361            value,
2362        )
2363    }
2364
2365    /// Sets one property.
2366    pub fn set_key(&mut self, key: StyleKey, value: StyleValue<'_>) -> Result<(), StyleError> {
2367        let l = &mut self.layout;
2368        match key {
2369            // Layout
2370            StyleKey::Display => {
2371                l.display = match keyword(value)? {
2372                    None | Some("flex") => Display::Flex,
2373                    Some("grid") => Display::Grid,
2374                    Some("block") => Display::Block,
2375                    Some("flow-root") => Display::FlowRoot,
2376                    Some("none") => Display::None,
2377                    Some(_) => return Err(StyleError::InvalidValue),
2378                }
2379            }
2380            StyleKey::BoxSizing => {
2381                l.box_sizing = match keyword(value)? {
2382                    None | Some("border-box") => taffy::BoxSizing::BorderBox,
2383                    Some("content-box") => taffy::BoxSizing::ContentBox,
2384                    _ => return Err(StyleError::InvalidValue),
2385                };
2386            }
2387            StyleKey::Position => {
2388                let (position, fixed, sticky) = match keyword(value)? {
2389                    None | Some("relative") => (Position::Relative, false, false),
2390                    Some("absolute") => (Position::Absolute, false, false),
2391                    Some("fixed") => (Position::Fixed, true, false),
2392                    Some("static") => (Position::Static, false, false),
2393                    Some("sticky") => (Position::Relative, false, true),
2394                    Some(_) => return Err(StyleError::InvalidValue),
2395                };
2396                l.position = position;
2397                self.pending.fixed_position = fixed;
2398                self.pending.sticky_position = sticky;
2399            }
2400            StyleKey::FlexDirection => {
2401                l.flex_direction = match keyword(value)? {
2402                    None | Some("column") => FlexDirection::Column,
2403                    Some("row") => FlexDirection::Row,
2404                    Some("column-reverse") => FlexDirection::ColumnReverse,
2405                    Some("row-reverse") => FlexDirection::RowReverse,
2406                    Some(_) => return Err(StyleError::InvalidValue),
2407                }
2408            }
2409            StyleKey::FlexWrap => {
2410                l.flex_wrap = match keyword(value)? {
2411                    None | Some("nowrap") => FlexWrap::NoWrap,
2412                    Some("wrap") => FlexWrap::Wrap,
2413                    Some("wrap-reverse") => FlexWrap::WrapReverse,
2414                    Some(_) => return Err(StyleError::InvalidValue),
2415                }
2416            }
2417            StyleKey::Flex => {
2418                // React Native semantics, not the CSS shorthand.
2419                let f = number(value, 0.0)?;
2420                if f > 0.0 {
2421                    l.flex_grow = f;
2422                    l.flex_shrink = 1.0;
2423                    l.flex_basis = Dimension::length(0.0);
2424                } else if f < 0.0 {
2425                    l.flex_grow = 0.0;
2426                    l.flex_shrink = -f;
2427                    l.flex_basis = Dimension::auto();
2428                } else {
2429                    l.flex_grow = 0.0;
2430                    l.flex_shrink = 0.0;
2431                    l.flex_basis = Dimension::auto();
2432                }
2433            }
2434            StyleKey::FlexGrow => l.flex_grow = number(value, 0.0)?,
2435            StyleKey::FlexShrink => l.flex_shrink = number(value, 0.0)?,
2436            StyleKey::FlexBasis => l.flex_basis = dimension(value)?,
2437            StyleKey::JustifyContent => l.justify_content = align_content(value)?,
2438            StyleKey::AlignItems => {
2439                l.align_items = align_items(value)?.unwrap_or(AlignItems::STRETCH)
2440            }
2441            StyleKey::AlignSelf => {
2442                l.align_self = match value {
2443                    StyleValue::Str("auto") => None,
2444                    v => align_items(v)?,
2445                }
2446            }
2447            StyleKey::AlignContent => l.align_content = align_content(value)?,
2448            StyleKey::Width => l.size.width = dimension(value)?,
2449            StyleKey::Height => l.size.height = dimension(value)?,
2450            StyleKey::MinWidth => l.min_size.width = min_len(value)?,
2451            StyleKey::MinHeight => l.min_size.height = min_len(value)?,
2452            StyleKey::MaxWidth => l.max_size.width = Len::parse(value)?.lpa(),
2453            StyleKey::MaxHeight => l.max_size.height = Len::parse(value)?.lpa(),
2454            StyleKey::AspectRatio => l.aspect_ratio = opt_number(value)?,
2455            StyleKey::Top => l.inset.top = Len::parse(value)?.lpa(),
2456            StyleKey::Right => l.inset.right = Len::parse(value)?.lpa(),
2457            StyleKey::Bottom => l.inset.bottom = Len::parse(value)?.lpa(),
2458            StyleKey::Left => l.inset.left = Len::parse(value)?.lpa(),
2459            StyleKey::Margin => {
2460                let (v, e) = margin_edge(value)?;
2461                l.margin = taffy::Rect {
2462                    left: v,
2463                    right: v,
2464                    top: v,
2465                    bottom: v,
2466                };
2467                self.pending.env.margin = [e; 4];
2468            }
2469            StyleKey::MarginHorizontal => {
2470                let (v, e) = margin_edge(value)?;
2471                (l.margin.left, l.margin.right) = (v, v);
2472                (self.pending.env.margin[1], self.pending.env.margin[3]) = (e, e);
2473            }
2474            StyleKey::MarginVertical => {
2475                let (v, e) = margin_edge(value)?;
2476                (l.margin.top, l.margin.bottom) = (v, v);
2477                (self.pending.env.margin[0], self.pending.env.margin[2]) = (e, e);
2478            }
2479            StyleKey::MarginTop => (l.margin.top, self.pending.env.margin[0]) = margin_edge(value)?,
2480            StyleKey::MarginRight => {
2481                (l.margin.right, self.pending.env.margin[1]) = margin_edge(value)?
2482            }
2483            StyleKey::MarginBottom => {
2484                (l.margin.bottom, self.pending.env.margin[2]) = margin_edge(value)?
2485            }
2486            StyleKey::MarginLeft => {
2487                (l.margin.left, self.pending.env.margin[3]) = margin_edge(value)?
2488            }
2489            StyleKey::Padding => {
2490                let (v, e) = padding_edge(value)?;
2491                l.padding = taffy::Rect {
2492                    left: v,
2493                    right: v,
2494                    top: v,
2495                    bottom: v,
2496                };
2497                self.pending.env.padding = [e; 4];
2498            }
2499            StyleKey::PaddingHorizontal => {
2500                let (v, e) = padding_edge(value)?;
2501                (l.padding.left, l.padding.right) = (v, v);
2502                (self.pending.env.padding[1], self.pending.env.padding[3]) = (e, e);
2503            }
2504            StyleKey::PaddingVertical => {
2505                let (v, e) = padding_edge(value)?;
2506                (l.padding.top, l.padding.bottom) = (v, v);
2507                (self.pending.env.padding[0], self.pending.env.padding[2]) = (e, e);
2508            }
2509            StyleKey::PaddingTop => {
2510                (l.padding.top, self.pending.env.padding[0]) = padding_edge(value)?
2511            }
2512            StyleKey::PaddingRight => {
2513                (l.padding.right, self.pending.env.padding[1]) = padding_edge(value)?
2514            }
2515            StyleKey::PaddingBottom => {
2516                (l.padding.bottom, self.pending.env.padding[2]) = padding_edge(value)?
2517            }
2518            StyleKey::PaddingLeft => {
2519                (l.padding.left, self.pending.env.padding[3]) = padding_edge(value)?
2520            }
2521            StyleKey::Gap => {
2522                let v = lp_or_zero(value)?;
2523                l.gap = taffy::Size {
2524                    width: v,
2525                    height: v,
2526                };
2527            }
2528            StyleKey::RowGap => l.gap.height = lp_or_zero(value)?,
2529            StyleKey::ColumnGap => l.gap.width = lp_or_zero(value)?,
2530            StyleKey::BorderWidth => self.set_border_width(&[0, 1, 2, 3], value)?,
2531            StyleKey::BorderTopWidth => self.set_border_width(&[0], value)?,
2532            StyleKey::BorderRightWidth => self.set_border_width(&[1], value)?,
2533            StyleKey::BorderBottomWidth => self.set_border_width(&[2], value)?,
2534            StyleKey::BorderLeftWidth => self.set_border_width(&[3], value)?,
2535            StyleKey::ZIndex => self.z_index = number(value, 0.0)? as i32,
2536            StyleKey::VerticalAlign => {
2537                self.vertical_align = match keyword(value)? {
2538                    None => VerticalAlign::Baseline,
2539                    Some(k) => VerticalAlign::parse(k).ok_or(StyleError::InvalidValue)?,
2540                }
2541            }
2542            StyleKey::Direction => {
2543                self.direction = match keyword(value)? {
2544                    None | Some("inherit") => None,
2545                    Some("ltr") => Some(false),
2546                    Some("rtl") => Some(true),
2547                    Some(_) => return Err(StyleError::InvalidValue),
2548                }
2549            }
2550            StyleKey::MarginStart => self.logical.margin[0] = opt_lpa(value)?,
2551            StyleKey::MarginEnd => self.logical.margin[1] = opt_lpa(value)?,
2552            StyleKey::PaddingStart => self.logical.padding[0] = opt_lp(value)?,
2553            StyleKey::PaddingEnd => self.logical.padding[1] = opt_lp(value)?,
2554            StyleKey::Start => self.logical.inset[0] = opt_lpa(value)?,
2555            StyleKey::End => self.logical.inset[1] = opt_lpa(value)?,
2556            StyleKey::BorderStartWidth => self.set_logical_border_width(0, value)?,
2557            StyleKey::BorderEndWidth => self.set_logical_border_width(1, value)?,
2558            StyleKey::BorderStartColor => self.logical.border_color[0] = color(value)?,
2559            StyleKey::BorderEndColor => self.logical.border_color[1] = color(value)?,
2560            StyleKey::BorderTopStartRadius => self.logical.radius[0] = opt_points(value)?,
2561            StyleKey::BorderTopEndRadius => self.logical.radius[1] = opt_points(value)?,
2562            StyleKey::BorderBottomEndRadius => self.logical.radius[2] = opt_points(value)?,
2563            StyleKey::BorderBottomStartRadius => self.logical.radius[3] = opt_points(value)?,
2564
2565            // View
2566            StyleKey::BackgroundColor => {
2567                self.view.background_color = color(value)?.unwrap_or(Color::TRANSPARENT)
2568            }
2569            StyleKey::BorderRadius => self.view.border_radius = px(number(value, 0.0)?),
2570            StyleKey::BorderTopLeftRadius => self.view.corner_radius.top_left = opt_points(value)?,
2571            StyleKey::BorderTopRightRadius => {
2572                self.view.corner_radius.top_right = opt_points(value)?
2573            }
2574            StyleKey::BorderBottomRightRadius => {
2575                self.view.corner_radius.bottom_right = opt_points(value)?
2576            }
2577            StyleKey::BorderBottomLeftRadius => {
2578                self.view.corner_radius.bottom_left = opt_points(value)?
2579            }
2580            StyleKey::ShadowColor => {
2581                self.view.shadow.color = color(value)?.unwrap_or(Shadow::DEFAULT.color)
2582            }
2583            StyleKey::ShadowOpacity => {
2584                self.view.shadow.opacity = number(value, Shadow::DEFAULT.opacity)?.clamp(0.0, 1.0)
2585            }
2586            StyleKey::ShadowRadius => {
2587                self.view.shadow.radius = px(number(value, Shadow::DEFAULT.radius.0)?.max(0.0))
2588            }
2589            StyleKey::BorderColor => self.set_border_color(&[0, 1, 2, 3], value)?,
2590            StyleKey::BorderTopColor => self.set_border_color(&[0], value)?,
2591            StyleKey::BorderRightColor => self.set_border_color(&[1], value)?,
2592            StyleKey::BorderBottomColor => self.set_border_color(&[2], value)?,
2593            StyleKey::BorderLeftColor => self.set_border_color(&[3], value)?,
2594            StyleKey::BorderStyle => {
2595                // `none` (and `hidden`, the same outside tables) draws and
2596                // lays out no border whatever the widths, set before or
2597                // after it (CSS).
2598                let (style, hidden) = match keyword(value)? {
2599                    None | Some("solid") => (BorderStyle::Solid, false),
2600                    Some("dashed") => (BorderStyle::Dashed, false),
2601                    Some("dotted") => (BorderStyle::Dotted, false),
2602                    Some("none") | Some("hidden") => (BorderStyle::Solid, true),
2603                    Some(_) => return Err(StyleError::InvalidValue),
2604                };
2605                self.view.borders.style = style;
2606                if hidden != self.pending.border_hidden {
2607                    self.pending.border_hidden = hidden;
2608                    for side in 0..4 {
2609                        let w = if hidden {
2610                            Points::ZERO
2611                        } else {
2612                            self.pending.border_widths[side]
2613                        };
2614                        self.set_used_border_width(side, w);
2615                    }
2616                    self.logical.border_width = if hidden {
2617                        [None; 2]
2618                    } else {
2619                        self.pending.border_logical
2620                    };
2621                }
2622            }
2623            StyleKey::BorderCurve => {
2624                self.view.continuous_corners = match keyword(value)? {
2625                    None | Some("circular") => false,
2626                    Some("continuous") => true,
2627                    Some(_) => return Err(StyleError::InvalidValue),
2628                }
2629            }
2630            StyleKey::TintColor => self.view.tint_color = color(value)?,
2631            StyleKey::ObjectPosition => {
2632                self.view.object_position = match keyword(value)? {
2633                    None => ObjectPosition::CENTER,
2634                    Some(s) => ObjectPosition::parse(s).ok_or(StyleError::InvalidValue)?,
2635                }
2636            }
2637            StyleKey::BackfaceVisibility => {
2638                self.view.backface_hidden = match keyword(value)? {
2639                    None | Some("visible") => false,
2640                    Some("hidden") => true,
2641                    Some(_) => return Err(StyleError::InvalidValue),
2642                }
2643            }
2644            StyleKey::TransformOrigin => {
2645                self.view.transform_origin = match keyword(value)? {
2646                    None => TransformOrigin::CENTER,
2647                    Some(s) => TransformOrigin::parse(s).ok_or(StyleError::InvalidValue)?,
2648                }
2649            }
2650            StyleKey::Opacity => self.view.opacity = number(value, 1.0)?.clamp(0.0, 1.0),
2651            StyleKey::Overflow => {
2652                self.view.overflow_hidden = match keyword(value)? {
2653                    None | Some("visible") => false,
2654                    Some("hidden") => true,
2655                    Some(_) => return Err(StyleError::InvalidValue),
2656                }
2657            }
2658
2659            // Text
2660            StyleKey::Color => self.text.color = color(value)?,
2661            StyleKey::Fill => self.paint.fill = svg_paint(value)?,
2662            StyleKey::Stroke => self.paint.stroke = svg_paint(value)?,
2663            StyleKey::StrokeWidth => {
2664                self.paint.stroke_width = match value {
2665                    StyleValue::Null => None,
2666                    StyleValue::Number(n) if n >= 0.0 => Some(px(n)),
2667                    StyleValue::Str(s) => match css::length(s) {
2668                        Some(n) if n >= 0.0 => Some(px(n)),
2669                        _ => return Err(StyleError::InvalidValue),
2670                    },
2671                    StyleValue::Number(_) => return Err(StyleError::InvalidValue),
2672                }
2673            }
2674            StyleKey::StrokeDasharray => self.paint.stroke_dasharray = dasharray(value)?,
2675            StyleKey::FontSize => self.text.font_size = opt_points(value)?,
2676            StyleKey::FontWeight => self.text.font_weight = font_weight(value)?,
2677            StyleKey::LineHeight => {
2678                // Numbers are points (React Native); strings may be a
2679                // multiple of the font size (`"1.5"`, `"1.5em"`) or points.
2680                let (points, multiple, em) = match value {
2681                    StyleValue::Str(s)
2682                        if s.ends_with("px") || s.ends_with("pt") || s.ends_with("rem") =>
2683                    {
2684                        (
2685                            Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
2686                            None,
2687                            None,
2688                        )
2689                    }
2690                    StyleValue::Str(s) if s.ends_with('%') || s.ends_with("em") => {
2691                        let n = if let Some(n) = s.strip_suffix('%') {
2692                            css::number(n).map(|n| n / 100.0)
2693                        } else {
2694                            css::number(s.strip_suffix("em").unwrap())
2695                        }
2696                        .filter(|n| *n >= 0.0)
2697                        .ok_or(StyleError::InvalidValue)?;
2698                        (None, None, Some(n))
2699                    }
2700                    StyleValue::Str(s) => {
2701                        let n = css::number(s)
2702                            .filter(|n| *n >= 0.0)
2703                            .ok_or(StyleError::InvalidValue)?;
2704                        (None, Some(n), None)
2705                    }
2706                    v => (opt_points(v)?, None, None),
2707                };
2708                self.text.line_height = points;
2709                self.text.line_height_multiple = multiple;
2710                self.text.line_height_em = em;
2711            }
2712            StyleKey::FontFamily => {
2713                self.text.font_family = keyword(value)?.map(|name| FontFamily::new(name.trim()))
2714            }
2715            StyleKey::FontStyle => {
2716                self.text.italic = match keyword(value)? {
2717                    None => None,
2718                    Some("normal") => Some(false),
2719                    Some("italic") => Some(true),
2720                    Some(_) => return Err(StyleError::InvalidValue),
2721                }
2722            }
2723            StyleKey::LetterSpacing => {
2724                let (points, em) = match value {
2725                    StyleValue::Str(s) if s.ends_with("em") && !s.ends_with("rem") => {
2726                        let n = css::number(&s[..s.len() - 2]).ok_or(StyleError::InvalidValue)?;
2727                        (None, Some(n))
2728                    }
2729                    StyleValue::Str(s) => (
2730                        Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
2731                        None,
2732                    ),
2733                    v => (opt_points(v)?, None),
2734                };
2735                self.text.letter_spacing = points;
2736                self.text.letter_spacing_em = em;
2737            }
2738            StyleKey::TextDecorationLine => {
2739                self.text.decoration = match keyword(value)? {
2740                    None => None,
2741                    Some(words) => {
2742                        let mut d = TextDecoration::default();
2743                        for word in words.split_whitespace() {
2744                            match word {
2745                                "none" => {}
2746                                "underline" => d.underline = true,
2747                                "line-through" => d.line_through = true,
2748                                _ => return Err(StyleError::InvalidValue),
2749                            }
2750                        }
2751                        Some(d)
2752                    }
2753                }
2754            }
2755            StyleKey::TextDecorationColor => self.text.decoration_color = color(value)?,
2756            StyleKey::PlaceholderColor => self.text.placeholder_color = color(value)?,
2757            StyleKey::SelectionColor => self.text.selection_color = color(value)?,
2758            StyleKey::TextAlignVertical => {
2759                self.text.align_vertical = match keyword(value)? {
2760                    None => None,
2761                    Some("auto" | "top") => Some(percentage(0.0)),
2762                    Some("center") => Some(percentage(0.5)),
2763                    Some("bottom") => Some(percentage(1.0)),
2764                    Some(_) => return Err(StyleError::InvalidValue),
2765                }
2766            }
2767            StyleKey::WritingDirection => {
2768                self.text.writing_direction = match keyword(value)? {
2769                    None | Some("auto") => None,
2770                    Some("ltr") => Some(false),
2771                    Some("rtl") => Some(true),
2772                    Some(_) => return Err(StyleError::InvalidValue),
2773                }
2774            }
2775            StyleKey::FontVariant => {
2776                self.text.font_variant = match keyword(value)? {
2777                    None => None,
2778                    Some(s) => Some(FontVariant::parse(s).ok_or(StyleError::InvalidValue)?),
2779                }
2780            }
2781            StyleKey::TextShadowColor => self.text.shadow_color = color(value)?,
2782            StyleKey::TextShadowRadius => self.text.shadow_radius = opt_points(value)?,
2783            StyleKey::TextTransform => {
2784                self.text.transform = match keyword(value)? {
2785                    None => None,
2786                    Some("none") => Some(TextTransform::None),
2787                    Some("uppercase") => Some(TextTransform::Uppercase),
2788                    Some("lowercase") => Some(TextTransform::Lowercase),
2789                    Some("capitalize") => Some(TextTransform::Capitalize),
2790                    Some(_) => return Err(StyleError::InvalidValue),
2791                }
2792            }
2793            StyleKey::TextAlign => {
2794                self.text.text_align_physical = false;
2795                self.text.text_align = match keyword(value)? {
2796                    None => None,
2797                    Some("auto") => Some(TextAlign::Auto),
2798                    Some("left") => Some(TextAlign::Left),
2799                    Some("center") => Some(TextAlign::Center),
2800                    Some("right") => Some(TextAlign::Right),
2801                    Some("justify") => Some(TextAlign::Justify),
2802                    Some(_) => return Err(StyleError::InvalidValue),
2803                }
2804            }
2805
2806            // Effects
2807            StyleKey::BoxShadow => {
2808                let list = match keyword(value)? {
2809                    None => Vec::new(),
2810                    Some(s) => css::box_shadows(s).ok_or(StyleError::InvalidValue)?,
2811                };
2812                self.edit_effects(|e| e.box_shadows = list);
2813            }
2814            StyleKey::BackgroundImage => {
2815                let list = match keyword(value)? {
2816                    None => Vec::new(),
2817                    Some(s) => css::gradients(s).ok_or(StyleError::InvalidValue)?,
2818                };
2819                self.edit_effects(|e| e.background_images = list);
2820            }
2821            StyleKey::MaskImage => {
2822                let list = match keyword(value)? {
2823                    None => Vec::new(),
2824                    Some("none") => Vec::new(),
2825                    Some(s) => css::gradients(s).ok_or(StyleError::InvalidValue)?,
2826                };
2827                self.edit_effects(|e| e.mask_images = list);
2828            }
2829            StyleKey::Filter => {
2830                let list = match keyword(value)? {
2831                    None => Vec::new(),
2832                    Some(s) => css::filters(s).ok_or(StyleError::InvalidValue)?,
2833                };
2834                self.edit_effects(|e| e.filters = list);
2835            }
2836            StyleKey::BackdropFilter => {
2837                let list = match keyword(value)? {
2838                    None => Vec::new(),
2839                    Some(s) => css::filters(s).ok_or(StyleError::InvalidValue)?,
2840                };
2841                self.edit_effects(|e| e.backdrop_filters = list);
2842            }
2843            StyleKey::GlassEffect => {
2844                self.view.glass_effect = match keyword(value)? {
2845                    None => GlassEffect::None,
2846                    Some(s) => GlassEffect::parse(s).ok_or(StyleError::InvalidValue)?,
2847                }
2848            }
2849            StyleKey::MixBlendMode => {
2850                self.view.blend_mode = match keyword(value)? {
2851                    None => BlendMode::Normal,
2852                    Some(s) => BlendMode::parse(s).ok_or(StyleError::InvalidValue)?,
2853                }
2854            }
2855            StyleKey::OutlineWidth => {
2856                let width = px(length_value(value, 0.0)?.max(0.0));
2857                self.pending.outline_width = width;
2858                if !self.pending.outline_hidden {
2859                    self.view.outline.width = width;
2860                }
2861            }
2862            StyleKey::OutlineColor => {
2863                self.view.outline.color = color(value)?.unwrap_or(Outline::NONE.color)
2864            }
2865            StyleKey::OutlineOffset => self.view.outline.offset = px(length_value(value, 0.0)?),
2866            StyleKey::OutlineStyle => {
2867                // `none` draws no outline whatever the width, set before
2868                // or after it (CSS).
2869                let (style, hidden) = match keyword(value)? {
2870                    None | Some("solid") => (BorderStyle::Solid, false),
2871                    Some("dashed") => (BorderStyle::Dashed, false),
2872                    Some("dotted") => (BorderStyle::Dotted, false),
2873                    Some("none") | Some("hidden") => (BorderStyle::Solid, true),
2874                    Some(_) => return Err(StyleError::InvalidValue),
2875                };
2876                self.view.outline.style = style;
2877                self.pending.outline_hidden = hidden;
2878                self.view.outline.width = if hidden {
2879                    Points::ZERO
2880                } else {
2881                    self.pending.outline_width
2882                };
2883            }
2884            StyleKey::Visibility => {
2885                self.view.hidden = match keyword(value)? {
2886                    None | Some("visible") => false,
2887                    Some("hidden") | Some("collapse") => true,
2888                    Some(_) => return Err(StyleError::InvalidValue),
2889                }
2890            }
2891            StyleKey::Cursor => {
2892                self.view.cursor = match keyword(value)? {
2893                    None => Cursor::Auto,
2894                    Some(s) => Cursor::parse(s).ok_or(StyleError::InvalidValue)?,
2895                }
2896            }
2897            StyleKey::TransitionProperty => {
2898                let props = match keyword(value)? {
2899                    None => TransitionProps(TransitionProps::ALL),
2900                    Some(s) => transition_properties(s).ok_or(StyleError::InvalidValue)?,
2901                };
2902                self.transition_mut().properties = props;
2903            }
2904            StyleKey::TransitionDuration => {
2905                let ms = duration(value)?;
2906                self.transition_mut().duration = ms;
2907            }
2908            StyleKey::TransitionDelay => {
2909                let ms = duration(value)?;
2910                self.transition_mut().delay = ms;
2911            }
2912            StyleKey::TransitionTimingFunction => {
2913                let easing = timing_function(value)?;
2914                self.transition_mut().easing = easing;
2915            }
2916            StyleKey::AnimationName => {
2917                let keyframes = match keyword(value)? {
2918                    None | Some("none") => None,
2919                    Some("spin") => Some(Keyframes::Spin),
2920                    Some("ping") => Some(Keyframes::Ping),
2921                    Some("pulse") => Some(Keyframes::Pulse),
2922                    Some("bounce") => Some(Keyframes::Bounce),
2923                    Some(_) => return Err(StyleError::InvalidValue),
2924                };
2925                // An animation already running (a class's) keeps its
2926                // values; a new one takes those set before its name.
2927                let pending = self.pending;
2928                self.view.animation = keyframes.map(|keyframes| {
2929                    let base = self
2930                        .view
2931                        .animation
2932                        .unwrap_or_else(|| pending.animation(KeyframeAnimation::new(keyframes)));
2933                    KeyframeAnimation { keyframes, ..base }
2934                });
2935            }
2936            StyleKey::AnimationDuration => {
2937                let ms = duration(value)?;
2938                self.pending.animation_duration = Some(ms);
2939                if let Some(a) = self.view.animation.as_mut() {
2940                    a.duration = ms;
2941                }
2942            }
2943            StyleKey::AnimationDelay => {
2944                let ms = duration(value)?;
2945                self.pending.animation_delay = Some(ms);
2946                if let Some(a) = self.view.animation.as_mut() {
2947                    a.delay = ms;
2948                }
2949            }
2950            StyleKey::AnimationTimingFunction => {
2951                let easing = timing_function(value)?;
2952                self.pending.animation_easing = Some(easing);
2953                if let Some(a) = self.view.animation.as_mut() {
2954                    a.easing = easing;
2955                }
2956            }
2957            StyleKey::AnimationIterationCount => {
2958                let count = match value {
2959                    StyleValue::Str("infinite") | StyleValue::Null => None,
2960                    v => Some(number(v, 1.0)?.max(0.0) as u32),
2961                };
2962                self.pending.animation_iterations = Some(count);
2963                if let Some(a) = self.view.animation.as_mut() {
2964                    a.iterations = count;
2965                }
2966            }
2967            StyleKey::TextDecorationStyle => {
2968                self.text.decoration_style = match keyword(value)? {
2969                    None => None,
2970                    Some("solid") => Some(DecorationStyle::Solid),
2971                    Some("double") => Some(DecorationStyle::Double),
2972                    Some("dotted") => Some(DecorationStyle::Dotted),
2973                    Some("dashed") => Some(DecorationStyle::Dashed),
2974                    Some("wavy") => Some(DecorationStyle::Wavy),
2975                    Some(_) => return Err(StyleError::InvalidValue),
2976                }
2977            }
2978            StyleKey::TextDecorationThickness => {
2979                self.text.decoration_thickness = match value {
2980                    StyleValue::Null | StyleValue::Str("auto") | StyleValue::Str("from-font") => {
2981                        None
2982                    }
2983                    v => Some(px(length_value(v, 1.0)?.max(0.0))),
2984                }
2985            }
2986            StyleKey::TextUnderlineOffset => {
2987                self.text.underline_offset = match value {
2988                    StyleValue::Null | StyleValue::Str("auto") => None,
2989                    v => Some(px(length_value(v, 0.0)?)),
2990                }
2991            }
2992
2993            // Grid
2994            StyleKey::GridTemplateColumns => {
2995                (l.grid_template_columns, l.grid_template_column_names) = grid_template(value)?;
2996            }
2997            StyleKey::GridTemplateRows => {
2998                (l.grid_template_rows, l.grid_template_row_names) = grid_template(value)?;
2999            }
3000            StyleKey::GridAutoColumns => {
3001                l.grid_auto_columns = grid_value(value, grid::auto_tracks)?;
3002            }
3003            StyleKey::GridAutoRows => {
3004                l.grid_auto_rows = grid_value(value, grid::auto_tracks)?;
3005            }
3006            StyleKey::GridAutoFlow => {
3007                l.grid_auto_flow = match keyword(value)? {
3008                    None => taffy::GridAutoFlow::Row,
3009                    Some(s) => grid::auto_flow(s).ok_or(StyleError::InvalidValue)?,
3010                }
3011            }
3012            StyleKey::GridColumn => l.grid_column = grid_line(value)?,
3013            StyleKey::GridRow => l.grid_row = grid_line(value)?,
3014            StyleKey::GridColumnStart => l.grid_column.start = grid_placement(value)?,
3015            StyleKey::GridColumnEnd => l.grid_column.end = grid_placement(value)?,
3016            StyleKey::GridRowStart => l.grid_row.start = grid_placement(value)?,
3017            StyleKey::GridRowEnd => l.grid_row.end = grid_placement(value)?,
3018            StyleKey::JustifyItems => {
3019                l.justify_items = align_items(value)?.unwrap_or(AlignItems::STRETCH);
3020            }
3021            StyleKey::JustifySelf => {
3022                l.justify_self = match value {
3023                    StyleValue::Str("auto") => None,
3024                    v => align_items(v)?,
3025                }
3026            }
3027        }
3028        Ok(())
3029    }
3030}
3031
3032#[cfg(test)]
3033mod tests {
3034    use super::*;
3035    use crate::geometry::{relative, size};
3036
3037    /// `fill`, `stroke`, `strokeWidth` and `strokeDasharray` take what CSS
3038    /// takes for them.
3039    #[test]
3040    fn svg_paint_properties() {
3041        let mut s = Style::default();
3042        s.set("fill", StyleValue::Str("#ff0000")).unwrap();
3043        s.set("stroke", StyleValue::Str("currentColor")).unwrap();
3044        s.set("strokeWidth", StyleValue::Str("2px")).unwrap();
3045        s.set("strokeDasharray", StyleValue::Str("4, 2 1")).unwrap();
3046        assert_eq!(s.paint.fill, Some(SvgPaint::Color(Color(0xff00_00ff))));
3047        assert_eq!(s.paint.stroke, Some(SvgPaint::CurrentColor));
3048        assert_eq!(s.paint.stroke_width, Some(px(2.0)));
3049        assert_eq!(
3050            s.paint.stroke_dasharray.as_deref(),
3051            Some(&[px(4.0), px(2.0), px(1.0)][..])
3052        );
3053        s.set("strokeDasharray", StyleValue::Number(3.0)).unwrap();
3054        assert_eq!(s.paint.stroke_dasharray.as_deref(), Some(&[px(3.0)][..]));
3055        // `none`, and dashes that add up to nothing: a solid line.
3056        for none in ["none", "0 0"] {
3057            s.set("strokeDasharray", StyleValue::Str(none)).unwrap();
3058            assert_eq!(s.paint.stroke_dasharray.as_deref(), Some(&[][..]));
3059        }
3060        s.set("fill", StyleValue::Str("none")).unwrap();
3061        assert_eq!(s.paint.fill, Some(SvgPaint::None));
3062        // Negative lengths are invalid, as in CSS.
3063        assert!(s.set("strokeWidth", StyleValue::Number(-1.0)).is_err());
3064        assert!(s.set("strokeDasharray", StyleValue::Str("4 -2")).is_err());
3065        assert!(s.set("fill", StyleValue::Str("nope")).is_err());
3066        s.set("stroke", StyleValue::Null).unwrap();
3067        assert_eq!(s.paint.stroke, None);
3068    }
3069
3070    #[test]
3071    fn parse_colors() {
3072        assert_eq!(Color::parse("#fff"), Some(Color(0xffff_ffff)));
3073        assert_eq!(Color::parse("#f008"), Some(Color(0xff00_0088)));
3074        assert_eq!(Color::parse("#123456"), Some(Color(0x1234_56ff)));
3075        assert_eq!(Color::parse("#12345678"), Some(Color(0x1234_5678)));
3076        assert_eq!(Color::parse("rgb(255, 0, 10)"), Some(Color(0xff00_0aff)));
3077        assert_eq!(Color::parse("rgba(0,0,0,0.5)"), Some(Color(0x0000_0080)));
3078        assert_eq!(Color::parse("white"), Some(Color(0xffff_ffff)));
3079        assert_eq!(Color::parse("#12"), None);
3080        assert_eq!(Color::parse("nope"), None);
3081    }
3082
3083    #[test]
3084    fn env_on_padding_and_margin() {
3085        use EnvVar::*;
3086        let mut s = Style::default();
3087        let k = StyleValue::Str;
3088        s.set("paddingBottom", k("env(keyboard-inset-height)"))
3089            .unwrap();
3090        assert_eq!(
3091            s.pending.env.padding,
3092            [None, None, Some(KeyboardInsetHeight), None]
3093        );
3094        assert_eq!(s.layout.padding.bottom, LengthPercentage::length(0.0));
3095        // `calc()` adds a length, on either side.
3096        s.set("paddingTop", k("calc(env(safe-area-inset-top) + 8px)"))
3097            .unwrap();
3098        assert_eq!(s.pending.env.padding[0], Some(SafeAreaInsetTop));
3099        assert_eq!(s.layout.padding.top, LengthPercentage::length(8.0));
3100        s.set("marginLeft", k("calc(0.5rem + env(safe-area-inset-left))"))
3101            .unwrap();
3102        assert_eq!(s.pending.env.margin[3], Some(SafeAreaInsetLeft));
3103        assert_eq!(s.layout.margin.left, LengthPercentageAuto::length(8.0));
3104        // Margins may go below zero.
3105        s.set("marginBottom", k("calc(env(keyboard-inset-height) + -4px)"))
3106            .unwrap();
3107        assert_eq!(s.layout.margin.bottom, LengthPercentageAuto::length(-4.0));
3108        // Shorthands set every edge they cover.
3109        s.set("paddingHorizontal", k("env(safe-area-inset-right)"))
3110            .unwrap();
3111        assert_eq!(s.pending.env.padding[1], Some(SafeAreaInsetRight));
3112        assert_eq!(s.pending.env.padding[3], Some(SafeAreaInsetRight));
3113        s.set("margin", k("env(safe-area-inset-top)")).unwrap();
3114        assert_eq!(s.pending.env.margin, [Some(SafeAreaInsetTop); 4]);
3115        // An unknown variable is its fallback.
3116        s.set("paddingRight", k("env(titlebar-area-x, 12px)"))
3117            .unwrap();
3118        assert_eq!(s.pending.env.padding[1], None);
3119        assert_eq!(s.layout.padding.right, LengthPercentage::length(12.0));
3120        // A known one ignores its fallback.
3121        s.set("paddingRight", k("env(safe-area-inset-right, 12px)"))
3122            .unwrap();
3123        assert_eq!(s.pending.env.padding[1], Some(SafeAreaInsetRight));
3124        assert_eq!(s.layout.padding.right, LengthPercentage::length(0.0));
3125        // A plain value or a reset drops the term.
3126        s.set("paddingTop", StyleValue::Number(4.0)).unwrap();
3127        s.set("paddingBottom", StyleValue::Null).unwrap();
3128        s.set("margin", StyleValue::Null).unwrap();
3129        assert_eq!(s.pending.env.padding[0], None);
3130        assert_eq!(s.pending.env.padding[2], None);
3131        assert_eq!(s.pending.env.margin, [None; 4]);
3132        // Anything else is rejected.
3133        for v in [
3134            "env(titlebar-area-x)",
3135            "env(safe-area-inset-top) + 8px",
3136            "calc(env(safe-area-inset-top)+8px)",
3137            "calc(env(safe-area-inset-top) - 8px)",
3138            "calc(env(safe-area-inset-top) + env(keyboard-inset-height))",
3139            "calc(env(safe-area-inset-top) + 10%)",
3140            "calc(env(safe-area-inset-top) + 1px + 2px)",
3141            "max(env(safe-area-inset-top), 8px)",
3142        ] {
3143            assert_eq!(
3144                s.set("paddingTop", k(v)),
3145                Err(StyleError::InvalidValue),
3146                "{v}"
3147            );
3148        }
3149        // Padding is never negative.
3150        assert_eq!(
3151            s.set("paddingTop", k("calc(env(safe-area-inset-top) + -8px)")),
3152            Err(StyleError::InvalidValue)
3153        );
3154        // Only padding and margin's physical edges take `env()`.
3155        for key in ["paddingStart", "marginEnd", "top", "width", "gap"] {
3156            assert!(s.set(key, k("env(safe-area-inset-top)")).is_err(), "{key}");
3157        }
3158    }
3159
3160    #[test]
3161    fn react_native_defaults() {
3162        let s = Style::default();
3163        assert_eq!(s.layout.flex_direction, FlexDirection::Column);
3164        assert_eq!(s.layout.flex_shrink, 0.0);
3165        assert_eq!(s.layout.position, Position::Relative);
3166        // Unset: `flex-start` once laid out outside grids.
3167        assert_eq!(s.layout.align_content, AlignContent::NORMAL);
3168        let mut layout = s.layout.clone();
3169        resolve_normal_alignment(&mut layout);
3170        assert_eq!(layout.align_content, AlignContent::FLEX_START);
3171        assert_eq!(s.layout.min_size.width, LengthPercentageAuto::length(0.0));
3172    }
3173
3174    #[test]
3175    fn css_alignment_keywords() {
3176        let mut s = Style::default();
3177        let k = StyleValue::Str;
3178        for key in ["alignItems", "alignSelf", "justifyItems", "justifySelf"] {
3179            for v in ["start", "end", "self-start", "self-end"] {
3180                s.set(key, k(v)).unwrap();
3181            }
3182        }
3183        assert_eq!(s.layout.justify_self, Some(AlignItems::SELF_END));
3184        for key in ["alignContent", "justifyContent"] {
3185            s.set(key, k("end")).unwrap();
3186            assert_eq!(s.set(key, k("self-end")), Err(StyleError::InvalidValue));
3187        }
3188        assert_eq!(s.layout.align_content, AlignContent::END);
3189        s.set("alignContent", k("normal")).unwrap();
3190        assert_eq!(s.layout.align_content, AlignContent::NORMAL);
3191        s.set("justifyContent", StyleValue::Null).unwrap();
3192        assert_eq!(s.layout.justify_content, AlignContent::NORMAL);
3193        // A grid keeps CSS's `normal`; other containers take `flex-start`.
3194        s.set("display", k("grid")).unwrap();
3195        let mut grid = s.layout.clone();
3196        resolve_normal_alignment(&mut grid);
3197        assert_eq!(grid.align_content, AlignContent::NORMAL);
3198        assert_eq!(
3199            s.set("gridTemplateColumns", k("[a] 40px [b")),
3200            Err(StyleError::InvalidValue)
3201        );
3202        s.set("gridTemplateRows", k("[a] 40px [b] 1fr")).unwrap();
3203        assert_eq!(s.layout.grid_template_row_names.len(), 3);
3204        s.set("gridTemplateRows", StyleValue::Null).unwrap();
3205        assert!(s.layout.grid_template_row_names.is_empty());
3206    }
3207
3208    #[test]
3209    fn transform_origins() {
3210        let p = |s| TransformOrigin::parse(s).unwrap();
3211        assert_eq!(p("top left").x, relative(0.0));
3212        assert_eq!(p("top left").y, relative(0.0));
3213        assert_eq!(p("bottom").y, relative(1.0));
3214        assert_eq!(p("bottom").x, relative(0.5));
3215        assert_eq!(p("10px 25%").x, DefiniteLength::from(px(10.0)));
3216        assert_eq!(p("10px 25%").y, relative(0.25));
3217        assert_eq!(p("right 5 3").z, px(3.0));
3218        assert_eq!(p("center top").y, relative(0.0));
3219        assert_eq!(
3220            p("0 0").offset(size(px(100.0), px(50.0))),
3221            (point(px(-50.0), px(-25.0)), Points::ZERO)
3222        );
3223        assert!(TransformOrigin::parse("sideways").is_none());
3224    }
3225
3226    #[test]
3227    fn font_variants() {
3228        let v = FontVariant::parse("small-caps tabular-nums").unwrap();
3229        assert_eq!(v.tags().collect::<Vec<_>>(), ["smcp", "tnum"]);
3230        assert!(FontVariant::parse("wide").is_none());
3231    }
3232
3233    #[test]
3234    fn flex_shorthand() {
3235        let mut s = Style::default();
3236        s.set("flex", StyleValue::Number(2.0)).unwrap();
3237        assert_eq!(s.layout.flex_grow, 2.0);
3238        assert_eq!(s.layout.flex_shrink, 1.0);
3239        assert_eq!(s.layout.flex_basis, Dimension::length(0.0));
3240    }
3241
3242    /// Every order of `decls`.
3243    fn permutations<T: Clone>(decls: &[T]) -> Vec<Vec<T>> {
3244        if decls.len() <= 1 {
3245            return vec![decls.to_vec()];
3246        }
3247        let mut out = Vec::new();
3248        for i in 0..decls.len() {
3249            let mut rest = decls.to_vec();
3250            let first = rest.remove(i);
3251            for mut tail in permutations(&rest) {
3252                tail.insert(0, first.clone());
3253                out.push(tail);
3254            }
3255        }
3256        out
3257    }
3258
3259    /// Checks the style of one style object with `decls` in every order:
3260    /// as recorded, and replayed from the patch (over classes).
3261    fn in_any_order(decls: &[(&str, StyleValue<'_>)], check: impl Fn(&Style)) {
3262        for order in permutations(decls) {
3263            let mut style = Style::default();
3264            let mut patch = StylePatch::default();
3265            for &(key, value) in &order {
3266                patch.set(&mut style, key, value).unwrap();
3267            }
3268            let keys: Vec<_> = order.iter().map(|(k, _)| *k).collect();
3269            println!("{keys:?}");
3270            check(&style);
3271            let mut replayed = Style::default();
3272            patch.apply(&mut replayed);
3273            check(&replayed);
3274        }
3275    }
3276
3277    #[test]
3278    fn border_longhands_override_the_shorthand_in_any_order() {
3279        use StyleValue::{Null, Number, Str};
3280        in_any_order(
3281            &[
3282                ("borderTopWidth", Number(5.0)),
3283                ("borderWidth", Number(2.0)),
3284                ("borderLeftColor", Str("red")),
3285                ("borderColor", Str("blue")),
3286            ],
3287            |s| {
3288                assert_eq!(
3289                    s.view.borders.widths.to_array().map(|w| w.0),
3290                    [5.0, 2.0, 2.0, 2.0]
3291                );
3292                assert_eq!(s.layout.border.top, LengthPercentage::length(5.0));
3293                assert_eq!(s.layout.border.left, LengthPercentage::length(2.0));
3294                let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
3295                assert_eq!(s.view.borders.colors, [blue, blue, blue, red]);
3296            },
3297        );
3298        // A null longhand is unset: the shorthand shows.
3299        in_any_order(
3300            &[("borderTopWidth", Null), ("borderWidth", Number(2.0))],
3301            |s| assert_eq!(s.view.borders.widths.to_array().map(|w| w.0), [2.0; 4]),
3302        );
3303        // Without its shorthand, null still resets the longhand (a class's).
3304        let mut s = Style::default();
3305        s.set("borderTopWidth", Number(4.0)).unwrap();
3306        StylePatch::default()
3307            .set(&mut s, "borderTopWidth", Null)
3308            .unwrap();
3309        assert_eq!(s.view.borders.widths.top, Points::ZERO);
3310    }
3311
3312    #[test]
3313    fn edge_longhands_override_their_shorthands_in_any_order() {
3314        use StyleValue::Number;
3315        let len = LengthPercentageAuto::length;
3316        in_any_order(
3317            &[
3318                ("marginTop", Number(1.0)),
3319                ("marginVertical", Number(2.0)),
3320                ("margin", Number(3.0)),
3321                ("marginLeft", Number(4.0)),
3322                ("marginHorizontal", Number(5.0)),
3323            ],
3324            |s| {
3325                let m = s.layout.margin;
3326                assert_eq!(
3327                    [m.top, m.bottom, m.left, m.right],
3328                    [len(1.0), len(2.0), len(4.0), len(5.0)]
3329                );
3330            },
3331        );
3332        let len = LengthPercentage::length;
3333        in_any_order(
3334            &[
3335                ("paddingRight", Number(1.0)),
3336                ("padding", Number(3.0)),
3337                ("paddingVertical", Number(2.0)),
3338            ],
3339            |s| {
3340                let p = s.layout.padding;
3341                assert_eq!(
3342                    [p.top, p.bottom, p.left, p.right],
3343                    [len(2.0), len(2.0), len(3.0), len(1.0)]
3344                );
3345            },
3346        );
3347        in_any_order(&[("rowGap", Number(4.0)), ("gap", Number(8.0))], |s| {
3348            assert_eq!(s.layout.gap.height, len(4.0));
3349            assert_eq!(s.layout.gap.width, len(8.0));
3350        });
3351    }
3352
3353    #[test]
3354    fn flex_and_grid_longhands_override_their_shorthands_in_any_order() {
3355        use StyleValue::{Number, Str};
3356        in_any_order(&[("flexGrow", Number(2.0)), ("flex", Number(1.0))], |s| {
3357            assert_eq!(s.layout.flex_grow, 2.0);
3358            assert_eq!(s.layout.flex_shrink, 1.0);
3359            assert_eq!(s.layout.flex_basis, Dimension::length(0.0));
3360        });
3361        in_any_order(
3362            &[
3363                ("gridColumnStart", Number(2.0)),
3364                ("gridColumn", Str("1 / 4")),
3365            ],
3366            |s| {
3367                assert_eq!(
3368                    Some(&s.layout.grid_column.start),
3369                    grid::placement("2").as_ref()
3370                );
3371                assert_eq!(
3372                    Some(&s.layout.grid_column.end),
3373                    grid::placement("4").as_ref()
3374                );
3375            },
3376        );
3377    }
3378
3379    #[test]
3380    fn outline_style_none_hides_the_outline_in_any_order() {
3381        use StyleValue::{Null, Number, Str};
3382        in_any_order(
3383            &[("outlineStyle", Str("none")), ("outlineWidth", Number(3.0))],
3384            |s| assert!(!s.view.outline.is_visible()),
3385        );
3386        in_any_order(
3387            &[
3388                ("outlineStyle", Str("dashed")),
3389                ("outlineWidth", Number(3.0)),
3390            ],
3391            |s| {
3392                assert_eq!(s.view.outline.width, px(3.0));
3393                assert_eq!(s.view.outline.style, BorderStyle::Dashed);
3394            },
3395        );
3396        // A later style (inline over classes) showing it again gets the
3397        // width back.
3398        let mut s = Style::default();
3399        s.set("outlineWidth", Number(3.0)).unwrap();
3400        s.set("outlineStyle", Str("none")).unwrap();
3401        s.set("outlineStyle", Null).unwrap();
3402        assert_eq!(s.view.outline.width, px(3.0));
3403    }
3404
3405    #[test]
3406    fn border_style_none_hides_the_border_in_any_order() {
3407        use StyleValue::{Null, Number, Str};
3408        for none in ["none", "hidden"] {
3409            in_any_order(
3410                &[
3411                    ("borderStyle", Str(none)),
3412                    ("borderWidth", Number(3.0)),
3413                    ("borderTopWidth", Number(4.0)),
3414                    ("borderStartWidth", Number(5.0)),
3415                ],
3416                |s| {
3417                    assert!(!s.view.borders.is_visible());
3418                    assert_eq!(s.view.borders.widths.to_array(), [Points::ZERO; 4]);
3419                    assert_eq!(s.layout.border.top, LengthPercentage::length(0.0));
3420                    assert_eq!(s.layout.border.left, LengthPercentage::length(0.0));
3421                    assert_eq!(s.logical.border_width, [None; 2]);
3422                },
3423            );
3424        }
3425        // A later style showing it again gets the widths back.
3426        let mut s = Style::default();
3427        s.set("borderWidth", Number(3.0)).unwrap();
3428        s.set("borderEndWidth", Number(1.0)).unwrap();
3429        s.set("borderStyle", Str("none")).unwrap();
3430        s.set("borderStyle", Str("dashed")).unwrap();
3431        assert_eq!(s.view.borders.widths.to_array(), [px(3.0); 4]);
3432        assert_eq!(s.layout.border.right, LengthPercentage::length(3.0));
3433        assert_eq!(s.logical.border_width, [None, Some(px(1.0))]);
3434        assert_eq!(s.view.borders.style, BorderStyle::Dashed);
3435        s.set("borderStyle", Str("hidden")).unwrap();
3436        s.set("borderStyle", Null).unwrap();
3437        assert_eq!(s.view.borders.widths.to_array(), [px(3.0); 4]);
3438    }
3439
3440    #[test]
3441    fn animation_keys_apply_in_any_order() {
3442        use StyleValue::{Number, Str};
3443        in_any_order(
3444            &[
3445                ("animationDuration", Number(500.0)),
3446                ("animationIterationCount", Number(2.0)),
3447                ("animationName", Str("spin")),
3448                ("animationDelay", Str("0.1s")),
3449                ("animationTimingFunction", Str("ease-in")),
3450            ],
3451            |s| {
3452                let a = s.view.animation.unwrap();
3453                assert_eq!(a.keyframes, Keyframes::Spin);
3454                assert_eq!(a.duration, 500.0);
3455                assert_eq!(a.iterations, Some(2));
3456                assert_eq!(a.delay, 100.0);
3457                assert_eq!(a.easing, [0.42, 0.0, 1.0, 1.0]);
3458            },
3459        );
3460        // Without a name nothing runs.
3461        in_any_order(&[("animationDuration", Number(500.0))], |s| {
3462            assert_eq!(s.view.animation, None)
3463        });
3464        // Over a running (class) animation, the values change it.
3465        let mut s = Style::default();
3466        s.set("animationName", Str("ping")).unwrap();
3467        s.set("animationDuration", Number(300.0)).unwrap();
3468        s.set("animationName", Str("spin")).unwrap();
3469        assert_eq!(s.view.animation.unwrap().duration, 300.0);
3470    }
3471
3472    #[test]
3473    fn transition_keys_apply_in_any_order() {
3474        use StyleValue::{Number, Str};
3475        in_any_order(
3476            &[
3477                ("transitionDuration", Number(300.0)),
3478                ("transitionDelay", Number(50.0)),
3479                ("transitionTimingFunction", Str("linear")),
3480                ("transitionProperty", Str("opacity")),
3481            ],
3482            |s| {
3483                let t = s.view.transition.unwrap();
3484                assert_eq!(t.properties, TransitionProps(TransitionProps::OPACITY));
3485                assert_eq!(t.duration, 300.0);
3486                assert_eq!(t.delay, 50.0);
3487                assert_eq!(t.easing, [0.0, 0.0, 1.0, 1.0]);
3488            },
3489        );
3490    }
3491
3492    #[test]
3493    fn corner_radii_override_the_shorthand_in_any_order() {
3494        let mut s = Style::default();
3495        s.set("borderTopLeftRadius", StyleValue::Number(4.0))
3496            .unwrap();
3497        s.set("borderRadius", StyleValue::Number(10.0)).unwrap();
3498        let r = s.view.radii();
3499        assert_eq!(r.to_array(), [px(4.0), px(10.0), px(10.0), px(10.0)]);
3500        assert_eq!(r.shared(), None);
3501        s.set("borderTopLeftRadius", StyleValue::Null).unwrap();
3502        assert_eq!(s.view.radii().shared(), Some(px(10.0)));
3503    }
3504
3505    #[test]
3506    fn shared_radius_ignores_square_corners() {
3507        let r = CornerRadii {
3508            top_left: px(12.0),
3509            top_right: px(12.0),
3510            ..CornerRadii::default()
3511        };
3512        assert_eq!(r.shared(), Some(px(12.0)));
3513        assert_eq!(CornerRadii::default().shared(), Some(px(0.0)));
3514        assert!(CornerRadii::default().is_zero());
3515    }
3516
3517    #[test]
3518    fn radii_fit_the_box() {
3519        // 100 + 300 on a 200 wide box: everything scales by 0.5.
3520        let r = CornerRadii {
3521            top_left: px(100.0),
3522            top_right: px(300.0),
3523            bottom_right: px(0.0),
3524            bottom_left: px(0.0),
3525            continuous: false,
3526        }
3527        .fit(size(px(200.0), px(1000.0)));
3528        assert_eq!(r.to_array(), [px(50.0), px(150.0), px(0.0), px(0.0)]);
3529        let fits = CornerRadii::all(px(10.0));
3530        assert_eq!(fits.fit(size(px(100.0), px(100.0))), fits);
3531        assert_eq!(fits.inset(px(4.0)), CornerRadii::all(px(6.0)));
3532        assert_eq!(fits.inset(px(40.0)), CornerRadii::all(px(0.0)));
3533    }
3534
3535    #[test]
3536    fn shadow_defaults_follow_react_native() {
3537        let mut s = Style::default();
3538        assert!(!s.view.shadow.is_visible());
3539        s.set("shadowOpacity", StyleValue::Number(0.3)).unwrap();
3540        s.set("shadowRadius", StyleValue::Number(8.0)).unwrap();
3541        s.set_shadow_offset(Some(point(px(0.0), px(4.0))));
3542        assert!(s.view.shadow.is_visible());
3543        assert_eq!(s.view.shadow.offset_y, px(4.0));
3544        s.set("shadowColor", StyleValue::Str("transparent"))
3545            .unwrap();
3546        assert!(!s.view.shadow.is_visible());
3547        s.set_shadow_offset(None);
3548        assert_eq!(s.view.shadow.offset_y, px(-3.0));
3549    }
3550
3551    #[test]
3552    fn text_styles_parse() {
3553        let mut s = Style::default();
3554        s.set("fontFamily", StyleValue::Str("Inter")).unwrap();
3555        s.set("fontStyle", StyleValue::Str("italic")).unwrap();
3556        s.set(
3557            "textDecorationLine",
3558            StyleValue::Str("underline line-through"),
3559        )
3560        .unwrap();
3561        s.set("textTransform", StyleValue::Str("capitalize"))
3562            .unwrap();
3563        assert_eq!(s.text.font_family, Some(FontFamily::new("Inter")));
3564        assert_eq!(&*s.text.font_family.unwrap().name(), "Inter");
3565        assert_eq!(s.text.italic, Some(true));
3566        assert_eq!(
3567            s.text.decoration,
3568            Some(TextDecoration {
3569                underline: true,
3570                line_through: true
3571            })
3572        );
3573        assert_eq!(
3574            TextTransform::Capitalize.apply("hello wörld-x  ünd"),
3575            "Hello Wörld-x  Ünd"
3576        );
3577        assert_eq!(
3578            s.set("fontStyle", StyleValue::Str("oblique")),
3579            Err(StyleError::InvalidValue)
3580        );
3581    }
3582
3583    #[test]
3584    fn mask_image_parses() {
3585        let mut s = Style::default();
3586        assert!(s.view.effects.is_none());
3587        s.set(
3588            "maskImage",
3589            StyleValue::Str("linear-gradient(black 70%, transparent)"),
3590        )
3591        .unwrap();
3592        let masks = &s.view.effects.as_ref().unwrap().mask_images;
3593        assert_eq!(masks.len(), 1);
3594        // `none`, and the null of a style that was taken off, both clear it.
3595        s.set("maskImage", StyleValue::Str("none")).unwrap();
3596        assert!(
3597            s.view
3598                .effects
3599                .as_ref()
3600                .is_none_or(|e| e.mask_images.is_empty())
3601        );
3602        s.set(
3603            "maskImage",
3604            StyleValue::Str("linear-gradient(black, transparent)"),
3605        )
3606        .unwrap();
3607        s.set("maskImage", StyleValue::Null).unwrap();
3608        assert!(
3609            s.view
3610                .effects
3611                .as_ref()
3612                .is_none_or(|e| e.mask_images.is_empty())
3613        );
3614        assert_eq!(
3615            s.set("maskImage", StyleValue::Str("url(a.png)")),
3616            Err(StyleError::InvalidValue)
3617        );
3618    }
3619
3620    #[test]
3621    fn glass_effect_parses() {
3622        let mut s = Style::default();
3623        assert_eq!(s.view.glass_effect, GlassEffect::None);
3624        s.set("glassEffect", StyleValue::Str("regular")).unwrap();
3625        assert_eq!(s.view.glass_effect, GlassEffect::Regular);
3626        s.set("glassEffect", StyleValue::Str("clear")).unwrap();
3627        assert_eq!(s.view.glass_effect, GlassEffect::Clear);
3628        // `none`, and the null of a style that was taken off, both clear it.
3629        s.set("glassEffect", StyleValue::Str("none")).unwrap();
3630        assert_eq!(s.view.glass_effect, GlassEffect::None);
3631        s.set("glassEffect", StyleValue::Str("clear")).unwrap();
3632        s.set("glassEffect", StyleValue::Null).unwrap();
3633        assert_eq!(s.view.glass_effect, GlassEffect::None);
3634        assert_eq!(
3635            s.set("glassEffect", StyleValue::Str("frosted")),
3636            Err(StyleError::InvalidValue)
3637        );
3638        assert_eq!(
3639            s.set("glassEffect", StyleValue::Number(1.0)),
3640            Err(StyleError::InvalidValue)
3641        );
3642    }
3643
3644    #[test]
3645    fn rejects_bad_values() {
3646        let mut s = Style::default();
3647        assert_eq!(
3648            s.set("width", StyleValue::Str("wide")),
3649            Err(StyleError::InvalidValue)
3650        );
3651        assert_eq!(
3652            s.set("nope", StyleValue::Number(1.0)),
3653            Err(StyleError::UnknownProperty)
3654        );
3655        s.set("width", StyleValue::Str("50%")).unwrap();
3656        assert_eq!(s.layout.size.width, Dimension::percent(0.5));
3657    }
3658}