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