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        BlendMode, BoxShadow, Cursor, Effects, Filter, Gradient, KeyframeAnimation, Keyframes,
12        Outline, Transition, TransitionProps,
13    },
14    geometry::{
15        AbsoluteLength, Corners, DefiniteLength, Edges, Percentage, Point, Points, REM_SIZE, Size,
16        percentage, point, px,
17    },
18    grid,
19    transform::{Transform, TransformKind},
20    ui::PropEnum,
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    /// `backfaceVisibility: "hidden"`: invisible when turned away.
499    pub backface_hidden: bool,
500    /// Layered / inset shadows, gradients and filters.
501    pub effects: Option<Arc<Effects>>,
502    /// `mixBlendMode`.
503    pub blend_mode: BlendMode,
504    /// `outline*`.
505    pub outline: Outline,
506    /// `visibility: "hidden"`: not drawn and not touchable, still laid out.
507    pub hidden: bool,
508    /// `cursor`.
509    pub cursor: Cursor,
510    /// `transition*`: style changes animate.
511    pub transition: Option<Transition>,
512    /// `animation*`: a keyframe animation runs.
513    pub animation: Option<KeyframeAnimation>,
514}
515
516/// `transformOrigin`: the point transforms rotate and scale around.
517#[derive(Debug, Clone, Copy, PartialEq)]
518pub struct TransformOrigin {
519    /// Horizontal position: from the left edge, or a fraction of the width.
520    pub x: DefiniteLength,
521    /// Vertical position: from the top edge, or a fraction of the height.
522    pub y: DefiniteLength,
523    /// Depth.
524    pub z: Points,
525}
526
527impl Default for TransformOrigin {
528    fn default() -> Self {
529        Self::CENTER
530    }
531}
532
533impl TransformOrigin {
534    /// The center (the default).
535    pub const CENTER: Self = Self {
536        x: DefiniteLength::Fraction(Percentage(0.5)),
537        y: DefiniteLength::Fraction(Percentage(0.5)),
538        z: Points::ZERO,
539    };
540
541    /// Offset of the origin from the center of a box of `size`, in the
542    /// plane, and its depth.
543    pub fn offset(&self, size: Size<Points>) -> (Point<Points>, Points) {
544        let at = |len: DefiniteLength, side: Points| {
545            len.to_points(AbsoluteLength::Points(side), REM_SIZE) - side / 2.0
546        };
547        (
548            point(at(self.x, size.width), at(self.y, size.height)),
549            self.z,
550        )
551    }
552
553    /// Parses CSS's syntax: one to three of keywords (`left`, `center`,
554    /// `right`, `top`, `bottom`), percentages and lengths (`10px` or a
555    /// bare number), the third being a depth.
556    pub fn parse(s: &str) -> Option<Self> {
557        let parts: Vec<&str> = s.split_whitespace().collect();
558        if parts.is_empty() || parts.len() > 3 {
559            return None;
560        }
561        let fraction = |f: f32| DefiniteLength::Fraction(percentage(f));
562        let len = |p: &str| -> Option<DefiniteLength> {
563            if let Some(pct) = p.strip_suffix('%') {
564                return pct.trim().parse::<f32>().ok().map(|v| fraction(v / 100.0));
565            }
566            p.strip_suffix("px")
567                .unwrap_or(p)
568                .parse::<f32>()
569                .ok()
570                .map(|v| px(v).into())
571        };
572        let mut x = None;
573        let mut y = None;
574        let mut free = Vec::new();
575        for &p in parts.iter().take(2) {
576            match p {
577                "left" => x = Some(fraction(0.0)),
578                "right" => x = Some(fraction(1.0)),
579                "top" => y = Some(fraction(0.0)),
580                "bottom" => y = Some(fraction(1.0)),
581                "center" => free.push(fraction(0.5)),
582                p => free.push(len(p)?),
583            }
584        }
585        // Unnamed values fill x, then y.
586        for v in free {
587            if x.is_none() {
588                x = Some(v);
589            } else if y.is_none() {
590                y = Some(v);
591            } else {
592                return None;
593            }
594        }
595        let z = match parts.get(2) {
596            Some(p) => px(p.strip_suffix("px").unwrap_or(p).parse::<f32>().ok()?),
597            None => Points::ZERO,
598        };
599        Some(Self {
600            x: x.unwrap_or(fraction(0.5)),
601            y: y.unwrap_or(fraction(0.5)),
602            z,
603        })
604    }
605}
606
607/// `fontVariant`: OpenType features, as bits.
608#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
609pub struct FontVariant(pub u8);
610
611impl FontVariant {
612    /// `small-caps`.
613    pub const SMALL_CAPS: u8 = 1;
614    /// `oldstyle-nums`.
615    pub const OLDSTYLE_NUMS: u8 = 2;
616    /// `lining-nums`.
617    pub const LINING_NUMS: u8 = 4;
618    /// `tabular-nums`.
619    pub const TABULAR_NUMS: u8 = 8;
620    /// `proportional-nums`.
621    pub const PROPORTIONAL_NUMS: u8 = 16;
622
623    /// Parses space-separated variant names.
624    pub fn parse(s: &str) -> Option<Self> {
625        let mut bits = 0;
626        for word in s.split_whitespace() {
627            bits |= match word {
628                "small-caps" => Self::SMALL_CAPS,
629                "oldstyle-nums" => Self::OLDSTYLE_NUMS,
630                "lining-nums" => Self::LINING_NUMS,
631                "tabular-nums" => Self::TABULAR_NUMS,
632                "proportional-nums" => Self::PROPORTIONAL_NUMS,
633                "normal" => 0,
634                _ => return None,
635            };
636        }
637        Some(Self(bits))
638    }
639
640    /// Whether `bit` is set.
641    pub fn has(self, bit: u8) -> bool {
642        self.0 & bit != 0
643    }
644
645    /// The OpenType feature tags.
646    pub fn tags(self) -> impl Iterator<Item = &'static str> {
647        [
648            (Self::SMALL_CAPS, "smcp"),
649            (Self::OLDSTYLE_NUMS, "onum"),
650            (Self::LINING_NUMS, "lnum"),
651            (Self::TABULAR_NUMS, "tnum"),
652            (Self::PROPORTIONAL_NUMS, "pnum"),
653        ]
654        .into_iter()
655        .filter(move |&(bit, _)| self.has(bit))
656        .map(|(_, tag)| tag)
657    }
658}
659
660impl ViewStyle {
661    /// Drops the gradient backgrounds, so the background color shows: what
662    /// press feedback and animated background colors do (a gradient is
663    /// drawn over the color and would hide them).
664    pub(crate) fn clear_background_images(&mut self) {
665        if let Some(e) = self
666            .effects
667            .as_deref()
668            .filter(|e| !e.background_images.is_empty())
669        {
670            let mut effects = e.clone();
671            effects.background_images.clear();
672            self.effects = crate::effects::shared(effects);
673        }
674    }
675
676    /// The radius of each corner (before fitting them to a size with
677    /// [`CornerRadii::fit`]).
678    pub fn radii(&self) -> CornerRadii {
679        let radii = self
680            .corner_radius
681            .map(|r| r.unwrap_or(self.border_radius).max(Points::ZERO));
682        CornerRadii {
683            continuous: self.continuous_corners,
684            ..CornerRadii::circular(radii)
685        }
686    }
687}
688
689impl Default for ViewStyle {
690    fn default() -> Self {
691        Self {
692            background_color: Color::TRANSPARENT,
693            border_radius: Points::ZERO,
694            corner_radius: Corners {
695                top_left: None,
696                top_right: None,
697                bottom_right: None,
698                bottom_left: None,
699            },
700            continuous_corners: false,
701            borders: Borders::NONE,
702            opacity: 1.0,
703            overflow_hidden: false,
704            shadow: Shadow::DEFAULT,
705            transform: Transform::IDENTITY,
706            tint_color: None,
707            elevation: Points::ZERO,
708            transform_origin: TransformOrigin::CENTER,
709            backface_hidden: false,
710            effects: None,
711            blend_mode: BlendMode::Normal,
712            outline: Outline::NONE,
713            hidden: false,
714            cursor: Cursor::Auto,
715            transition: None,
716            animation: None,
717        }
718    }
719}
720
721/// A shadow behind text (`textShadow*`).
722#[derive(Debug, Clone, Copy, PartialEq)]
723pub struct TextShadow {
724    /// Color.
725    pub color: Color,
726    /// Horizontal offset.
727    pub offset_x: Points,
728    /// Vertical offset.
729    pub offset_y: Points,
730    /// Blur radius.
731    pub radius: Points,
732}
733
734/// Text properties as written on a node; unset values are inherited from
735/// the enclosing text.
736#[derive(Debug, Clone, Copy, PartialEq, Default)]
737pub struct TextStyle {
738    /// Foreground color.
739    pub color: Option<Color>,
740    /// Font size.
741    pub font_size: Option<Points>,
742    /// Font weight, `100..=900`.
743    pub font_weight: Option<u16>,
744    /// Line height.
745    pub line_height: Option<Points>,
746    /// Block alignment (only meaningful on a text block).
747    pub text_align: Option<TextAlign>,
748    /// Font family; `None` inherits (the system font at the root).
749    pub font_family: Option<FontFamily>,
750    /// Italic (`fontStyle`).
751    pub italic: Option<bool>,
752    /// Extra space between characters.
753    pub letter_spacing: Option<Points>,
754    /// Extra space between characters in ems of this node's font size
755    /// (`"0.05em"`); overrides `letter_spacing` when set after it.
756    pub letter_spacing_em: Option<f32>,
757    /// Line height as a multiple of the font size (`"1.5"`, `"1.5em"`),
758    /// inherited as a multiple.
759    pub line_height_multiple: Option<f32>,
760    /// Underline / strikethrough.
761    pub decoration: Option<TextDecoration>,
762    /// `textDecorationStyle`.
763    pub decoration_style: Option<DecorationStyle>,
764    /// `textDecorationThickness`.
765    pub decoration_thickness: Option<Points>,
766    /// `textUnderlineOffset`: below the baseline.
767    pub underline_offset: Option<Points>,
768    /// Color of the decoration lines; the text color by default.
769    pub decoration_color: Option<Color>,
770    /// Case transform.
771    pub transform: Option<TextTransform>,
772    /// `textShadowColor`.
773    pub shadow_color: Option<Color>,
774    /// `textShadowOffset`.
775    pub shadow_offset: Option<Point<Points>>,
776    /// `textShadowRadius`.
777    pub shadow_radius: Option<Points>,
778    /// `fontVariant`.
779    pub font_variant: Option<FontVariant>,
780    /// `writingDirection`: right to left (`Some(true)`), left to right, or
781    /// the layout's direction (`None`, `auto`).
782    pub writing_direction: Option<bool>,
783    /// `textAlignVertical`: where text shorter than its box sits, 0% top
784    /// (`auto`, `top`), 50% `center`, 100% `bottom`.
785    pub align_vertical: Option<Percentage>,
786    /// `placeholderColor`: an input's placeholder (not inherited).
787    pub placeholder_color: Option<Color>,
788    /// `selectionColor`: an input's caret and selection, a selectable
789    /// text's selection highlight (not inherited).
790    pub selection_color: Option<Color>,
791}
792
793impl TextStyle {
794    /// The text shadow these properties describe, if any. Like NSShadow, an
795    /// offset or radius without a color uses black at a third of opacity.
796    pub fn shadow(&self) -> Option<TextShadow> {
797        if self.shadow_color.is_none()
798            && self.shadow_offset.is_none()
799            && self.shadow_radius.is_none()
800        {
801            return None;
802        }
803        let color = self.shadow_color.unwrap_or(Color(0x0000_0055));
804        if color.is_transparent() {
805            return None;
806        }
807        let offset = self.shadow_offset.unwrap_or_default();
808        Some(TextShadow {
809            color,
810            offset_x: offset.x,
811            offset_y: offset.y,
812            radius: self.shadow_radius.unwrap_or_default().max(Points::ZERO),
813        })
814    }
815}
816
817/// A complete node style, split by consumer.
818#[derive(Debug, Clone)]
819pub struct Style {
820    /// Layout properties, consumed by taffy.
821    pub layout: taffy::Style,
822    /// Visual properties of the native view.
823    pub view: ViewStyle,
824    /// Text properties.
825    pub text: TextStyle,
826    /// Visual properties driven by native animation nodes; they override
827    /// the static values while bound.
828    pub animated: Vec<(crate::animation::AnimationProp, crate::animation::NodeId)>,
829    /// `zIndex`: stacking order among siblings (higher on top).
830    pub z_index: i32,
831    /// `verticalAlign`: where the element sits in its line when it is
832    /// inside a `<Text>`.
833    pub vertical_align: VerticalAlign,
834    /// `direction`: right to left (`Some(true)`), left to right, or
835    /// inherited (`None`).
836    pub direction: Option<bool>,
837    /// Start / end properties, placed by the resolved direction.
838    pub logical: Logical,
839    /// Values that only show together with another property.
840    pub(crate) pending: Pending,
841}
842
843/// Values of properties that take effect only together with another one,
844/// kept so that the result does not depend on the order they are set in:
845/// `outlineWidth` under `outlineStyle: "none"` (no outline, as in CSS),
846/// `animationDuration` and the other `animation*` keys before
847/// `animationName`.
848#[derive(Clone, Copy, Default)]
849pub(crate) struct Pending {
850    /// `outlineWidth` as set.
851    outline_width: Points,
852    /// `outlineStyle: "none"` / `"hidden"`.
853    outline_hidden: bool,
854    /// `animationDuration`.
855    animation_duration: Option<f32>,
856    /// `animationDelay`.
857    animation_delay: Option<f32>,
858    /// `animationTimingFunction`.
859    animation_easing: Option<[f32; 4]>,
860    /// `animationIterationCount` (`None` inside: forever).
861    animation_iterations: Option<Option<u32>>,
862}
863
864/// Bookkeeping, not what the style shows: styles that look the same print
865/// the same (tests compare typed styles and classes so).
866impl std::fmt::Debug for Pending {
867    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868        f.write_str("Pending")
869    }
870}
871
872impl Pending {
873    /// `animation` with the `animation*` values set.
874    fn animation(&self, mut animation: KeyframeAnimation) -> KeyframeAnimation {
875        if let Some(ms) = self.animation_duration {
876            animation.duration = ms;
877        }
878        if let Some(ms) = self.animation_delay {
879            animation.delay = ms;
880        }
881        if let Some(easing) = self.animation_easing {
882            animation.easing = easing;
883        }
884        if let Some(count) = self.animation_iterations {
885            animation.iterations = count;
886        }
887        animation
888    }
889}
890
891/// Properties named by start and end (`marginStart`, `borderTopEndRadius`
892/// ...): left and right in left-to-right layouts, the other way around in
893/// right-to-left ones.
894#[derive(Debug, Clone, Copy, PartialEq, Default)]
895pub struct Logical {
896    /// `marginStart`, `marginEnd`.
897    pub margin: [Option<LengthPercentageAuto>; 2],
898    /// `paddingStart`, `paddingEnd`.
899    pub padding: [Option<LengthPercentage>; 2],
900    /// `start`, `end`.
901    pub inset: [Option<LengthPercentageAuto>; 2],
902    /// `borderStartWidth`, `borderEndWidth`.
903    pub border_width: [Option<Points>; 2],
904    /// `borderStartColor`, `borderEndColor`.
905    pub border_color: [Option<Color>; 2],
906    /// `borderTopStartRadius`, `borderTopEndRadius`,
907    /// `borderBottomEndRadius`, `borderBottomStartRadius`.
908    pub radius: [Option<Points>; 4],
909}
910
911impl Logical {
912    /// Whether no start / end property is set.
913    pub fn is_empty(&self) -> bool {
914        *self == Self::default()
915    }
916}
917
918fn set_side<T>(rect: &mut taffy::Rect<T>, left: bool, value: T) {
919    if left {
920        rect.left = value;
921    } else {
922        rect.right = value;
923    }
924}
925
926/// Swaps the left and right properties: in right-to-left layouts they
927/// mean start and end, as in React Native. An involution.
928pub(crate) fn swap_sides(layout: &mut taffy::Style, view: &mut ViewStyle) {
929    fn swap<T>(r: &mut taffy::Rect<T>) {
930        std::mem::swap(&mut r.left, &mut r.right);
931    }
932    swap(&mut layout.margin);
933    swap(&mut layout.padding);
934    swap(&mut layout.inset);
935    swap(&mut layout.border);
936    let (w, r) = (&mut view.borders.widths, &mut view.corner_radius);
937    std::mem::swap(&mut w.left, &mut w.right);
938    view.borders.colors.swap(1, 3);
939    std::mem::swap(&mut r.top_left, &mut r.top_right);
940    std::mem::swap(&mut r.bottom_left, &mut r.bottom_right);
941}
942
943/// Gives an unset `alignContent` (taffy's `normal`) its meaning for the
944/// node's display: React Native's `flex-start` for flex (and block)
945/// containers, where taffy's `normal` would stretch wrapped lines, and
946/// CSS's `normal` for grids, whose auto tracks then stretch to fill the
947/// container. (`justifyContent`'s `normal` is already `flex-start` in
948/// flex containers.)
949pub(crate) fn resolve_normal_alignment(layout: &mut taffy::Style) {
950    if layout.display != Display::Grid && layout.align_content == AlignContent::NORMAL {
951        layout.align_content = AlignContent::FLEX_START;
952    }
953}
954
955/// Lays a node out in direction `rtl`: swaps its left and right
956/// properties when right to left, then places the start / end ones.
957pub(crate) fn apply_direction(
958    layout: &mut taffy::Style,
959    view: &mut ViewStyle,
960    logical: &Logical,
961    rtl: bool,
962) {
963    layout.direction = if rtl {
964        taffy::Direction::Rtl
965    } else {
966        taffy::Direction::Ltr
967    };
968    if rtl {
969        swap_sides(layout, view);
970    }
971    if logical.is_empty() {
972        return;
973    }
974    // Start is the left side left to right.
975    for (i, left) in [!rtl, rtl].into_iter().enumerate() {
976        if let Some(v) = logical.margin[i] {
977            set_side(&mut layout.margin, left, v);
978        }
979        if let Some(v) = logical.padding[i] {
980            set_side(&mut layout.padding, left, v);
981        }
982        if let Some(v) = logical.inset[i] {
983            set_side(&mut layout.inset, left, v);
984        }
985        let side = if left { 3 } else { 1 };
986        if let Some(w) = logical.border_width[i] {
987            set_side(&mut layout.border, left, LengthPercentage::length(w.0));
988            *view.borders.width_mut(side) = w;
989        }
990        if let Some(c) = logical.border_color[i] {
991            view.borders.colors[side] = c;
992        }
993    }
994    // Corners: top start, top end, bottom end, bottom start.
995    let [top_start, top_end, bottom_end, bottom_start] = logical.radius;
996    let c = &mut view.corner_radius;
997    let (top_left, top_right, bottom_right, bottom_left) = if rtl {
998        (top_end, top_start, bottom_start, bottom_end)
999    } else {
1000        (top_start, top_end, bottom_end, bottom_start)
1001    };
1002    for (corner, r) in [
1003        (&mut c.top_left, top_left),
1004        (&mut c.top_right, top_right),
1005        (&mut c.bottom_right, bottom_right),
1006        (&mut c.bottom_left, bottom_left),
1007    ] {
1008        if r.is_some() {
1009            *corner = r;
1010        }
1011    }
1012}
1013
1014impl Default for Style {
1015    /// React Native defaults, which differ from CSS (and taffy) defaults.
1016    fn default() -> Self {
1017        let layout = taffy::Style {
1018            display: Display::Flex,
1019            position: Position::Relative,
1020            flex_direction: FlexDirection::Column,
1021            flex_shrink: 0.0,
1022            // Unset: `flex-start` (React Native) outside grids, CSS's
1023            // `normal` in grids (`resolve_normal_alignment`).
1024            align_content: AlignContent::NORMAL,
1025            // Yoga has no automatic minimum size (see `min_len`).
1026            min_size: taffy::Size {
1027                width: LengthPercentageAuto::length(0.0),
1028                height: LengthPercentageAuto::length(0.0),
1029            },
1030            ..taffy::Style::DEFAULT
1031        };
1032        Self {
1033            layout,
1034            view: ViewStyle::default(),
1035            text: TextStyle::default(),
1036            animated: Vec::new(),
1037            z_index: 0,
1038            vertical_align: VerticalAlign::Baseline,
1039            direction: None,
1040            logical: Logical::default(),
1041            pending: Pending::default(),
1042        }
1043    }
1044}
1045
1046/// Which TypeScript style interface a property belongs to (each extends
1047/// the one before: layout, then views, then text or images).
1048#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1049pub(crate) enum StyleGroup {
1050    Layout,
1051    View,
1052    Text,
1053    Image,
1054}
1055
1056/// A style property's TypeScript declaration (`js::style`).
1057#[derive(Debug, Clone, Copy)]
1058pub(crate) struct StyleType {
1059    pub(crate) name: &'static str,
1060    pub(crate) group: StyleGroup,
1061    pub(crate) ts: &'static str,
1062    pub(crate) doc: Option<&'static str>,
1063}
1064
1065/// The style properties the JS bridge decodes itself (objects and lists,
1066/// `crates/nsh-js/src/protocol.rs`), for the TypeScript declarations.
1067pub(crate) const OBJECT_STYLE_TYPES: &[StyleType] = &[
1068    StyleType {
1069        name: "transform",
1070        group: StyleGroup::View,
1071        ts: "TransformStep[]",
1072        doc: None,
1073    },
1074    StyleType {
1075        name: "shadowOffset",
1076        group: StyleGroup::View,
1077        ts: "{ width: number; height: number }",
1078        doc: Some("Default `{ width: 0, height: -3 }`, as in React Native."),
1079    },
1080    StyleType {
1081        name: "textShadowOffset",
1082        group: StyleGroup::Text,
1083        ts: "{ width: number; height: number }",
1084        doc: None,
1085    },
1086];
1087
1088macro_rules! style_keys {
1089    ($($key:ident = $name:literal: $group:ident $ts:literal $($doc:literal)?),* $(,)?) => {
1090        /// The style properties' TypeScript declarations, in order.
1091        pub(crate) const STYLE_TYPES: &[StyleType] = &[$(StyleType {
1092            name: $name,
1093            group: StyleGroup::$group,
1094            ts: $ts,
1095            doc: style_keys!(@doc $($doc)?),
1096        }),*];
1097
1098        /// A style property, by its React Native name.
1099        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1100        pub enum StyleKey {
1101            $(
1102                #[doc = concat!("`", $name, "`")]
1103                $key,
1104            )*
1105        }
1106
1107        impl StyleKey {
1108            /// The key named `name` (React Native's camel case).
1109            pub fn parse(name: &str) -> Option<StyleKey> {
1110                Some(match name {
1111                    $($name => StyleKey::$key,)*
1112                    _ => return None,
1113                })
1114            }
1115
1116            /// The React Native name.
1117            pub fn name(self) -> &'static str {
1118                match self {
1119                    $(StyleKey::$key => $name,)*
1120                }
1121            }
1122        }
1123    };
1124    (@doc) => { None };
1125    (@doc $doc:literal) => { Some($doc) };
1126}
1127
1128style_keys! {
1129    Display = "display": Layout "\"flex\" | \"grid\" | \"block\" | \"none\"",
1130    Position = "position": Layout "\"relative\" | \"absolute\"",
1131    FlexDirection = "flexDirection": Layout "\"row\" | \"column\" | \"row-reverse\" | \"column-reverse\"",
1132    FlexWrap = "flexWrap": Layout "\"wrap\" | \"nowrap\" | \"wrap-reverse\"",
1133    Flex = "flex": Layout "number",
1134    FlexGrow = "flexGrow": Layout "number",
1135    FlexShrink = "flexShrink": Layout "number",
1136    FlexBasis = "flexBasis": Layout "DimensionValue",
1137    JustifyContent = "justifyContent": Layout "Exclude<Distribute, \"stretch\"> | \"stretch\"",
1138    AlignItems = "alignItems": Layout "Align",
1139    AlignSelf = "alignSelf": Layout "Align | \"auto\"",
1140    AlignContent = "alignContent": Layout "Distribute",
1141    Width = "width": Layout "DimensionValue",
1142    Height = "height": Layout "DimensionValue",
1143    MinWidth = "minWidth": Layout "LengthValue",
1144    MinHeight = "minHeight": Layout "LengthValue",
1145    MaxWidth = "maxWidth": Layout "LengthValue",
1146    MaxHeight = "maxHeight": Layout "LengthValue",
1147    AspectRatio = "aspectRatio": Layout "number",
1148    Top = "top": Layout "DimensionValue",
1149    Right = "right": Layout "DimensionValue",
1150    Bottom = "bottom": Layout "DimensionValue",
1151    Left = "left": Layout "DimensionValue",
1152    Margin = "margin": Layout "DimensionValue",
1153    MarginHorizontal = "marginHorizontal": Layout "DimensionValue",
1154    MarginVertical = "marginVertical": Layout "DimensionValue",
1155    MarginTop = "marginTop": Layout "DimensionValue",
1156    MarginRight = "marginRight": Layout "DimensionValue",
1157    MarginBottom = "marginBottom": Layout "DimensionValue",
1158    MarginLeft = "marginLeft": Layout "DimensionValue",
1159    Padding = "padding": Layout "LengthValue",
1160    PaddingHorizontal = "paddingHorizontal": Layout "LengthValue",
1161    PaddingVertical = "paddingVertical": Layout "LengthValue",
1162    PaddingTop = "paddingTop": Layout "LengthValue",
1163    PaddingRight = "paddingRight": Layout "LengthValue",
1164    PaddingBottom = "paddingBottom": Layout "LengthValue",
1165    PaddingLeft = "paddingLeft": Layout "LengthValue",
1166    Gap = "gap": Layout "LengthValue",
1167    RowGap = "rowGap": Layout "LengthValue",
1168    ColumnGap = "columnGap": Layout "LengthValue",
1169    BorderWidth = "borderWidth": View "number",
1170    BorderTopWidth = "borderTopWidth": View "number",
1171    BorderRightWidth = "borderRightWidth": View "number",
1172    BorderBottomWidth = "borderBottomWidth": View "number",
1173    BorderLeftWidth = "borderLeftWidth": View "number",
1174    ZIndex = "zIndex": Layout "number" "Order among siblings (stable); also the native stacking order.",
1175    BoxShadow = "boxShadow": View "string" "CSS `box-shadow`: offsets, blur, spread and color, several separated by commas, `inset` for inner shadows.",
1176    BackgroundImage = "backgroundImage": View "string" "CSS gradients drawn over the background color: `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`, several separated by commas.",
1177    Filter = "filter": View "string" "CSS filters of the view and its content: `brightness()`, `contrast()`, `grayscale()`, `hue-rotate()`, `invert()`, `saturate()`, `sepia()`, `opacity()`, `blur()`, `drop-shadow()`.",
1178    BackdropFilter = "backdropFilter": View "string" "CSS filters of what is behind the view (`blur(10px)`).",
1179    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.",
1180    OutlineWidth = "outlineWidth": View "number" "A line outside the border that takes no space.",
1181    OutlineColor = "outlineColor": View "ColorValue",
1182    OutlineStyle = "outlineStyle": View "\"solid\" | \"double\" | \"dashed\" | \"dotted\" | \"none\" | \"hidden\"",
1183    OutlineOffset = "outlineOffset": View "number" "Distance from the border edge (negative: inside).",
1184    Visibility = "visibility": View "\"visible\" | \"hidden\" | \"collapse\"" "Hidden views keep their space.",
1185    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).",
1186    TransitionProperty = "transitionProperty": View "string" "The properties that animate when they change (`\"opacity, transform\"`, `\"all\"`, `\"colors\"`).",
1187    TransitionDuration = "transitionDuration": View "number | `${number}ms` | `${number}s`" "Milliseconds as a number, or `\"150ms\"` / `\"0.2s\"`.",
1188    TransitionDelay = "transitionDelay": View "number | `${number}ms` | `${number}s`",
1189    TransitionTimingFunction = "transitionTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
1190    AnimationName = "animationName": View "\"none\" | \"spin\" | \"ping\" | \"pulse\" | \"bounce\"" "A built-in keyframe animation, run natively.",
1191    AnimationDuration = "animationDuration": View "number | `${number}ms` | `${number}s`",
1192    AnimationDelay = "animationDelay": View "number | `${number}ms` | `${number}s`",
1193    AnimationTimingFunction = "animationTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
1194    AnimationIterationCount = "animationIterationCount": View "number | \"infinite\"",
1195    TextDecorationStyle = "textDecorationStyle": Text "\"solid\" | \"double\" | \"dotted\" | \"dashed\" | \"wavy\"",
1196    TextDecorationThickness = "textDecorationThickness": Text "number | \"auto\" | \"from-font\"",
1197    TextUnderlineOffset = "textUnderlineOffset": Text "number | \"auto\"",
1198    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]\"`).",
1199    GridTemplateRows = "gridTemplateRows": Layout "string",
1200    GridAutoColumns = "gridAutoColumns": Layout "string" "Tracks of implicitly created columns.",
1201    GridAutoRows = "gridAutoRows": Layout "string",
1202    GridAutoFlow = "gridAutoFlow": Layout "\"row\" | \"column\" | \"dense\" | \"row dense\" | \"column dense\"",
1203    GridColumn = "gridColumn": Layout "number | string" "`\"1 / 3\"`, `\"span 2\"`, a line number or name (`\"content-start / full-end\"`, `\"span col\"`).",
1204    GridColumnStart = "gridColumnStart": Layout "number | string",
1205    GridColumnEnd = "gridColumnEnd": Layout "number | string",
1206    GridRow = "gridRow": Layout "number | string",
1207    GridRowStart = "gridRowStart": Layout "number | string",
1208    GridRowEnd = "gridRowEnd": Layout "number | string",
1209    JustifyItems = "justifyItems": Layout "Align" "How grid items sit in their areas along the row.",
1210    JustifySelf = "justifySelf": Layout "Align | \"auto\"",
1211    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).",
1212    MarginStart = "marginStart": Layout "DimensionValue",
1213    MarginEnd = "marginEnd": Layout "DimensionValue",
1214    PaddingStart = "paddingStart": Layout "LengthValue",
1215    PaddingEnd = "paddingEnd": Layout "LengthValue",
1216    Start = "start": Layout "DimensionValue" "Left in left-to-right layouts, right in right-to-left ones.",
1217    End = "end": Layout "DimensionValue",
1218    BorderStartWidth = "borderStartWidth": View "number",
1219    BorderEndWidth = "borderEndWidth": View "number",
1220    BorderStartColor = "borderStartColor": View "ColorValue",
1221    BorderEndColor = "borderEndColor": View "ColorValue",
1222    BorderTopStartRadius = "borderTopStartRadius": View "number",
1223    BorderTopEndRadius = "borderTopEndRadius": View "number",
1224    BorderBottomEndRadius = "borderBottomEndRadius": View "number",
1225    BorderBottomStartRadius = "borderBottomStartRadius": View "number",
1226    BackgroundColor = "backgroundColor": View "ColorValue | AnimatedNode",
1227    BorderRadius = "borderRadius": View "number",
1228    BorderTopLeftRadius = "borderTopLeftRadius": View "number",
1229    BorderTopRightRadius = "borderTopRightRadius": View "number",
1230    BorderBottomRightRadius = "borderBottomRightRadius": View "number",
1231    BorderBottomLeftRadius = "borderBottomLeftRadius": View "number",
1232    ShadowColor = "shadowColor": View "ColorValue | AnimatedNode",
1233    ShadowOpacity = "shadowOpacity": View "number | AnimatedNode",
1234    ShadowRadius = "shadowRadius": View "number | AnimatedNode",
1235    BorderColor = "borderColor": View "ColorValue | AnimatedNode",
1236    BorderTopColor = "borderTopColor": View "ColorValue",
1237    BorderRightColor = "borderRightColor": View "ColorValue",
1238    BorderBottomColor = "borderBottomColor": View "ColorValue",
1239    BorderLeftColor = "borderLeftColor": View "ColorValue",
1240    BorderStyle = "borderStyle": View "\"solid\" | \"dashed\" | \"dotted\"",
1241    BorderCurve = "borderCurve": View "\"circular\" | \"continuous\"" "`continuous`: corners whose curvature eases into the edges (iOS app icons).",
1242    TintColor = "tintColor": Image "ColorValue" "Recolors a template image.",
1243    BackfaceVisibility = "backfaceVisibility": View "\"visible\" | \"hidden\"" "`\"hidden\"`: invisible while turned away (3D rotations).",
1244    TransformOrigin = "transformOrigin": View "string | (number | string)[]" "The point `transform` acts around: keywords, percentages and lengths (\"top left\", \"50% 0\", `[10, 20]`). Default the center.",
1245    Opacity = "opacity": View "number | AnimatedNode",
1246    Overflow = "overflow": View "\"visible\" | \"hidden\"",
1247    Color = "color": Text "ColorValue | AnimatedNode",
1248    FontSize = "fontSize": Text "number",
1249    FontWeight = "fontWeight": Text "\"normal\" | \"bold\" | number | `${number}`" "`\"normal\"` (400), `\"bold\"` (700) or 100–900.",
1250    LineHeight = "lineHeight": Text "number",
1251    FontFamily = "fontFamily": Text "string" "A system family or the name an imported font (`import Inter from \"./Inter.ttf\"`) evaluates to.",
1252    FontStyle = "fontStyle": Text "\"normal\" | \"italic\"",
1253    LetterSpacing = "letterSpacing": Text "number",
1254    TextDecorationLine = "textDecorationLine": Text "\"none\" | \"underline\" | \"line-through\" | \"underline line-through\"",
1255    TextDecorationColor = "textDecorationColor": Text "ColorValue",
1256    WritingDirection = "writingDirection": Text "\"auto\" | \"ltr\" | \"rtl\"" "Base direction of the text; `auto` takes it from the content.",
1257    TextAlignVertical = "textAlignVertical": Text "\"auto\" | \"top\" | \"center\" | \"bottom\"" "Where text shorter than its box sits (`<Text>` with a height).",
1258    FontVariant = "fontVariant": Text "(\"small-caps\" | \"oldstyle-nums\" | \"lining-nums\" | \"tabular-nums\" | \"proportional-nums\")[]" "OpenType number and letter forms.",
1259    TextShadowColor = "textShadowColor": Text "ColorValue",
1260    TextShadowRadius = "textShadowRadius": Text "number",
1261    TextTransform = "textTransform": Text "\"none\" | \"uppercase\" | \"lowercase\" | \"capitalize\"",
1262    TextAlign = "textAlign": Text "\"auto\" | \"left\" | \"center\" | \"right\" | \"justify\"",
1263    PlaceholderColor = "placeholderColor": Text "ColorValue" "An input's placeholder (`placeholder:text-*`).",
1264    SelectionColor = "selectionColor": Text "ColorValue" "An input's caret and selection, a selectable text's selection highlight (`selection:text-*`).",
1265    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.",
1266}
1267
1268/// A style property value as read from JS.
1269#[derive(Debug, Clone, Copy)]
1270pub enum StyleValue<'a> {
1271    /// A number.
1272    Number(f32),
1273    /// A string.
1274    Str(&'a str),
1275    /// `null` / `undefined`: resets the property to its default.
1276    Null,
1277}
1278
1279/// A style property value owned by a [`StylePatch`].
1280#[derive(Debug, Clone, PartialEq)]
1281pub enum PatchValue {
1282    /// A number.
1283    Number(f32),
1284    /// A string.
1285    Str(Box<str>),
1286    /// Resets the property to its default.
1287    Null,
1288}
1289
1290impl PatchValue {
1291    /// The value as [`Style::set`] takes it.
1292    pub fn as_value(&self) -> StyleValue<'_> {
1293        match self {
1294            PatchValue::Number(n) => StyleValue::Number(*n),
1295            PatchValue::Str(s) => StyleValue::Str(s),
1296            PatchValue::Null => StyleValue::Null,
1297        }
1298    }
1299}
1300
1301impl From<StyleValue<'_>> for PatchValue {
1302    fn from(v: StyleValue<'_>) -> Self {
1303        match v {
1304            StyleValue::Number(n) => PatchValue::Number(n),
1305            StyleValue::Str(s) => PatchValue::Str(s.into()),
1306            StyleValue::Null => PatchValue::Null,
1307        }
1308    }
1309}
1310
1311/// One declaration of a [`StylePatch`].
1312#[derive(Debug, Clone, PartialEq)]
1313pub enum StyleDecl {
1314    /// A property.
1315    Set(StyleKey, PatchValue),
1316    /// Starts the `transform` list over: a `transform` replaces the
1317    /// transforms set before it (by classes).
1318    ClearTransform,
1319    /// Appends a `transform` entry, driven by an animated value when given
1320    /// (the amount is then the identity until it is bound).
1321    Transform(TransformKind, f32, Option<crate::animation::NodeId>),
1322    /// `shadowOffset`; `None` restores the default.
1323    ShadowOffset(Option<Point<Points>>),
1324    /// `textShadowOffset`.
1325    TextShadowOffset(Option<Point<Points>>),
1326    /// A property driven by a native animation node.
1327    Animated(crate::animation::AnimationProp, crate::animation::NodeId),
1328}
1329
1330impl StyleDecl {
1331    /// Applies the declaration to `style`.
1332    pub fn apply(&self, style: &mut Style) -> Result<(), StyleError> {
1333        match self {
1334            StyleDecl::Set(key, value) => style.set_key(*key, value.as_value()),
1335            StyleDecl::ClearTransform => {
1336                style.view.transform = Transform::IDENTITY;
1337                style.animated.retain(|(prop, _)| {
1338                    !matches!(prop, crate::animation::AnimationProp::Transform(_))
1339                });
1340                Ok(())
1341            }
1342            StyleDecl::Transform(kind, amount, node) => {
1343                let index = style
1344                    .view
1345                    .transform
1346                    .push(*kind, *amount)
1347                    .ok_or(StyleError::InvalidValue)?;
1348                if let Some(node) = node {
1349                    style
1350                        .animated
1351                        .push((crate::animation::AnimationProp::Transform(index), *node));
1352                }
1353                Ok(())
1354            }
1355            StyleDecl::ShadowOffset(offset) => {
1356                style.set_shadow_offset(*offset);
1357                Ok(())
1358            }
1359            StyleDecl::TextShadowOffset(offset) => {
1360                style.set_text_shadow_offset(*offset);
1361                Ok(())
1362            }
1363            StyleDecl::Animated(prop, node) => {
1364                style.animated.push((*prop, *node));
1365                Ok(())
1366            }
1367        }
1368    }
1369}
1370
1371/// A style as written (`style={...}`): its declarations in order (the
1372/// shorthands of [`StylePatch::set`] before their longhands), kept so the
1373/// core can apply them again over class styles when those change.
1374#[derive(Debug, Clone, Default, PartialEq)]
1375pub struct StylePatch {
1376    decls: Vec<StyleDecl>,
1377}
1378
1379impl StylePatch {
1380    /// Applies `decl` to `style` and records it if it applied.
1381    pub fn push(&mut self, style: &mut Style, decl: StyleDecl) -> Result<(), StyleError> {
1382        decl.apply(style)?;
1383        self.decls.push(decl);
1384        Ok(())
1385    }
1386
1387    /// Sets property `key` of the style object this patch records on
1388    /// `style`, and records it. As in React Native, a longhand
1389    /// (`borderTopWidth`, `marginHorizontal`, `flexGrow`, ...) wins over
1390    /// its shorthand (`borderWidth`, `margin`, `flex`) in one object
1391    /// whatever their order: a shorthand set after its longhands is
1392    /// recorded before them, and they apply again; a `null` longhand is
1393    /// unset, so its shorthand shows.
1394    pub fn set(
1395        &mut self,
1396        style: &mut Style,
1397        key: &str,
1398        value: StyleValue<'_>,
1399    ) -> Result<(), StyleError> {
1400        let key = StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?;
1401        if matches!(value, StyleValue::Null) && self.has_shorthand_of(key) {
1402            return Ok(());
1403        }
1404        style.set_key(key, value)?;
1405        let decl = StyleDecl::Set(key, value.into());
1406        let longhands = key.longhands();
1407        let Some(at) = self
1408            .decls
1409            .iter()
1410            .position(|d| matches!(d, StyleDecl::Set(k, _) if longhands.contains(k)))
1411        else {
1412            self.decls.push(decl);
1413            return Ok(());
1414        };
1415        // Nulls set before are dropped (the shorthand shows); the others
1416        // apply again over it.
1417        self.decls
1418            .retain(|d| !matches!(d, StyleDecl::Set(k, PatchValue::Null) if longhands.contains(k)));
1419        let at = at.min(self.decls.len());
1420        self.decls.insert(at, decl);
1421        for d in &self.decls[at + 1..] {
1422            if let StyleDecl::Set(k, v) = d
1423                && longhands.contains(k)
1424            {
1425                let _ = style.set_key(*k, v.as_value());
1426            }
1427        }
1428        Ok(())
1429    }
1430
1431    /// Whether a shorthand of `key` is recorded.
1432    fn has_shorthand_of(&self, key: StyleKey) -> bool {
1433        self.decls
1434            .iter()
1435            .any(|d| matches!(d, StyleDecl::Set(k, _) if k.longhands().contains(&key)))
1436    }
1437
1438    /// Applies every declaration to `style`, in order.
1439    pub fn apply(&self, style: &mut Style) {
1440        for decl in &self.decls {
1441            // Declarations were checked when they were recorded.
1442            let _ = decl.apply(style);
1443        }
1444    }
1445
1446    /// Whether there are no declarations.
1447    pub fn is_empty(&self) -> bool {
1448        self.decls.is_empty()
1449    }
1450
1451    /// The declarations.
1452    pub fn decls(&self) -> &[StyleDecl] {
1453        &self.decls
1454    }
1455}
1456
1457impl StyleKey {
1458    /// The properties that override this shorthand in a style object
1459    /// whatever their order (Yoga takes an edge's own value before its
1460    /// axis' and that of all edges, `flexGrow` before `flex`).
1461    fn longhands(self) -> &'static [StyleKey] {
1462        use StyleKey as K;
1463        match self {
1464            K::Margin => &[
1465                K::MarginHorizontal,
1466                K::MarginVertical,
1467                K::MarginTop,
1468                K::MarginRight,
1469                K::MarginBottom,
1470                K::MarginLeft,
1471            ],
1472            K::MarginHorizontal => &[K::MarginLeft, K::MarginRight],
1473            K::MarginVertical => &[K::MarginTop, K::MarginBottom],
1474            K::Padding => &[
1475                K::PaddingHorizontal,
1476                K::PaddingVertical,
1477                K::PaddingTop,
1478                K::PaddingRight,
1479                K::PaddingBottom,
1480                K::PaddingLeft,
1481            ],
1482            K::PaddingHorizontal => &[K::PaddingLeft, K::PaddingRight],
1483            K::PaddingVertical => &[K::PaddingTop, K::PaddingBottom],
1484            K::BorderWidth => &[
1485                K::BorderTopWidth,
1486                K::BorderRightWidth,
1487                K::BorderBottomWidth,
1488                K::BorderLeftWidth,
1489            ],
1490            K::BorderColor => &[
1491                K::BorderTopColor,
1492                K::BorderRightColor,
1493                K::BorderBottomColor,
1494                K::BorderLeftColor,
1495            ],
1496            K::Gap => &[K::RowGap, K::ColumnGap],
1497            K::Flex => &[K::FlexGrow, K::FlexShrink, K::FlexBasis],
1498            K::GridColumn => &[K::GridColumnStart, K::GridColumnEnd],
1499            K::GridRow => &[K::GridRowStart, K::GridRowEnd],
1500            _ => &[],
1501        }
1502    }
1503}
1504
1505/// Why a style property was rejected.
1506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1507pub enum StyleError {
1508    /// The property name is not supported.
1509    UnknownProperty,
1510    /// The value has the wrong type or format.
1511    InvalidValue,
1512}
1513
1514enum Len {
1515    Px(f32),
1516    Pct(f32),
1517    Auto,
1518}
1519
1520impl Len {
1521    fn parse(v: StyleValue<'_>) -> Result<Len, StyleError> {
1522        match v {
1523            StyleValue::Number(n) => Ok(Len::Px(n)),
1524            StyleValue::Str("auto") => Ok(Len::Auto),
1525            StyleValue::Str(s) => s
1526                .strip_suffix('%')
1527                .and_then(|p| p.trim().parse::<f32>().ok())
1528                .map(|p| Len::Pct(p / 100.0))
1529                .ok_or(StyleError::InvalidValue),
1530            StyleValue::Null => Ok(Len::Auto),
1531        }
1532    }
1533
1534    fn dim(self) -> Dimension {
1535        match self {
1536            Len::Px(v) => Dimension::length(v),
1537            Len::Pct(v) => Dimension::percent(v),
1538            Len::Auto => Dimension::auto(),
1539        }
1540    }
1541
1542    fn lpa(self) -> LengthPercentageAuto {
1543        match self {
1544            Len::Px(v) => LengthPercentageAuto::length(v),
1545            Len::Pct(v) => LengthPercentageAuto::percent(v),
1546            Len::Auto => LengthPercentageAuto::auto(),
1547        }
1548    }
1549
1550    fn lp(self) -> Result<LengthPercentage, StyleError> {
1551        match self {
1552            Len::Px(v) => Ok(LengthPercentage::length(v)),
1553            Len::Pct(v) => Ok(LengthPercentage::percent(v)),
1554            Len::Auto => Err(StyleError::InvalidValue),
1555        }
1556    }
1557}
1558
1559/// A zero-default length: `null` resets to 0 rather than `auto`.
1560fn lp_or_zero(v: StyleValue<'_>) -> Result<LengthPercentage, StyleError> {
1561    match v {
1562        StyleValue::Null => Ok(LengthPercentage::length(0.0)),
1563        v => Len::parse(v)?.lp(),
1564    }
1565}
1566
1567fn opt_lpa(v: StyleValue<'_>) -> Result<Option<LengthPercentageAuto>, StyleError> {
1568    match v {
1569        StyleValue::Null => Ok(None),
1570        v => Ok(Some(Len::parse(v)?.lpa())),
1571    }
1572}
1573
1574fn opt_lp(v: StyleValue<'_>) -> Result<Option<LengthPercentage>, StyleError> {
1575    match v {
1576        StyleValue::Null => Ok(None),
1577        v => Ok(Some(Len::parse(v)?.lp()?)),
1578    }
1579}
1580
1581/// A minimum size: unset is 0, as in Yoga. Taffy's `auto` would be CSS's
1582/// automatic minimum (the min-content size), which keeps flex items from
1583/// shrinking below their content (`flex: 1` text in a row would overflow).
1584fn min_len(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
1585    Ok(match Len::parse(v)? {
1586        Len::Auto => LengthPercentageAuto::length(0.0),
1587        len => len.lpa(),
1588    })
1589}
1590
1591fn lpa_or_zero(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
1592    match v {
1593        StyleValue::Null => Ok(LengthPercentageAuto::length(0.0)),
1594        v => Ok(Len::parse(v)?.lpa()),
1595    }
1596}
1597
1598fn number(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
1599    match v {
1600        StyleValue::Number(n) => Ok(n),
1601        StyleValue::Null => Ok(default),
1602        StyleValue::Str(_) => Err(StyleError::InvalidValue),
1603    }
1604}
1605
1606fn opt_number(v: StyleValue<'_>) -> Result<Option<f32>, StyleError> {
1607    match v {
1608        StyleValue::Number(n) => Ok(Some(n)),
1609        StyleValue::Null => Ok(None),
1610        StyleValue::Str(_) => Err(StyleError::InvalidValue),
1611    }
1612}
1613
1614fn opt_points(v: StyleValue<'_>) -> Result<Option<Points>, StyleError> {
1615    Ok(opt_number(v)?.map(px))
1616}
1617
1618fn color(v: StyleValue<'_>) -> Result<Option<Color>, StyleError> {
1619    match v {
1620        StyleValue::Str(s) => Color::parse(s).map(Some).ok_or(StyleError::InvalidValue),
1621        StyleValue::Null => Ok(None),
1622        StyleValue::Number(_) => Err(StyleError::InvalidValue),
1623    }
1624}
1625
1626fn keyword<'a>(v: StyleValue<'a>) -> Result<Option<&'a str>, StyleError> {
1627    match v {
1628        StyleValue::Str(s) => Ok(Some(s)),
1629        StyleValue::Null => Ok(None),
1630        StyleValue::Number(_) => Err(StyleError::InvalidValue),
1631    }
1632}
1633
1634fn align_items(v: StyleValue<'_>) -> Result<Option<AlignItems>, StyleError> {
1635    Ok(match keyword(v)? {
1636        None => None,
1637        Some("flex-start") => Some(AlignItems::FLEX_START),
1638        Some("flex-end") => Some(AlignItems::FLEX_END),
1639        // CSS's logical keywords: the writing direction's start and end
1640        // (right to left, `start` is the right), not the flex direction's.
1641        Some("start") => Some(AlignItems::START),
1642        Some("end") => Some(AlignItems::END),
1643        Some("self-start") => Some(AlignItems::SELF_START),
1644        Some("self-end") => Some(AlignItems::SELF_END),
1645        Some("center") => Some(AlignItems::CENTER),
1646        Some("stretch") => Some(AlignItems::STRETCH),
1647        Some("baseline") => Some(AlignItems::BASELINE),
1648        // CSS's `normal`: `stretch` for items without an aspect ratio.
1649        Some("normal") => Some(AlignItems::NORMAL),
1650        Some(_) => return Err(StyleError::InvalidValue),
1651    })
1652}
1653
1654/// `alignContent` / `justifyContent`; unset (null, `normal`) is CSS's
1655/// `normal`, which [`resolve_normal_alignment`] makes React Native's
1656/// `flex-start` outside grids.
1657fn align_content(v: StyleValue<'_>) -> Result<AlignContent, StyleError> {
1658    Ok(match keyword(v)? {
1659        None | Some("normal") => AlignContent::NORMAL,
1660        Some("flex-start") => AlignContent::FLEX_START,
1661        Some("flex-end") => AlignContent::FLEX_END,
1662        Some("start") => AlignContent::START,
1663        Some("end") => AlignContent::END,
1664        Some("center") => AlignContent::CENTER,
1665        Some("stretch") => AlignContent::STRETCH,
1666        Some("space-between") => AlignContent::SPACE_BETWEEN,
1667        Some("space-around") => AlignContent::SPACE_AROUND,
1668        Some("space-evenly") => AlignContent::SPACE_EVENLY,
1669        Some(_) => return Err(StyleError::InvalidValue),
1670    })
1671}
1672
1673fn font_weight(v: StyleValue<'_>) -> Result<Option<u16>, StyleError> {
1674    Ok(match v {
1675        StyleValue::Null => None,
1676        StyleValue::Number(n) => Some((n as u16).clamp(100, 900)),
1677        StyleValue::Str("normal") => Some(400),
1678        StyleValue::Str("bold") => Some(700),
1679        StyleValue::Str(s) => Some(
1680            s.parse::<u16>()
1681                .map_err(|_| StyleError::InvalidValue)?
1682                .clamp(100, 900),
1683        ),
1684    })
1685}
1686
1687/// A length in points from a number or a string (`"2px"`, `"0.5rem"`).
1688fn length_value(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
1689    match v {
1690        StyleValue::Number(n) => Ok(n),
1691        StyleValue::Str(s) => css::length(s).ok_or(StyleError::InvalidValue),
1692        StyleValue::Null => Ok(default),
1693    }
1694}
1695
1696/// Milliseconds from a number or `"150ms"` / `"0.2s"`.
1697fn duration(v: StyleValue<'_>) -> Result<f32, StyleError> {
1698    match v {
1699        StyleValue::Number(n) => Ok(n.max(0.0)),
1700        StyleValue::Null => Ok(0.0),
1701        StyleValue::Str(s) => {
1702            let s = s.trim();
1703            let ms = if let Some(n) = s.strip_suffix("ms") {
1704                css::number(n)
1705            } else if let Some(n) = s.strip_suffix('s') {
1706                css::number(n).map(|n| n * 1000.0)
1707            } else {
1708                css::number(s)
1709            };
1710            ms.map(|n| n.max(0.0)).ok_or(StyleError::InvalidValue)
1711        }
1712    }
1713}
1714
1715/// A CSS timing function as cubic Bézier control points.
1716fn timing_function(v: StyleValue<'_>) -> Result<[f32; 4], StyleError> {
1717    let Some(s) = keyword(v)? else {
1718        return Ok(Transition::EASE);
1719    };
1720    Ok(match s.trim() {
1721        "linear" => [0.0, 0.0, 1.0, 1.0],
1722        "ease" => Transition::EASE,
1723        "ease-in" => [0.42, 0.0, 1.0, 1.0],
1724        "ease-out" => [0.0, 0.0, 0.58, 1.0],
1725        "ease-in-out" => [0.42, 0.0, 0.58, 1.0],
1726        s => {
1727            let args = s
1728                .strip_prefix("cubic-bezier(")
1729                .and_then(|a| a.strip_suffix(')'))
1730                .ok_or(StyleError::InvalidValue)?;
1731            let n: Vec<f32> = args.split(',').filter_map(css::number).collect();
1732            let [a, b, c, d] = n.as_slice() else {
1733                return Err(StyleError::InvalidValue);
1734            };
1735            [*a, *b, *c, *d]
1736        }
1737    })
1738}
1739
1740/// `transitionProperty`: CSS property names, mapped to the groups that
1741/// transition natively.
1742fn transition_properties(s: &str) -> Option<TransitionProps> {
1743    let mut bits = 0;
1744    for name in s.split(',').map(str::trim) {
1745        bits |= match name {
1746            "all" => TransitionProps::ALL,
1747            "none" => 0,
1748            "color"
1749            | "colors"
1750            | "background-color"
1751            | "backgroundColor"
1752            | "border-color"
1753            | "borderColor"
1754            | "outline-color"
1755            | "text-decoration-color"
1756            | "fill"
1757            | "stroke"
1758            | "--tw-gradient-from"
1759            | "--tw-gradient-via"
1760            | "--tw-gradient-to" => TransitionProps::COLORS,
1761            "opacity" => TransitionProps::OPACITY,
1762            "transform" | "translate" | "scale" | "rotate" => TransitionProps::TRANSFORM,
1763            "box-shadow" | "boxShadow" | "shadow" => TransitionProps::SHADOW,
1764            "border-radius" | "borderRadius" | "border-width" | "borderWidth" => {
1765                TransitionProps::SHAPE
1766            }
1767            // Properties that do not animate natively.
1768            "filter" | "backdrop-filter" | "display" | "visibility" | "content-visibility"
1769            | "overlay" | "pointer-events" => 0,
1770            _ => return None,
1771        };
1772    }
1773    Some(TransitionProps(bits))
1774}
1775
1776fn grid_value<T>(
1777    v: StyleValue<'_>,
1778    parse: impl Fn(&str) -> Option<Vec<T>>,
1779) -> Result<Vec<T>, StyleError> {
1780    match keyword(v)? {
1781        None => Ok(Vec::new()),
1782        Some(s) => parse(s).ok_or(StyleError::InvalidValue),
1783    }
1784}
1785
1786fn grid_template(v: StyleValue<'_>) -> Result<grid::Template, StyleError> {
1787    match keyword(v)? {
1788        None => Ok((Vec::new(), Vec::new())),
1789        Some(s) => grid::template(s).ok_or(StyleError::InvalidValue),
1790    }
1791}
1792
1793fn grid_placement(v: StyleValue<'_>) -> Result<taffy::GridPlacement<String>, StyleError> {
1794    match v {
1795        StyleValue::Null => Ok(taffy::GridPlacement::Auto),
1796        StyleValue::Number(n) => {
1797            grid::placement(&(n as i32).to_string()).ok_or(StyleError::InvalidValue)
1798        }
1799        StyleValue::Str(s) => grid::placement(s).ok_or(StyleError::InvalidValue),
1800    }
1801}
1802
1803fn grid_line(v: StyleValue<'_>) -> Result<taffy::Line<taffy::GridPlacement<String>>, StyleError> {
1804    match v {
1805        StyleValue::Null => Ok(taffy::Line {
1806            start: taffy::GridPlacement::Auto,
1807            end: taffy::GridPlacement::Auto,
1808        }),
1809        StyleValue::Number(n) => {
1810            grid::line(&(n as i32).to_string()).ok_or(StyleError::InvalidValue)
1811        }
1812        StyleValue::Str(s) => grid::line(s).ok_or(StyleError::InvalidValue),
1813    }
1814}
1815
1816impl Style {
1817    /// Changes the effects lists (copying them if shared).
1818    pub fn edit_effects(&mut self, f: impl FnOnce(&mut Effects)) {
1819        let mut effects = self
1820            .view
1821            .effects
1822            .take()
1823            .map(|e| (*e).clone())
1824            .unwrap_or_default();
1825        f(&mut effects);
1826        self.view.effects = crate::effects::shared(effects);
1827    }
1828
1829    /// Sets the box shadows (top layer first).
1830    pub fn set_box_shadows(&mut self, shadows: Vec<BoxShadow>) {
1831        self.edit_effects(|e| e.box_shadows = shadows);
1832    }
1833
1834    /// Sets the gradient backgrounds (top layer first).
1835    pub fn set_background_images(&mut self, images: Vec<Gradient>) {
1836        self.edit_effects(|e| e.background_images = images);
1837    }
1838
1839    /// Sets the filters.
1840    pub fn set_filters(&mut self, filters: Vec<Filter>, backdrop: bool) {
1841        self.edit_effects(|e| {
1842            if backdrop {
1843                e.backdrop_filters = filters;
1844            } else {
1845                e.filters = filters;
1846            }
1847        });
1848    }
1849
1850    fn transition_mut(&mut self) -> &mut Transition {
1851        self.view.transition.get_or_insert(Transition {
1852            properties: TransitionProps(TransitionProps::ALL),
1853            duration: 0.0,
1854            delay: 0.0,
1855            easing: Transition::EASE,
1856        })
1857    }
1858
1859    /// Appends an entry to the `transform` list (`translateX`, `scale`,
1860    /// ...); rotations and skews are degrees (`"45deg"` strings are parsed
1861    /// by the caller). Returns the entry's index.
1862    pub fn push_transform(&mut self, key: &str, value: f32) -> Result<u8, StyleError> {
1863        let kind = TransformKind::parse(key).ok_or(StyleError::UnknownProperty)?;
1864        self.view
1865            .transform
1866            .push(kind, value)
1867            .ok_or(StyleError::InvalidValue)
1868    }
1869
1870    /// Sets `shadowOffset: { width, height }`; `None` restores the default.
1871    pub fn set_shadow_offset(&mut self, offset: Option<Point<Points>>) {
1872        let offset =
1873            offset.unwrap_or_else(|| point(Shadow::DEFAULT.offset_x, Shadow::DEFAULT.offset_y));
1874        self.view.shadow.offset_x = offset.x;
1875        self.view.shadow.offset_y = offset.y;
1876    }
1877
1878    /// Sets `textShadowOffset: { width, height }`.
1879    pub fn set_text_shadow_offset(&mut self, offset: Option<Point<Points>>) {
1880        self.text.shadow_offset = offset;
1881    }
1882
1883    fn set_border_width(
1884        &mut self,
1885        sides: &[usize],
1886        value: StyleValue<'_>,
1887    ) -> Result<(), StyleError> {
1888        let w = number(value, 0.0)?.max(0.0);
1889        let v = LengthPercentage::length(w);
1890        for &side in sides {
1891            *self.view.borders.width_mut(side) = px(w);
1892            let b = &mut self.layout.border;
1893            match side {
1894                0 => b.top = v,
1895                1 => b.right = v,
1896                2 => b.bottom = v,
1897                _ => b.left = v,
1898            }
1899        }
1900        Ok(())
1901    }
1902
1903    fn set_border_color(
1904        &mut self,
1905        sides: &[usize],
1906        value: StyleValue<'_>,
1907    ) -> Result<(), StyleError> {
1908        let c = color(value)?.unwrap_or(Color::BLACK);
1909        for &side in sides {
1910            self.view.borders.colors[side] = c;
1911        }
1912        Ok(())
1913    }
1914
1915    /// Sets one property using its React Native name.
1916    pub fn set(&mut self, key: &str, value: StyleValue<'_>) -> Result<(), StyleError> {
1917        self.set_key(
1918            StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?,
1919            value,
1920        )
1921    }
1922
1923    /// Sets one property.
1924    pub fn set_key(&mut self, key: StyleKey, value: StyleValue<'_>) -> Result<(), StyleError> {
1925        let l = &mut self.layout;
1926        match key {
1927            // Layout
1928            StyleKey::Display => {
1929                l.display = match keyword(value)? {
1930                    None | Some("flex") => Display::Flex,
1931                    Some("grid") => Display::Grid,
1932                    Some("block") => Display::Block,
1933                    Some("none") => Display::None,
1934                    Some(_) => return Err(StyleError::InvalidValue),
1935                }
1936            }
1937            StyleKey::Position => {
1938                l.position = match keyword(value)? {
1939                    None | Some("relative") => Position::Relative,
1940                    Some("absolute") => Position::Absolute,
1941                    Some(_) => return Err(StyleError::InvalidValue),
1942                }
1943            }
1944            StyleKey::FlexDirection => {
1945                l.flex_direction = match keyword(value)? {
1946                    None | Some("column") => FlexDirection::Column,
1947                    Some("row") => FlexDirection::Row,
1948                    Some("column-reverse") => FlexDirection::ColumnReverse,
1949                    Some("row-reverse") => FlexDirection::RowReverse,
1950                    Some(_) => return Err(StyleError::InvalidValue),
1951                }
1952            }
1953            StyleKey::FlexWrap => {
1954                l.flex_wrap = match keyword(value)? {
1955                    None | Some("nowrap") => FlexWrap::NoWrap,
1956                    Some("wrap") => FlexWrap::Wrap,
1957                    Some("wrap-reverse") => FlexWrap::WrapReverse,
1958                    Some(_) => return Err(StyleError::InvalidValue),
1959                }
1960            }
1961            StyleKey::Flex => {
1962                // React Native semantics, not the CSS shorthand.
1963                let f = number(value, 0.0)?;
1964                if f > 0.0 {
1965                    l.flex_grow = f;
1966                    l.flex_shrink = 1.0;
1967                    l.flex_basis = Dimension::length(0.0);
1968                } else if f < 0.0 {
1969                    l.flex_grow = 0.0;
1970                    l.flex_shrink = -f;
1971                    l.flex_basis = Dimension::auto();
1972                } else {
1973                    l.flex_grow = 0.0;
1974                    l.flex_shrink = 0.0;
1975                    l.flex_basis = Dimension::auto();
1976                }
1977            }
1978            StyleKey::FlexGrow => l.flex_grow = number(value, 0.0)?,
1979            StyleKey::FlexShrink => l.flex_shrink = number(value, 0.0)?,
1980            StyleKey::FlexBasis => l.flex_basis = Len::parse(value)?.dim(),
1981            StyleKey::JustifyContent => l.justify_content = align_content(value)?,
1982            StyleKey::AlignItems => {
1983                l.align_items = align_items(value)?.unwrap_or(AlignItems::STRETCH)
1984            }
1985            StyleKey::AlignSelf => {
1986                l.align_self = match value {
1987                    StyleValue::Str("auto") => None,
1988                    v => align_items(v)?,
1989                }
1990            }
1991            StyleKey::AlignContent => l.align_content = align_content(value)?,
1992            StyleKey::Width => l.size.width = Len::parse(value)?.dim(),
1993            StyleKey::Height => l.size.height = Len::parse(value)?.dim(),
1994            StyleKey::MinWidth => l.min_size.width = min_len(value)?,
1995            StyleKey::MinHeight => l.min_size.height = min_len(value)?,
1996            StyleKey::MaxWidth => l.max_size.width = Len::parse(value)?.lpa(),
1997            StyleKey::MaxHeight => l.max_size.height = Len::parse(value)?.lpa(),
1998            StyleKey::AspectRatio => l.aspect_ratio = opt_number(value)?,
1999            StyleKey::Top => l.inset.top = Len::parse(value)?.lpa(),
2000            StyleKey::Right => l.inset.right = Len::parse(value)?.lpa(),
2001            StyleKey::Bottom => l.inset.bottom = Len::parse(value)?.lpa(),
2002            StyleKey::Left => l.inset.left = Len::parse(value)?.lpa(),
2003            StyleKey::Margin => {
2004                let v = lpa_or_zero(value)?;
2005                l.margin = taffy::Rect {
2006                    left: v,
2007                    right: v,
2008                    top: v,
2009                    bottom: v,
2010                };
2011            }
2012            StyleKey::MarginHorizontal => {
2013                let v = lpa_or_zero(value)?;
2014                (l.margin.left, l.margin.right) = (v, v);
2015            }
2016            StyleKey::MarginVertical => {
2017                let v = lpa_or_zero(value)?;
2018                (l.margin.top, l.margin.bottom) = (v, v);
2019            }
2020            StyleKey::MarginTop => l.margin.top = lpa_or_zero(value)?,
2021            StyleKey::MarginRight => l.margin.right = lpa_or_zero(value)?,
2022            StyleKey::MarginBottom => l.margin.bottom = lpa_or_zero(value)?,
2023            StyleKey::MarginLeft => l.margin.left = lpa_or_zero(value)?,
2024            StyleKey::Padding => {
2025                let v = lp_or_zero(value)?;
2026                l.padding = taffy::Rect {
2027                    left: v,
2028                    right: v,
2029                    top: v,
2030                    bottom: v,
2031                };
2032            }
2033            StyleKey::PaddingHorizontal => {
2034                let v = lp_or_zero(value)?;
2035                (l.padding.left, l.padding.right) = (v, v);
2036            }
2037            StyleKey::PaddingVertical => {
2038                let v = lp_or_zero(value)?;
2039                (l.padding.top, l.padding.bottom) = (v, v);
2040            }
2041            StyleKey::PaddingTop => l.padding.top = lp_or_zero(value)?,
2042            StyleKey::PaddingRight => l.padding.right = lp_or_zero(value)?,
2043            StyleKey::PaddingBottom => l.padding.bottom = lp_or_zero(value)?,
2044            StyleKey::PaddingLeft => l.padding.left = lp_or_zero(value)?,
2045            StyleKey::Gap => {
2046                let v = lp_or_zero(value)?;
2047                l.gap = taffy::Size {
2048                    width: v,
2049                    height: v,
2050                };
2051            }
2052            StyleKey::RowGap => l.gap.height = lp_or_zero(value)?,
2053            StyleKey::ColumnGap => l.gap.width = lp_or_zero(value)?,
2054            StyleKey::BorderWidth => self.set_border_width(&[0, 1, 2, 3], value)?,
2055            StyleKey::BorderTopWidth => self.set_border_width(&[0], value)?,
2056            StyleKey::BorderRightWidth => self.set_border_width(&[1], value)?,
2057            StyleKey::BorderBottomWidth => self.set_border_width(&[2], value)?,
2058            StyleKey::BorderLeftWidth => self.set_border_width(&[3], value)?,
2059            StyleKey::ZIndex => self.z_index = number(value, 0.0)? as i32,
2060            StyleKey::VerticalAlign => {
2061                self.vertical_align = match keyword(value)? {
2062                    None => VerticalAlign::Baseline,
2063                    Some(k) => VerticalAlign::parse(k).ok_or(StyleError::InvalidValue)?,
2064                }
2065            }
2066            StyleKey::Direction => {
2067                self.direction = match keyword(value)? {
2068                    None | Some("inherit") => None,
2069                    Some("ltr") => Some(false),
2070                    Some("rtl") => Some(true),
2071                    Some(_) => return Err(StyleError::InvalidValue),
2072                }
2073            }
2074            StyleKey::MarginStart => self.logical.margin[0] = opt_lpa(value)?,
2075            StyleKey::MarginEnd => self.logical.margin[1] = opt_lpa(value)?,
2076            StyleKey::PaddingStart => self.logical.padding[0] = opt_lp(value)?,
2077            StyleKey::PaddingEnd => self.logical.padding[1] = opt_lp(value)?,
2078            StyleKey::Start => self.logical.inset[0] = opt_lpa(value)?,
2079            StyleKey::End => self.logical.inset[1] = opt_lpa(value)?,
2080            StyleKey::BorderStartWidth => {
2081                self.logical.border_width[0] = opt_points(value)?.map(|w| w.max(Points::ZERO))
2082            }
2083            StyleKey::BorderEndWidth => {
2084                self.logical.border_width[1] = opt_points(value)?.map(|w| w.max(Points::ZERO))
2085            }
2086            StyleKey::BorderStartColor => self.logical.border_color[0] = color(value)?,
2087            StyleKey::BorderEndColor => self.logical.border_color[1] = color(value)?,
2088            StyleKey::BorderTopStartRadius => self.logical.radius[0] = opt_points(value)?,
2089            StyleKey::BorderTopEndRadius => self.logical.radius[1] = opt_points(value)?,
2090            StyleKey::BorderBottomEndRadius => self.logical.radius[2] = opt_points(value)?,
2091            StyleKey::BorderBottomStartRadius => self.logical.radius[3] = opt_points(value)?,
2092
2093            // View
2094            StyleKey::BackgroundColor => {
2095                self.view.background_color = color(value)?.unwrap_or(Color::TRANSPARENT)
2096            }
2097            StyleKey::BorderRadius => self.view.border_radius = px(number(value, 0.0)?),
2098            StyleKey::BorderTopLeftRadius => self.view.corner_radius.top_left = opt_points(value)?,
2099            StyleKey::BorderTopRightRadius => {
2100                self.view.corner_radius.top_right = opt_points(value)?
2101            }
2102            StyleKey::BorderBottomRightRadius => {
2103                self.view.corner_radius.bottom_right = opt_points(value)?
2104            }
2105            StyleKey::BorderBottomLeftRadius => {
2106                self.view.corner_radius.bottom_left = opt_points(value)?
2107            }
2108            StyleKey::ShadowColor => {
2109                self.view.shadow.color = color(value)?.unwrap_or(Shadow::DEFAULT.color)
2110            }
2111            StyleKey::ShadowOpacity => {
2112                self.view.shadow.opacity = number(value, Shadow::DEFAULT.opacity)?.clamp(0.0, 1.0)
2113            }
2114            StyleKey::ShadowRadius => {
2115                self.view.shadow.radius = px(number(value, Shadow::DEFAULT.radius.0)?.max(0.0))
2116            }
2117            StyleKey::BorderColor => self.set_border_color(&[0, 1, 2, 3], value)?,
2118            StyleKey::BorderTopColor => self.set_border_color(&[0], value)?,
2119            StyleKey::BorderRightColor => self.set_border_color(&[1], value)?,
2120            StyleKey::BorderBottomColor => self.set_border_color(&[2], value)?,
2121            StyleKey::BorderLeftColor => self.set_border_color(&[3], value)?,
2122            StyleKey::BorderStyle => {
2123                self.view.borders.style = match keyword(value)? {
2124                    None | Some("solid") => BorderStyle::Solid,
2125                    Some("dashed") => BorderStyle::Dashed,
2126                    Some("dotted") => BorderStyle::Dotted,
2127                    Some(_) => return Err(StyleError::InvalidValue),
2128                }
2129            }
2130            StyleKey::BorderCurve => {
2131                self.view.continuous_corners = match keyword(value)? {
2132                    None | Some("circular") => false,
2133                    Some("continuous") => true,
2134                    Some(_) => return Err(StyleError::InvalidValue),
2135                }
2136            }
2137            StyleKey::TintColor => self.view.tint_color = color(value)?,
2138            StyleKey::BackfaceVisibility => {
2139                self.view.backface_hidden = match keyword(value)? {
2140                    None | Some("visible") => false,
2141                    Some("hidden") => true,
2142                    Some(_) => return Err(StyleError::InvalidValue),
2143                }
2144            }
2145            StyleKey::TransformOrigin => {
2146                self.view.transform_origin = match keyword(value)? {
2147                    None => TransformOrigin::CENTER,
2148                    Some(s) => TransformOrigin::parse(s).ok_or(StyleError::InvalidValue)?,
2149                }
2150            }
2151            StyleKey::Opacity => self.view.opacity = number(value, 1.0)?.clamp(0.0, 1.0),
2152            StyleKey::Overflow => {
2153                self.view.overflow_hidden = match keyword(value)? {
2154                    None | Some("visible") => false,
2155                    Some("hidden") => true,
2156                    Some(_) => return Err(StyleError::InvalidValue),
2157                }
2158            }
2159
2160            // Text
2161            StyleKey::Color => self.text.color = color(value)?,
2162            StyleKey::FontSize => self.text.font_size = opt_points(value)?,
2163            StyleKey::FontWeight => self.text.font_weight = font_weight(value)?,
2164            StyleKey::LineHeight => {
2165                // Numbers are points (React Native); strings may be a
2166                // multiple of the font size (`"1.5"`, `"1.5em"`) or points.
2167                let (points, multiple) = match value {
2168                    StyleValue::Str(s)
2169                        if s.ends_with("px") || s.ends_with("pt") || s.ends_with("rem") =>
2170                    {
2171                        (
2172                            Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
2173                            None,
2174                        )
2175                    }
2176                    StyleValue::Str(s) => {
2177                        let n = css::number(s.strip_suffix("em").unwrap_or(s))
2178                            .ok_or(StyleError::InvalidValue)?;
2179                        (None, Some(n.max(0.0)))
2180                    }
2181                    v => (opt_points(v)?, None),
2182                };
2183                self.text.line_height = points;
2184                self.text.line_height_multiple = multiple;
2185            }
2186            StyleKey::FontFamily => {
2187                self.text.font_family = keyword(value)?.map(|name| FontFamily::new(name.trim()))
2188            }
2189            StyleKey::FontStyle => {
2190                self.text.italic = match keyword(value)? {
2191                    None => None,
2192                    Some("normal") => Some(false),
2193                    Some("italic") => Some(true),
2194                    Some(_) => return Err(StyleError::InvalidValue),
2195                }
2196            }
2197            StyleKey::LetterSpacing => {
2198                let (points, em) = match value {
2199                    StyleValue::Str(s) if s.ends_with("em") && !s.ends_with("rem") => {
2200                        let n = css::number(&s[..s.len() - 2]).ok_or(StyleError::InvalidValue)?;
2201                        (None, Some(n))
2202                    }
2203                    StyleValue::Str(s) => (
2204                        Some(px(css::length(s).ok_or(StyleError::InvalidValue)?)),
2205                        None,
2206                    ),
2207                    v => (opt_points(v)?, None),
2208                };
2209                self.text.letter_spacing = points;
2210                self.text.letter_spacing_em = em;
2211            }
2212            StyleKey::TextDecorationLine => {
2213                self.text.decoration = match keyword(value)? {
2214                    None => None,
2215                    Some(words) => {
2216                        let mut d = TextDecoration::default();
2217                        for word in words.split_whitespace() {
2218                            match word {
2219                                "none" => {}
2220                                "underline" => d.underline = true,
2221                                "line-through" => d.line_through = true,
2222                                _ => return Err(StyleError::InvalidValue),
2223                            }
2224                        }
2225                        Some(d)
2226                    }
2227                }
2228            }
2229            StyleKey::TextDecorationColor => self.text.decoration_color = color(value)?,
2230            StyleKey::PlaceholderColor => self.text.placeholder_color = color(value)?,
2231            StyleKey::SelectionColor => self.text.selection_color = color(value)?,
2232            StyleKey::TextAlignVertical => {
2233                self.text.align_vertical = match keyword(value)? {
2234                    None => None,
2235                    Some("auto" | "top") => Some(percentage(0.0)),
2236                    Some("center") => Some(percentage(0.5)),
2237                    Some("bottom") => Some(percentage(1.0)),
2238                    Some(_) => return Err(StyleError::InvalidValue),
2239                }
2240            }
2241            StyleKey::WritingDirection => {
2242                self.text.writing_direction = match keyword(value)? {
2243                    None | Some("auto") => None,
2244                    Some("ltr") => Some(false),
2245                    Some("rtl") => Some(true),
2246                    Some(_) => return Err(StyleError::InvalidValue),
2247                }
2248            }
2249            StyleKey::FontVariant => {
2250                self.text.font_variant = match keyword(value)? {
2251                    None => None,
2252                    Some(s) => Some(FontVariant::parse(s).ok_or(StyleError::InvalidValue)?),
2253                }
2254            }
2255            StyleKey::TextShadowColor => self.text.shadow_color = color(value)?,
2256            StyleKey::TextShadowRadius => self.text.shadow_radius = opt_points(value)?,
2257            StyleKey::TextTransform => {
2258                self.text.transform = match keyword(value)? {
2259                    None => None,
2260                    Some("none") => Some(TextTransform::None),
2261                    Some("uppercase") => Some(TextTransform::Uppercase),
2262                    Some("lowercase") => Some(TextTransform::Lowercase),
2263                    Some("capitalize") => Some(TextTransform::Capitalize),
2264                    Some(_) => return Err(StyleError::InvalidValue),
2265                }
2266            }
2267            StyleKey::TextAlign => {
2268                self.text.text_align = match keyword(value)? {
2269                    None => None,
2270                    Some("auto") => Some(TextAlign::Auto),
2271                    Some("left") => Some(TextAlign::Left),
2272                    Some("center") => Some(TextAlign::Center),
2273                    Some("right") => Some(TextAlign::Right),
2274                    Some("justify") => Some(TextAlign::Justify),
2275                    Some(_) => return Err(StyleError::InvalidValue),
2276                }
2277            }
2278
2279            // Effects
2280            StyleKey::BoxShadow => {
2281                let list = match keyword(value)? {
2282                    None => Vec::new(),
2283                    Some(s) => css::box_shadows(s).ok_or(StyleError::InvalidValue)?,
2284                };
2285                self.edit_effects(|e| e.box_shadows = list);
2286            }
2287            StyleKey::BackgroundImage => {
2288                let list = match keyword(value)? {
2289                    None => Vec::new(),
2290                    Some(s) => css::gradients(s).ok_or(StyleError::InvalidValue)?,
2291                };
2292                self.edit_effects(|e| e.background_images = list);
2293            }
2294            StyleKey::Filter => {
2295                let list = match keyword(value)? {
2296                    None => Vec::new(),
2297                    Some(s) => css::filters(s).ok_or(StyleError::InvalidValue)?,
2298                };
2299                self.edit_effects(|e| e.filters = list);
2300            }
2301            StyleKey::BackdropFilter => {
2302                let list = match keyword(value)? {
2303                    None => Vec::new(),
2304                    Some(s) => css::filters(s).ok_or(StyleError::InvalidValue)?,
2305                };
2306                self.edit_effects(|e| e.backdrop_filters = list);
2307            }
2308            StyleKey::MixBlendMode => {
2309                self.view.blend_mode = match keyword(value)? {
2310                    None => BlendMode::Normal,
2311                    Some(s) => BlendMode::parse(s).ok_or(StyleError::InvalidValue)?,
2312                }
2313            }
2314            StyleKey::OutlineWidth => {
2315                let width = px(length_value(value, 0.0)?.max(0.0));
2316                self.pending.outline_width = width;
2317                if !self.pending.outline_hidden {
2318                    self.view.outline.width = width;
2319                }
2320            }
2321            StyleKey::OutlineColor => {
2322                self.view.outline.color = color(value)?.unwrap_or(Outline::NONE.color)
2323            }
2324            StyleKey::OutlineOffset => self.view.outline.offset = px(length_value(value, 0.0)?),
2325            StyleKey::OutlineStyle => {
2326                // `none` draws no outline whatever the width, set before
2327                // or after it (CSS).
2328                let (style, hidden) = match keyword(value)? {
2329                    None | Some("solid") | Some("double") => (BorderStyle::Solid, false),
2330                    Some("dashed") => (BorderStyle::Dashed, false),
2331                    Some("dotted") => (BorderStyle::Dotted, false),
2332                    Some("none") | Some("hidden") => (BorderStyle::Solid, true),
2333                    Some(_) => return Err(StyleError::InvalidValue),
2334                };
2335                self.view.outline.style = style;
2336                self.pending.outline_hidden = hidden;
2337                self.view.outline.width = if hidden {
2338                    Points::ZERO
2339                } else {
2340                    self.pending.outline_width
2341                };
2342            }
2343            StyleKey::Visibility => {
2344                self.view.hidden = match keyword(value)? {
2345                    None | Some("visible") => false,
2346                    Some("hidden") | Some("collapse") => true,
2347                    Some(_) => return Err(StyleError::InvalidValue),
2348                }
2349            }
2350            StyleKey::Cursor => {
2351                self.view.cursor = match keyword(value)? {
2352                    None => Cursor::Auto,
2353                    Some(s) => Cursor::parse(s).ok_or(StyleError::InvalidValue)?,
2354                }
2355            }
2356            StyleKey::TransitionProperty => {
2357                let props = match keyword(value)? {
2358                    None => TransitionProps(TransitionProps::ALL),
2359                    Some(s) => transition_properties(s).ok_or(StyleError::InvalidValue)?,
2360                };
2361                self.transition_mut().properties = props;
2362            }
2363            StyleKey::TransitionDuration => {
2364                let ms = duration(value)?;
2365                self.transition_mut().duration = ms;
2366            }
2367            StyleKey::TransitionDelay => {
2368                let ms = duration(value)?;
2369                self.transition_mut().delay = ms;
2370            }
2371            StyleKey::TransitionTimingFunction => {
2372                let easing = timing_function(value)?;
2373                self.transition_mut().easing = easing;
2374            }
2375            StyleKey::AnimationName => {
2376                let keyframes = match keyword(value)? {
2377                    None | Some("none") => None,
2378                    Some("spin") => Some(Keyframes::Spin),
2379                    Some("ping") => Some(Keyframes::Ping),
2380                    Some("pulse") => Some(Keyframes::Pulse),
2381                    Some("bounce") => Some(Keyframes::Bounce),
2382                    Some(_) => return Err(StyleError::InvalidValue),
2383                };
2384                // An animation already running (a class's) keeps its
2385                // values; a new one takes those set before its name.
2386                let pending = self.pending;
2387                self.view.animation = keyframes.map(|keyframes| {
2388                    let base = self
2389                        .view
2390                        .animation
2391                        .unwrap_or_else(|| pending.animation(KeyframeAnimation::new(keyframes)));
2392                    KeyframeAnimation { keyframes, ..base }
2393                });
2394            }
2395            StyleKey::AnimationDuration => {
2396                let ms = duration(value)?;
2397                self.pending.animation_duration = Some(ms);
2398                if let Some(a) = self.view.animation.as_mut() {
2399                    a.duration = ms;
2400                }
2401            }
2402            StyleKey::AnimationDelay => {
2403                let ms = duration(value)?;
2404                self.pending.animation_delay = Some(ms);
2405                if let Some(a) = self.view.animation.as_mut() {
2406                    a.delay = ms;
2407                }
2408            }
2409            StyleKey::AnimationTimingFunction => {
2410                let easing = timing_function(value)?;
2411                self.pending.animation_easing = Some(easing);
2412                if let Some(a) = self.view.animation.as_mut() {
2413                    a.easing = easing;
2414                }
2415            }
2416            StyleKey::AnimationIterationCount => {
2417                let count = match value {
2418                    StyleValue::Str("infinite") | StyleValue::Null => None,
2419                    v => Some(number(v, 1.0)?.max(0.0) as u32),
2420                };
2421                self.pending.animation_iterations = Some(count);
2422                if let Some(a) = self.view.animation.as_mut() {
2423                    a.iterations = count;
2424                }
2425            }
2426            StyleKey::TextDecorationStyle => {
2427                self.text.decoration_style = match keyword(value)? {
2428                    None => None,
2429                    Some("solid") => Some(DecorationStyle::Solid),
2430                    Some("double") => Some(DecorationStyle::Double),
2431                    Some("dotted") => Some(DecorationStyle::Dotted),
2432                    Some("dashed") => Some(DecorationStyle::Dashed),
2433                    Some("wavy") => Some(DecorationStyle::Wavy),
2434                    Some(_) => return Err(StyleError::InvalidValue),
2435                }
2436            }
2437            StyleKey::TextDecorationThickness => {
2438                self.text.decoration_thickness = match value {
2439                    StyleValue::Null | StyleValue::Str("auto") | StyleValue::Str("from-font") => {
2440                        None
2441                    }
2442                    v => Some(px(length_value(v, 1.0)?.max(0.0))),
2443                }
2444            }
2445            StyleKey::TextUnderlineOffset => {
2446                self.text.underline_offset = match value {
2447                    StyleValue::Null | StyleValue::Str("auto") => None,
2448                    v => Some(px(length_value(v, 0.0)?)),
2449                }
2450            }
2451
2452            // Grid
2453            StyleKey::GridTemplateColumns => {
2454                (l.grid_template_columns, l.grid_template_column_names) = grid_template(value)?;
2455            }
2456            StyleKey::GridTemplateRows => {
2457                (l.grid_template_rows, l.grid_template_row_names) = grid_template(value)?;
2458            }
2459            StyleKey::GridAutoColumns => {
2460                l.grid_auto_columns = grid_value(value, grid::auto_tracks)?;
2461            }
2462            StyleKey::GridAutoRows => {
2463                l.grid_auto_rows = grid_value(value, grid::auto_tracks)?;
2464            }
2465            StyleKey::GridAutoFlow => {
2466                l.grid_auto_flow = match keyword(value)? {
2467                    None => taffy::GridAutoFlow::Row,
2468                    Some(s) => grid::auto_flow(s).ok_or(StyleError::InvalidValue)?,
2469                }
2470            }
2471            StyleKey::GridColumn => l.grid_column = grid_line(value)?,
2472            StyleKey::GridRow => l.grid_row = grid_line(value)?,
2473            StyleKey::GridColumnStart => l.grid_column.start = grid_placement(value)?,
2474            StyleKey::GridColumnEnd => l.grid_column.end = grid_placement(value)?,
2475            StyleKey::GridRowStart => l.grid_row.start = grid_placement(value)?,
2476            StyleKey::GridRowEnd => l.grid_row.end = grid_placement(value)?,
2477            StyleKey::JustifyItems => {
2478                l.justify_items = align_items(value)?.unwrap_or(AlignItems::STRETCH);
2479            }
2480            StyleKey::JustifySelf => {
2481                l.justify_self = match value {
2482                    StyleValue::Str("auto") => None,
2483                    v => align_items(v)?,
2484                }
2485            }
2486        }
2487        Ok(())
2488    }
2489}
2490
2491#[cfg(test)]
2492mod tests {
2493    use super::*;
2494    use crate::geometry::{relative, size};
2495
2496    #[test]
2497    fn parse_colors() {
2498        assert_eq!(Color::parse("#fff"), Some(Color(0xffff_ffff)));
2499        assert_eq!(Color::parse("#f008"), Some(Color(0xff00_0088)));
2500        assert_eq!(Color::parse("#123456"), Some(Color(0x1234_56ff)));
2501        assert_eq!(Color::parse("#12345678"), Some(Color(0x1234_5678)));
2502        assert_eq!(Color::parse("rgb(255, 0, 10)"), Some(Color(0xff00_0aff)));
2503        assert_eq!(Color::parse("rgba(0,0,0,0.5)"), Some(Color(0x0000_0080)));
2504        assert_eq!(Color::parse("white"), Some(Color(0xffff_ffff)));
2505        assert_eq!(Color::parse("#12"), None);
2506        assert_eq!(Color::parse("nope"), None);
2507    }
2508
2509    #[test]
2510    fn react_native_defaults() {
2511        let s = Style::default();
2512        assert_eq!(s.layout.flex_direction, FlexDirection::Column);
2513        assert_eq!(s.layout.flex_shrink, 0.0);
2514        assert_eq!(s.layout.position, Position::Relative);
2515        // Unset: `flex-start` once laid out outside grids.
2516        assert_eq!(s.layout.align_content, AlignContent::NORMAL);
2517        let mut layout = s.layout.clone();
2518        resolve_normal_alignment(&mut layout);
2519        assert_eq!(layout.align_content, AlignContent::FLEX_START);
2520        assert_eq!(s.layout.min_size.width, LengthPercentageAuto::length(0.0));
2521    }
2522
2523    #[test]
2524    fn css_alignment_keywords() {
2525        let mut s = Style::default();
2526        let k = StyleValue::Str;
2527        for key in ["alignItems", "alignSelf", "justifyItems", "justifySelf"] {
2528            for v in ["start", "end", "self-start", "self-end"] {
2529                s.set(key, k(v)).unwrap();
2530            }
2531        }
2532        assert_eq!(s.layout.justify_self, Some(AlignItems::SELF_END));
2533        for key in ["alignContent", "justifyContent"] {
2534            s.set(key, k("end")).unwrap();
2535            assert_eq!(s.set(key, k("self-end")), Err(StyleError::InvalidValue));
2536        }
2537        assert_eq!(s.layout.align_content, AlignContent::END);
2538        s.set("alignContent", k("normal")).unwrap();
2539        assert_eq!(s.layout.align_content, AlignContent::NORMAL);
2540        s.set("justifyContent", StyleValue::Null).unwrap();
2541        assert_eq!(s.layout.justify_content, AlignContent::NORMAL);
2542        // A grid keeps CSS's `normal`; other containers take `flex-start`.
2543        s.set("display", k("grid")).unwrap();
2544        let mut grid = s.layout.clone();
2545        resolve_normal_alignment(&mut grid);
2546        assert_eq!(grid.align_content, AlignContent::NORMAL);
2547        assert_eq!(
2548            s.set("gridTemplateColumns", k("[a] 40px [b")),
2549            Err(StyleError::InvalidValue)
2550        );
2551        s.set("gridTemplateRows", k("[a] 40px [b] 1fr")).unwrap();
2552        assert_eq!(s.layout.grid_template_row_names.len(), 3);
2553        s.set("gridTemplateRows", StyleValue::Null).unwrap();
2554        assert!(s.layout.grid_template_row_names.is_empty());
2555    }
2556
2557    #[test]
2558    fn transform_origins() {
2559        let p = |s| TransformOrigin::parse(s).unwrap();
2560        assert_eq!(p("top left").x, relative(0.0));
2561        assert_eq!(p("top left").y, relative(0.0));
2562        assert_eq!(p("bottom").y, relative(1.0));
2563        assert_eq!(p("bottom").x, relative(0.5));
2564        assert_eq!(p("10px 25%").x, DefiniteLength::from(px(10.0)));
2565        assert_eq!(p("10px 25%").y, relative(0.25));
2566        assert_eq!(p("right 5 3").z, px(3.0));
2567        assert_eq!(p("center top").y, relative(0.0));
2568        assert_eq!(
2569            p("0 0").offset(size(px(100.0), px(50.0))),
2570            (point(px(-50.0), px(-25.0)), Points::ZERO)
2571        );
2572        assert!(TransformOrigin::parse("sideways").is_none());
2573    }
2574
2575    #[test]
2576    fn font_variants() {
2577        let v = FontVariant::parse("small-caps tabular-nums").unwrap();
2578        assert_eq!(v.tags().collect::<Vec<_>>(), ["smcp", "tnum"]);
2579        assert!(FontVariant::parse("wide").is_none());
2580    }
2581
2582    #[test]
2583    fn flex_shorthand() {
2584        let mut s = Style::default();
2585        s.set("flex", StyleValue::Number(2.0)).unwrap();
2586        assert_eq!(s.layout.flex_grow, 2.0);
2587        assert_eq!(s.layout.flex_shrink, 1.0);
2588        assert_eq!(s.layout.flex_basis, Dimension::length(0.0));
2589    }
2590
2591    /// Every order of `decls`.
2592    fn permutations<T: Clone>(decls: &[T]) -> Vec<Vec<T>> {
2593        if decls.len() <= 1 {
2594            return vec![decls.to_vec()];
2595        }
2596        let mut out = Vec::new();
2597        for i in 0..decls.len() {
2598            let mut rest = decls.to_vec();
2599            let first = rest.remove(i);
2600            for mut tail in permutations(&rest) {
2601                tail.insert(0, first.clone());
2602                out.push(tail);
2603            }
2604        }
2605        out
2606    }
2607
2608    /// Checks the style of one style object with `decls` in every order:
2609    /// as recorded, and replayed from the patch (over classes).
2610    fn in_any_order(decls: &[(&str, StyleValue<'_>)], check: impl Fn(&Style)) {
2611        for order in permutations(decls) {
2612            let mut style = Style::default();
2613            let mut patch = StylePatch::default();
2614            for &(key, value) in &order {
2615                patch.set(&mut style, key, value).unwrap();
2616            }
2617            let keys: Vec<_> = order.iter().map(|(k, _)| *k).collect();
2618            println!("{keys:?}");
2619            check(&style);
2620            let mut replayed = Style::default();
2621            patch.apply(&mut replayed);
2622            check(&replayed);
2623        }
2624    }
2625
2626    #[test]
2627    fn border_longhands_override_the_shorthand_in_any_order() {
2628        use StyleValue::{Null, Number, Str};
2629        in_any_order(
2630            &[
2631                ("borderTopWidth", Number(5.0)),
2632                ("borderWidth", Number(2.0)),
2633                ("borderLeftColor", Str("red")),
2634                ("borderColor", Str("blue")),
2635            ],
2636            |s| {
2637                assert_eq!(
2638                    s.view.borders.widths.to_array().map(|w| w.0),
2639                    [5.0, 2.0, 2.0, 2.0]
2640                );
2641                assert_eq!(s.layout.border.top, LengthPercentage::length(5.0));
2642                assert_eq!(s.layout.border.left, LengthPercentage::length(2.0));
2643                let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
2644                assert_eq!(s.view.borders.colors, [blue, blue, blue, red]);
2645            },
2646        );
2647        // A null longhand is unset: the shorthand shows.
2648        in_any_order(
2649            &[("borderTopWidth", Null), ("borderWidth", Number(2.0))],
2650            |s| assert_eq!(s.view.borders.widths.to_array().map(|w| w.0), [2.0; 4]),
2651        );
2652        // Without its shorthand, null still resets the longhand (a class's).
2653        let mut s = Style::default();
2654        s.set("borderTopWidth", Number(4.0)).unwrap();
2655        StylePatch::default()
2656            .set(&mut s, "borderTopWidth", Null)
2657            .unwrap();
2658        assert_eq!(s.view.borders.widths.top, Points::ZERO);
2659    }
2660
2661    #[test]
2662    fn edge_longhands_override_their_shorthands_in_any_order() {
2663        use StyleValue::Number;
2664        let len = LengthPercentageAuto::length;
2665        in_any_order(
2666            &[
2667                ("marginTop", Number(1.0)),
2668                ("marginVertical", Number(2.0)),
2669                ("margin", Number(3.0)),
2670                ("marginLeft", Number(4.0)),
2671                ("marginHorizontal", Number(5.0)),
2672            ],
2673            |s| {
2674                let m = s.layout.margin;
2675                assert_eq!(
2676                    [m.top, m.bottom, m.left, m.right],
2677                    [len(1.0), len(2.0), len(4.0), len(5.0)]
2678                );
2679            },
2680        );
2681        let len = LengthPercentage::length;
2682        in_any_order(
2683            &[
2684                ("paddingRight", Number(1.0)),
2685                ("padding", Number(3.0)),
2686                ("paddingVertical", Number(2.0)),
2687            ],
2688            |s| {
2689                let p = s.layout.padding;
2690                assert_eq!(
2691                    [p.top, p.bottom, p.left, p.right],
2692                    [len(2.0), len(2.0), len(3.0), len(1.0)]
2693                );
2694            },
2695        );
2696        in_any_order(&[("rowGap", Number(4.0)), ("gap", Number(8.0))], |s| {
2697            assert_eq!(s.layout.gap.height, len(4.0));
2698            assert_eq!(s.layout.gap.width, len(8.0));
2699        });
2700    }
2701
2702    #[test]
2703    fn flex_and_grid_longhands_override_their_shorthands_in_any_order() {
2704        use StyleValue::{Number, Str};
2705        in_any_order(&[("flexGrow", Number(2.0)), ("flex", Number(1.0))], |s| {
2706            assert_eq!(s.layout.flex_grow, 2.0);
2707            assert_eq!(s.layout.flex_shrink, 1.0);
2708            assert_eq!(s.layout.flex_basis, Dimension::length(0.0));
2709        });
2710        in_any_order(
2711            &[
2712                ("gridColumnStart", Number(2.0)),
2713                ("gridColumn", Str("1 / 4")),
2714            ],
2715            |s| {
2716                assert_eq!(
2717                    Some(&s.layout.grid_column.start),
2718                    grid::placement("2").as_ref()
2719                );
2720                assert_eq!(
2721                    Some(&s.layout.grid_column.end),
2722                    grid::placement("4").as_ref()
2723                );
2724            },
2725        );
2726    }
2727
2728    #[test]
2729    fn outline_style_none_hides_the_outline_in_any_order() {
2730        use StyleValue::{Null, Number, Str};
2731        in_any_order(
2732            &[("outlineStyle", Str("none")), ("outlineWidth", Number(3.0))],
2733            |s| assert!(!s.view.outline.is_visible()),
2734        );
2735        in_any_order(
2736            &[
2737                ("outlineStyle", Str("dashed")),
2738                ("outlineWidth", Number(3.0)),
2739            ],
2740            |s| {
2741                assert_eq!(s.view.outline.width, px(3.0));
2742                assert_eq!(s.view.outline.style, BorderStyle::Dashed);
2743            },
2744        );
2745        // A later style (inline over classes) showing it again gets the
2746        // width back.
2747        let mut s = Style::default();
2748        s.set("outlineWidth", Number(3.0)).unwrap();
2749        s.set("outlineStyle", Str("none")).unwrap();
2750        s.set("outlineStyle", Null).unwrap();
2751        assert_eq!(s.view.outline.width, px(3.0));
2752    }
2753
2754    #[test]
2755    fn animation_keys_apply_in_any_order() {
2756        use StyleValue::{Number, Str};
2757        in_any_order(
2758            &[
2759                ("animationDuration", Number(500.0)),
2760                ("animationIterationCount", Number(2.0)),
2761                ("animationName", Str("spin")),
2762                ("animationDelay", Str("0.1s")),
2763                ("animationTimingFunction", Str("ease-in")),
2764            ],
2765            |s| {
2766                let a = s.view.animation.unwrap();
2767                assert_eq!(a.keyframes, Keyframes::Spin);
2768                assert_eq!(a.duration, 500.0);
2769                assert_eq!(a.iterations, Some(2));
2770                assert_eq!(a.delay, 100.0);
2771                assert_eq!(a.easing, [0.42, 0.0, 1.0, 1.0]);
2772            },
2773        );
2774        // Without a name nothing runs.
2775        in_any_order(&[("animationDuration", Number(500.0))], |s| {
2776            assert_eq!(s.view.animation, None)
2777        });
2778        // Over a running (class) animation, the values change it.
2779        let mut s = Style::default();
2780        s.set("animationName", Str("ping")).unwrap();
2781        s.set("animationDuration", Number(300.0)).unwrap();
2782        s.set("animationName", Str("spin")).unwrap();
2783        assert_eq!(s.view.animation.unwrap().duration, 300.0);
2784    }
2785
2786    #[test]
2787    fn transition_keys_apply_in_any_order() {
2788        use StyleValue::{Number, Str};
2789        in_any_order(
2790            &[
2791                ("transitionDuration", Number(300.0)),
2792                ("transitionDelay", Number(50.0)),
2793                ("transitionTimingFunction", Str("linear")),
2794                ("transitionProperty", Str("opacity")),
2795            ],
2796            |s| {
2797                let t = s.view.transition.unwrap();
2798                assert_eq!(t.properties, TransitionProps(TransitionProps::OPACITY));
2799                assert_eq!(t.duration, 300.0);
2800                assert_eq!(t.delay, 50.0);
2801                assert_eq!(t.easing, [0.0, 0.0, 1.0, 1.0]);
2802            },
2803        );
2804    }
2805
2806    #[test]
2807    fn corner_radii_override_the_shorthand_in_any_order() {
2808        let mut s = Style::default();
2809        s.set("borderTopLeftRadius", StyleValue::Number(4.0))
2810            .unwrap();
2811        s.set("borderRadius", StyleValue::Number(10.0)).unwrap();
2812        let r = s.view.radii();
2813        assert_eq!(r.to_array(), [px(4.0), px(10.0), px(10.0), px(10.0)]);
2814        assert_eq!(r.shared(), None);
2815        s.set("borderTopLeftRadius", StyleValue::Null).unwrap();
2816        assert_eq!(s.view.radii().shared(), Some(px(10.0)));
2817    }
2818
2819    #[test]
2820    fn shared_radius_ignores_square_corners() {
2821        let r = CornerRadii {
2822            top_left: px(12.0),
2823            top_right: px(12.0),
2824            ..CornerRadii::default()
2825        };
2826        assert_eq!(r.shared(), Some(px(12.0)));
2827        assert_eq!(CornerRadii::default().shared(), Some(px(0.0)));
2828        assert!(CornerRadii::default().is_zero());
2829    }
2830
2831    #[test]
2832    fn radii_fit_the_box() {
2833        // 100 + 300 on a 200 wide box: everything scales by 0.5.
2834        let r = CornerRadii {
2835            top_left: px(100.0),
2836            top_right: px(300.0),
2837            bottom_right: px(0.0),
2838            bottom_left: px(0.0),
2839            continuous: false,
2840        }
2841        .fit(size(px(200.0), px(1000.0)));
2842        assert_eq!(r.to_array(), [px(50.0), px(150.0), px(0.0), px(0.0)]);
2843        let fits = CornerRadii::all(px(10.0));
2844        assert_eq!(fits.fit(size(px(100.0), px(100.0))), fits);
2845        assert_eq!(fits.inset(px(4.0)), CornerRadii::all(px(6.0)));
2846        assert_eq!(fits.inset(px(40.0)), CornerRadii::all(px(0.0)));
2847    }
2848
2849    #[test]
2850    fn shadow_defaults_follow_react_native() {
2851        let mut s = Style::default();
2852        assert!(!s.view.shadow.is_visible());
2853        s.set("shadowOpacity", StyleValue::Number(0.3)).unwrap();
2854        s.set("shadowRadius", StyleValue::Number(8.0)).unwrap();
2855        s.set_shadow_offset(Some(point(px(0.0), px(4.0))));
2856        assert!(s.view.shadow.is_visible());
2857        assert_eq!(s.view.shadow.offset_y, px(4.0));
2858        s.set("shadowColor", StyleValue::Str("transparent"))
2859            .unwrap();
2860        assert!(!s.view.shadow.is_visible());
2861        s.set_shadow_offset(None);
2862        assert_eq!(s.view.shadow.offset_y, px(-3.0));
2863    }
2864
2865    #[test]
2866    fn text_styles_parse() {
2867        let mut s = Style::default();
2868        s.set("fontFamily", StyleValue::Str("Inter")).unwrap();
2869        s.set("fontStyle", StyleValue::Str("italic")).unwrap();
2870        s.set(
2871            "textDecorationLine",
2872            StyleValue::Str("underline line-through"),
2873        )
2874        .unwrap();
2875        s.set("textTransform", StyleValue::Str("capitalize"))
2876            .unwrap();
2877        assert_eq!(s.text.font_family, Some(FontFamily::new("Inter")));
2878        assert_eq!(&*s.text.font_family.unwrap().name(), "Inter");
2879        assert_eq!(s.text.italic, Some(true));
2880        assert_eq!(
2881            s.text.decoration,
2882            Some(TextDecoration {
2883                underline: true,
2884                line_through: true
2885            })
2886        );
2887        assert_eq!(
2888            TextTransform::Capitalize.apply("hello wörld-x  ünd"),
2889            "Hello Wörld-x  Ünd"
2890        );
2891        assert_eq!(
2892            s.set("fontStyle", StyleValue::Str("oblique")),
2893            Err(StyleError::InvalidValue)
2894        );
2895    }
2896
2897    #[test]
2898    fn rejects_bad_values() {
2899        let mut s = Style::default();
2900        assert_eq!(
2901            s.set("width", StyleValue::Str("wide")),
2902            Err(StyleError::InvalidValue)
2903        );
2904        assert_eq!(
2905            s.set("nope", StyleValue::Number(1.0)),
2906            Err(StyleError::UnknownProperty)
2907        );
2908        s.set("width", StyleValue::Str("50%")).unwrap();
2909        assert_eq!(s.layout.size.width, Dimension::percent(0.5));
2910    }
2911}