Skip to main content

rspack_lightningcss/values/
easing.rs

1//! CSS easing functions.
2
3use crate::error::{ParserError, PrinterError};
4use crate::traits::{Parse, ToCss};
5use crate::values::number::{CSSInteger, CSSNumber};
6#[cfg(feature = "visitor")]
7use crate::visitor::Visit;
8use cssparser::*;
9
10/// A CSS [easing function](https://www.w3.org/TR/css-easing-1/#easing-functions).
11#[derive(Debug, Clone, PartialEq)]
12#[cfg_attr(feature = "visitor", derive(Visit))]
13#[cfg_attr(
14  feature = "serde",
15  derive(serde::Serialize, serde::Deserialize),
16  serde(tag = "type", rename_all = "kebab-case")
17)]
18#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
19#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
20pub enum EasingFunction {
21  /// A linear easing function.
22  Linear,
23  /// Equivalent to `cubic-bezier(0.25, 0.1, 0.25, 1)`.
24  Ease,
25  /// Equivalent to `cubic-bezier(0.42, 0, 1, 1)`.
26  EaseIn,
27  /// Equivalent to `cubic-bezier(0, 0, 0.58, 1)`.
28  EaseOut,
29  /// Equivalent to `cubic-bezier(0.42, 0, 0.58, 1)`.
30  EaseInOut,
31  /// A custom cubic Bézier easing function.
32  CubicBezier {
33    /// The x-position of the first point in the curve.
34    x1: CSSNumber,
35    /// The y-position of the first point in the curve.
36    y1: CSSNumber,
37    /// The x-position of the second point in the curve.
38    x2: CSSNumber,
39    /// The y-position of the second point in the curve.
40    y2: CSSNumber,
41  },
42  /// A step easing function.
43  Steps {
44    /// The number of intervals in the function.
45    count: CSSInteger,
46    /// The step position.
47    #[cfg_attr(feature = "serde", serde(default))]
48    position: StepPosition,
49  },
50}
51
52impl EasingFunction {
53  /// Returns whether the easing function is equivalent to the `ease` keyword.
54  pub fn is_ease(&self) -> bool {
55    *self == EasingFunction::Ease
56      || *self
57        == EasingFunction::CubicBezier {
58          x1: 0.25,
59          y1: 0.1,
60          x2: 0.25,
61          y2: 1.0,
62        }
63  }
64}
65
66impl<'i> Parse<'i> for EasingFunction {
67  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
68    let location = input.current_source_location();
69    if let Ok(ident) = input.try_parse(|i| i.expect_ident_cloned()) {
70      let keyword = match_ignore_ascii_case! { &ident,
71        "linear" => EasingFunction::Linear,
72        "ease" => EasingFunction::Ease,
73        "ease-in" => EasingFunction::EaseIn,
74        "ease-out" => EasingFunction::EaseOut,
75        "ease-in-out" => EasingFunction::EaseInOut,
76        "step-start" => EasingFunction::Steps { count: 1, position: StepPosition::Start },
77        "step-end" => EasingFunction::Steps { count: 1, position: StepPosition::End },
78        _ => return Err(location.new_unexpected_token_error(Token::Ident(ident.clone())))
79      };
80      return Ok(keyword);
81    }
82
83    let function = input.expect_function()?.clone();
84    input.parse_nested_block(|input| {
85      match_ignore_ascii_case! { &function,
86        "cubic-bezier" => {
87          let x1 = CSSNumber::parse(input)?;
88          input.expect_comma()?;
89          let y1 = CSSNumber::parse(input)?;
90          input.expect_comma()?;
91          let x2 = CSSNumber::parse(input)?;
92          input.expect_comma()?;
93          let y2 = CSSNumber::parse(input)?;
94          Ok(EasingFunction::CubicBezier { x1, y1, x2, y2 })
95        },
96        "steps" => {
97          let count = CSSInteger::parse(input)?;
98          let position = input.try_parse(|input| {
99            input.expect_comma()?;
100            StepPosition::parse(input)
101          }).unwrap_or_default();
102          Ok(EasingFunction::Steps { count, position })
103        },
104        _ => return Err(location.new_unexpected_token_error(Token::Ident(function.clone())))
105      }
106    })
107  }
108}
109
110impl ToCss for EasingFunction {
111  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
112    match self {
113      EasingFunction::Linear => dest.write_str("linear")?,
114      EasingFunction::Ease => dest.write_str("ease")?,
115      EasingFunction::EaseIn => dest.write_str("ease-in")?,
116      EasingFunction::EaseOut => dest.write_str("ease-out")?,
117      EasingFunction::EaseInOut => dest.write_str("ease-in-out")?,
118      _ if self.is_ease() => dest.write_str("ease")?,
119      x if *x
120        == EasingFunction::CubicBezier {
121          x1: 0.42,
122          y1: 0.0,
123          x2: 1.0,
124          y2: 1.0,
125        } =>
126      {
127        dest.write_str("ease-in")?;
128      }
129      x if *x
130        == EasingFunction::CubicBezier {
131          x1: 0.0,
132          y1: 0.0,
133          x2: 0.58,
134          y2: 1.0,
135        } =>
136      {
137        dest.write_str("ease-out")?;
138      }
139      x if *x
140        == EasingFunction::CubicBezier {
141          x1: 0.42,
142          y1: 0.0,
143          x2: 0.58,
144          y2: 1.0,
145        } =>
146      {
147        dest.write_str("ease-in-out")?;
148      }
149      EasingFunction::CubicBezier { x1, y1, x2, y2 } => {
150        dest.write_str("cubic-bezier(")?;
151        x1.to_css(dest)?;
152        dest.delim(',', false)?;
153        y1.to_css(dest)?;
154        dest.delim(',', false)?;
155        x2.to_css(dest)?;
156        dest.delim(',', false)?;
157        y2.to_css(dest)?;
158        dest.write_char(')')?;
159      }
160      EasingFunction::Steps {
161        count: 1,
162        position: StepPosition::Start,
163      } => dest.write_str("step-start")?,
164      EasingFunction::Steps {
165        count: 1,
166        position: StepPosition::End,
167      } => dest.write_str("step-end")?,
168      EasingFunction::Steps { count, position } => {
169        dest.write_str("steps(")?;
170        write!(dest, "{}", count)?;
171        dest.delim(',', false)?;
172        position.to_css(dest)?;
173        dest.write_char(')')?;
174      }
175    };
176    Ok(())
177  }
178}
179
180impl EasingFunction {
181  /// Returns whether the given string is a valid easing function name.
182  pub fn is_ident(s: &str) -> bool {
183    match s {
184      "linear" | "ease" | "ease-in" | "ease-out" | "ease-in-out" | "step-start" | "step-end" => true,
185      _ => false,
186    }
187  }
188}
189
190/// A [step position](https://www.w3.org/TR/css-easing-1/#step-position), used within the `steps()` function.
191#[derive(Debug, Clone, PartialEq, ToCss)]
192#[cfg_attr(feature = "visitor", derive(Visit))]
193#[cfg_attr(
194  feature = "serde",
195  derive(serde::Serialize, serde::Deserialize),
196  serde(tag = "type", content = "value", rename_all = "kebab-case")
197)]
198#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
199pub enum StepPosition {
200  /// The first rise occurs at input progress value of 0.
201  Start,
202  /// The last rise occurs at input progress value of 1.
203  End,
204  /// All rises occur within the range (0, 1).
205  JumpNone,
206  /// The first rise occurs at input progress value of 0 and the last rise occurs at input progress value of 1.
207  JumpBoth,
208}
209
210impl Default for StepPosition {
211  fn default() -> Self {
212    StepPosition::End
213  }
214}
215
216impl<'i> Parse<'i> for StepPosition {
217  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
218    let location = input.current_source_location();
219    let ident = input.expect_ident()?;
220    let keyword = match_ignore_ascii_case! { &ident,
221      "start" => StepPosition::Start,
222      "end" => StepPosition::End,
223      "jump-start" => StepPosition::Start,
224      "jump-end" => StepPosition::End,
225      "jump-none" => StepPosition::JumpNone,
226      "jump-both" => StepPosition::JumpBoth,
227      _ => return Err(location.new_unexpected_token_error(Token::Ident(ident.clone())))
228    };
229    Ok(keyword)
230  }
231}