tailwind_css_fixes/systems/units/length/
mod.rs1use std::ops::Rem;
2
3use tailwind_ast::parse_fraction;
4
5use super::*;
6
7#[derive(Debug, Copy, Clone)]
8pub enum LengthUnit {
9 Fraction(u32, u32),
10 Unit(f32, &'static str),
11}
12
13impl Display for LengthUnit {
14 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
15 match self {
16 Self::Fraction(a, b) => write!(f, "{}/{}", a, b),
17 Self::Unit(a, b) => write!(f, "{}{}", a, b),
18 }
19 }
20}
21
22impl LengthUnit {
23 pub fn parse_fraction(input: &str) -> Result<Self> {
25 let (a, b) = parse_fraction(input)?.1;
26 Ok(Self::ratio(a as u32, b as u32))
27 }
28 pub fn parse_length(input: &str) -> Result<Self> {
29 let valid = (unit("px"), unit("em"), unit("rem"), unit("%"), unit("vh"), unit("vw"));
30 let (f, unit) = tuple((parse_f32, alt(valid)))(input)?.1;
31 Ok(Self::Unit(f, unit))
32 }
33 pub fn parse_angle(input: &str) -> Result<Self> {
34 let valid = (unit("deg"), unit("rad"), unit("grad"), unit("turn"));
35 let (f, unit) = tuple((parse_f32, alt(valid)))(input)?.1;
36 Ok(Self::Unit(f, unit))
37 }
38 pub fn px(x: f32) -> Self {
39 Self::Unit(x, "px")
40 }
41 pub fn em(x: f32) -> Self {
42 Self::Unit(x, "em")
43 }
44 pub fn rem(x: f32) -> Self {
45 Self::Unit(x, "rem")
46 }
47 pub fn percent(x: f32) -> Self {
48 Self::Unit(x, "%")
49 }
50 pub fn vh(x: f32) -> Self {
51 Self::Unit(x, "vh")
52 }
53 pub fn vw(x: f32) -> Self {
54 Self::Unit(x, "vw")
55 }
56 pub fn ratio(a: u32, b: u32) -> Self {
57 if b.eq(&0) {
58 return Self::Fraction(0, 1);
59 }
60 let n = gcd(a, b);
61 Self::Fraction(a / n, b / n)
62 }
63}
64
65pub fn gcd<T>(a: T, b: T) -> T
66where
67 T: PartialEq + Rem<Output = T> + Default + Copy,
68{
69 if b == T::default() { a } else { gcd(b, a % b) }
70}
71
72fn unit(unit: &'static str) -> impl Fn(&str) -> IResult<&str, &'static str> {
73 move |input: &str| tag(unit)(input).map(|(s, _)| (s, unit))
74}
75
76impl LengthUnit {
77 #[inline]
78 pub fn get_class(&self) -> String {
79 self.to_string()
80 }
81 #[inline]
82 pub fn get_class_arbitrary(&self) -> String {
83 format!("[{}]", self)
84 }
85 #[inline]
86 pub fn get_properties(&self) -> String {
87 match self {
88 Self::Fraction(a, b) => {
89 let p = *a as f32 / *b as f32;
90 format!("{}%", 100.0 * p)
91 },
92 Self::Unit(a, b) => format!("{}{}", a, b),
93 }
94 }
95
96 pub fn is_fraction(&self) -> bool {
97 matches!(self, Self::Fraction { .. })
98 }
99 pub fn is_fraction_eq(&self) -> bool {
100 match self {
101 Self::Fraction(a, b) => a.eq(b),
102 _ => false,
103 }
104 }
105 pub fn is_fraction_zero(&self) -> bool {
106 match self {
107 Self::Fraction(a, _) => a.eq(&0),
108 _ => false,
109 }
110 }
111 pub fn is_zero(&self) -> bool {
114 match self {
115 Self::Fraction(a, _) => a.eq(&0),
116 Self::Unit(a, _) => a.eq(&0.0),
117 }
118 }
119}