Skip to main content

takumi_core/style/
animation.rs

1use std::borrow::Cow;
2
3use serde::Deserialize;
4use typed_builder::TypedBuilder;
5
6use crate::{
7  Xxh3HashSet,
8  sort_key::sort_by_key,
9  style::{
10    StyleDeclarationBlock,
11    selector::{MediaQueryList, StyleSheet},
12    *,
13  },
14  viewport::Viewport,
15};
16
17#[derive(Debug, Clone, Deserialize, PartialEq, TypedBuilder)]
18#[serde(rename_all = "camelCase")]
19/// A single structured keyframe rule.
20pub struct KeyframeRule {
21  /// Keyframe offsets as values between 0.0 and 1.0.
22  #[builder(setter(into))]
23  pub offsets: Vec<f32>,
24  /// Declarations applied at this step.
25  pub declarations: StyleDeclarationBlock,
26}
27
28#[derive(Debug, Clone, Deserialize, PartialEq, TypedBuilder)]
29#[serde(rename_all = "camelCase")]
30/// Structured keyframes that can be passed directly in render options.
31pub struct KeyframesRule {
32  /// Animation name matched by `animation-name`.
33  #[builder(setter(into))]
34  pub name: String,
35  /// Individual keyframe rules for this animation.
36  #[builder(setter(into))]
37  pub keyframes: Vec<KeyframeRule>,
38  /// Media queries gating this `@keyframes` rule.
39  #[serde(skip, default)]
40  #[builder(default, setter(skip))]
41  pub media_queries: Vec<MediaQueryList>,
42}
43
44/// Applies a stylesheet's matching animations to a style at the given time.
45pub(crate) fn apply_stylesheet_animations(
46  mut base_style: ComputedStyle,
47  stylesheet: &StyleSheet,
48  time: u64,
49  sizing: &SizingContext,
50  current_color: Color,
51) -> ComputedStyle {
52  if base_style.misc1_data.animation_name.is_empty() {
53    return base_style;
54  }
55
56  let base_snapshot = base_style.clone();
57
58  for animation in active_animations(&base_snapshot, stylesheet, time, sizing.viewport) {
59    let resolved_frames = resolve_keyframes(&animation.keyframes, &base_snapshot);
60    let Some(segment) =
61      sample_keyframe_segment(&resolved_frames, &base_snapshot, animation.sample.progress)
62    else {
63      continue;
64    };
65
66    let eased_progress = animation
67      .timing_function
68      .apply(segment.progress, animation.sample.before);
69    base_style.apply_interpolated_properties(
70      segment.from_style,
71      segment.to_style,
72      &segment.animated_properties,
73      eased_progress,
74      sizing,
75      current_color,
76    );
77  }
78
79  base_style
80}
81
82/// The custom properties the stylesheet's animations set on `base_style` at `time`, each after
83/// the earlier animations that set it: a registered one interpolated as its syntax types it, any
84/// other switching half way, as css-variables-1 animates one.
85/// <https://drafts.css-houdini.org/css-properties-values-api-1/#animation-behavior-of-custom-properties>
86pub(crate) fn animated_custom_properties(
87  base_style: &ComputedStyle,
88  stylesheet: &StyleSheet,
89  time: u64,
90  sizing: &SizingContext,
91  current_color: Color,
92) -> Vec<(String, String)> {
93  let mut animated = Vec::new();
94
95  for animation in active_animations(base_style, stylesheet, time, sizing.viewport) {
96    for name in animation.keyframes.custom_property_names() {
97      let (from, to, progress) = animation.keyframes.custom_property_segment(
98        name,
99        base_style.custom_properties.get(name),
100        animation.sample.progress,
101      );
102      let resolve = |value: Option<&str>| {
103        value.map(|value| {
104          resolve_var_references(value, &base_style.custom_properties)
105            .unwrap_or_else(|| value.to_owned())
106        })
107      };
108      let (from, to) = (resolve(from), resolve(to));
109      let progress = animation
110        .timing_function
111        .apply(progress, animation.sample.before);
112      let interpolated = from.as_deref().zip(to.as_deref()).and_then(|(from, to)| {
113        base_style
114          .custom_properties
115          .registration(name)?
116          .syntax
117          .interpolate(from, to, progress, sizing, current_color)
118      });
119      // An endpoint no keyframe and no underlying value gives is the guaranteed-invalid value,
120      // which `initial` declares.
121      let value = interpolated
122        .or_else(|| discrete(&from, &to, progress))
123        .unwrap_or_else(|| "initial".to_owned());
124
125      animated.push((name.to_owned(), value));
126    }
127  }
128
129  animated
130}
131
132/// An animation `animation-name` runs that is sampled at the render's time.
133struct ActiveAnimation<'s> {
134  keyframes: Cow<'s, KeyframesRule>,
135  sample: AnimationSample,
136  timing_function: AnimationTimingFunction,
137}
138
139/// The animations `base_style` names that `time` falls in or fills, in `animation-name` order.
140fn active_animations<'s>(
141  base_style: &'s ComputedStyle,
142  stylesheet: &'s StyleSheet,
143  time: u64,
144  viewport: Viewport,
145) -> impl Iterator<Item = ActiveAnimation<'s>> {
146  let animation = &base_style.misc1_data;
147
148  animation
149    .animation_name
150    .iter()
151    .enumerate()
152    .filter_map(move |(index, name)| {
153      let keyframes = find_keyframes(stylesheet, name.as_ref()?, viewport)?;
154      let duration: AnimationTime = repeated_list_value(&animation.animation_duration, index);
155      let delay: AnimationTime = repeated_list_value(&animation.animation_delay, index);
156      let sample = sample_animation_progress(
157        time as f32,
158        duration.milliseconds,
159        delay.milliseconds,
160        repeated_list_value(&animation.animation_iteration_count, index),
161        repeated_list_value(&animation.animation_direction, index),
162        repeated_list_value(&animation.animation_fill_mode, index),
163      )?;
164
165      Some(ActiveAnimation {
166        keyframes,
167        sample,
168        timing_function: repeated_list_value(&animation.animation_timing_function, index),
169      })
170    })
171}
172
173pub(crate) fn find_keyframes<'a>(
174  stylesheet: &'a StyleSheet,
175  name: &str,
176  viewport: Viewport,
177) -> Option<Cow<'a, KeyframesRule>> {
178  stylesheet
179    .keyframes
180    .iter()
181    .rev()
182    .find(|rule| {
183      rule.name.eq_ignore_ascii_case(name)
184        && rule
185          .media_queries
186          .iter()
187          .all(|media_query| media_query.matches(viewport))
188    })
189    .map(Cow::Borrowed)
190    .or_else(|| tailwind_animation_keyframes(name).map(Cow::Owned))
191}
192
193impl KeyframesRule {
194  /// The names of the custom properties its keyframes declare, each once.
195  fn custom_property_names(&self) -> Vec<&str> {
196    let mut seen = Xxh3HashSet::default();
197
198    self
199      .custom_properties()
200      .filter(|name| seen.insert(*name))
201      .collect()
202  }
203
204  /// The keyframes on either side of `progress` that declare the custom property `name`, the
205  /// `underlying` value standing in for an offset of 0 or 1 none declares, and the progress
206  /// between them, as Blink samples each property's keyframes apart from the others.
207  fn custom_property_segment<'k>(
208    &'k self,
209    name: &str,
210    underlying: Option<&'k str>,
211    progress: f32,
212  ) -> (Option<&'k str>, Option<&'k str>, f32) {
213    let mut points: Vec<(f32, Option<&str>)> = self
214      .keyframes
215      .iter()
216      .filter_map(|keyframe| {
217        let value =
218          keyframe
219            .declarations
220            .iter()
221            .rev()
222            .find_map(|declaration| match declaration {
223              StyleDeclaration::CustomProperty(declared, value) if declared == name => {
224                Some(value.as_str())
225              }
226              _ => None,
227            })?;
228
229        Some(
230          keyframe
231            .offsets
232            .iter()
233            .map(move |&offset| (offset, Some(value))),
234        )
235      })
236      .flatten()
237      .collect();
238
239    sort_by_key(&mut points, |&(offset, _)| offset);
240    if points.first().is_none_or(|&(offset, _)| offset > 0.0) {
241      points.insert(0, (0.0, underlying));
242    }
243    if points.last().is_none_or(|&(offset, _)| offset < 1.0) {
244      points.push((1.0, underlying));
245    }
246
247    let end = points
248      .iter()
249      .position(|&(offset, _)| offset >= progress)
250      .unwrap_or(points.len() - 1)
251      .max(1);
252    let ((from_offset, from), (to_offset, to)) = (points[end - 1], points[end]);
253    let width = to_offset - from_offset;
254    let local = if width <= f32::EPSILON {
255      1.0
256    } else {
257      ((progress - from_offset) / width).clamp(0.0, 1.0)
258    };
259
260    (from, to, local)
261  }
262
263  /// Whether a keyframe declares a custom property.
264  pub(crate) fn animates_custom_properties(&self) -> bool {
265    self.custom_properties().next().is_some()
266  }
267
268  /// The name of each custom property declaration in its keyframes.
269  fn custom_properties(&self) -> impl Iterator<Item = &str> {
270    self
271      .keyframes
272      .iter()
273      .flat_map(|keyframe| keyframe.declarations.iter())
274      .filter_map(|declaration| match declaration {
275        StyleDeclaration::CustomProperty(name, _) => Some(name.as_str()),
276        _ => None,
277      })
278  }
279}
280
281fn tailwind_animation_keyframes(name: &str) -> Option<KeyframesRule> {
282  match name.to_ascii_lowercase().as_str() {
283    "spin" => Some(KeyframesRule {
284      name: "spin".to_string(),
285      keyframes: vec![
286        keyframe(0.25, [StyleDeclaration::rotate(Some(Angle::new(90.0)))]),
287        keyframe(0.5, [StyleDeclaration::rotate(Some(Angle::new(180.0)))]),
288        keyframe(0.75, [StyleDeclaration::rotate(Some(Angle::new(270.0)))]),
289        keyframe(1.0, [StyleDeclaration::rotate(Some(Angle::new(359.999)))]),
290      ],
291      media_queries: Vec::new(),
292    }),
293    "ping" => Some(KeyframesRule {
294      name: "ping".to_string(),
295      keyframes: vec![
296        keyframe(
297          0.75,
298          [
299            StyleDeclaration::scale(Some(SpacePair::from_single(PercentageNumber(2.0)))),
300            StyleDeclaration::opacity(PercentageNumber(0.0)),
301          ],
302        ),
303        keyframe(
304          1.0,
305          [
306            StyleDeclaration::scale(Some(SpacePair::from_single(PercentageNumber(2.0)))),
307            StyleDeclaration::opacity(PercentageNumber(0.0)),
308          ],
309        ),
310      ],
311      media_queries: Vec::new(),
312    }),
313    "pulse" => Some(KeyframesRule {
314      name: "pulse".to_string(),
315      keyframes: vec![keyframe(
316        0.5,
317        [StyleDeclaration::opacity(PercentageNumber(0.5))],
318      )],
319      media_queries: Vec::new(),
320    }),
321    "bounce" => Some(KeyframesRule {
322      name: "bounce".to_string(),
323      keyframes: vec![
324        keyframe(
325          0.0,
326          [StyleDeclaration::translate(SpacePair::from_pair(
327            Length::Px(0.0),
328            Length::Percentage(-25.0),
329          ))],
330        ),
331        keyframe(
332          0.5,
333          [StyleDeclaration::translate(SpacePair::from_pair(
334            Length::Px(0.0),
335            Length::Percentage(0.0),
336          ))],
337        ),
338        keyframe(
339          1.0,
340          [StyleDeclaration::translate(SpacePair::from_pair(
341            Length::Px(0.0),
342            Length::Percentage(-25.0),
343          ))],
344        ),
345      ],
346      media_queries: Vec::new(),
347    }),
348    _ => None,
349  }
350}
351
352fn keyframe<const N: usize>(offset: f32, declarations: [StyleDeclaration; N]) -> KeyframeRule {
353  let mut block = StyleDeclarationBlock::default();
354  for declaration in declarations {
355    block.push(declaration, false);
356  }
357
358  KeyframeRule {
359    offsets: vec![offset],
360    declarations: block,
361  }
362}
363
364/// One sampled point on an animation's timeline.
365#[derive(Debug, Clone, Copy, PartialEq)]
366struct AnimationSample {
367  /// Progress through the current iteration.
368  progress: f32,
369  /// Whether the sample comes from before the active phase, which the step
370  /// easing functions treat as sitting on the lower step.
371  before: bool,
372}
373
374impl AnimationSample {
375  fn active(progress: f32) -> Self {
376    Self {
377      progress,
378      before: false,
379    }
380  }
381
382  fn before(progress: f32) -> Self {
383    Self {
384      progress,
385      before: true,
386    }
387  }
388}
389
390fn sample_animation_progress(
391  time_ms: f32,
392  duration_ms: f32,
393  delay_ms: f32,
394  iteration_count: AnimationIterationCount,
395  direction: AnimationDirection,
396  fill_mode: AnimationFillMode,
397) -> Option<AnimationSample> {
398  let active_time = time_ms - delay_ms;
399
400  if active_time < 0.0 {
401    return match fill_mode {
402      AnimationFillMode::Backwards | AnimationFillMode::Both => {
403        Some(AnimationSample::before(start_progress(direction)))
404      }
405      _ => None,
406    };
407  }
408
409  if duration_ms <= 0.0 {
410    return Some(AnimationSample::active(end_progress(direction, 0)));
411  }
412
413  let total_active_duration = match iteration_count {
414    AnimationIterationCount::Infinite => f32::INFINITY,
415    AnimationIterationCount::Number(count) => duration_ms * count.max(0.0),
416  };
417
418  if active_time >= total_active_duration {
419    return match fill_mode {
420      AnimationFillMode::Forwards | AnimationFillMode::Both => {
421        let end_progress = match iteration_count {
422          AnimationIterationCount::Infinite => end_progress(direction, 0),
423          AnimationIterationCount::Number(count) => {
424            let count = count.max(0.0);
425            let completed_iterations = count.floor() as usize;
426            let fraction = count.fract();
427            if fraction > f32::EPSILON {
428              apply_direction(fraction, direction, completed_iterations)
429            } else {
430              end_progress(direction, count.max(1.0) as usize - 1)
431            }
432          }
433        };
434        Some(AnimationSample::active(end_progress))
435      }
436      _ => None,
437    };
438  }
439
440  let progress_within_iteration = active_time / duration_ms;
441  let mut iteration_index = progress_within_iteration.floor() as usize;
442  let mut progress = progress_within_iteration.fract();
443  if active_time > 0.0 && progress_within_iteration.fract().abs() <= f32::EPSILON {
444    progress = 1.0;
445    iteration_index = iteration_index.saturating_sub(1);
446  }
447
448  Some(AnimationSample::active(apply_direction(
449    progress,
450    direction,
451    iteration_index,
452  )))
453}
454
455fn start_progress(direction: AnimationDirection) -> f32 {
456  apply_direction(0.0, direction, 0)
457}
458
459fn end_progress(direction: AnimationDirection, iteration_index: usize) -> f32 {
460  apply_direction(1.0, direction, iteration_index)
461}
462
463fn apply_direction(progress: f32, direction: AnimationDirection, iteration_index: usize) -> f32 {
464  match direction {
465    AnimationDirection::Normal => progress,
466    AnimationDirection::Reverse => 1.0 - progress,
467    AnimationDirection::Alternate => {
468      if iteration_index.is_multiple_of(2) {
469        progress
470      } else {
471        1.0 - progress
472      }
473    }
474    AnimationDirection::AlternateReverse => {
475      if iteration_index.is_multiple_of(2) {
476        1.0 - progress
477      } else {
478        progress
479      }
480    }
481  }
482}
483
484fn sample_keyframe_segment<'a>(
485  resolved_frames: &'a ResolvedKeyframes,
486  base_style: &'a ComputedStyle,
487  progress: f32,
488) -> Option<InterpolationSegment<'a>> {
489  let first = resolved_frames.points.first()?;
490
491  // A progress on the first keyframe starts the interval from it.
492  if progress < first.offset {
493    let segment_progress = if first.offset <= 0.0 {
494      1.0
495    } else {
496      progress / first.offset
497    };
498    let to = resolved_frames.style(first);
499
500    return Some(InterpolationSegment {
501      from_style: base_style,
502      to_style: &to.style,
503      animated_properties: to.mask,
504      progress: segment_progress.clamp(0.0, 1.0),
505    });
506  }
507
508  for window in resolved_frames.points.windows(2) {
509    let [start_point, end_point] = window else {
510      continue;
511    };
512    if progress <= end_point.offset {
513      let width = end_point.offset - start_point.offset;
514      let segment_progress = if width <= f32::EPSILON {
515        1.0
516      } else {
517        (progress - start_point.offset) / width
518      };
519      let from = resolved_frames.style(start_point);
520      let to = resolved_frames.style(end_point);
521      let mut animated_properties = from.mask;
522
523      animated_properties.union(&to.mask);
524      return Some(InterpolationSegment {
525        from_style: &from.style,
526        to_style: &to.style,
527        animated_properties,
528        progress: segment_progress.clamp(0.0, 1.0),
529      });
530    }
531  }
532
533  let last = resolved_frames.points.last()?;
534  let segment_progress = if last.offset >= 1.0 {
535    1.0
536  } else {
537    (progress - last.offset) / (1.0 - last.offset)
538  };
539  let from = resolved_frames.style(last);
540
541  Some(InterpolationSegment {
542    from_style: &from.style,
543    to_style: base_style,
544    animated_properties: from.mask,
545    progress: segment_progress.clamp(0.0, 1.0),
546  })
547}
548
549fn resolve_keyframes(keyframes: &KeyframesRule, base_style: &ComputedStyle) -> ResolvedKeyframes {
550  let mut points = keyframes
551    .keyframes
552    .iter()
553    .enumerate()
554    .flat_map(|(style_index, keyframe)| {
555      keyframe
556        .offsets
557        .iter()
558        .copied()
559        .map(move |offset| ResolvedKeyframePoint {
560          offset,
561          style_index,
562        })
563    })
564    .collect::<Vec<_>>();
565
566  sort_by_key(&mut points, |point| point.offset);
567
568  let mut styles: Vec<ResolvedKeyframeStyle> = Vec::with_capacity(points.len());
569  let mut merged_points: Vec<ResolvedKeyframePoint> = Vec::with_capacity(points.len());
570  for point in points {
571    let keyframe = &keyframes.keyframes[point.style_index];
572
573    if let Some(last_point) = merged_points.last_mut()
574      && (last_point.offset - point.offset).abs() <= f32::EPSILON
575    {
576      styles[last_point.style_index].apply(keyframe);
577      continue;
578    }
579
580    let style_index = styles.len();
581    let mut style = ResolvedKeyframeStyle {
582      style: base_style.clone(),
583      mask: PropertyMask::new(),
584    };
585
586    style.apply(keyframe);
587    styles.push(style);
588    merged_points.push(ResolvedKeyframePoint {
589      offset: point.offset,
590      style_index,
591    });
592  }
593
594  ResolvedKeyframes {
595    points: merged_points,
596    styles,
597  }
598}
599
600/// A keyframe's style and the longhands its declarations animate.
601#[derive(Debug)]
602struct ResolvedKeyframeStyle {
603  style: ComputedStyle,
604  mask: PropertyMask,
605}
606
607impl ResolvedKeyframeStyle {
608  fn apply(&mut self, keyframe: &KeyframeRule) {
609    for declaration in keyframe.declarations.iter() {
610      declaration.apply_to_computed(&mut self.style);
611      self.mask.extend(declaration.affected_longhands().iter());
612    }
613  }
614}
615
616#[derive(Debug)]
617struct ResolvedKeyframePoint {
618  offset: f32,
619  style_index: usize,
620}
621
622#[derive(Debug)]
623struct ResolvedKeyframes {
624  points: Vec<ResolvedKeyframePoint>,
625  styles: Vec<ResolvedKeyframeStyle>,
626}
627
628impl ResolvedKeyframes {
629  fn style(&self, point: &ResolvedKeyframePoint) -> &ResolvedKeyframeStyle {
630    &self.styles[point.style_index]
631  }
632}
633
634#[derive(Debug)]
635struct InterpolationSegment<'a> {
636  from_style: &'a ComputedStyle,
637  to_style: &'a ComputedStyle,
638  animated_properties: PropertyMask,
639  progress: f32,
640}
641
642macro_rules! impl_passthrough_animatable {
643  ($($ty:ty),* $(,)?) => {
644    $(
645      impl Animatable for $ty {}
646    )*
647  };
648}
649
650impl_passthrough_animatable!(
651  AnimationNames,
652  AnimationDurations,
653  AnimationTimingFunctions,
654  AnimationIterationCounts,
655  AlignItems,
656  JustifyContent,
657  Border,
658  GridAutoFlow,
659  GridLine,
660  GridTemplateAreas,
661  TextOverflow,
662  FontStyle,
663  FontFamily,
664  LineHeight,
665  FontSynthesis,
666  LineClamp,
667  TextStroke,
668  TextDecoration,
669  TextDecorationLines,
670  BasicShape,
671  OffsetPath,
672  OffsetAnchor,
673  OffsetPosition,
674  WhiteSpace,
675  TextWrap,
676  VerticalAlign,
677  Flex,
678  Background,
679  GridTrackSize,
680  GridTemplateComponent,
681  FontFeature,
682  FontVariation,
683);
684
685impl Animatable for Length {
686  fn interpolate(
687    &mut self,
688    from: &Self,
689    to: &Self,
690    progress: f32,
691    sizing: &SizingContext,
692    _current_color: Color,
693  ) {
694    *self = interpolate_length(*from, *to, progress)
695      .or_else(|| {
696        resolve_length_with_sizing(*from, sizing).and_then(|resolved_from| {
697          resolve_length_with_sizing(*to, sizing)
698            .map(|resolved_to| Length::Px(lerp(resolved_from, resolved_to, progress)))
699        })
700      })
701      .unwrap_or_else(|| discrete(from, to, progress));
702  }
703}
704
705fn interpolate_length(from: Length, to: Length, progress: f32) -> Option<Length> {
706  macro_rules! lerp_variants {
707    ($($variant:ident),+ $(,)?) => {
708      match (from, to) {
709        $(
710          (Length::$variant(lhs), Length::$variant(rhs)) => {
711            Some(Length::$variant(lerp(lhs, rhs, progress)))
712          }
713        )+
714        (Length::Auto, Length::Auto) => Some(Length::Auto),
715        _ => None,
716      }
717    };
718  }
719  lerp_variants!(
720    Percentage, Rem, Em, Vh, Vw, CqH, CqW, CqMin, CqMax, VMin, VMax, Cm, Mm, In, Q, Pt, Pc, Px,
721  )
722}
723
724fn resolve_length_with_sizing(value: Length, sizing: &SizingContext) -> Option<f32> {
725  if matches!(value, Length::Auto) {
726    return None;
727  }
728
729  Some(value.to_px(
730    sizing,
731    sizing.viewport.size.width.unwrap_or_default() as f32,
732  ))
733}
734
735#[cfg(test)]
736mod tests {
737  use std::rc::Rc;
738
739  use crate::{
740    geometry::Size,
741    style::{
742      SizingContext,
743      animation::{sample_animation_progress, tailwind_animation_keyframes},
744      *,
745    },
746    viewport::Viewport,
747  };
748
749  #[test]
750  fn stylesheet_animation_interpolates_corner_shape() {
751    let stylesheet = StyleSheet::parse(
752      r#"
753      @keyframes morph {
754        from { corner-shape: squircle; }
755        to { corner-shape: bevel; }
756      }
757      "#,
758    )
759    .unwrap();
760
761    let style = ComputedStyle {
762      misc1_data: Rc::new(StyleMisc1Data {
763        animation_name: AnimationNames::from_css_str("morph").unwrap(),
764        animation_duration: AnimationDurations::from_css_str("1000ms").unwrap(),
765        animation_timing_function: AnimationTimingFunctions::from_css_str("linear").unwrap(),
766        animation_fill_mode: AnimationFillModes::from_css_str("both").unwrap(),
767        ..Default::default()
768      }),
769      ..Default::default()
770    };
771
772    let at = |time: u64| {
773      apply_stylesheet_animations(style.clone(), &stylesheet, time, &sizing(), current_color())
774        .surround_data
775        .corner_top_left_shape
776    };
777
778    assert_eq!(at(0), Superellipse::SQUIRCLE);
779    assert_eq!(at(1000), Superellipse::BEVEL);
780
781    let midpoint = at(500);
782
783    assert!(
784      midpoint.0 > 0.0 && midpoint.0 < 2.0,
785      "expected value between bevel and squircle, got {}",
786      midpoint.0
787    );
788  }
789
790  /// At its start an animation samples the interval from its first keyframe, so a step that jumps
791  /// at the start shows its first step there.
792  /// <https://drafts.csswg.org/web-animations-1/#the-effect-value-of-a-keyframe-animation-effect>
793  #[test]
794  fn a_start_step_jumps_at_the_first_keyframe() {
795    let stylesheet =
796      StyleSheet::parse("@keyframes fade { from { opacity: 0 } to { opacity: 1 } }").unwrap();
797    let style = ComputedStyle {
798      misc1_data: Rc::new(StyleMisc1Data {
799        animation_name: AnimationNames::from_css_str("fade").unwrap(),
800        animation_duration: AnimationDurations::from_css_str("1000ms").unwrap(),
801        animation_timing_function: AnimationTimingFunctions::from_css_str("steps(2, start)")
802          .unwrap(),
803        ..Default::default()
804      }),
805      ..Default::default()
806    };
807    let animated = apply_stylesheet_animations(style, &stylesheet, 0, &sizing(), current_color());
808
809    assert_eq!(animated.svg_data.opacity.0, 0.5);
810  }
811
812  fn sizing() -> SizingContext {
813    SizingContext {
814      viewport: Viewport::new((200, 100)),
815      container_size: Size::NONE,
816      container_read: Default::default(),
817      font_read: None,
818      font_size: 16.0,
819      root_font_size: None,
820      line_height: 0.0,
821      root_line_height: None,
822      ch: 16.0 / 2.0,
823      ex: 16.0 / 2.0,
824    }
825  }
826
827  fn current_color() -> Color {
828    Color([10, 20, 30, 255])
829  }
830
831  #[derive(Clone, Copy, Debug, PartialEq)]
832  struct Dummy(u8);
833
834  impl Animatable for Dummy {}
835
836  #[test]
837  fn animatable_default_flips_at_half_progress() {
838    let mut target = Dummy(9);
839    target.interpolate(&Dummy(3), &Dummy(7), 0.25, &sizing(), current_color());
840    assert_eq!(target, Dummy(3));
841
842    target.interpolate(&Dummy(3), &Dummy(7), 0.5, &sizing(), current_color());
843    assert_eq!(target, Dummy(7));
844  }
845
846  #[test]
847  fn animation_keyword_lists_remain_discrete() {
848    fn interpolate<T: Animatable>(from: T, to: T, progress: f32) -> T {
849      let mut value = from.clone();
850
851      value.interpolate(&from, &to, progress, &sizing(), current_color());
852      value
853    }
854
855    macro_rules! assert_discrete_list {
856      ($type:ty; [$($from:expr),*]; [$($to:expr),*]) => {
857        let from: $type = Box::from([$($from),*]);
858        let to: $type = Box::from([$($to),*]);
859
860        assert_eq!(interpolate(from.clone(), to.clone(), 0.49), from);
861        assert_eq!(interpolate(from.clone(), to.clone(), 0.5), to);
862      };
863    }
864
865    assert_discrete_list!(
866      AnimationDirections;
867      [AnimationDirection::Normal, AnimationDirection::Reverse];
868      [AnimationDirection::Alternate, AnimationDirection::AlternateReverse]
869    );
870    assert_discrete_list!(
871      AnimationDirections;
872      [AnimationDirection::Normal];
873      [AnimationDirection::Reverse, AnimationDirection::Alternate]
874    );
875    assert_discrete_list!(
876      AnimationFillModes;
877      [AnimationFillMode::None, AnimationFillMode::Forwards];
878      [AnimationFillMode::Backwards, AnimationFillMode::Both]
879    );
880    assert_discrete_list!(
881      AnimationFillModes;
882      [AnimationFillMode::None];
883      [AnimationFillMode::Forwards, AnimationFillMode::Both]
884    );
885    assert_discrete_list!(
886      AnimationPlayStates;
887      [AnimationPlayState::Running, AnimationPlayState::Paused];
888      [AnimationPlayState::Paused, AnimationPlayState::Running]
889    );
890    assert_discrete_list!(
891      AnimationPlayStates;
892      [AnimationPlayState::Running];
893      [AnimationPlayState::Paused, AnimationPlayState::Running]
894    );
895  }
896
897  #[test]
898  fn blend_modes_repeat_to_lcm() {
899    let from: BlendModes = Box::from([BlendMode::Normal, BlendMode::Multiply]);
900    let to: BlendModes = Box::from([BlendMode::Screen, BlendMode::Overlay, BlendMode::Darken]);
901    let mut value = from.clone();
902
903    value.interpolate(&from, &to, 0.5, &sizing(), current_color());
904
905    assert_eq!(
906      value.as_ref(),
907      [
908        BlendMode::Screen,
909        BlendMode::Overlay,
910        BlendMode::Darken,
911        BlendMode::Screen,
912        BlendMode::Overlay,
913        BlendMode::Darken,
914      ]
915    );
916  }
917
918  #[test]
919  fn length_interpolates_continuously() {
920    let mut target: Length = Length::zero();
921    target.interpolate(
922      &Length::Px(10.0),
923      &Length::Px(30.0),
924      0.25,
925      &sizing(),
926      current_color(),
927    );
928    assert_eq!(target, Length::Px(15.0));
929  }
930
931  #[test]
932  fn mixed_unit_length_interpolates_via_sizing() {
933    let mut target: Length = Length::zero();
934    target.interpolate(
935      &Length::Px(0.0),
936      &Length::Percentage(50.0),
937      0.5,
938      &sizing(),
939      current_color(),
940    );
941
942    assert_eq!(target, Length::Px(50.0));
943  }
944
945  #[test]
946  fn option_length_uses_discrete_fallback() {
947    let mut target: Option<Length> = None;
948    target.interpolate(
949      &Some(Length::Px(10.0)),
950      &None,
951      0.25,
952      &sizing(),
953      current_color(),
954    );
955    assert_eq!(target, Some(Length::Px(10.0)));
956
957    target.interpolate(
958      &Some(Length::Px(10.0)),
959      &None,
960      0.75,
961      &sizing(),
962      current_color(),
963    );
964    assert_eq!(target, None);
965  }
966
967  #[test]
968  fn background_position_interpolates_components() {
969    let mut target: PositionValue = PositionValue::default();
970    target.interpolate(
971      &PositionValue(SpacePair::from_pair(
972        PositionComponent::KeywordX(PositionKeywordX::Left),
973        PositionComponent::KeywordY(PositionKeywordY::Top),
974      )),
975      &PositionValue(SpacePair::from_pair(
976        PositionComponent::KeywordX(PositionKeywordX::Right),
977        PositionComponent::KeywordY(PositionKeywordY::Bottom),
978      )),
979      0.5,
980      &sizing(),
981      current_color(),
982    );
983
984    assert_eq!(
985      target,
986      PositionValue(SpacePair::from_pair(
987        PositionComponent::Length(Length::Percentage(50.0)),
988        PositionComponent::Length(Length::Percentage(50.0)),
989      ))
990    );
991  }
992
993  #[test]
994  fn border_radius_interpolates_via_container_impls() {
995    let mut target = BorderRadius::default();
996    target.interpolate(
997      &BorderRadius::from(4.0),
998      &BorderRadius::from(12.0),
999      0.5,
1000      &sizing(),
1001      current_color(),
1002    );
1003
1004    assert_eq!(target, BorderRadius::from(8.0));
1005  }
1006
1007  #[test]
1008  fn percentage_number_interpolates() {
1009    let mut target = PercentageNumber::default();
1010    target.interpolate(
1011      &PercentageNumber(0.2),
1012      &PercentageNumber(0.6),
1013      0.5,
1014      &sizing(),
1015      current_color(),
1016    );
1017
1018    assert!((target.0 - 0.4).abs() < f32::EPSILON);
1019  }
1020
1021  #[test]
1022  fn option_angle_interpolates_inner_angle() {
1023    let mut target: Option<Angle> = None;
1024    target.interpolate(
1025      &Some(Angle::new(0.0)),
1026      &Some(Angle::new(90.0)),
1027      0.5,
1028      &sizing(),
1029      current_color(),
1030    );
1031
1032    assert_eq!(target, Some(Angle::new(45.0)));
1033  }
1034
1035  #[test]
1036  fn scale_interpolates_from_none_as_identity() {
1037    let mut target: Option<SpacePair<PercentageNumber>> = None;
1038    target.interpolate(
1039      &None,
1040      &Some(SpacePair::from_single(PercentageNumber(2.0))),
1041      0.5,
1042      &sizing(),
1043      current_color(),
1044    );
1045
1046    assert_eq!(target, Some(SpacePair::from_single(PercentageNumber(1.5))));
1047  }
1048
1049  #[test]
1050  fn aspect_ratio_interpolates_ratio_values() {
1051    let mut target = AspectRatio::Auto;
1052    target.interpolate(
1053      &AspectRatio::Ratio(1.0),
1054      &AspectRatio::Ratio(2.0),
1055      0.25,
1056      &sizing(),
1057      current_color(),
1058    );
1059
1060    assert_eq!(target, AspectRatio::Ratio(1.25));
1061  }
1062
1063  #[test]
1064  fn font_stretch_interpolates_percentages() {
1065    let mut target = FontStretch::from_percentage(0.0);
1066    target.interpolate(
1067      &FontStretch::from_percentage(0.75),
1068      &FontStretch::from_percentage(1.25),
1069      0.5,
1070      &sizing(),
1071      current_color(),
1072    );
1073
1074    assert!((target.percentage() - 1.0).abs() < f32::EPSILON);
1075  }
1076
1077  #[test]
1078  fn font_weight_interpolates_numeric_values() {
1079    let mut target = FontWeight::default();
1080    target.interpolate(
1081      &FontWeight::from(400.0),
1082      &FontWeight::from(700.0),
1083      0.5,
1084      &sizing(),
1085      current_color(),
1086    );
1087
1088    assert!((target.value() - 550.0).abs() < f32::EPSILON);
1089  }
1090
1091  #[test]
1092  fn text_decoration_thickness_interpolates_lengths() {
1093    let mut target = TextDecorationThickness::default();
1094    target.interpolate(
1095      &TextDecorationThickness::Length(Length::Px(2.0)),
1096      &TextDecorationThickness::Length(Length::Px(10.0)),
1097      0.25,
1098      &sizing(),
1099      current_color(),
1100    );
1101
1102    assert_eq!(target, TextDecorationThickness::Length(Length::Px(4.0)));
1103  }
1104
1105  #[test]
1106  fn flex_grow_interpolates_numeric_values() {
1107    let mut target = FlexGrow(0.0);
1108    target.interpolate(
1109      &FlexGrow(1.0),
1110      &FlexGrow(3.0),
1111      0.5,
1112      &sizing(),
1113      current_color(),
1114    );
1115
1116    assert!((target.0 - 2.0).abs() < f32::EPSILON);
1117  }
1118
1119  #[test]
1120  fn transform_translate_interpolates_lengths() {
1121    let mut target = Transform::Translate(Length::zero(), Length::zero());
1122    target.interpolate(
1123      &Transform::Translate(Length::Px(0.0), Length::Px(10.0)),
1124      &Transform::Translate(Length::Px(20.0), Length::Px(30.0)),
1125      0.5,
1126      &sizing(),
1127      current_color(),
1128    );
1129
1130    assert_eq!(
1131      target,
1132      Transform::Translate(Length::Px(10.0), Length::Px(20.0))
1133    );
1134  }
1135
1136  #[test]
1137  fn background_size_interpolates_explicit_lengths() {
1138    let mut target = BackgroundSize::default();
1139    target.interpolate(
1140      &BackgroundSize::Explicit {
1141        width: Length::Px(10.0),
1142        height: Length::Px(20.0),
1143      },
1144      &BackgroundSize::Explicit {
1145        width: Length::Px(30.0),
1146        height: Length::Px(60.0),
1147      },
1148      0.5,
1149      &sizing(),
1150      current_color(),
1151    );
1152
1153    assert_eq!(
1154      target,
1155      BackgroundSize::Explicit {
1156        width: Length::Px(20.0),
1157        height: Length::Px(40.0),
1158      }
1159    );
1160  }
1161
1162  #[test]
1163  fn box_shadow_interpolates_lengths_and_color() {
1164    let mut target = BoxShadow {
1165      inset: false,
1166      offset_x: Length::zero(),
1167      offset_y: Length::zero(),
1168      blur_radius: Length::zero(),
1169      spread_radius: Length::zero(),
1170      color: ColorInput::CurrentColor,
1171    };
1172    target.interpolate(
1173      &BoxShadow {
1174        inset: false,
1175        offset_x: Length::Px(0.0),
1176        offset_y: Length::Px(10.0),
1177        blur_radius: Length::Px(20.0),
1178        spread_radius: Length::Px(30.0),
1179        color: ColorInput::Value(Color([0, 0, 0, 255])),
1180      },
1181      &BoxShadow {
1182        inset: false,
1183        offset_x: Length::Px(20.0),
1184        offset_y: Length::Px(30.0),
1185        blur_radius: Length::Px(40.0),
1186        spread_radius: Length::Px(50.0),
1187        color: ColorInput::Value(Color([200, 100, 50, 255])),
1188      },
1189      0.5,
1190      &sizing(),
1191      current_color(),
1192    );
1193
1194    assert_eq!(
1195      target,
1196      BoxShadow {
1197        inset: false,
1198        offset_x: Length::Px(10.0),
1199        offset_y: Length::Px(20.0),
1200        blur_radius: Length::Px(30.0),
1201        spread_radius: Length::Px(40.0),
1202        color: ColorInput::Value(Color([100, 50, 25, 255])),
1203      }
1204    );
1205  }
1206
1207  #[test]
1208  fn text_shadow_interpolates_lengths_and_color() {
1209    let mut target = TextShadow {
1210      offset_x: Length::zero(),
1211      offset_y: Length::zero(),
1212      blur_radius: Length::zero(),
1213      color: ColorInput::CurrentColor,
1214    };
1215    target.interpolate(
1216      &TextShadow {
1217        offset_x: Length::Px(0.0),
1218        offset_y: Length::Px(10.0),
1219        blur_radius: Length::Px(20.0),
1220        color: ColorInput::Value(Color([0, 0, 0, 255])),
1221      },
1222      &TextShadow {
1223        offset_x: Length::Px(20.0),
1224        offset_y: Length::Px(30.0),
1225        blur_radius: Length::Px(40.0),
1226        color: ColorInput::Value(Color([200, 100, 50, 255])),
1227      },
1228      0.5,
1229      &sizing(),
1230      current_color(),
1231    );
1232
1233    assert_eq!(
1234      target,
1235      TextShadow {
1236        offset_x: Length::Px(10.0),
1237        offset_y: Length::Px(20.0),
1238        blur_radius: Length::Px(30.0),
1239        color: ColorInput::Value(Color([100, 50, 25, 255])),
1240      }
1241    );
1242  }
1243
1244  #[test]
1245  fn filter_blur_interpolates_lengths() {
1246    let mut target = Filter::Blur(Length::zero());
1247    target.interpolate(
1248      &Filter::Blur(Length::Px(4.0)),
1249      &Filter::Blur(Length::Px(12.0)),
1250      0.5,
1251      &sizing(),
1252      current_color(),
1253    );
1254
1255    assert_eq!(target, Filter::Blur(Length::Px(8.0)));
1256  }
1257
1258  #[test]
1259  fn backwards_fill_samples_from_before_the_active_phase() {
1260    let sample = sample_animation_progress(
1261      0.0,
1262      1000.0,
1263      500.0,
1264      AnimationIterationCount::Number(1.0),
1265      AnimationDirection::Normal,
1266      AnimationFillMode::Backwards,
1267    )
1268    .expect("backwards fill applies during the delay");
1269
1270    assert_eq!(sample.progress, 0.0);
1271    assert!(sample.before);
1272  }
1273
1274  #[test]
1275  fn animation_progress_uses_next_iteration_start_at_boundaries() {
1276    let progress = sample_animation_progress(
1277      1000.0,
1278      1000.0,
1279      0.0,
1280      AnimationIterationCount::Infinite,
1281      AnimationDirection::Alternate,
1282      AnimationFillMode::Both,
1283    );
1284
1285    assert_eq!(progress.map(|sample| sample.progress), Some(1.0));
1286  }
1287
1288  #[test]
1289  fn animation_progress_keeps_final_state_after_finite_completion() {
1290    let progress = sample_animation_progress(
1291      2000.0,
1292      1000.0,
1293      0.0,
1294      AnimationIterationCount::Number(2.0),
1295      AnimationDirection::Alternate,
1296      AnimationFillMode::Forwards,
1297    );
1298
1299    assert_eq!(progress.map(|sample| sample.progress), Some(0.0));
1300  }
1301
1302  #[test]
1303  fn animation_progress_keeps_fractional_final_iteration_state() {
1304    let progress = sample_animation_progress(
1305      1500.0,
1306      1000.0,
1307      0.0,
1308      AnimationIterationCount::Number(1.5),
1309      AnimationDirection::Normal,
1310      AnimationFillMode::Forwards,
1311    );
1312
1313    assert_eq!(progress.map(|sample| sample.progress), Some(0.5));
1314  }
1315
1316  #[test]
1317  fn animation_progress_uses_end_of_iteration_for_exact_normal_boundaries() {
1318    let progress = sample_animation_progress(
1319      1000.0,
1320      1000.0,
1321      0.0,
1322      AnimationIterationCount::Infinite,
1323      AnimationDirection::Normal,
1324      AnimationFillMode::Both,
1325    );
1326
1327    assert_eq!(progress.map(|sample| sample.progress), Some(1.0));
1328  }
1329
1330  #[test]
1331  fn tailwind_animation_presets_include_built_in_keyframes() {
1332    assert!(tailwind_animation_keyframes("spin").is_some());
1333    assert!(tailwind_animation_keyframes("ping").is_some());
1334    assert!(tailwind_animation_keyframes("pulse").is_some());
1335    assert!(tailwind_animation_keyframes("bounce").is_some());
1336  }
1337
1338  #[test]
1339  fn vec_animates_pairwise() {
1340    let mut values: Vec<Length> = vec![Length::Px(0.0), Length::Px(10.0)];
1341    values.interpolate(
1342      &vec![Length::Px(0.0), Length::Px(10.0)],
1343      &vec![Length::Px(20.0), Length::Px(30.0)],
1344      0.5,
1345      &sizing(),
1346      current_color(),
1347    );
1348
1349    assert_eq!(values, vec![Length::Px(10.0), Length::Px(20.0)]);
1350  }
1351
1352  #[test]
1353  fn boxed_background_lists_animate_repeatable_lists_to_lcm_length() {
1354    let mut values: Box<[BackgroundSize]> = Box::default();
1355    values.interpolate(
1356      &[BackgroundSize::Explicit {
1357        width: Length::Px(10.0),
1358        height: Length::Px(20.0),
1359      }]
1360      .into(),
1361      &[
1362        BackgroundSize::Explicit {
1363          width: Length::Px(30.0),
1364          height: Length::Px(40.0),
1365        },
1366        BackgroundSize::Explicit {
1367          width: Length::Px(50.0),
1368          height: Length::Px(60.0),
1369        },
1370      ]
1371      .into(),
1372      0.5,
1373      &sizing(),
1374      current_color(),
1375    );
1376
1377    assert_eq!(
1378      values,
1379      [
1380        BackgroundSize::Explicit {
1381          width: Length::Px(20.0),
1382          height: Length::Px(30.0),
1383        },
1384        BackgroundSize::Explicit {
1385          width: Length::Px(30.0),
1386          height: Length::Px(40.0),
1387        },
1388      ]
1389      .into()
1390    );
1391  }
1392
1393  #[test]
1394  fn boxed_transform_lists_pad_to_longest_with_neutral_values() {
1395    let mut values: Box<[Transform]> = Box::default();
1396    values.interpolate(
1397      &[Transform::Scale(1.0, 1.0)].into(),
1398      &[Transform::Scale(2.0, 2.0), Transform::Scale(4.0, 4.0)].into(),
1399      0.5,
1400      &sizing(),
1401      current_color(),
1402    );
1403
1404    assert_eq!(
1405      values,
1406      [Transform::Scale(1.5, 1.5), Transform::Scale(2.5, 2.5)].into()
1407    );
1408  }
1409
1410  #[test]
1411  fn apply_interpolated_properties_only_updates_masked_fields() {
1412    let mut base_style = ComputedStyle {
1413      box_data: Rc::new(StyleBoxData {
1414        width: Length::Px(10.0).into(),
1415        height: Length::Px(20.0).into(),
1416        ..Default::default()
1417      }),
1418      ..ComputedStyle::default()
1419    };
1420    let from = ComputedStyle {
1421      box_data: Rc::new(StyleBoxData {
1422        width: Length::Px(10.0).into(),
1423        height: Length::Px(100.0).into(),
1424        ..Default::default()
1425      }),
1426      ..ComputedStyle::default()
1427    };
1428    let to = ComputedStyle {
1429      box_data: Rc::new(StyleBoxData {
1430        width: Length::Px(30.0).into(),
1431        height: Length::Px(200.0).into(),
1432        ..Default::default()
1433      }),
1434      ..ComputedStyle::default()
1435    };
1436    let animated_properties: PropertyMask = [LonghandId::Width].into_iter().collect();
1437
1438    base_style.apply_interpolated_properties(
1439      &from,
1440      &to,
1441      &animated_properties,
1442      0.5,
1443      &sizing(),
1444      current_color(),
1445    );
1446
1447    assert_eq!(base_style.box_data.width, Length::Px(20.0).into());
1448    assert_eq!(base_style.box_data.height, Length::Px(20.0).into());
1449  }
1450
1451  #[test]
1452  fn apply_interpolated_properties_interpolates_rotate_from_implicit_none() {
1453    let mut base_style = ComputedStyle::default();
1454    let from = ComputedStyle::default();
1455    let to = ComputedStyle {
1456      misc3_data: Rc::new(StyleMisc3Data {
1457        rotate: Some(Angle::new(45.0)),
1458        ..Default::default()
1459      }),
1460      ..ComputedStyle::default()
1461    };
1462    let animated_properties: PropertyMask = [LonghandId::Rotate].into_iter().collect();
1463
1464    base_style.apply_interpolated_properties(
1465      &from,
1466      &to,
1467      &animated_properties,
1468      0.5,
1469      &sizing(),
1470      current_color(),
1471    );
1472
1473    assert_eq!(base_style.misc3_data.rotate, Some(Angle::new(22.5)));
1474  }
1475
1476  #[test]
1477  fn apply_interpolated_properties_interpolates_flex_grow_from_implicit_zero() {
1478    let mut base_style = ComputedStyle::default();
1479    let from = ComputedStyle::default();
1480    let to = ComputedStyle {
1481      misc1_data: Rc::new(StyleMisc1Data {
1482        flex_grow: Some(FlexGrow(4.0)),
1483        ..Default::default()
1484      }),
1485      ..ComputedStyle::default()
1486    };
1487    let animated_properties: PropertyMask = [LonghandId::FlexGrow].into_iter().collect();
1488
1489    base_style.apply_interpolated_properties(
1490      &from,
1491      &to,
1492      &animated_properties,
1493      0.5,
1494      &sizing(),
1495      current_color(),
1496    );
1497
1498    assert_eq!(base_style.misc1_data.flex_grow, Some(FlexGrow(2.0)));
1499  }
1500
1501  #[test]
1502  fn apply_interpolated_properties_interpolates_flex_shrink_from_implicit_one() {
1503    let mut base_style = ComputedStyle::default();
1504    let from = ComputedStyle::default();
1505    let to = ComputedStyle {
1506      misc2_data: Rc::new(StyleMisc2Data {
1507        flex_shrink: Some(FlexGrow(3.0)),
1508        ..Default::default()
1509      }),
1510      ..ComputedStyle::default()
1511    };
1512    let animated_properties: PropertyMask = [LonghandId::FlexShrink].into_iter().collect();
1513
1514    base_style.apply_interpolated_properties(
1515      &from,
1516      &to,
1517      &animated_properties,
1518      0.5,
1519      &sizing(),
1520      current_color(),
1521    );
1522
1523    assert_eq!(base_style.misc2_data.flex_shrink, Some(FlexGrow(2.0)));
1524  }
1525
1526  #[test]
1527  fn apply_interpolated_properties_interpolates_text_stroke_width_from_implicit_zero() {
1528    let mut base_style = ComputedStyle::default();
1529    let from = ComputedStyle::default();
1530    let to = ComputedStyle {
1531      misc_inherited1_data: Rc::new(StyleMiscInherited1Data {
1532        webkit_text_stroke_width: Some(Length::Px(6.0)),
1533        ..Default::default()
1534      }),
1535      ..ComputedStyle::default()
1536    };
1537    let animated_properties: PropertyMask =
1538      [LonghandId::WebkitTextStrokeWidth].into_iter().collect();
1539
1540    base_style.apply_interpolated_properties(
1541      &from,
1542      &to,
1543      &animated_properties,
1544      0.5,
1545      &sizing(),
1546      current_color(),
1547    );
1548
1549    assert_eq!(
1550      base_style.misc_inherited1_data.webkit_text_stroke_width,
1551      Some(Length::Px(3.0))
1552    );
1553  }
1554
1555  #[test]
1556  fn apply_interpolated_properties_interpolates_text_stroke_color_from_current_color() {
1557    let mut base_style = ComputedStyle::default();
1558    let from = ComputedStyle::default();
1559    let to = ComputedStyle {
1560      misc_inherited1_data: Rc::new(StyleMiscInherited1Data {
1561        webkit_text_stroke_color: Some(ColorInput::Value(Color([110, 120, 130, 255]))),
1562        ..Default::default()
1563      }),
1564      ..ComputedStyle::default()
1565    };
1566    let animated_properties: PropertyMask =
1567      [LonghandId::WebkitTextStrokeColor].into_iter().collect();
1568
1569    base_style.apply_interpolated_properties(
1570      &from,
1571      &to,
1572      &animated_properties,
1573      0.5,
1574      &sizing(),
1575      current_color(),
1576    );
1577
1578    assert_eq!(
1579      base_style.misc_inherited1_data.webkit_text_stroke_color,
1580      Some(ColorInput::Value(Color([60, 70, 80, 255])))
1581    );
1582  }
1583
1584  #[test]
1585  fn apply_interpolated_properties_interpolates_text_fill_color_from_style_color() {
1586    let mut base_style = ComputedStyle::default();
1587    let from = ComputedStyle {
1588      inherited_data: Rc::new(StyleInheritedData {
1589        color: ColorInput::Value(Color([20, 40, 60, 255])),
1590        ..Default::default()
1591      }),
1592      ..ComputedStyle::default()
1593    };
1594    let to = ComputedStyle {
1595      inherited_data: Rc::new(StyleInheritedData {
1596        color: ColorInput::Value(Color([20, 40, 60, 255])),
1597        ..Default::default()
1598      }),
1599      misc_inherited1_data: Rc::new(StyleMiscInherited1Data {
1600        webkit_text_fill_color: Some(ColorInput::Value(Color([120, 140, 160, 255]))),
1601        ..Default::default()
1602      }),
1603      ..ComputedStyle::default()
1604    };
1605    let animated_properties: PropertyMask = [LonghandId::WebkitTextFillColor].into_iter().collect();
1606
1607    base_style.apply_interpolated_properties(
1608      &from,
1609      &to,
1610      &animated_properties,
1611      0.5,
1612      &sizing(),
1613      current_color(),
1614    );
1615
1616    assert_eq!(
1617      base_style.misc_inherited1_data.webkit_text_fill_color,
1618      Some(ColorInput::Value(Color([70, 90, 110, 255])))
1619    );
1620  }
1621
1622  #[test]
1623  fn text_indent_interpolates_amount_continuously() {
1624    let mut target = TextIndent::default();
1625    let from = TextIndent {
1626      amount: Length::Px(10.0),
1627      each_line: false,
1628      hanging: false,
1629    };
1630    let to = TextIndent {
1631      amount: Length::Px(30.0),
1632      each_line: true,
1633      hanging: true,
1634    };
1635
1636    target.interpolate(&from, &to, 0.25, &sizing(), current_color());
1637    assert_eq!(target.amount, Length::Px(15.0));
1638    assert!(!target.each_line);
1639    assert!(!target.hanging);
1640
1641    target.interpolate(&from, &to, 0.75, &sizing(), current_color());
1642    assert_eq!(target.amount, Length::Px(25.0));
1643    assert!(target.each_line);
1644    assert!(target.hanging);
1645  }
1646}