Skip to main content

takumi_core/style/properties/
animation.rs

1use std::{borrow::Cow, fmt};
2
3use cssparser::{
4  BasicParseErrorKind, ParseError as CssParseError, Parser, Token, match_ignore_ascii_case,
5  serialize_string,
6};
7use typed_builder::TypedBuilder;
8
9use crate::style::{
10  FromCss, FromCssStr, LinearEasing, MakeComputed, ParseResult, ToCss, impl_comma_list_from_css,
11  impl_css_enum, next_is_comma, tw::TailwindPropertyParser, unexpected_token,
12};
13
14/// Represents a CSS animation time value stored in milliseconds.
15#[derive(Debug, Clone, Copy, PartialEq, Default)]
16pub struct AnimationTime {
17  /// Milliseconds represented by this time value.
18  pub milliseconds: f32,
19}
20
21impl AnimationTime {
22  /// Creates a time value from milliseconds.
23  pub const fn from_milliseconds(milliseconds: f32) -> Self {
24    Self { milliseconds }
25  }
26}
27
28impl MakeComputed for AnimationTime {}
29
30impl<'i> FromCss<'i> for AnimationTime {
31  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
32    let token = input.next()?;
33
34    match token {
35      Token::Dimension { value, unit, .. } => match_ignore_ascii_case! {unit.as_ref(),
36        "ms" => Ok(Self::from_milliseconds(*value)),
37        "s" => Ok(Self::from_milliseconds(*value * 1000.0)),
38        _ => Err(unexpected_token!(token)),
39      },
40      Token::Number { value, .. } if *value == 0.0 => Ok(Self::from_milliseconds(0.0)),
41      _ => Err(unexpected_token!(token)),
42    }
43  }
44
45  const VALID_TOKENS: &'static [&'static str] = &["<time>"];
46}
47
48/// Parsed value for one `animation-name`.
49pub(crate) type AnimationName = Option<String>;
50
51/// Parsed values for `animation-name`.
52pub(crate) type AnimationNames = Box<[AnimationName]>;
53
54impl MakeComputed for AnimationNames {}
55
56impl_comma_list_from_css!(
57  AnimationNames,
58  AnimationName,
59  &["none", "<custom-ident>", "<string>",]
60);
61
62/// Parsed values for `animation-duration` and `animation-delay`.
63pub(crate) type AnimationDurations = Box<[AnimationTime]>;
64
65impl_comma_list_from_css!(AnimationDurations, AnimationTime);
66
67/// Supported CSS timing functions for animations.
68#[derive(Debug, Clone, Copy, PartialEq, Default)]
69#[non_exhaustive]
70pub enum AnimationTimingFunction {
71  /// Uses linear interpolation.
72  Linear,
73  /// Uses the CSS `ease` curve.
74  #[default]
75  Ease,
76  /// Uses the CSS `ease-in` curve.
77  EaseIn,
78  /// Uses the CSS `ease-out` curve.
79  EaseOut,
80  /// Uses the CSS `ease-in-out` curve.
81  EaseInOut,
82  /// Uses the CSS `step-start` timing function.
83  StepStart,
84  /// Uses the CSS `step-end` timing function.
85  StepEnd,
86  /// Uses a stepped timing function with an explicit position.
87  Steps(u32, StepPosition),
88  /// Uses a custom cubic bezier timing curve.
89  CubicBezier(f32, f32, f32, f32),
90  /// Uses a `linear()` curve through its control points.
91  LinearCurve(LinearEasing),
92}
93
94impl MakeComputed for AnimationTimingFunction {}
95
96/// Supported step positions for CSS stepped easing functions.
97#[derive(Debug, Clone, Copy, PartialEq)]
98#[non_exhaustive]
99pub enum StepPosition {
100  /// Jumps at the start of each step interval.
101  Start,
102  /// Jumps at the end of each step interval.
103  End,
104  /// Jumps at both ends, giving one more jump than steps.
105  JumpBoth,
106  /// Jumps at neither end, giving one fewer jump than steps.
107  JumpNone,
108}
109
110impl<'i> FromCss<'i> for AnimationTimingFunction {
111  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
112    if let Ok(function) = input.try_parse(parse_timing_keyword) {
113      return Ok(function);
114    }
115
116    if let Ok(function) = input.try_parse(parse_steps_function) {
117      return Ok(function);
118    }
119
120    if let Ok(curve) = input.try_parse(|input| {
121      input.expect_function_matching("linear")?;
122      input.parse_nested_block(LinearEasing::parse)
123    }) {
124      return Ok(Self::LinearCurve(curve));
125    }
126
127    input.expect_function_matching("cubic-bezier")?;
128    input.parse_nested_block(|input| {
129      let x1 = expect_number(input)?;
130      input.expect_comma()?;
131      let y1 = expect_number(input)?;
132      input.expect_comma()?;
133      let x2 = expect_number(input)?;
134      input.expect_comma()?;
135      let y2 = expect_number(input)?;
136
137      if !(0.0..=1.0).contains(&x1) || !(0.0..=1.0).contains(&x2) {
138        return Err(CssParseError::from_basic_kind(
139          BasicParseErrorKind::QualifiedRuleInvalid,
140        ));
141      }
142
143      Ok(Self::CubicBezier(x1, y1, x2, y2))
144    })
145  }
146
147  const VALID_TOKENS: &'static [&'static str] = &[
148    "linear",
149    "ease",
150    "ease-in",
151    "ease-out",
152    "ease-in-out",
153    "step-start",
154    "step-end",
155    "<steps()>",
156    "<cubic-bezier()>",
157    "<linear()>",
158  ];
159}
160
161/// Parsed values for `animation-timing-function`.
162pub(crate) type AnimationTimingFunctions = Box<[AnimationTimingFunction]>;
163
164impl_comma_list_from_css!(AnimationTimingFunctions, AnimationTimingFunction);
165
166/// Supported values for `animation-iteration-count`.
167#[derive(Debug, Clone, Copy, PartialEq)]
168#[non_exhaustive]
169pub enum AnimationIterationCount {
170  /// A finite iteration count.
171  Number(f32),
172  /// Repeats forever.
173  Infinite,
174}
175
176impl Default for AnimationIterationCount {
177  fn default() -> Self {
178    Self::Number(1.0)
179  }
180}
181
182impl MakeComputed for AnimationIterationCount {}
183
184impl<'i> FromCss<'i> for AnimationIterationCount {
185  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
186    if input
187      .try_parse(|parser| parser.expect_ident_matching("infinite"))
188      .is_ok()
189    {
190      return Ok(Self::Infinite);
191    }
192
193    let value = expect_number(input)?;
194    if value < 0.0 {
195      return Err(CssParseError::from_basic_kind(
196        BasicParseErrorKind::QualifiedRuleInvalid,
197      ));
198    }
199
200    Ok(Self::Number(value))
201  }
202
203  const VALID_TOKENS: &'static [&'static str] = &["<number>", "infinite"];
204}
205
206/// Parsed values for `animation-iteration-count`.
207pub(crate) type AnimationIterationCounts = Box<[AnimationIterationCount]>;
208
209impl_comma_list_from_css!(AnimationIterationCounts, AnimationIterationCount);
210
211/// Supported values for `animation-direction`.
212#[derive(Debug, Clone, Copy, PartialEq, Default)]
213#[non_exhaustive]
214pub enum AnimationDirection {
215  #[default]
216  /// Plays from the first keyframe to the last keyframe.
217  Normal,
218  /// Plays from the last keyframe to the first keyframe.
219  Reverse,
220  /// Alternates between forward and reverse playback.
221  Alternate,
222  /// Alternates between reverse and forward playback.
223  AlternateReverse,
224}
225
226impl_css_enum!(
227  AnimationDirection,
228  "normal" => AnimationDirection::Normal,
229  "reverse" => AnimationDirection::Reverse,
230  "alternate" => AnimationDirection::Alternate,
231  "alternate-reverse" => AnimationDirection::AlternateReverse,
232);
233
234/// Parsed values for `animation-direction`.
235pub(crate) type AnimationDirections = Box<[AnimationDirection]>;
236
237impl_comma_list_from_css!(AnimationDirections, AnimationDirection);
238
239/// Supported values for `animation-fill-mode`.
240#[derive(Debug, Clone, Copy, PartialEq, Default)]
241#[non_exhaustive]
242pub enum AnimationFillMode {
243  #[default]
244  /// Does not apply keyframe values outside the active interval.
245  None,
246  /// Keeps the final keyframe value after completion.
247  Forwards,
248  /// Applies the starting keyframe value during delay.
249  Backwards,
250  /// Applies both backwards and forwards fill behavior.
251  Both,
252}
253
254impl_css_enum!(
255  AnimationFillMode,
256  "none" => AnimationFillMode::None,
257  "forwards" => AnimationFillMode::Forwards,
258  "backwards" => AnimationFillMode::Backwards,
259  "both" => AnimationFillMode::Both,
260);
261
262/// Parsed values for `animation-fill-mode`.
263pub(crate) type AnimationFillModes = Box<[AnimationFillMode]>;
264
265impl_comma_list_from_css!(AnimationFillModes, AnimationFillMode);
266
267/// Supported values for `animation-play-state`.
268#[derive(Debug, Clone, Copy, PartialEq, Default)]
269#[non_exhaustive]
270pub enum AnimationPlayState {
271  #[default]
272  /// The animation is actively progressing with time.
273  Running,
274  /// The animation is frozen and does not advance.
275  Paused,
276}
277
278impl_css_enum!(
279  AnimationPlayState,
280  "running" => AnimationPlayState::Running,
281  "paused" => AnimationPlayState::Paused,
282);
283
284/// Parsed values for `animation-play-state`.
285pub(crate) type AnimationPlayStates = Box<[AnimationPlayState]>;
286
287impl_comma_list_from_css!(AnimationPlayStates, AnimationPlayState);
288
289/// Parsed value for one `animation` shorthand item.
290#[derive(Debug, Clone, PartialEq, Default, TypedBuilder)]
291#[builder(field_defaults(default))]
292#[non_exhaustive]
293pub struct Animation {
294  /// Parsed `animation-duration`.
295  pub duration: AnimationTime,
296  /// Parsed `animation-delay`.
297  pub delay: AnimationTime,
298  /// Parsed `animation-timing-function`.
299  pub timing_function: AnimationTimingFunction,
300  /// Parsed `animation-iteration-count`.
301  pub iteration_count: AnimationIterationCount,
302  /// Parsed `animation-direction`.
303  pub direction: AnimationDirection,
304  /// Parsed `animation-fill-mode`.
305  pub fill_mode: AnimationFillMode,
306  /// Parsed `animation-play-state`.
307  pub play_state: AnimationPlayState,
308  /// Parsed `animation-name`, with `None` representing the CSS `none` keyword.
309  #[builder(setter(strip_option))]
310  pub name: Option<String>,
311}
312
313impl MakeComputed for Animation {}
314
315impl<'i> FromCss<'i> for Animation {
316  fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
317    let mut animation = Self::default();
318    let mut time_count = 0;
319
320    while !input.is_exhausted() && !next_is_comma(input) {
321      if let Ok(value) = input.try_parse(AnimationTime::from_css) {
322        match time_count {
323          0 => animation.duration = value,
324          1 => animation.delay = value,
325          _ => return Err(input.new_error_for_next_token()),
326        }
327        time_count += 1;
328        continue;
329      }
330
331      if let Ok(value) = input.try_parse(AnimationTimingFunction::from_css) {
332        animation.timing_function = value;
333        continue;
334      }
335
336      if let Ok(value) = input.try_parse(AnimationIterationCount::from_css) {
337        animation.iteration_count = value;
338        continue;
339      }
340
341      if let Ok(value) = input.try_parse(AnimationDirection::from_css) {
342        animation.direction = value;
343        continue;
344      }
345
346      if let Ok(value) = input.try_parse(AnimationFillMode::from_css) {
347        animation.fill_mode = value;
348        continue;
349      }
350
351      if let Ok(value) = input.try_parse(AnimationPlayState::from_css) {
352        animation.play_state = value;
353        continue;
354      }
355
356      if let Ok(value) = input.try_parse(AnimationName::from_css) {
357        animation.name = value;
358        continue;
359      }
360
361      return Err(input.new_error_for_next_token());
362    }
363
364    Ok(animation)
365  }
366
367  const VALID_TOKENS: &'static [&'static str] = Animations::VALID_TOKENS;
368}
369
370/// Parsed values for the `animation` shorthand.
371pub(crate) type Animations = Box<[Animation]>;
372
373impl_comma_list_from_css!(
374  Animations,
375  Animation,
376  &[
377    "<time>",
378    "<easing-function>",
379    "<number>",
380    "infinite",
381    "normal",
382    "reverse",
383    "alternate",
384    "alternate-reverse",
385    "none",
386    "forwards",
387    "backwards",
388    "both",
389    "running",
390    "paused",
391    "<custom-ident>",
392    "<string>",
393  ]
394);
395
396impl TailwindPropertyParser for Animations {
397  fn parse_tw(token: &str) -> Option<Self> {
398    match_ignore_ascii_case! {token,
399      "none" => Some(Box::from([Animation::default()])),
400      "spin" => Some(Box::from([Animation {
401        duration: AnimationTime::from_milliseconds(1000.0),
402        timing_function: AnimationTimingFunction::Linear,
403        iteration_count: AnimationIterationCount::Infinite,
404        name: Some("spin".to_string()),
405        ..Animation::default()
406      }])),
407      "ping" => Some(Box::from([Animation {
408        duration: AnimationTime::from_milliseconds(1000.0),
409        timing_function: AnimationTimingFunction::CubicBezier(0.0, 0.0, 0.2, 1.0),
410        iteration_count: AnimationIterationCount::Infinite,
411        name: Some("ping".to_string()),
412        ..Animation::default()
413      }])),
414      "pulse" => Some(Box::from([Animation {
415        duration: AnimationTime::from_milliseconds(2000.0),
416        timing_function: AnimationTimingFunction::CubicBezier(0.4, 0.0, 0.6, 1.0),
417        iteration_count: AnimationIterationCount::Infinite,
418        name: Some("pulse".to_string()),
419        ..Animation::default()
420      }])),
421      "bounce" => Some(Box::from([Animation {
422        duration: AnimationTime::from_milliseconds(1000.0),
423        iteration_count: AnimationIterationCount::Infinite,
424        name: Some("bounce".to_string()),
425        ..Animation::default()
426      }])),
427      _ => None,
428    }
429  }
430
431  fn parse_tw_with_arbitrary(token: &str) -> Option<Self> {
432    if let Some(value) = token
433      .strip_prefix('[')
434      .and_then(|value| value.strip_suffix(']'))
435    {
436      let value = if value.contains('_') {
437        Cow::Owned(value.replace('_', " "))
438      } else {
439        Cow::Borrowed(value)
440      };
441
442      return Self::from_css_str(&value).ok();
443    }
444
445    Self::parse_tw(token)
446  }
447}
448
449fn parse_timing_keyword<'i>(input: &mut Parser<'i>) -> ParseResult<'i, AnimationTimingFunction> {
450  let token = input.next()?;
451  let Token::Ident(ident) = token else {
452    return Err(unexpected_token!(AnimationTimingFunction, token));
453  };
454
455  match_ignore_ascii_case! {ident,
456    "linear" => Ok(AnimationTimingFunction::Linear),
457    "ease" => Ok(AnimationTimingFunction::Ease),
458    "ease-in" => Ok(AnimationTimingFunction::EaseIn),
459    "ease-out" => Ok(AnimationTimingFunction::EaseOut),
460    "ease-in-out" => Ok(AnimationTimingFunction::EaseInOut),
461    "step-start" => Ok(AnimationTimingFunction::StepStart),
462    "step-end" => Ok(AnimationTimingFunction::StepEnd),
463    _ => Err(unexpected_token!(AnimationTimingFunction, token)),
464  }
465}
466
467fn parse_step_position<'i>(input: &mut Parser<'i>) -> ParseResult<'i, StepPosition> {
468  let token = input.next()?;
469  let Token::Ident(ident) = token else {
470    return Err(unexpected_token!(AnimationTimingFunction, token));
471  };
472
473  match_ignore_ascii_case! {ident,
474    "start" | "jump-start" => Ok(StepPosition::Start),
475    "end" | "jump-end" => Ok(StepPosition::End),
476    "jump-both" => Ok(StepPosition::JumpBoth),
477    "jump-none" => Ok(StepPosition::JumpNone),
478    _ => Err(unexpected_token!(AnimationTimingFunction, token)),
479  }
480}
481
482fn parse_steps_function<'i>(input: &mut Parser<'i>) -> ParseResult<'i, AnimationTimingFunction> {
483  input.expect_function_matching("steps")?;
484  input.parse_nested_block(|input| {
485    let count = input.expect_integer()?;
486    if count <= 0 {
487      return Err(CssParseError::from_basic_kind(
488        BasicParseErrorKind::QualifiedRuleInvalid,
489      ));
490    }
491
492    let position = if input.try_parse(Parser::expect_comma).is_ok() {
493      parse_step_position(input)?
494    } else {
495      StepPosition::End
496    };
497
498    if position == StepPosition::JumpNone && count < 2 {
499      return Err(CssParseError::from_basic_kind(
500        BasicParseErrorKind::QualifiedRuleInvalid,
501      ));
502    }
503
504    Ok(AnimationTimingFunction::Steps(count as u32, position))
505  })
506}
507
508fn expect_number<'i>(input: &mut Parser<'i>) -> ParseResult<'i, f32> {
509  let token = input.next()?;
510  let Token::Number { value, .. } = token else {
511    return Err(unexpected_token!(AnimationTime, token));
512  };
513  Ok(*value)
514}
515
516/// The `index`th entry of an `animation-*` list, repeating the list to fit; the initial value when empty.
517pub(crate) fn repeated_list_value<T: Clone + Default>(values: &[T], index: usize) -> T {
518  if values.is_empty() {
519    return T::default();
520  }
521
522  values[index % values.len()].clone()
523}
524
525fn cubic_bezier_sample(x1: f32, y1: f32, x2: f32, y2: f32, progress: f32) -> f32 {
526  fn sample_curve(a: f32, b: f32, c: f32, t: f32) -> f32 {
527    ((a * t + b) * t + c) * t
528  }
529
530  fn sample_derivative(a: f32, b: f32, c: f32, t: f32) -> f32 {
531    (3.0 * a * t + 2.0 * b) * t + c
532  }
533
534  let cx = 3.0 * x1;
535  let bx = 3.0 * (x2 - x1) - cx;
536  let ax = 1.0 - cx - bx;
537  let cy = 3.0 * y1;
538  let by = 3.0 * (y2 - y1) - cy;
539  let ay = 1.0 - cy - by;
540
541  let mut t = progress.clamp(0.0, 1.0);
542  for _ in 0..6 {
543    let x = sample_curve(ax, bx, cx, t) - progress;
544    let derivative = sample_derivative(ax, bx, cx, t);
545    if derivative.abs() < f32::EPSILON {
546      break;
547    }
548    t = (t - x / derivative).clamp(0.0, 1.0);
549  }
550
551  sample_curve(ay, by, cy, t)
552}
553
554fn steps_sample(step_count: u32, position: StepPosition, progress: f32, before: bool) -> f32 {
555  let steps = step_count as f32;
556  let progress = progress.clamp(0.0, 1.0);
557
558  // Jumps differ from steps when both or neither end point is discontinuous.
559  // https://drafts.csswg.org/css-easing-1/#step-easing-functions
560  let (jumps, start_offset) = match position {
561    StepPosition::Start => (steps, 1.0),
562    StepPosition::End => (steps, 0.0),
563    StepPosition::JumpBoth => (steps + 1.0, 1.0),
564    StepPosition::JumpNone => ((steps - 1.0).max(1.0), 0.0),
565  };
566
567  let scaled = progress * steps;
568  let mut current_step = (scaled + start_offset).floor();
569  if before && scaled.fract() == 0.0 {
570    current_step -= 1.0;
571  }
572
573  current_step.clamp(0.0, jumps) / jumps
574}
575
576impl AnimationTimingFunction {
577  /// Samples the easing curve at `progress`. `before` marks a sample taken from
578  /// the interval before the animation's active phase, where a step function
579  /// sitting exactly on a jump takes the lower step.
580  /// https://drafts.csswg.org/css-easing-1/#step-easing-algo
581  pub(crate) fn apply(self, progress: f32, before: bool) -> f32 {
582    match self {
583      Self::Linear => progress,
584      Self::Ease => cubic_bezier_sample(0.25, 0.1, 0.25, 1.0, progress),
585      Self::EaseIn => cubic_bezier_sample(0.42, 0.0, 1.0, 1.0, progress),
586      Self::EaseOut => cubic_bezier_sample(0.0, 0.0, 0.58, 1.0, progress),
587      Self::EaseInOut => cubic_bezier_sample(0.42, 0.0, 0.58, 1.0, progress),
588      Self::StepStart => steps_sample(1, StepPosition::Start, progress, before),
589      Self::StepEnd => steps_sample(1, StepPosition::End, progress, before),
590      Self::Steps(count, position) => steps_sample(count, position, progress, before),
591      Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier_sample(x1, y1, x2, y2, progress),
592      Self::LinearCurve(curve) => curve.apply(progress),
593    }
594  }
595}
596
597impl ToCss for AnimationTime {
598  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
599    write!(dest, "{milliseconds}ms", milliseconds = self.milliseconds)
600  }
601}
602
603impl ToCss for StepPosition {
604  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
605    match self {
606      Self::Start => dest.write_str("start"),
607      Self::End => dest.write_str("end"),
608      Self::JumpBoth => dest.write_str("jump-both"),
609      Self::JumpNone => dest.write_str("jump-none"),
610    }
611  }
612}
613
614impl ToCss for AnimationTimingFunction {
615  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
616    match self {
617      Self::Linear => dest.write_str("linear"),
618      Self::Ease => dest.write_str("ease"),
619      Self::EaseIn => dest.write_str("ease-in"),
620      Self::EaseOut => dest.write_str("ease-out"),
621      Self::EaseInOut => dest.write_str("ease-in-out"),
622      Self::StepStart => dest.write_str("step-start"),
623      Self::StepEnd => dest.write_str("step-end"),
624      Self::Steps(count, position) => {
625        write!(dest, "steps({count}")?;
626        if *position != StepPosition::End {
627          dest.write_str(", ")?;
628          position.to_css(dest)?;
629        }
630        dest.write_char(')')
631      }
632      Self::CubicBezier(x1, y1, x2, y2) => write!(dest, "cubic-bezier({x1}, {y1}, {x2}, {y2})"),
633      Self::LinearCurve(curve) => curve.to_css(dest),
634    }
635  }
636}
637
638impl ToCss for AnimationIterationCount {
639  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
640    match self {
641      Self::Number(n) => write!(dest, "{n}"),
642      Self::Infinite => dest.write_str("infinite"),
643    }
644  }
645}
646
647impl ToCss for Animation {
648  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
649    if let Some(ref name) = self.name {
650      let needs_quoting = name
651        .chars()
652        .any(|c| !matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '-'));
653      if needs_quoting {
654        serialize_string(name, dest)?;
655      } else {
656        dest.write_str(name)?;
657      }
658    } else {
659      dest.write_str("none")?;
660    }
661    dest.write_char(' ')?;
662    self.duration.to_css(dest)?;
663    dest.write_char(' ')?;
664    self.timing_function.to_css(dest)?;
665    dest.write_char(' ')?;
666    self.delay.to_css(dest)?;
667    dest.write_char(' ')?;
668    self.iteration_count.to_css(dest)?;
669    dest.write_char(' ')?;
670    self.direction.to_css(dest)?;
671    dest.write_char(' ')?;
672    self.fill_mode.to_css(dest)?;
673    dest.write_char(' ')?;
674    self.play_state.to_css(dest)
675  }
676}
677
678#[cfg(test)]
679mod tests {
680  use std::assert_matches;
681
682  use super::*;
683
684  #[test]
685  fn parse_animation_time() {
686    assert_eq!(
687      AnimationTime::from_css_str("150ms"),
688      Ok(AnimationTime::from_milliseconds(150.0))
689    );
690    assert_eq!(
691      AnimationTime::from_css_str("2s"),
692      Ok(AnimationTime::from_milliseconds(2000.0))
693    );
694  }
695
696  #[test]
697  fn parse_animation_names() {
698    assert_matches!(
699      AnimationNames::from_css_str("fade, slide"),
700      Ok(names) if names.as_ref() == [Some("fade".to_string()), Some("slide".to_string())]
701    );
702  }
703
704  #[test]
705  fn parse_quoted_animation_names() {
706    assert_matches!(
707      AnimationNames::from_css_str("\"fade\", slide"),
708      Ok(names) if names.as_ref() == [Some("fade".to_string()), Some("slide".to_string())]
709    );
710  }
711
712  #[test]
713  fn parse_animation_names_with_none_entry() {
714    assert_matches!(
715      AnimationNames::from_css_str("none, slide"),
716      Ok(names) if names.as_ref() == [None, Some("slide".to_string())]
717    );
718  }
719
720  #[test]
721  fn parse_steps_timing_functions() {
722    assert_eq!(
723      AnimationTimingFunction::from_css_str("step-start"),
724      Ok(AnimationTimingFunction::StepStart)
725    );
726    assert_eq!(
727      AnimationTimingFunction::from_css_str("step-end"),
728      Ok(AnimationTimingFunction::StepEnd)
729    );
730    assert_eq!(
731      AnimationTimingFunction::from_css_str("steps(4, end)"),
732      Ok(AnimationTimingFunction::Steps(4, StepPosition::End))
733    );
734    assert_eq!(
735      AnimationTimingFunction::from_css_str("steps(4)"),
736      Ok(AnimationTimingFunction::Steps(4, StepPosition::End))
737    );
738    assert_eq!(
739      AnimationTimingFunction::from_css_str("steps(4, jump-start)"),
740      Ok(AnimationTimingFunction::Steps(4, StepPosition::Start))
741    );
742    assert_eq!(
743      AnimationTimingFunction::from_css_str("steps(4, jump-none)"),
744      Ok(AnimationTimingFunction::Steps(4, StepPosition::JumpNone))
745    );
746    assert_eq!(
747      AnimationTimingFunction::from_css_str("steps(4, jump-both)"),
748      Ok(AnimationTimingFunction::Steps(4, StepPosition::JumpBoth))
749    );
750  }
751
752  #[test]
753  fn reject_single_step_jump_none() {
754    assert!(AnimationTimingFunction::from_css_str("steps(1, jump-none)").is_err());
755  }
756
757  #[test]
758  fn steps_timing_functions_sample_as_staircase() {
759    let sample = |css: &str, progress: f32| {
760      AnimationTimingFunction::from_css_str(css)
761        .unwrap()
762        .apply(progress, false)
763    };
764
765    for (progress, expected) in [(0.0, 0.0), (0.3, 0.25), (0.6, 0.5), (1.0, 1.0)] {
766      assert_eq!(sample("steps(4, jump-end)", progress), expected);
767    }
768
769    for (progress, expected) in [(0.0, 0.0), (0.3, 1.0 / 3.0), (0.6, 2.0 / 3.0), (1.0, 1.0)] {
770      assert_eq!(sample("steps(4, jump-none)", progress), expected);
771    }
772
773    for (progress, expected) in [(0.0, 0.2), (0.3, 0.4), (0.6, 0.6), (1.0, 1.0)] {
774      assert_eq!(sample("steps(4, jump-both)", progress), expected);
775    }
776
777    for (progress, expected) in [(0.0, 0.25), (0.3, 0.5), (0.6, 0.75), (1.0, 1.0)] {
778      assert_eq!(sample("steps(4, jump-start)", progress), expected);
779    }
780  }
781
782  #[test]
783  fn steps_timing_functions_hold_the_lower_step_before_the_active_phase() {
784    let sample = |css: &str, progress: f32| {
785      AnimationTimingFunction::from_css_str(css)
786        .unwrap()
787        .apply(progress, true)
788    };
789
790    // A backwards-filled delay samples progress 0, which sits on a jump for
791    // every start-anchored position.
792    assert_eq!(sample("steps(4, jump-start)", 0.0), 0.0);
793    assert_eq!(sample("steps(4, jump-both)", 0.0), 0.0);
794    assert_eq!(sample("steps(4, jump-end)", 0.0), 0.0);
795    assert_eq!(sample("step-start", 0.0), 0.0);
796
797    // Reverse playback fills from the far end instead.
798    assert_eq!(sample("steps(4, jump-end)", 1.0), 0.75);
799    assert_eq!(sample("steps(4, jump-start)", 1.0), 1.0);
800
801    // Away from a jump the flag changes nothing.
802    assert_eq!(sample("steps(4, jump-end)", 0.3), 0.25);
803  }
804
805  #[test]
806  fn steps_timing_functions_serialize_without_a_default_position() {
807    let round_trip = |css: &str| {
808      AnimationTimingFunction::from_css_str(css)
809        .unwrap()
810        .to_css_string()
811    };
812
813    assert_eq!(round_trip("steps(4)"), "steps(4)");
814    assert_eq!(round_trip("steps(4, end)"), "steps(4)");
815    assert_eq!(round_trip("steps(4, jump-end)"), "steps(4)");
816    assert_eq!(round_trip("steps(4, jump-start)"), "steps(4, start)");
817    assert_eq!(round_trip("steps(4, jump-none)"), "steps(4, jump-none)");
818    assert_eq!(round_trip("steps(4, jump-both)"), "steps(4, jump-both)");
819  }
820
821  #[test]
822  fn parse_animation_shorthand_with_steps() {
823    assert_eq!(
824      Animations::from_css_str("fade 1s steps(4, jump-none)"),
825      Ok(Box::from([Animation {
826        duration: AnimationTime::from_milliseconds(1000.0),
827        timing_function: AnimationTimingFunction::Steps(4, StepPosition::JumpNone),
828        name: Some("fade".to_string()),
829        ..Animation::default()
830      }]))
831    );
832  }
833
834  #[test]
835  fn reject_invalid_cubic_bezier_x_coordinates() {
836    assert!(AnimationTimingFunction::from_css_str("cubic-bezier(-0.1, 0, 0.2, 1)").is_err());
837    assert!(AnimationTimingFunction::from_css_str("cubic-bezier(0.1, 0, 1.2, 1)").is_err());
838  }
839
840  #[test]
841  fn reject_negative_animation_iteration_count() {
842    assert!(AnimationIterationCount::from_css_str("-1").is_err());
843  }
844
845  #[test]
846  fn cubic_bezier_preserves_overshoot() {
847    let function =
848      AnimationTimingFunction::from_css_str("cubic-bezier(0.68, -0.6, 0.32, 1.6)").unwrap();
849
850    let early = function.apply(0.2, false);
851    let late = function.apply(0.8, false);
852
853    assert!(early < 0.0, "expected negative overshoot, got {early}");
854    assert!(late > 1.0, "expected positive overshoot, got {late}");
855  }
856
857  #[test]
858  fn repeated_list_value_wraps() {
859    let values: AnimationDirections =
860      [AnimationDirection::Normal, AnimationDirection::Reverse].into();
861    assert_eq!(repeated_list_value(&values, 2), AnimationDirection::Normal);
862  }
863
864  #[test]
865  fn parse_animation_shorthand() {
866    assert_eq!(
867      Animations::from_css_str("fade 1s ease-in 200ms 2 alternate both paused"),
868      Ok(Box::from([Animation {
869        duration: AnimationTime::from_milliseconds(1000.0),
870        delay: AnimationTime::from_milliseconds(200.0),
871        timing_function: AnimationTimingFunction::EaseIn,
872        iteration_count: AnimationIterationCount::Number(2.0),
873        direction: AnimationDirection::Alternate,
874        fill_mode: AnimationFillMode::Both,
875        play_state: AnimationPlayState::Paused,
876        name: Some("fade".to_string()),
877      }]))
878    );
879  }
880
881  #[test]
882  fn parse_animation_shorthand_with_quoted_name() {
883    assert_eq!(
884      Animations::from_css_str("\"fade\" 1s linear"),
885      Ok(Box::from([Animation {
886        duration: AnimationTime::from_milliseconds(1000.0),
887        timing_function: AnimationTimingFunction::Linear,
888        name: Some("fade".to_string()),
889        ..Animation::default()
890      }]))
891    );
892  }
893
894  #[test]
895  fn parse_multiple_animation_shorthand_values() {
896    assert_eq!(
897      Animations::from_css_str("fade 1s linear, 2s slide"),
898      Ok(Box::from([
899        Animation {
900          duration: AnimationTime::from_milliseconds(1000.0),
901          timing_function: AnimationTimingFunction::Linear,
902          name: Some("fade".to_string()),
903          ..Animation::default()
904        },
905        Animation {
906          duration: AnimationTime::from_milliseconds(2000.0),
907          name: Some("slide".to_string()),
908          ..Animation::default()
909        },
910      ]))
911    );
912  }
913}