use std::sync::Arc;
use taffy::{
AlignContent, AlignItems, Dimension, Display, FlexDirection, FlexWrap, LengthPercentage,
LengthPercentageAuto, Position,
};
use crate::{
css,
effects::{
BlendMode, BoxShadow, Cursor, Effects, Filter, Gradient, KeyframeAnimation, Keyframes,
Outline, Transition, TransitionProps,
},
grid,
transform::{Transform, TransformKind},
ui::PropEnum,
};
/// An sRGB color packed as `0xRRGGBBAA`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Color(pub u32);
impl Color {
/// Fully transparent.
pub const TRANSPARENT: Color = Color(0);
/// Opaque black.
pub const BLACK: Color = Color(0x0000_00ff);
/// Creates a color from 8-bit components.
#[inline]
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
Color((r as u32) << 24 | (g as u32) << 16 | (b as u32) << 8 | a as u32)
}
/// Returns `(r, g, b, a)` in `0.0..=1.0`.
#[inline]
pub fn to_f64(self) -> (f64, f64, f64, f64) {
let c = self.0;
(
(c >> 24) as f64 / 255.0,
((c >> 16) & 0xff) as f64 / 255.0,
((c >> 8) & 0xff) as f64 / 255.0,
(c & 0xff) as f64 / 255.0,
)
}
/// Returns true if the alpha component is zero.
#[inline]
pub const fn is_transparent(self) -> bool {
self.0 & 0xff == 0
}
/// Parses a CSS color: hex, `rgb()` / `rgba()`, `hsl()` / `hsla()`,
/// `oklch()`, `oklab()` or a CSS named color.
pub fn parse(s: &str) -> Option<Color> {
crate::css::color(s)
}
}
/// Horizontal alignment of a text block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
/// Natural alignment for the writing direction.
#[default]
Auto,
/// Left aligned.
Left,
/// Centered.
Center,
/// Right aligned.
Right,
/// Justified.
Justify,
}
/// A font family name, interned: copying and comparing one is free, so
/// resolved text styles stay `Copy` and cheap to hash.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FontFamily(u32);
static FAMILIES: std::sync::Mutex<Vec<std::sync::Arc<str>>> = std::sync::Mutex::new(Vec::new());
impl FontFamily {
/// Interns `name`. Apps use a handful of families, so the table is a
/// small vector scanned linearly.
pub fn new(name: &str) -> FontFamily {
let mut families = FAMILIES.lock().unwrap_or_else(|e| e.into_inner());
if let Some(i) = families.iter().position(|f| &**f == name) {
return FontFamily(i as u32);
}
families.push(name.into());
FontFamily(families.len() as u32 - 1)
}
/// The family name.
pub fn name(self) -> std::sync::Arc<str> {
FAMILIES.lock().unwrap_or_else(|e| e.into_inner())[self.0 as usize].clone()
}
}
impl std::fmt::Debug for FontFamily {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "FontFamily({:?})", self.name())
}
}
/// Lines drawn through or under text (`textDecorationLine`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct TextDecoration {
/// Underline.
pub underline: bool,
/// Strikethrough.
pub line_through: bool,
}
impl TextDecoration {
/// True if no line is drawn.
#[inline]
pub const fn is_none(self) -> bool {
!self.underline && !self.line_through
}
}
/// How decoration lines are drawn (`textDecorationStyle`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum DecorationStyle {
/// One solid line (default).
#[default]
Solid,
/// Two lines.
Double,
/// Dots.
Dotted,
/// Dashes.
Dashed,
/// A wavy line.
Wavy,
}
/// Case changes applied to text (`textTransform`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextTransform {
/// As written.
#[default]
None,
/// UPPER CASE.
Uppercase,
/// lower case.
Lowercase,
/// First Letter Of Each Word.
Capitalize,
}
impl TextTransform {
/// Applies the transform to `s`.
pub fn apply<'a>(self, s: &'a str) -> std::borrow::Cow<'a, str> {
match self {
TextTransform::None => s.into(),
TextTransform::Uppercase => s.to_uppercase().into(),
TextTransform::Lowercase => s.to_lowercase().into(),
TextTransform::Capitalize => {
let mut out = String::with_capacity(s.len());
let mut start = true;
for c in s.chars() {
if start && c.is_alphanumeric() {
out.extend(c.to_uppercase());
start = false;
} else {
out.push(c);
start |= c.is_whitespace();
}
}
out.into()
}
}
}
}
/// Where text that does not fit `numberOfLines` is cut (`ellipsizeMode`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
pub enum EllipsizeMode {
/// "Lorem ips…" (default).
#[default]
Tail,
/// "…sum dolor".
Head,
/// "Lorem…dolor".
Middle,
/// Cut without an ellipsis.
Clip,
}
/// Corner radii in points, clockwise from the top left.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct CornerRadii {
/// Top left.
pub top_left: f32,
/// Top right.
pub top_right: f32,
/// Bottom right.
pub bottom_right: f32,
/// Bottom left.
pub bottom_left: f32,
/// `borderCurve: "continuous"`: corners whose curvature grows from the
/// edges (iOS app icons) instead of circular arcs; see [`crate::shape`].
pub continuous: bool,
}
impl CornerRadii {
/// The same circular radius on every corner.
pub const fn all(r: f32) -> Self {
Self {
top_left: r,
top_right: r,
bottom_right: r,
bottom_left: r,
continuous: false,
}
}
/// `[top_left, top_right, bottom_right, bottom_left]`.
#[inline]
pub const fn to_array(self) -> [f32; 4] {
[
self.top_left,
self.top_right,
self.bottom_right,
self.bottom_left,
]
}
/// True if no corner is rounded.
#[inline]
pub fn is_zero(&self) -> bool {
self.to_array().iter().all(|&r| r <= 0.0)
}
/// The radius shared by every rounded corner, if they all share one.
/// Platforms render such shapes with a single radius plus a mask of
/// the rounded corners (no paths).
pub fn shared(&self) -> Option<f32> {
let mut shared = 0.0;
for r in self.to_array() {
if r > 0.0 {
if shared > 0.0 && r != shared {
return None;
}
shared = r;
}
}
Some(shared)
}
/// Scales the radii down so adjacent corners do not overlap on a
/// `width` x `height` box (CSS rule).
pub fn fit(self, width: f32, height: f32) -> Self {
let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1.0 };
let f = ratio(width, self.top_left, self.top_right)
.min(ratio(width, self.bottom_left, self.bottom_right))
.min(ratio(height, self.top_left, self.bottom_left))
.min(ratio(height, self.top_right, self.bottom_right))
.max(0.0);
if f >= 1.0 {
return self;
}
Self {
top_left: self.top_left * f,
top_right: self.top_right * f,
bottom_right: self.bottom_right * f,
bottom_left: self.bottom_left * f,
..self
}
}
/// The radii of a curve `d` points inside this one (e.g. the inner edge
/// of a border).
pub fn inset(self, d: f32) -> Self {
Self {
top_left: (self.top_left - d).max(0.0),
top_right: (self.top_right - d).max(0.0),
bottom_right: (self.bottom_right - d).max(0.0),
bottom_left: (self.bottom_left - d).max(0.0),
..self
}
}
}
/// A drop shadow (React Native's `shadow*` properties).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Shadow {
/// Shadow color; its alpha is multiplied by `opacity`.
pub color: Color,
/// Horizontal offset in points.
pub offset_x: f32,
/// Vertical offset in points.
pub offset_y: f32,
/// Opacity in `0.0..=1.0`; 0 (the default) means no shadow.
pub opacity: f32,
/// Blur radius in points.
pub radius: f32,
}
impl Shadow {
/// React Native's defaults: black, offset `(0, -3)`, radius 3, opacity 0.
pub const DEFAULT: Shadow = Shadow {
color: Color::BLACK,
offset_x: 0.0,
offset_y: -3.0,
opacity: 0.0,
radius: 3.0,
};
/// True if the shadow draws anything.
#[inline]
pub fn is_visible(&self) -> bool {
self.opacity > 0.0 && !self.color.is_transparent()
}
}
impl Default for Shadow {
fn default() -> Self {
Self::DEFAULT
}
}
/// How borders are drawn (`borderStyle`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BorderStyle {
/// A solid line (default).
#[default]
Solid,
/// Dashes.
Dashed,
/// Dots.
Dotted,
}
/// Border widths and colors, per side.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Borders {
/// Widths in points: top, right, bottom, left.
pub widths: [f32; 4],
/// Colors: top, right, bottom, left.
pub colors: [Color; 4],
/// Line style.
pub style: BorderStyle,
}
impl Borders {
/// No border.
pub const NONE: Borders = Borders {
widths: [0.0; 4],
colors: [Color::BLACK; 4],
style: BorderStyle::Solid,
};
/// True if some side draws something.
pub fn is_visible(&self) -> bool {
(0..4).any(|i| self.widths[i] > 0.0 && !self.colors[i].is_transparent())
}
/// `(width, color)` when every side is the same.
pub fn uniform(&self) -> Option<(f32, Color)> {
let [w, ..] = self.widths;
let [c, ..] = self.colors;
(self.widths.iter().all(|&x| x == w) && self.colors.iter().all(|&x| x == c))
.then_some((w, c))
}
}
impl Default for Borders {
fn default() -> Self {
Self::NONE
}
}
/// Visual (non-layout) properties of a native view.
#[derive(Debug, Clone, PartialEq)]
pub struct ViewStyle {
/// Background fill.
pub background_color: Color,
/// `borderRadius`: the radius of corners without their own.
pub border_radius: f32,
/// `borderTopLeftRadius` etc., clockwise from the top left; they
/// override `border_radius`.
pub corner_radius: [Option<f32>; 4],
/// `borderCurve: "continuous"`.
pub continuous_corners: bool,
/// Borders (their widths also affect layout).
pub borders: Borders,
/// Opacity in `0.0..=1.0`.
pub opacity: f32,
/// Clip children to the (rounded) bounds.
pub overflow_hidden: bool,
/// Drop shadow.
pub shadow: Shadow,
/// Static transform, around the view's center.
pub transform: Transform,
/// `tintColor`: recolors an image's opaque pixels.
pub tint_color: Option<Color>,
/// Android's material shadow (points): the node's `android={{ elevation }}`
/// prop, not a style.
pub elevation: f32,
/// `transformOrigin`: the point transforms act around.
pub transform_origin: TransformOrigin,
/// `backfaceVisibility: "hidden"`: invisible when turned away.
pub backface_hidden: bool,
/// Layered / inset shadows, gradients and filters.
pub effects: Option<Arc<Effects>>,
/// `mixBlendMode`.
pub blend_mode: BlendMode,
/// `outline*`.
pub outline: Outline,
/// `visibility: "hidden"`: not drawn and not touchable, still laid out.
pub hidden: bool,
/// `cursor`.
pub cursor: Cursor,
/// `transition*`: style changes animate.
pub transition: Option<Transition>,
/// `animation*`: a keyframe animation runs.
pub animation: Option<KeyframeAnimation>,
}
/// A coordinate of [`TransformOrigin`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OriginLen {
/// Points from the left / top edge.
Px(f32),
/// A fraction of the width / height.
Fraction(f32),
}
impl OriginLen {
/// The coordinate in a box `length` points long.
pub fn resolve(self, length: f32) -> f32 {
match self {
OriginLen::Px(v) => v,
OriginLen::Fraction(f) => f * length,
}
}
}
/// `transformOrigin`: the point transforms rotate and scale around.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TransformOrigin {
/// Horizontal position.
pub x: OriginLen,
/// Vertical position.
pub y: OriginLen,
/// Depth in points.
pub z: f32,
}
impl Default for TransformOrigin {
fn default() -> Self {
Self::CENTER
}
}
impl TransformOrigin {
/// The center (the default).
pub const CENTER: Self = Self {
x: OriginLen::Fraction(0.5),
y: OriginLen::Fraction(0.5),
z: 0.0,
};
/// Offset of the origin from the center of a `width` × `height` box.
pub fn offset(&self, width: f32, height: f32) -> (f32, f32, f32) {
(
self.x.resolve(width) - width / 2.0,
self.y.resolve(height) - height / 2.0,
self.z,
)
}
/// Parses CSS's syntax: one to three of keywords (`left`, `center`,
/// `right`, `top`, `bottom`), percentages and lengths (`10px` or a
/// bare number), the third being a depth.
pub fn parse(s: &str) -> Option<Self> {
let parts: Vec<&str> = s.split_whitespace().collect();
if parts.is_empty() || parts.len() > 3 {
return None;
}
let len = |p: &str| -> Option<OriginLen> {
if let Some(pct) = p.strip_suffix('%') {
return pct
.trim()
.parse::<f32>()
.ok()
.map(|v| OriginLen::Fraction(v / 100.0));
}
p.strip_suffix("px")
.unwrap_or(p)
.parse::<f32>()
.ok()
.map(OriginLen::Px)
};
let mut x = None;
let mut y = None;
let mut free = Vec::new();
for &p in parts.iter().take(2) {
match p {
"left" => x = Some(OriginLen::Fraction(0.0)),
"right" => x = Some(OriginLen::Fraction(1.0)),
"top" => y = Some(OriginLen::Fraction(0.0)),
"bottom" => y = Some(OriginLen::Fraction(1.0)),
"center" => free.push(OriginLen::Fraction(0.5)),
p => free.push(len(p)?),
}
}
// Unnamed values fill x, then y.
for v in free {
if x.is_none() {
x = Some(v);
} else if y.is_none() {
y = Some(v);
} else {
return None;
}
}
let z = match parts.get(2) {
Some(p) => p.strip_suffix("px").unwrap_or(p).parse::<f32>().ok()?,
None => 0.0,
};
Some(Self {
x: x.unwrap_or(OriginLen::Fraction(0.5)),
y: y.unwrap_or(OriginLen::Fraction(0.5)),
z,
})
}
}
/// `fontVariant`: OpenType features, as bits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FontVariant(pub u8);
impl FontVariant {
/// `small-caps`.
pub const SMALL_CAPS: u8 = 1;
/// `oldstyle-nums`.
pub const OLDSTYLE_NUMS: u8 = 2;
/// `lining-nums`.
pub const LINING_NUMS: u8 = 4;
/// `tabular-nums`.
pub const TABULAR_NUMS: u8 = 8;
/// `proportional-nums`.
pub const PROPORTIONAL_NUMS: u8 = 16;
/// Parses space-separated variant names.
pub fn parse(s: &str) -> Option<Self> {
let mut bits = 0;
for word in s.split_whitespace() {
bits |= match word {
"small-caps" => Self::SMALL_CAPS,
"oldstyle-nums" => Self::OLDSTYLE_NUMS,
"lining-nums" => Self::LINING_NUMS,
"tabular-nums" => Self::TABULAR_NUMS,
"proportional-nums" => Self::PROPORTIONAL_NUMS,
"normal" => 0,
_ => return None,
};
}
Some(Self(bits))
}
/// Whether `bit` is set.
pub fn has(self, bit: u8) -> bool {
self.0 & bit != 0
}
/// The OpenType feature tags.
pub fn tags(self) -> impl Iterator<Item = &'static str> {
[
(Self::SMALL_CAPS, "smcp"),
(Self::OLDSTYLE_NUMS, "onum"),
(Self::LINING_NUMS, "lnum"),
(Self::TABULAR_NUMS, "tnum"),
(Self::PROPORTIONAL_NUMS, "pnum"),
]
.into_iter()
.filter(move |&(bit, _)| self.has(bit))
.map(|(_, tag)| tag)
}
}
impl ViewStyle {
/// Drops the gradient backgrounds, so the background color shows: what
/// press feedback and animated background colors do (a gradient is
/// drawn over the color and would hide them).
pub(crate) fn clear_background_images(&mut self) {
if let Some(e) = self
.effects
.as_deref()
.filter(|e| !e.background_images.is_empty())
{
let mut effects = e.clone();
effects.background_images.clear();
self.effects = crate::effects::shared(effects);
}
}
/// The radius of each corner (before fitting them to a size with
/// [`CornerRadii::fit`]).
pub fn radii(&self) -> CornerRadii {
let [tl, tr, br, bl] = self
.corner_radius
.map(|r| r.unwrap_or(self.border_radius).max(0.0));
CornerRadii {
top_left: tl,
top_right: tr,
bottom_right: br,
bottom_left: bl,
continuous: self.continuous_corners,
}
}
}
impl Default for ViewStyle {
fn default() -> Self {
Self {
background_color: Color::TRANSPARENT,
border_radius: 0.0,
corner_radius: [None; 4],
continuous_corners: false,
borders: Borders::NONE,
opacity: 1.0,
overflow_hidden: false,
shadow: Shadow::DEFAULT,
transform: Transform::IDENTITY,
tint_color: None,
elevation: 0.0,
transform_origin: TransformOrigin::CENTER,
backface_hidden: false,
effects: None,
blend_mode: BlendMode::Normal,
outline: Outline::NONE,
hidden: false,
cursor: Cursor::Auto,
transition: None,
animation: None,
}
}
}
/// A shadow behind text (`textShadow*`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextShadow {
/// Color.
pub color: Color,
/// Horizontal offset in points.
pub offset_x: f32,
/// Vertical offset in points.
pub offset_y: f32,
/// Blur radius in points.
pub radius: f32,
}
/// Text properties as written on a node; unset values are inherited from
/// the enclosing text.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct TextStyle {
/// Foreground color.
pub color: Option<Color>,
/// Font size in points.
pub font_size: Option<f32>,
/// Font weight, `100..=900`.
pub font_weight: Option<u16>,
/// Line height in points.
pub line_height: Option<f32>,
/// Block alignment (only meaningful on a text block).
pub text_align: Option<TextAlign>,
/// Font family; `None` inherits (the system font at the root).
pub font_family: Option<FontFamily>,
/// Italic (`fontStyle`).
pub italic: Option<bool>,
/// Extra space between characters in points.
pub letter_spacing: Option<f32>,
/// Extra space between characters in ems of this node's font size
/// (`"0.05em"`); overrides `letter_spacing` when set after it.
pub letter_spacing_em: Option<f32>,
/// Line height as a multiple of the font size (`"1.5"`, `"1.5em"`),
/// inherited as a multiple.
pub line_height_multiple: Option<f32>,
/// Underline / strikethrough.
pub decoration: Option<TextDecoration>,
/// `textDecorationStyle`.
pub decoration_style: Option<DecorationStyle>,
/// `textDecorationThickness` in points.
pub decoration_thickness: Option<f32>,
/// `textUnderlineOffset` in points below the baseline.
pub underline_offset: Option<f32>,
/// Color of the decoration lines; the text color by default.
pub decoration_color: Option<Color>,
/// Case transform.
pub transform: Option<TextTransform>,
/// `textShadowColor`.
pub shadow_color: Option<Color>,
/// `textShadowOffset`.
pub shadow_offset: Option<(f32, f32)>,
/// `textShadowRadius`.
pub shadow_radius: Option<f32>,
/// `fontVariant`.
pub font_variant: Option<FontVariant>,
/// `writingDirection`: right to left (`Some(true)`), left to right, or
/// the layout's direction (`None`, `auto`).
pub writing_direction: Option<bool>,
/// `textAlignVertical`: where text shorter than its box sits, 0 top
/// (`auto`, `top`), 0.5 `center`, 1 `bottom`.
pub align_vertical: Option<f32>,
}
impl TextStyle {
/// The text shadow these properties describe, if any. Like NSShadow, an
/// offset or radius without a color uses black at a third of opacity.
pub fn shadow(&self) -> Option<TextShadow> {
if self.shadow_color.is_none()
&& self.shadow_offset.is_none()
&& self.shadow_radius.is_none()
{
return None;
}
let color = self.shadow_color.unwrap_or(Color(0x0000_0055));
if color.is_transparent() {
return None;
}
let (offset_x, offset_y) = self.shadow_offset.unwrap_or((0.0, 0.0));
Some(TextShadow {
color,
offset_x,
offset_y,
radius: self.shadow_radius.unwrap_or(0.0).max(0.0),
})
}
}
/// A complete node style, split by consumer.
#[derive(Debug, Clone)]
pub struct Style {
/// Layout properties, consumed by taffy.
pub layout: taffy::Style,
/// Visual properties of the native view.
pub view: ViewStyle,
/// Text properties.
pub text: TextStyle,
/// Visual properties driven by native animation nodes; they override
/// the static values while bound.
pub animated: Vec<(nsh_animation::AnimationProp, nsh_animation::NodeId)>,
/// `zIndex`: stacking order among siblings (higher on top).
pub z_index: i32,
/// `direction`: right to left (`Some(true)`), left to right, or
/// inherited (`None`).
pub direction: Option<bool>,
/// Start / end properties, placed by the resolved direction.
pub logical: Logical,
}
/// Properties named by start and end (`marginStart`, `borderTopEndRadius`
/// ...): left and right in left-to-right layouts, the other way around in
/// right-to-left ones.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Logical {
/// `marginStart`, `marginEnd`.
pub margin: [Option<LengthPercentageAuto>; 2],
/// `paddingStart`, `paddingEnd`.
pub padding: [Option<LengthPercentage>; 2],
/// `start`, `end`.
pub inset: [Option<LengthPercentageAuto>; 2],
/// `borderStartWidth`, `borderEndWidth`.
pub border_width: [Option<f32>; 2],
/// `borderStartColor`, `borderEndColor`.
pub border_color: [Option<Color>; 2],
/// `borderTopStartRadius`, `borderTopEndRadius`,
/// `borderBottomEndRadius`, `borderBottomStartRadius`.
pub radius: [Option<f32>; 4],
}
impl Logical {
/// Whether no start / end property is set.
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
}
fn set_side<T>(rect: &mut taffy::Rect<T>, left: bool, value: T) {
if left {
rect.left = value;
} else {
rect.right = value;
}
}
/// Swaps the left and right properties: in right-to-left layouts they
/// mean start and end, as in React Native. An involution.
pub(crate) fn swap_sides(layout: &mut taffy::Style, view: &mut ViewStyle) {
fn swap<T>(r: &mut taffy::Rect<T>) {
std::mem::swap(&mut r.left, &mut r.right);
}
swap(&mut layout.margin);
swap(&mut layout.padding);
swap(&mut layout.inset);
swap(&mut layout.border);
view.borders.widths.swap(1, 3);
view.borders.colors.swap(1, 3);
// top left, top right, bottom right, bottom left
view.corner_radius.swap(0, 1);
view.corner_radius.swap(2, 3);
}
/// Lays a node out in direction `rtl`: swaps its left and right
/// properties when right to left, then places the start / end ones.
pub(crate) fn apply_direction(
layout: &mut taffy::Style,
view: &mut ViewStyle,
logical: &Logical,
rtl: bool,
) {
layout.direction = if rtl {
taffy::Direction::Rtl
} else {
taffy::Direction::Ltr
};
if rtl {
swap_sides(layout, view);
}
if logical.is_empty() {
return;
}
// Start is the left side left to right.
for (i, left) in [!rtl, rtl].into_iter().enumerate() {
if let Some(v) = logical.margin[i] {
set_side(&mut layout.margin, left, v);
}
if let Some(v) = logical.padding[i] {
set_side(&mut layout.padding, left, v);
}
if let Some(v) = logical.inset[i] {
set_side(&mut layout.inset, left, v);
}
let side = if left { 3 } else { 1 };
if let Some(w) = logical.border_width[i] {
set_side(&mut layout.border, left, LengthPercentage::length(w));
view.borders.widths[side] = w;
}
if let Some(c) = logical.border_color[i] {
view.borders.colors[side] = c;
}
}
// Corners: top start, top end, bottom end, bottom start.
let corners = if rtl { [1, 0, 3, 2] } else { [0, 1, 2, 3] };
for (i, &corner) in corners.iter().enumerate() {
if let Some(r) = logical.radius[i] {
view.corner_radius[corner] = Some(r);
}
}
}
impl Default for Style {
/// React Native defaults, which differ from CSS (and taffy) defaults.
fn default() -> Self {
let layout = taffy::Style {
display: Display::Flex,
position: Position::Relative,
flex_direction: FlexDirection::Column,
flex_shrink: 0.0,
align_content: AlignContent::FLEX_START,
// Yoga has no automatic minimum size (see `min_len`).
min_size: taffy::Size {
width: LengthPercentageAuto::length(0.0),
height: LengthPercentageAuto::length(0.0),
},
..taffy::Style::DEFAULT
};
Self {
layout,
view: ViewStyle::default(),
text: TextStyle::default(),
animated: Vec::new(),
z_index: 0,
direction: None,
logical: Logical::default(),
}
}
}
/// Which TypeScript style interface a property belongs to (each extends
/// the one before: layout, then views, then text or images).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StyleGroup {
Layout,
View,
Text,
Image,
}
/// A style property's TypeScript declaration (`js::style`).
#[derive(Debug, Clone, Copy)]
pub(crate) struct StyleType {
pub(crate) name: &'static str,
pub(crate) group: StyleGroup,
pub(crate) ts: &'static str,
pub(crate) doc: Option<&'static str>,
}
/// The style properties the JS bridge decodes itself (objects and lists,
/// `crates/nsh-js/src/protocol.rs`), for the TypeScript declarations.
pub(crate) const OBJECT_STYLE_TYPES: &[StyleType] = &[
StyleType {
name: "transform",
group: StyleGroup::View,
ts: "TransformStep[]",
doc: None,
},
StyleType {
name: "shadowOffset",
group: StyleGroup::View,
ts: "{ width: number; height: number }",
doc: Some("Default `{ width: 0, height: -3 }`, as in React Native."),
},
StyleType {
name: "textShadowOffset",
group: StyleGroup::Text,
ts: "{ width: number; height: number }",
doc: None,
},
];
macro_rules! style_keys {
($($key:ident = $name:literal: $group:ident $ts:literal $($doc:literal)?),* $(,)?) => {
/// The style properties' TypeScript declarations, in order.
pub(crate) const STYLE_TYPES: &[StyleType] = &[$(StyleType {
name: $name,
group: StyleGroup::$group,
ts: $ts,
doc: style_keys!(@doc $($doc)?),
}),*];
/// A style property, by its React Native name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StyleKey {
$(
#[doc = concat!("`", $name, "`")]
$key,
)*
}
impl StyleKey {
/// The key named `name` (React Native's camel case).
pub fn parse(name: &str) -> Option<StyleKey> {
Some(match name {
$($name => StyleKey::$key,)*
_ => return None,
})
}
/// The React Native name.
pub fn name(self) -> &'static str {
match self {
$(StyleKey::$key => $name,)*
}
}
}
};
(@doc) => { None };
(@doc $doc:literal) => { Some($doc) };
}
style_keys! {
Display = "display": Layout "\"flex\" | \"grid\" | \"block\" | \"none\"",
Position = "position": Layout "\"relative\" | \"absolute\"",
FlexDirection = "flexDirection": Layout "\"row\" | \"column\" | \"row-reverse\" | \"column-reverse\"",
FlexWrap = "flexWrap": Layout "\"wrap\" | \"nowrap\" | \"wrap-reverse\"",
Flex = "flex": Layout "number",
FlexGrow = "flexGrow": Layout "number",
FlexShrink = "flexShrink": Layout "number",
FlexBasis = "flexBasis": Layout "DimensionValue",
JustifyContent = "justifyContent": Layout "Exclude<Distribute, \"stretch\"> | \"stretch\"",
AlignItems = "alignItems": Layout "Align",
AlignSelf = "alignSelf": Layout "Align | \"auto\"",
AlignContent = "alignContent": Layout "Distribute",
Width = "width": Layout "DimensionValue",
Height = "height": Layout "DimensionValue",
MinWidth = "minWidth": Layout "LengthValue",
MinHeight = "minHeight": Layout "LengthValue",
MaxWidth = "maxWidth": Layout "LengthValue",
MaxHeight = "maxHeight": Layout "LengthValue",
AspectRatio = "aspectRatio": Layout "number",
Top = "top": Layout "DimensionValue",
Right = "right": Layout "DimensionValue",
Bottom = "bottom": Layout "DimensionValue",
Left = "left": Layout "DimensionValue",
Margin = "margin": Layout "DimensionValue",
MarginHorizontal = "marginHorizontal": Layout "DimensionValue",
MarginVertical = "marginVertical": Layout "DimensionValue",
MarginTop = "marginTop": Layout "DimensionValue",
MarginRight = "marginRight": Layout "DimensionValue",
MarginBottom = "marginBottom": Layout "DimensionValue",
MarginLeft = "marginLeft": Layout "DimensionValue",
Padding = "padding": Layout "LengthValue",
PaddingHorizontal = "paddingHorizontal": Layout "LengthValue",
PaddingVertical = "paddingVertical": Layout "LengthValue",
PaddingTop = "paddingTop": Layout "LengthValue",
PaddingRight = "paddingRight": Layout "LengthValue",
PaddingBottom = "paddingBottom": Layout "LengthValue",
PaddingLeft = "paddingLeft": Layout "LengthValue",
Gap = "gap": Layout "LengthValue",
RowGap = "rowGap": Layout "LengthValue",
ColumnGap = "columnGap": Layout "LengthValue",
BorderWidth = "borderWidth": View "number",
BorderTopWidth = "borderTopWidth": View "number",
BorderRightWidth = "borderRightWidth": View "number",
BorderBottomWidth = "borderBottomWidth": View "number",
BorderLeftWidth = "borderLeftWidth": View "number",
ZIndex = "zIndex": Layout "number" "Order among siblings (stable); also the native stacking order.",
BoxShadow = "boxShadow": View "string" "CSS `box-shadow`: offsets, blur, spread and color, several separated by commas, `inset` for inner shadows.",
BackgroundImage = "backgroundImage": View "string" "CSS gradients drawn over the background color: `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`, several separated by commas.",
ExperimentalBackgroundImage = "experimental_backgroundImage": View "string" "React Native's name of `backgroundImage`.",
Filter = "filter": View "string" "CSS filters of the view and its content: `brightness()`, `contrast()`, `grayscale()`, `hue-rotate()`, `invert()`, `saturate()`, `sepia()`, `opacity()`, `blur()`, `drop-shadow()`.",
BackdropFilter = "backdropFilter": View "string" "CSS filters of what is behind the view (`blur(10px)`).",
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.",
OutlineWidth = "outlineWidth": View "number" "A line outside the border that takes no space.",
OutlineColor = "outlineColor": View "ColorValue",
OutlineStyle = "outlineStyle": View "\"solid\" | \"double\" | \"dashed\" | \"dotted\" | \"none\" | \"hidden\"",
OutlineOffset = "outlineOffset": View "number" "Distance from the border edge (negative: inside).",
Visibility = "visibility": View "\"visible\" | \"hidden\" | \"collapse\"" "Hidden views keep their space.",
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).",
TransitionProperty = "transitionProperty": View "string" "The properties that animate when they change (`\"opacity, transform\"`, `\"all\"`, `\"colors\"`).",
TransitionDuration = "transitionDuration": View "number | `${number}ms` | `${number}s`" "Milliseconds as a number, or `\"150ms\"` / `\"0.2s\"`.",
TransitionDelay = "transitionDelay": View "number | `${number}ms` | `${number}s`",
TransitionTimingFunction = "transitionTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
AnimationName = "animationName": View "\"none\" | \"spin\" | \"ping\" | \"pulse\" | \"bounce\"" "A built-in keyframe animation, run natively.",
AnimationDuration = "animationDuration": View "number | `${number}ms` | `${number}s`",
AnimationDelay = "animationDelay": View "number | `${number}ms` | `${number}s`",
AnimationTimingFunction = "animationTimingFunction": View "\"linear\" | \"ease\" | \"ease-in\" | \"ease-out\" | \"ease-in-out\" | `cubic-bezier(${string})`",
AnimationIterationCount = "animationIterationCount": View "number | \"infinite\"",
TextDecorationStyle = "textDecorationStyle": Text "\"solid\" | \"double\" | \"dotted\" | \"dashed\" | \"wavy\"",
TextDecorationThickness = "textDecorationThickness": Text "number | \"auto\" | \"from-font\"",
TextUnderlineOffset = "textUnderlineOffset": Text "number | \"auto\"",
GridTemplateColumns = "gridTemplateColumns": Layout "string" "CSS grid tracks: `\"repeat(3, 1fr)\"`, `\"200px 1fr\"`, `minmax()`, `auto-fill` / `auto-fit`, line names.",
GridTemplateRows = "gridTemplateRows": Layout "string",
GridAutoColumns = "gridAutoColumns": Layout "string" "Tracks of implicitly created columns.",
GridAutoRows = "gridAutoRows": Layout "string",
GridAutoFlow = "gridAutoFlow": Layout "\"row\" | \"column\" | \"dense\" | \"row dense\" | \"column dense\"",
GridColumn = "gridColumn": Layout "number | string" "`\"1 / 3\"`, `\"span 2\"`, a line number or name.",
GridColumnStart = "gridColumnStart": Layout "number | string",
GridColumnEnd = "gridColumnEnd": Layout "number | string",
GridRow = "gridRow": Layout "number | string",
GridRowStart = "gridRowStart": Layout "number | string",
GridRowEnd = "gridRowEnd": Layout "number | string",
JustifyItems = "justifyItems": Layout "Align" "How grid items sit in their areas along the row.",
JustifySelf = "justifySelf": Layout "Align | \"auto\"",
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).",
MarginStart = "marginStart": Layout "DimensionValue",
MarginEnd = "marginEnd": Layout "DimensionValue",
PaddingStart = "paddingStart": Layout "LengthValue",
PaddingEnd = "paddingEnd": Layout "LengthValue",
Start = "start": Layout "DimensionValue" "Left in left-to-right layouts, right in right-to-left ones.",
End = "end": Layout "DimensionValue",
BorderStartWidth = "borderStartWidth": View "number",
BorderEndWidth = "borderEndWidth": View "number",
BorderStartColor = "borderStartColor": View "ColorValue",
BorderEndColor = "borderEndColor": View "ColorValue",
BorderTopStartRadius = "borderTopStartRadius": View "number",
BorderTopEndRadius = "borderTopEndRadius": View "number",
BorderBottomEndRadius = "borderBottomEndRadius": View "number",
BorderBottomStartRadius = "borderBottomStartRadius": View "number",
BackgroundColor = "backgroundColor": View "ColorValue | NativeNode",
BorderRadius = "borderRadius": View "number",
BorderTopLeftRadius = "borderTopLeftRadius": View "number",
BorderTopRightRadius = "borderTopRightRadius": View "number",
BorderBottomRightRadius = "borderBottomRightRadius": View "number",
BorderBottomLeftRadius = "borderBottomLeftRadius": View "number",
ShadowColor = "shadowColor": View "ColorValue | NativeNode",
ShadowOpacity = "shadowOpacity": View "number | NativeNode",
ShadowRadius = "shadowRadius": View "number | NativeNode",
BorderColor = "borderColor": View "ColorValue | NativeNode",
BorderTopColor = "borderTopColor": View "ColorValue",
BorderRightColor = "borderRightColor": View "ColorValue",
BorderBottomColor = "borderBottomColor": View "ColorValue",
BorderLeftColor = "borderLeftColor": View "ColorValue",
BorderStyle = "borderStyle": View "\"solid\" | \"dashed\" | \"dotted\"",
BorderCurve = "borderCurve": View "\"circular\" | \"continuous\"" "`continuous`: corners whose curvature eases into the edges (iOS app icons).",
TintColor = "tintColor": Image "ColorValue" "Recolors a template image.",
BackfaceVisibility = "backfaceVisibility": View "\"visible\" | \"hidden\"" "`\"hidden\"`: invisible while turned away (3D rotations).",
TransformOrigin = "transformOrigin": View "string | (number | string)[]" "The point `transform` acts around: keywords, percentages and lengths (\"top left\", \"50% 0\", `[10, 20]`). Default the center.",
Opacity = "opacity": View "number | NativeNode",
Overflow = "overflow": View "\"visible\" | \"hidden\"",
Color = "color": Text "ColorValue | NativeNode",
FontSize = "fontSize": Text "number",
FontWeight = "fontWeight": Text "\"normal\" | \"bold\" | number | `${number}`" "`\"normal\"` (400), `\"bold\"` (700) or 100–900.",
LineHeight = "lineHeight": Text "number",
FontFamily = "fontFamily": Text "string" "A system family or the name an imported font (`import Inter from \"./Inter.ttf\"`) evaluates to.",
FontStyle = "fontStyle": Text "\"normal\" | \"italic\"",
LetterSpacing = "letterSpacing": Text "number",
TextDecorationLine = "textDecorationLine": Text "\"none\" | \"underline\" | \"line-through\" | \"underline line-through\"",
TextDecorationColor = "textDecorationColor": Text "ColorValue",
WritingDirection = "writingDirection": Text "\"auto\" | \"ltr\" | \"rtl\"" "Base direction of the text; `auto` takes it from the content.",
TextAlignVertical = "textAlignVertical": Text "\"auto\" | \"top\" | \"center\" | \"bottom\"" "Where text shorter than its box sits (`<Text>` with a height).",
FontVariant = "fontVariant": Text "(\"small-caps\" | \"oldstyle-nums\" | \"lining-nums\" | \"tabular-nums\" | \"proportional-nums\")[]" "OpenType number and letter forms.",
TextShadowColor = "textShadowColor": Text "ColorValue",
TextShadowRadius = "textShadowRadius": Text "number",
TextTransform = "textTransform": Text "\"none\" | \"uppercase\" | \"lowercase\" | \"capitalize\"",
TextAlign = "textAlign": Text "\"auto\" | \"left\" | \"center\" | \"right\" | \"justify\"",
}
/// A style property value as read from JS.
#[derive(Debug, Clone, Copy)]
pub enum StyleValue<'a> {
/// A number.
Number(f32),
/// A string.
Str(&'a str),
/// `null` / `undefined`: resets the property to its default.
Null,
}
/// A style property value owned by a [`StylePatch`].
#[derive(Debug, Clone, PartialEq)]
pub enum PatchValue {
/// A number.
Number(f32),
/// A string.
Str(Box<str>),
/// Resets the property to its default.
Null,
}
impl PatchValue {
/// The value as [`Style::set`] takes it.
pub fn as_value(&self) -> StyleValue<'_> {
match self {
PatchValue::Number(n) => StyleValue::Number(*n),
PatchValue::Str(s) => StyleValue::Str(s),
PatchValue::Null => StyleValue::Null,
}
}
}
impl From<StyleValue<'_>> for PatchValue {
fn from(v: StyleValue<'_>) -> Self {
match v {
StyleValue::Number(n) => PatchValue::Number(n),
StyleValue::Str(s) => PatchValue::Str(s.into()),
StyleValue::Null => PatchValue::Null,
}
}
}
/// One declaration of a [`StylePatch`].
#[derive(Debug, Clone, PartialEq)]
pub enum StyleDecl {
/// A property.
Set(StyleKey, PatchValue),
/// Starts the `transform` list over: a `transform` replaces the
/// transforms set before it (by classes).
ClearTransform,
/// Appends a `transform` entry, driven by a native value when given
/// (the amount is then the identity until it is bound).
Transform(TransformKind, f32, Option<nsh_animation::NodeId>),
/// `shadowOffset`; `None` restores the default.
ShadowOffset(Option<(f32, f32)>),
/// `textShadowOffset`.
TextShadowOffset(Option<(f32, f32)>),
/// A property driven by a native animation node.
Animated(nsh_animation::AnimationProp, nsh_animation::NodeId),
}
impl StyleDecl {
/// Applies the declaration to `style`.
pub fn apply(&self, style: &mut Style) -> Result<(), StyleError> {
match self {
StyleDecl::Set(key, value) => style.set_key(*key, value.as_value()),
StyleDecl::ClearTransform => {
style.view.transform = Transform::IDENTITY;
style.animated.retain(|(prop, _)| {
!matches!(prop, nsh_animation::AnimationProp::Transform(_))
});
Ok(())
}
StyleDecl::Transform(kind, amount, node) => {
let index = style
.view
.transform
.push(*kind, *amount)
.ok_or(StyleError::InvalidValue)?;
if let Some(node) = node {
style
.animated
.push((nsh_animation::AnimationProp::Transform(index), *node));
}
Ok(())
}
StyleDecl::ShadowOffset(offset) => {
style.set_shadow_offset(*offset);
Ok(())
}
StyleDecl::TextShadowOffset(offset) => {
style.set_text_shadow_offset(*offset);
Ok(())
}
StyleDecl::Animated(prop, node) => {
style.animated.push((*prop, *node));
Ok(())
}
}
}
}
/// A style as written (`style={...}`): its declarations in order, kept so
/// the core can apply them again over class styles when those change.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StylePatch {
decls: Vec<StyleDecl>,
}
impl StylePatch {
/// Applies `decl` to `style` and records it if it applied.
pub fn push(&mut self, style: &mut Style, decl: StyleDecl) -> Result<(), StyleError> {
decl.apply(style)?;
self.decls.push(decl);
Ok(())
}
/// Sets property `key` on `style` and records it.
pub fn set(
&mut self,
style: &mut Style,
key: &str,
value: StyleValue<'_>,
) -> Result<(), StyleError> {
let key = StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?;
style.set_key(key, value)?;
self.decls.push(StyleDecl::Set(key, value.into()));
Ok(())
}
/// Applies every declaration to `style`, in order.
pub fn apply(&self, style: &mut Style) {
for decl in &self.decls {
// Declarations were checked when they were recorded.
let _ = decl.apply(style);
}
}
/// Whether there are no declarations.
pub fn is_empty(&self) -> bool {
self.decls.is_empty()
}
/// The declarations.
pub fn decls(&self) -> &[StyleDecl] {
&self.decls
}
}
/// Why a style property was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StyleError {
/// The property name is not supported.
UnknownProperty,
/// The value has the wrong type or format.
InvalidValue,
}
enum Len {
Px(f32),
Pct(f32),
Auto,
}
impl Len {
fn parse(v: StyleValue<'_>) -> Result<Len, StyleError> {
match v {
StyleValue::Number(n) => Ok(Len::Px(n)),
StyleValue::Str("auto") => Ok(Len::Auto),
StyleValue::Str(s) => s
.strip_suffix('%')
.and_then(|p| p.trim().parse::<f32>().ok())
.map(|p| Len::Pct(p / 100.0))
.ok_or(StyleError::InvalidValue),
StyleValue::Null => Ok(Len::Auto),
}
}
fn dim(self) -> Dimension {
match self {
Len::Px(v) => Dimension::length(v),
Len::Pct(v) => Dimension::percent(v),
Len::Auto => Dimension::auto(),
}
}
fn lpa(self) -> LengthPercentageAuto {
match self {
Len::Px(v) => LengthPercentageAuto::length(v),
Len::Pct(v) => LengthPercentageAuto::percent(v),
Len::Auto => LengthPercentageAuto::auto(),
}
}
fn lp(self) -> Result<LengthPercentage, StyleError> {
match self {
Len::Px(v) => Ok(LengthPercentage::length(v)),
Len::Pct(v) => Ok(LengthPercentage::percent(v)),
Len::Auto => Err(StyleError::InvalidValue),
}
}
}
/// A zero-default length: `null` resets to 0 rather than `auto`.
fn lp_or_zero(v: StyleValue<'_>) -> Result<LengthPercentage, StyleError> {
match v {
StyleValue::Null => Ok(LengthPercentage::length(0.0)),
v => Len::parse(v)?.lp(),
}
}
fn opt_lpa(v: StyleValue<'_>) -> Result<Option<LengthPercentageAuto>, StyleError> {
match v {
StyleValue::Null => Ok(None),
v => Ok(Some(Len::parse(v)?.lpa())),
}
}
fn opt_lp(v: StyleValue<'_>) -> Result<Option<LengthPercentage>, StyleError> {
match v {
StyleValue::Null => Ok(None),
v => Ok(Some(Len::parse(v)?.lp()?)),
}
}
/// A minimum size: unset is 0, as in Yoga. Taffy's `auto` would be CSS's
/// automatic minimum (the min-content size), which keeps flex items from
/// shrinking below their content (`flex: 1` text in a row would overflow).
fn min_len(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
Ok(match Len::parse(v)? {
Len::Auto => LengthPercentageAuto::length(0.0),
len => len.lpa(),
})
}
fn lpa_or_zero(v: StyleValue<'_>) -> Result<LengthPercentageAuto, StyleError> {
match v {
StyleValue::Null => Ok(LengthPercentageAuto::length(0.0)),
v => Ok(Len::parse(v)?.lpa()),
}
}
fn number(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
match v {
StyleValue::Number(n) => Ok(n),
StyleValue::Null => Ok(default),
StyleValue::Str(_) => Err(StyleError::InvalidValue),
}
}
fn opt_number(v: StyleValue<'_>) -> Result<Option<f32>, StyleError> {
match v {
StyleValue::Number(n) => Ok(Some(n)),
StyleValue::Null => Ok(None),
StyleValue::Str(_) => Err(StyleError::InvalidValue),
}
}
fn color(v: StyleValue<'_>) -> Result<Option<Color>, StyleError> {
match v {
StyleValue::Str(s) => Color::parse(s).map(Some).ok_or(StyleError::InvalidValue),
StyleValue::Null => Ok(None),
StyleValue::Number(_) => Err(StyleError::InvalidValue),
}
}
fn keyword<'a>(v: StyleValue<'a>) -> Result<Option<&'a str>, StyleError> {
match v {
StyleValue::Str(s) => Ok(Some(s)),
StyleValue::Null => Ok(None),
StyleValue::Number(_) => Err(StyleError::InvalidValue),
}
}
fn align_items(v: StyleValue<'_>) -> Result<Option<AlignItems>, StyleError> {
Ok(match keyword(v)? {
None => None,
Some("flex-start") => Some(AlignItems::FLEX_START),
Some("flex-end") => Some(AlignItems::FLEX_END),
Some("center") => Some(AlignItems::CENTER),
Some("stretch") => Some(AlignItems::STRETCH),
Some("baseline") => Some(AlignItems::BASELINE),
Some(_) => return Err(StyleError::InvalidValue),
})
}
fn align_content(v: StyleValue<'_>, default: AlignContent) -> Result<AlignContent, StyleError> {
Ok(match keyword(v)? {
None => default,
Some("flex-start") => AlignContent::FLEX_START,
Some("flex-end") => AlignContent::FLEX_END,
Some("center") => AlignContent::CENTER,
Some("stretch") => AlignContent::STRETCH,
Some("space-between") => AlignContent::SPACE_BETWEEN,
Some("space-around") => AlignContent::SPACE_AROUND,
Some("space-evenly") => AlignContent::SPACE_EVENLY,
Some(_) => return Err(StyleError::InvalidValue),
})
}
fn font_weight(v: StyleValue<'_>) -> Result<Option<u16>, StyleError> {
Ok(match v {
StyleValue::Null => None,
StyleValue::Number(n) => Some((n as u16).clamp(100, 900)),
StyleValue::Str("normal") => Some(400),
StyleValue::Str("bold") => Some(700),
StyleValue::Str(s) => Some(
s.parse::<u16>()
.map_err(|_| StyleError::InvalidValue)?
.clamp(100, 900),
),
})
}
/// A length in points from a number or a string (`"2px"`, `"0.5rem"`).
fn length_value(v: StyleValue<'_>, default: f32) -> Result<f32, StyleError> {
match v {
StyleValue::Number(n) => Ok(n),
StyleValue::Str(s) => css::length(s).ok_or(StyleError::InvalidValue),
StyleValue::Null => Ok(default),
}
}
/// Milliseconds from a number or `"150ms"` / `"0.2s"`.
fn duration(v: StyleValue<'_>) -> Result<f32, StyleError> {
match v {
StyleValue::Number(n) => Ok(n.max(0.0)),
StyleValue::Null => Ok(0.0),
StyleValue::Str(s) => {
let s = s.trim();
let ms = if let Some(n) = s.strip_suffix("ms") {
css::number(n)
} else if let Some(n) = s.strip_suffix('s') {
css::number(n).map(|n| n * 1000.0)
} else {
css::number(s)
};
ms.map(|n| n.max(0.0)).ok_or(StyleError::InvalidValue)
}
}
}
/// A CSS timing function as cubic Bézier control points.
fn timing_function(v: StyleValue<'_>) -> Result<[f32; 4], StyleError> {
let Some(s) = keyword(v)? else {
return Ok(Transition::EASE);
};
Ok(match s.trim() {
"linear" => [0.0, 0.0, 1.0, 1.0],
"ease" => Transition::EASE,
"ease-in" => [0.42, 0.0, 1.0, 1.0],
"ease-out" => [0.0, 0.0, 0.58, 1.0],
"ease-in-out" => [0.42, 0.0, 0.58, 1.0],
s => {
let args = s
.strip_prefix("cubic-bezier(")
.and_then(|a| a.strip_suffix(')'))
.ok_or(StyleError::InvalidValue)?;
let n: Vec<f32> = args.split(',').filter_map(css::number).collect();
let [a, b, c, d] = n.as_slice() else {
return Err(StyleError::InvalidValue);
};
[*a, *b, *c, *d]
}
})
}
/// `transitionProperty`: CSS property names, mapped to the groups that
/// transition natively.
fn transition_properties(s: &str) -> Option<TransitionProps> {
let mut bits = 0;
for name in s.split(',').map(str::trim) {
bits |= match name {
"all" => TransitionProps::ALL,
"none" => 0,
"color"
| "colors"
| "background-color"
| "backgroundColor"
| "border-color"
| "borderColor"
| "outline-color"
| "text-decoration-color"
| "fill"
| "stroke"
| "--tw-gradient-from"
| "--tw-gradient-via"
| "--tw-gradient-to" => TransitionProps::COLORS,
"opacity" => TransitionProps::OPACITY,
"transform" | "translate" | "scale" | "rotate" => TransitionProps::TRANSFORM,
"box-shadow" | "boxShadow" | "shadow" => TransitionProps::SHADOW,
"border-radius" | "borderRadius" | "border-width" | "borderWidth" => {
TransitionProps::SHAPE
}
// Properties that do not animate natively.
"filter" | "backdrop-filter" | "display" | "visibility" | "content-visibility"
| "overlay" | "pointer-events" => 0,
_ => return None,
};
}
Some(TransitionProps(bits))
}
fn grid_value<T>(
v: StyleValue<'_>,
parse: impl Fn(&str) -> Option<Vec<T>>,
) -> Result<Vec<T>, StyleError> {
match keyword(v)? {
None => Ok(Vec::new()),
Some(s) => parse(s).ok_or(StyleError::InvalidValue),
}
}
fn grid_placement(v: StyleValue<'_>) -> Result<taffy::GridPlacement<String>, StyleError> {
match v {
StyleValue::Null => Ok(taffy::GridPlacement::Auto),
StyleValue::Number(n) => {
grid::placement(&(n as i32).to_string()).ok_or(StyleError::InvalidValue)
}
StyleValue::Str(s) => grid::placement(s).ok_or(StyleError::InvalidValue),
}
}
fn grid_line(v: StyleValue<'_>) -> Result<taffy::Line<taffy::GridPlacement<String>>, StyleError> {
match v {
StyleValue::Null => Ok(taffy::Line {
start: taffy::GridPlacement::Auto,
end: taffy::GridPlacement::Auto,
}),
StyleValue::Number(n) => {
grid::line(&(n as i32).to_string()).ok_or(StyleError::InvalidValue)
}
StyleValue::Str(s) => grid::line(s).ok_or(StyleError::InvalidValue),
}
}
impl Style {
/// Changes the effects lists (copying them if shared).
pub fn edit_effects(&mut self, f: impl FnOnce(&mut Effects)) {
let mut effects = self
.view
.effects
.take()
.map(|e| (*e).clone())
.unwrap_or_default();
f(&mut effects);
self.view.effects = crate::effects::shared(effects);
}
/// Sets the box shadows (top layer first).
pub fn set_box_shadows(&mut self, shadows: Vec<BoxShadow>) {
self.edit_effects(|e| e.box_shadows = shadows);
}
/// Sets the gradient backgrounds (top layer first).
pub fn set_background_images(&mut self, images: Vec<Gradient>) {
self.edit_effects(|e| e.background_images = images);
}
/// Sets the filters.
pub fn set_filters(&mut self, filters: Vec<Filter>, backdrop: bool) {
self.edit_effects(|e| {
if backdrop {
e.backdrop_filters = filters;
} else {
e.filters = filters;
}
});
}
fn transition_mut(&mut self) -> &mut Transition {
self.view.transition.get_or_insert(Transition {
properties: TransitionProps(TransitionProps::ALL),
duration: 0.0,
delay: 0.0,
easing: Transition::EASE,
})
}
/// Appends an entry to the `transform` list (`translateX`, `scale`,
/// ...); rotations and skews are degrees (`"45deg"` strings are parsed
/// by the caller). Returns the entry's index.
pub fn push_transform(&mut self, key: &str, value: f32) -> Result<u8, StyleError> {
let kind = TransformKind::parse(key).ok_or(StyleError::UnknownProperty)?;
self.view
.transform
.push(kind, value)
.ok_or(StyleError::InvalidValue)
}
/// Sets `shadowOffset: { width, height }`; `None` restores the default.
pub fn set_shadow_offset(&mut self, offset: Option<(f32, f32)>) {
let (x, y) = offset.unwrap_or((Shadow::DEFAULT.offset_x, Shadow::DEFAULT.offset_y));
self.view.shadow.offset_x = x;
self.view.shadow.offset_y = y;
}
/// Sets `textShadowOffset: { width, height }`.
pub fn set_text_shadow_offset(&mut self, offset: Option<(f32, f32)>) {
self.text.shadow_offset = offset;
}
fn set_border_width(
&mut self,
sides: &[usize],
value: StyleValue<'_>,
) -> Result<(), StyleError> {
let w = number(value, 0.0)?.max(0.0);
let v = LengthPercentage::length(w);
for &side in sides {
self.view.borders.widths[side] = w;
let b = &mut self.layout.border;
match side {
0 => b.top = v,
1 => b.right = v,
2 => b.bottom = v,
_ => b.left = v,
}
}
Ok(())
}
fn set_border_color(
&mut self,
sides: &[usize],
value: StyleValue<'_>,
) -> Result<(), StyleError> {
let c = color(value)?.unwrap_or(Color::BLACK);
for &side in sides {
self.view.borders.colors[side] = c;
}
Ok(())
}
/// Sets one property using its React Native name.
pub fn set(&mut self, key: &str, value: StyleValue<'_>) -> Result<(), StyleError> {
self.set_key(
StyleKey::parse(key).ok_or(StyleError::UnknownProperty)?,
value,
)
}
/// Sets one property.
pub fn set_key(&mut self, key: StyleKey, value: StyleValue<'_>) -> Result<(), StyleError> {
let l = &mut self.layout;
match key {
// Layout
StyleKey::Display => {
l.display = match keyword(value)? {
None | Some("flex") => Display::Flex,
Some("grid") => Display::Grid,
Some("block") => Display::Block,
Some("none") => Display::None,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::Position => {
l.position = match keyword(value)? {
None | Some("relative") => Position::Relative,
Some("absolute") => Position::Absolute,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::FlexDirection => {
l.flex_direction = match keyword(value)? {
None | Some("column") => FlexDirection::Column,
Some("row") => FlexDirection::Row,
Some("column-reverse") => FlexDirection::ColumnReverse,
Some("row-reverse") => FlexDirection::RowReverse,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::FlexWrap => {
l.flex_wrap = match keyword(value)? {
None | Some("nowrap") => FlexWrap::NoWrap,
Some("wrap") => FlexWrap::Wrap,
Some("wrap-reverse") => FlexWrap::WrapReverse,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::Flex => {
// React Native semantics, not the CSS shorthand.
let f = number(value, 0.0)?;
if f > 0.0 {
l.flex_grow = f;
l.flex_shrink = 1.0;
l.flex_basis = Dimension::length(0.0);
} else if f < 0.0 {
l.flex_grow = 0.0;
l.flex_shrink = -f;
l.flex_basis = Dimension::auto();
} else {
l.flex_grow = 0.0;
l.flex_shrink = 0.0;
l.flex_basis = Dimension::auto();
}
}
StyleKey::FlexGrow => l.flex_grow = number(value, 0.0)?,
StyleKey::FlexShrink => l.flex_shrink = number(value, 0.0)?,
StyleKey::FlexBasis => l.flex_basis = Len::parse(value)?.dim(),
StyleKey::JustifyContent => {
l.justify_content = align_content(value, AlignContent::FLEX_START)?
}
StyleKey::AlignItems => {
l.align_items = align_items(value)?.unwrap_or(AlignItems::STRETCH)
}
StyleKey::AlignSelf => {
l.align_self = match value {
StyleValue::Str("auto") => None,
v => align_items(v)?,
}
}
StyleKey::AlignContent => {
l.align_content = align_content(value, AlignContent::FLEX_START)?
}
StyleKey::Width => l.size.width = Len::parse(value)?.dim(),
StyleKey::Height => l.size.height = Len::parse(value)?.dim(),
StyleKey::MinWidth => l.min_size.width = min_len(value)?,
StyleKey::MinHeight => l.min_size.height = min_len(value)?,
StyleKey::MaxWidth => l.max_size.width = Len::parse(value)?.lpa(),
StyleKey::MaxHeight => l.max_size.height = Len::parse(value)?.lpa(),
StyleKey::AspectRatio => l.aspect_ratio = opt_number(value)?,
StyleKey::Top => l.inset.top = Len::parse(value)?.lpa(),
StyleKey::Right => l.inset.right = Len::parse(value)?.lpa(),
StyleKey::Bottom => l.inset.bottom = Len::parse(value)?.lpa(),
StyleKey::Left => l.inset.left = Len::parse(value)?.lpa(),
StyleKey::Margin => {
let v = lpa_or_zero(value)?;
l.margin = taffy::Rect {
left: v,
right: v,
top: v,
bottom: v,
};
}
StyleKey::MarginHorizontal => {
let v = lpa_or_zero(value)?;
(l.margin.left, l.margin.right) = (v, v);
}
StyleKey::MarginVertical => {
let v = lpa_or_zero(value)?;
(l.margin.top, l.margin.bottom) = (v, v);
}
StyleKey::MarginTop => l.margin.top = lpa_or_zero(value)?,
StyleKey::MarginRight => l.margin.right = lpa_or_zero(value)?,
StyleKey::MarginBottom => l.margin.bottom = lpa_or_zero(value)?,
StyleKey::MarginLeft => l.margin.left = lpa_or_zero(value)?,
StyleKey::Padding => {
let v = lp_or_zero(value)?;
l.padding = taffy::Rect {
left: v,
right: v,
top: v,
bottom: v,
};
}
StyleKey::PaddingHorizontal => {
let v = lp_or_zero(value)?;
(l.padding.left, l.padding.right) = (v, v);
}
StyleKey::PaddingVertical => {
let v = lp_or_zero(value)?;
(l.padding.top, l.padding.bottom) = (v, v);
}
StyleKey::PaddingTop => l.padding.top = lp_or_zero(value)?,
StyleKey::PaddingRight => l.padding.right = lp_or_zero(value)?,
StyleKey::PaddingBottom => l.padding.bottom = lp_or_zero(value)?,
StyleKey::PaddingLeft => l.padding.left = lp_or_zero(value)?,
StyleKey::Gap => {
let v = lp_or_zero(value)?;
l.gap = taffy::Size {
width: v,
height: v,
};
}
StyleKey::RowGap => l.gap.height = lp_or_zero(value)?,
StyleKey::ColumnGap => l.gap.width = lp_or_zero(value)?,
StyleKey::BorderWidth => self.set_border_width(&[0, 1, 2, 3], value)?,
StyleKey::BorderTopWidth => self.set_border_width(&[0], value)?,
StyleKey::BorderRightWidth => self.set_border_width(&[1], value)?,
StyleKey::BorderBottomWidth => self.set_border_width(&[2], value)?,
StyleKey::BorderLeftWidth => self.set_border_width(&[3], value)?,
StyleKey::ZIndex => self.z_index = number(value, 0.0)? as i32,
StyleKey::Direction => {
self.direction = match keyword(value)? {
None | Some("inherit") => None,
Some("ltr") => Some(false),
Some("rtl") => Some(true),
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::MarginStart => self.logical.margin[0] = opt_lpa(value)?,
StyleKey::MarginEnd => self.logical.margin[1] = opt_lpa(value)?,
StyleKey::PaddingStart => self.logical.padding[0] = opt_lp(value)?,
StyleKey::PaddingEnd => self.logical.padding[1] = opt_lp(value)?,
StyleKey::Start => self.logical.inset[0] = opt_lpa(value)?,
StyleKey::End => self.logical.inset[1] = opt_lpa(value)?,
StyleKey::BorderStartWidth => {
self.logical.border_width[0] = opt_number(value)?.map(|w| w.max(0.0))
}
StyleKey::BorderEndWidth => {
self.logical.border_width[1] = opt_number(value)?.map(|w| w.max(0.0))
}
StyleKey::BorderStartColor => self.logical.border_color[0] = color(value)?,
StyleKey::BorderEndColor => self.logical.border_color[1] = color(value)?,
StyleKey::BorderTopStartRadius => self.logical.radius[0] = opt_number(value)?,
StyleKey::BorderTopEndRadius => self.logical.radius[1] = opt_number(value)?,
StyleKey::BorderBottomEndRadius => self.logical.radius[2] = opt_number(value)?,
StyleKey::BorderBottomStartRadius => self.logical.radius[3] = opt_number(value)?,
// View
StyleKey::BackgroundColor => {
self.view.background_color = color(value)?.unwrap_or(Color::TRANSPARENT)
}
StyleKey::BorderRadius => self.view.border_radius = number(value, 0.0)?,
StyleKey::BorderTopLeftRadius => self.view.corner_radius[0] = opt_number(value)?,
StyleKey::BorderTopRightRadius => self.view.corner_radius[1] = opt_number(value)?,
StyleKey::BorderBottomRightRadius => self.view.corner_radius[2] = opt_number(value)?,
StyleKey::BorderBottomLeftRadius => self.view.corner_radius[3] = opt_number(value)?,
StyleKey::ShadowColor => {
self.view.shadow.color = color(value)?.unwrap_or(Shadow::DEFAULT.color)
}
StyleKey::ShadowOpacity => {
self.view.shadow.opacity = number(value, Shadow::DEFAULT.opacity)?.clamp(0.0, 1.0)
}
StyleKey::ShadowRadius => {
self.view.shadow.radius = number(value, Shadow::DEFAULT.radius)?.max(0.0)
}
StyleKey::BorderColor => self.set_border_color(&[0, 1, 2, 3], value)?,
StyleKey::BorderTopColor => self.set_border_color(&[0], value)?,
StyleKey::BorderRightColor => self.set_border_color(&[1], value)?,
StyleKey::BorderBottomColor => self.set_border_color(&[2], value)?,
StyleKey::BorderLeftColor => self.set_border_color(&[3], value)?,
StyleKey::BorderStyle => {
self.view.borders.style = match keyword(value)? {
None | Some("solid") => BorderStyle::Solid,
Some("dashed") => BorderStyle::Dashed,
Some("dotted") => BorderStyle::Dotted,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::BorderCurve => {
self.view.continuous_corners = match keyword(value)? {
None | Some("circular") => false,
Some("continuous") => true,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::TintColor => self.view.tint_color = color(value)?,
StyleKey::BackfaceVisibility => {
self.view.backface_hidden = match keyword(value)? {
None | Some("visible") => false,
Some("hidden") => true,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::TransformOrigin => {
self.view.transform_origin = match keyword(value)? {
None => TransformOrigin::CENTER,
Some(s) => TransformOrigin::parse(s).ok_or(StyleError::InvalidValue)?,
}
}
StyleKey::Opacity => self.view.opacity = number(value, 1.0)?.clamp(0.0, 1.0),
StyleKey::Overflow => {
self.view.overflow_hidden = match keyword(value)? {
None | Some("visible") => false,
Some("hidden") => true,
Some(_) => return Err(StyleError::InvalidValue),
}
}
// Text
StyleKey::Color => self.text.color = color(value)?,
StyleKey::FontSize => self.text.font_size = opt_number(value)?,
StyleKey::FontWeight => self.text.font_weight = font_weight(value)?,
StyleKey::LineHeight => {
// Numbers are points (React Native); strings may be a
// multiple of the font size (`"1.5"`, `"1.5em"`) or points.
let (points, multiple) = match value {
StyleValue::Str(s)
if s.ends_with("px") || s.ends_with("pt") || s.ends_with("rem") =>
{
(Some(css::length(s).ok_or(StyleError::InvalidValue)?), None)
}
StyleValue::Str(s) => {
let n = css::number(s.strip_suffix("em").unwrap_or(s))
.ok_or(StyleError::InvalidValue)?;
(None, Some(n.max(0.0)))
}
v => (opt_number(v)?, None),
};
self.text.line_height = points;
self.text.line_height_multiple = multiple;
}
StyleKey::FontFamily => {
self.text.font_family = keyword(value)?.map(|name| FontFamily::new(name.trim()))
}
StyleKey::FontStyle => {
self.text.italic = match keyword(value)? {
None => None,
Some("normal") => Some(false),
Some("italic") => Some(true),
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::LetterSpacing => {
let (points, em) = match value {
StyleValue::Str(s) if s.ends_with("em") && !s.ends_with("rem") => {
let n = css::number(&s[..s.len() - 2]).ok_or(StyleError::InvalidValue)?;
(None, Some(n))
}
StyleValue::Str(s) => {
(Some(css::length(s).ok_or(StyleError::InvalidValue)?), None)
}
v => (opt_number(v)?, None),
};
self.text.letter_spacing = points;
self.text.letter_spacing_em = em;
}
StyleKey::TextDecorationLine => {
self.text.decoration = match keyword(value)? {
None => None,
Some(words) => {
let mut d = TextDecoration::default();
for word in words.split_whitespace() {
match word {
"none" => {}
"underline" => d.underline = true,
"line-through" => d.line_through = true,
_ => return Err(StyleError::InvalidValue),
}
}
Some(d)
}
}
}
StyleKey::TextDecorationColor => self.text.decoration_color = color(value)?,
StyleKey::TextAlignVertical => {
self.text.align_vertical = match keyword(value)? {
None => None,
Some("auto" | "top") => Some(0.0),
Some("center") => Some(0.5),
Some("bottom") => Some(1.0),
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::WritingDirection => {
self.text.writing_direction = match keyword(value)? {
None | Some("auto") => None,
Some("ltr") => Some(false),
Some("rtl") => Some(true),
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::FontVariant => {
self.text.font_variant = match keyword(value)? {
None => None,
Some(s) => Some(FontVariant::parse(s).ok_or(StyleError::InvalidValue)?),
}
}
StyleKey::TextShadowColor => self.text.shadow_color = color(value)?,
StyleKey::TextShadowRadius => self.text.shadow_radius = opt_number(value)?,
StyleKey::TextTransform => {
self.text.transform = match keyword(value)? {
None => None,
Some("none") => Some(TextTransform::None),
Some("uppercase") => Some(TextTransform::Uppercase),
Some("lowercase") => Some(TextTransform::Lowercase),
Some("capitalize") => Some(TextTransform::Capitalize),
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::TextAlign => {
self.text.text_align = match keyword(value)? {
None => None,
Some("auto") => Some(TextAlign::Auto),
Some("left") => Some(TextAlign::Left),
Some("center") => Some(TextAlign::Center),
Some("right") => Some(TextAlign::Right),
Some("justify") => Some(TextAlign::Justify),
Some(_) => return Err(StyleError::InvalidValue),
}
}
// Effects
StyleKey::BoxShadow => {
let list = match keyword(value)? {
None => Vec::new(),
Some(s) => css::box_shadows(s).ok_or(StyleError::InvalidValue)?,
};
self.edit_effects(|e| e.box_shadows = list);
}
StyleKey::BackgroundImage | StyleKey::ExperimentalBackgroundImage => {
let list = match keyword(value)? {
None => Vec::new(),
Some(s) => css::gradients(s).ok_or(StyleError::InvalidValue)?,
};
self.edit_effects(|e| e.background_images = list);
}
StyleKey::Filter => {
let list = match keyword(value)? {
None => Vec::new(),
Some(s) => css::filters(s).ok_or(StyleError::InvalidValue)?,
};
self.edit_effects(|e| e.filters = list);
}
StyleKey::BackdropFilter => {
let list = match keyword(value)? {
None => Vec::new(),
Some(s) => css::filters(s).ok_or(StyleError::InvalidValue)?,
};
self.edit_effects(|e| e.backdrop_filters = list);
}
StyleKey::MixBlendMode => {
self.view.blend_mode = match keyword(value)? {
None => BlendMode::Normal,
Some(s) => BlendMode::parse(s).ok_or(StyleError::InvalidValue)?,
}
}
StyleKey::OutlineWidth => self.view.outline.width = length_value(value, 0.0)?.max(0.0),
StyleKey::OutlineColor => {
self.view.outline.color = color(value)?.unwrap_or(Outline::NONE.color)
}
StyleKey::OutlineOffset => self.view.outline.offset = length_value(value, 0.0)?,
StyleKey::OutlineStyle => {
self.view.outline.style = match keyword(value)? {
None | Some("solid") | Some("double") => BorderStyle::Solid,
Some("dashed") => BorderStyle::Dashed,
Some("dotted") => BorderStyle::Dotted,
Some("none") | Some("hidden") => {
self.view.outline.width = 0.0;
BorderStyle::Solid
}
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::Visibility => {
self.view.hidden = match keyword(value)? {
None | Some("visible") => false,
Some("hidden") | Some("collapse") => true,
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::Cursor => {
self.view.cursor = match keyword(value)? {
None => Cursor::Auto,
Some(s) => Cursor::parse(s).ok_or(StyleError::InvalidValue)?,
}
}
StyleKey::TransitionProperty => {
let props = match keyword(value)? {
None => TransitionProps(TransitionProps::ALL),
Some(s) => transition_properties(s).ok_or(StyleError::InvalidValue)?,
};
self.transition_mut().properties = props;
}
StyleKey::TransitionDuration => {
let ms = duration(value)?;
self.transition_mut().duration = ms;
}
StyleKey::TransitionDelay => {
let ms = duration(value)?;
self.transition_mut().delay = ms;
}
StyleKey::TransitionTimingFunction => {
let easing = timing_function(value)?;
self.transition_mut().easing = easing;
}
StyleKey::AnimationName => {
let keyframes = match keyword(value)? {
None | Some("none") => None,
Some("spin") => Some(Keyframes::Spin),
Some("ping") => Some(Keyframes::Ping),
Some("pulse") => Some(Keyframes::Pulse),
Some("bounce") => Some(Keyframes::Bounce),
Some(_) => return Err(StyleError::InvalidValue),
};
self.view.animation = keyframes.map(|keyframes| {
let base = self.view.animation.unwrap_or(KeyframeAnimation {
keyframes,
duration: 1000.0,
delay: 0.0,
easing: [0.0, 0.0, 1.0, 1.0],
iterations: None,
});
KeyframeAnimation { keyframes, ..base }
});
}
StyleKey::AnimationDuration => {
let ms = duration(value)?;
if let Some(a) = self.view.animation.as_mut() {
a.duration = ms;
}
}
StyleKey::AnimationDelay => {
let ms = duration(value)?;
if let Some(a) = self.view.animation.as_mut() {
a.delay = ms;
}
}
StyleKey::AnimationTimingFunction => {
let easing = timing_function(value)?;
if let Some(a) = self.view.animation.as_mut() {
a.easing = easing;
}
}
StyleKey::AnimationIterationCount => {
let count = match value {
StyleValue::Str("infinite") | StyleValue::Null => None,
v => Some(number(v, 1.0)?.max(0.0) as u32),
};
if let Some(a) = self.view.animation.as_mut() {
a.iterations = count;
}
}
StyleKey::TextDecorationStyle => {
self.text.decoration_style = match keyword(value)? {
None => None,
Some("solid") => Some(DecorationStyle::Solid),
Some("double") => Some(DecorationStyle::Double),
Some("dotted") => Some(DecorationStyle::Dotted),
Some("dashed") => Some(DecorationStyle::Dashed),
Some("wavy") => Some(DecorationStyle::Wavy),
Some(_) => return Err(StyleError::InvalidValue),
}
}
StyleKey::TextDecorationThickness => {
self.text.decoration_thickness = match value {
StyleValue::Null | StyleValue::Str("auto") | StyleValue::Str("from-font") => {
None
}
v => Some(length_value(v, 1.0)?.max(0.0)),
}
}
StyleKey::TextUnderlineOffset => {
self.text.underline_offset = match value {
StyleValue::Null | StyleValue::Str("auto") => None,
v => Some(length_value(v, 0.0)?),
}
}
// Grid
StyleKey::GridTemplateColumns => {
l.grid_template_columns = grid_value(value, grid::template)?;
}
StyleKey::GridTemplateRows => {
l.grid_template_rows = grid_value(value, grid::template)?;
}
StyleKey::GridAutoColumns => {
l.grid_auto_columns = grid_value(value, grid::auto_tracks)?;
}
StyleKey::GridAutoRows => {
l.grid_auto_rows = grid_value(value, grid::auto_tracks)?;
}
StyleKey::GridAutoFlow => {
l.grid_auto_flow = match keyword(value)? {
None => taffy::GridAutoFlow::Row,
Some(s) => grid::auto_flow(s).ok_or(StyleError::InvalidValue)?,
}
}
StyleKey::GridColumn => l.grid_column = grid_line(value)?,
StyleKey::GridRow => l.grid_row = grid_line(value)?,
StyleKey::GridColumnStart => l.grid_column.start = grid_placement(value)?,
StyleKey::GridColumnEnd => l.grid_column.end = grid_placement(value)?,
StyleKey::GridRowStart => l.grid_row.start = grid_placement(value)?,
StyleKey::GridRowEnd => l.grid_row.end = grid_placement(value)?,
StyleKey::JustifyItems => {
l.justify_items = align_items(value)?.unwrap_or(AlignItems::STRETCH);
}
StyleKey::JustifySelf => {
l.justify_self = match value {
StyleValue::Str("auto") => None,
v => align_items(v)?,
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_colors() {
assert_eq!(Color::parse("#fff"), Some(Color(0xffff_ffff)));
assert_eq!(Color::parse("#f008"), Some(Color(0xff00_0088)));
assert_eq!(Color::parse("#123456"), Some(Color(0x1234_56ff)));
assert_eq!(Color::parse("#12345678"), Some(Color(0x1234_5678)));
assert_eq!(Color::parse("rgb(255, 0, 10)"), Some(Color(0xff00_0aff)));
assert_eq!(Color::parse("rgba(0,0,0,0.5)"), Some(Color(0x0000_0080)));
assert_eq!(Color::parse("white"), Some(Color(0xffff_ffff)));
assert_eq!(Color::parse("#12"), None);
assert_eq!(Color::parse("nope"), None);
}
#[test]
fn react_native_defaults() {
let s = Style::default();
assert_eq!(s.layout.flex_direction, FlexDirection::Column);
assert_eq!(s.layout.flex_shrink, 0.0);
assert_eq!(s.layout.position, Position::Relative);
assert_eq!(s.layout.align_content, AlignContent::FLEX_START);
assert_eq!(s.layout.min_size.width, LengthPercentageAuto::length(0.0));
}
#[test]
fn transform_origins() {
let p = |s| TransformOrigin::parse(s).unwrap();
assert_eq!(p("top left").x, OriginLen::Fraction(0.0));
assert_eq!(p("top left").y, OriginLen::Fraction(0.0));
assert_eq!(p("bottom").y, OriginLen::Fraction(1.0));
assert_eq!(p("bottom").x, OriginLen::Fraction(0.5));
assert_eq!(p("10px 25%").x, OriginLen::Px(10.0));
assert_eq!(p("10px 25%").y, OriginLen::Fraction(0.25));
assert_eq!(p("right 5 3").z, 3.0);
assert_eq!(p("center top").y, OriginLen::Fraction(0.0));
assert_eq!(p("0 0").offset(100.0, 50.0), (-50.0, -25.0, 0.0));
assert!(TransformOrigin::parse("sideways").is_none());
}
#[test]
fn font_variants() {
let v = FontVariant::parse("small-caps tabular-nums").unwrap();
assert_eq!(v.tags().collect::<Vec<_>>(), ["smcp", "tnum"]);
assert!(FontVariant::parse("wide").is_none());
}
#[test]
fn flex_shorthand() {
let mut s = Style::default();
s.set("flex", StyleValue::Number(2.0)).unwrap();
assert_eq!(s.layout.flex_grow, 2.0);
assert_eq!(s.layout.flex_shrink, 1.0);
assert_eq!(s.layout.flex_basis, Dimension::length(0.0));
}
#[test]
fn corner_radii_override_the_shorthand_in_any_order() {
let mut s = Style::default();
s.set("borderTopLeftRadius", StyleValue::Number(4.0))
.unwrap();
s.set("borderRadius", StyleValue::Number(10.0)).unwrap();
let r = s.view.radii();
assert_eq!(r.to_array(), [4.0, 10.0, 10.0, 10.0]);
assert_eq!(r.shared(), None);
s.set("borderTopLeftRadius", StyleValue::Null).unwrap();
assert_eq!(s.view.radii().shared(), Some(10.0));
}
#[test]
fn shared_radius_ignores_square_corners() {
let r = CornerRadii {
top_left: 12.0,
top_right: 12.0,
..CornerRadii::default()
};
assert_eq!(r.shared(), Some(12.0));
assert_eq!(CornerRadii::default().shared(), Some(0.0));
assert!(CornerRadii::default().is_zero());
}
#[test]
fn radii_fit_the_box() {
// 100 + 300 on a 200 wide box: everything scales by 0.5.
let r = CornerRadii {
top_left: 100.0,
top_right: 300.0,
bottom_right: 0.0,
bottom_left: 0.0,
continuous: false,
}
.fit(200.0, 1000.0);
assert_eq!(r.to_array(), [50.0, 150.0, 0.0, 0.0]);
let fits = CornerRadii::all(10.0);
assert_eq!(fits.fit(100.0, 100.0), fits);
assert_eq!(fits.inset(4.0), CornerRadii::all(6.0));
assert_eq!(fits.inset(40.0), CornerRadii::all(0.0));
}
#[test]
fn shadow_defaults_follow_react_native() {
let mut s = Style::default();
assert!(!s.view.shadow.is_visible());
s.set("shadowOpacity", StyleValue::Number(0.3)).unwrap();
s.set("shadowRadius", StyleValue::Number(8.0)).unwrap();
s.set_shadow_offset(Some((0.0, 4.0)));
assert!(s.view.shadow.is_visible());
assert_eq!(s.view.shadow.offset_y, 4.0);
s.set("shadowColor", StyleValue::Str("transparent"))
.unwrap();
assert!(!s.view.shadow.is_visible());
s.set_shadow_offset(None);
assert_eq!(s.view.shadow.offset_y, -3.0);
}
#[test]
fn text_styles_parse() {
let mut s = Style::default();
s.set("fontFamily", StyleValue::Str("Inter")).unwrap();
s.set("fontStyle", StyleValue::Str("italic")).unwrap();
s.set(
"textDecorationLine",
StyleValue::Str("underline line-through"),
)
.unwrap();
s.set("textTransform", StyleValue::Str("capitalize"))
.unwrap();
assert_eq!(s.text.font_family, Some(FontFamily::new("Inter")));
assert_eq!(&*s.text.font_family.unwrap().name(), "Inter");
assert_eq!(s.text.italic, Some(true));
assert_eq!(
s.text.decoration,
Some(TextDecoration {
underline: true,
line_through: true
})
);
assert_eq!(
TextTransform::Capitalize.apply("hello wörld-x ünd"),
"Hello Wörld-x Ünd"
);
assert_eq!(
s.set("fontStyle", StyleValue::Str("oblique")),
Err(StyleError::InvalidValue)
);
}
#[test]
fn rejects_bad_values() {
let mut s = Style::default();
assert_eq!(
s.set("width", StyleValue::Str("wide")),
Err(StyleError::InvalidValue)
);
assert_eq!(
s.set("nope", StyleValue::Number(1.0)),
Err(StyleError::UnknownProperty)
);
s.set("width", StyleValue::Str("50%")).unwrap();
assert_eq!(s.layout.size.width, Dimension::percent(0.5));
}
}