Skip to main content

rspack_lightningcss/values/
time.rs

1//! CSS time values.
2
3use super::angle::impl_try_from_angle;
4use super::calc::Calc;
5use super::number::{CSSNumber, NumericRange};
6use crate::error::{ParserError, PrinterError};
7use crate::traits::private::AddInternal;
8use crate::traits::{impl_op, Map, Op, Parse, ParseNumeric, Sign, ToCss, Zero};
9#[cfg(feature = "visitor")]
10use crate::visitor::Visit;
11use cssparser::*;
12
13/// A CSS [`<time>`](https://www.w3.org/TR/css-values-4/#time) value, in either
14/// seconds or milliseconds.
15///
16/// Time values may be explicit or computed by `calc()`, but are always stored and serialized
17/// as their computed value.
18#[derive(Debug, Clone, PartialEq)]
19#[cfg_attr(feature = "visitor", derive(Visit))]
20#[cfg_attr(feature = "visitor", visit(visit_time, TIMES))]
21#[cfg_attr(
22  feature = "serde",
23  derive(serde::Serialize, serde::Deserialize),
24  serde(tag = "type", content = "value", rename_all = "kebab-case")
25)]
26#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
27#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
28pub enum Time {
29  /// A time in seconds.
30  Seconds(CSSNumber),
31  /// A time in milliseconds.
32  Milliseconds(CSSNumber),
33}
34
35impl Time {
36  /// Returns the time in milliseconds.
37  pub fn to_ms(&self) -> CSSNumber {
38    match self {
39      Time::Seconds(s) => s * 1000.0,
40      Time::Milliseconds(ms) => *ms,
41    }
42  }
43}
44
45impl Zero for Time {
46  fn zero() -> Self {
47    Time::Milliseconds(0.0)
48  }
49
50  fn is_zero(&self) -> bool {
51    match self {
52      Time::Seconds(s) => s.is_zero(),
53      Time::Milliseconds(s) => s.is_zero(),
54    }
55  }
56}
57
58impl<'i> Parse<'i> for Time {
59  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
60    Self::parse_with_range(input, NumericRange::All)
61  }
62}
63
64impl<'i> ParseNumeric<'i> for Time {
65  fn parse_with_range<'t>(
66    input: &mut Parser<'i, 't>,
67    range: NumericRange,
68  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
69    match input.try_parse(Calc::<Self>::parse) {
70      Ok(Calc::Value(v)) => return Ok(v.map(|value| range.clamp(value))),
71      // Time is always compatible, so they will always compute to a value.
72      Ok(_) => return Err(input.new_custom_error(ParserError::InvalidValue)),
73      _ => {}
74    }
75
76    let location = input.current_source_location();
77    match *input.next()? {
78      Token::Dimension { value, ref unit, .. } => {
79        let value = range.check(value, location)?;
80        match_ignore_ascii_case! { unit,
81          "s" => Ok(Time::Seconds(value)),
82          "ms" => Ok(Time::Milliseconds(value)),
83          _ => Err(location.new_unexpected_token_error(Token::Ident(unit.clone())))
84        }
85      }
86      ref t => Err(location.new_unexpected_token_error(t.clone())),
87    }
88  }
89}
90
91impl<'i> TryFrom<&Token<'i>> for Time {
92  type Error = ();
93
94  fn try_from(token: &Token) -> Result<Self, Self::Error> {
95    match token {
96      Token::Dimension { value, ref unit, .. } => match_ignore_ascii_case! { unit,
97        "s" => Ok(Time::Seconds(*value)),
98        "ms" => Ok(Time::Milliseconds(*value)),
99        _ => Err(()),
100      },
101      _ => Err(()),
102    }
103  }
104}
105
106impl ToCss for Time {
107  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
108    // 0.1s is shorter than 100ms
109    // anything smaller is longer
110    match self {
111      Time::Seconds(s) => {
112        if *s > 0.0 && *s < 0.1 {
113          (*s * 1000.0).to_css(dest)?;
114          dest.write_str("ms")?;
115          Ok(())
116        } else {
117          s.to_css(dest)?;
118          dest.write_str("s")?;
119          Ok(())
120        }
121      }
122      Time::Milliseconds(ms) => {
123        if *ms == 0.0 || *ms >= 100.0 {
124          (*ms / 1000.0).to_css(dest)?;
125          dest.write_str("s")?;
126          Ok(())
127        } else {
128          ms.to_css(dest)?;
129          dest.write_str("ms")?;
130          Ok(())
131        }
132      }
133    }
134  }
135}
136
137impl std::convert::Into<Calc<Time>> for Time {
138  fn into(self) -> Calc<Time> {
139    Calc::Value(Box::new(self))
140  }
141}
142
143impl std::convert::TryFrom<Calc<Time>> for Time {
144  type Error = ();
145
146  fn try_from(calc: Calc<Time>) -> Result<Time, Self::Error> {
147    match calc {
148      Calc::Value(v) => Ok(*v),
149      _ => Err(()),
150    }
151  }
152}
153
154impl std::ops::Mul<f32> for Time {
155  type Output = Self;
156
157  fn mul(self, other: f32) -> Time {
158    match self {
159      Time::Seconds(t) => Time::Seconds(t * other),
160      Time::Milliseconds(t) => Time::Milliseconds(t * other),
161    }
162  }
163}
164
165impl AddInternal for Time {
166  fn add(self, other: Self) -> Self {
167    self + other
168  }
169}
170
171impl std::cmp::PartialOrd<Time> for Time {
172  fn partial_cmp(&self, other: &Time) -> Option<std::cmp::Ordering> {
173    self.to_ms().partial_cmp(&other.to_ms())
174  }
175}
176
177impl Op for Time {
178  fn op<F: FnOnce(f32, f32) -> f32>(&self, to: &Self, op: F) -> Self {
179    match (self, to) {
180      (Time::Seconds(a), Time::Seconds(b)) => Time::Seconds(op(*a, *b)),
181      (Time::Milliseconds(a), Time::Milliseconds(b)) => Time::Milliseconds(op(*a, *b)),
182      (Time::Seconds(a), Time::Milliseconds(b)) => Time::Seconds(op(*a, b / 1000.0)),
183      (Time::Milliseconds(a), Time::Seconds(b)) => Time::Milliseconds(op(*a, b * 1000.0)),
184    }
185  }
186
187  fn op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> T {
188    match (self, rhs) {
189      (Time::Seconds(a), Time::Seconds(b)) => op(*a, *b),
190      (Time::Milliseconds(a), Time::Milliseconds(b)) => op(*a, *b),
191      (Time::Seconds(a), Time::Milliseconds(b)) => op(*a, b / 1000.0),
192      (Time::Milliseconds(a), Time::Seconds(b)) => op(*a, b * 1000.0),
193    }
194  }
195}
196
197impl Map for Time {
198  fn map<F: FnOnce(f32) -> f32>(&self, op: F) -> Self {
199    match self {
200      Time::Seconds(t) => Time::Seconds(op(*t)),
201      Time::Milliseconds(t) => Time::Milliseconds(op(*t)),
202    }
203  }
204}
205
206impl Sign for Time {
207  fn sign(&self) -> f32 {
208    match self {
209      Time::Seconds(v) | Time::Milliseconds(v) => v.sign(),
210    }
211  }
212}
213
214impl_op!(Time, std::ops::Rem, rem);
215impl_op!(Time, std::ops::Add, add);
216
217impl_try_from_angle!(Time);