Skip to content

Truly independent web browser

LibCompositing+LibWeb: Move the animation timing model to Rust

Andreas Klinge9b9afc65fd2
diff --git a/Libraries/LibCompositing/Rust/build.rs b/Libraries/LibCompositing/Rust/build.rs
index a05edd9f2cf..a20fa8adb2c 100644
--- a/Libraries/LibCompositing/Rust/build.rs
+++ b/Libraries/LibCompositing/Rust/build.rs
@@ -401,8 +401,6 @@ fn main() -> Result<(), Box<dyn Error>> {
"FfiFilterFunctionKind",
"FfiVisualContextTreeInputs",
"FfiVisualAnimationTargetKind",
- "FfiVisualAnimationPlaybackDirection",
- "FfiVisualAnimationFillMode",
"FfiVisualAnimationTransformOperationKind",
"FfiCompositorAnimationPublishOutcome",
"FfiVisualAnimationSummary",
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs b/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs
new file mode 100644
index 00000000000..17907864cbd
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/calculations.rs
@@ -0,0 +1,813 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The timing calculations of Web Animations, from the normalized timing of an animation effect and
+//! the state of its animation and timeline.
+
+use super::effect_timing::{
+ AnimationDirection, AnimationEffectPhase, AnimationEffectTiming, FillMode, PlaybackDirection, SpecifiedEffectTiming,
+};
+use super::playback::{AnimationPlayState, AnimationPlayback, AnimationReplaceState, TimelineSample};
+use super::time_value::{TimeValue, TimeValueType, max, min};
+use crate::easing::Easing;
+
+/// Two times of a progress-based timeline, in percent, closer than this are the same but for
+/// floating point error.
+pub const PROGRESS_TIMELINE_TOLERANCE: f64 = 1e-6;
+
+/// Everything a progress calculation needs, resolved together from one local time.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct ResolvedEffectTiming {
+ pub phase: AnimationEffectPhase,
+ pub local_time: Option<TimeValue>,
+ pub active_time: Option<TimeValue>,
+ pub overall_progress: Option<f64>,
+}
+
+/// https://drafts.csswg.org/web-animations-2/#intrinsic-iteration-duration
+/// `time_unit` is the unit of the associated timeline's times, milliseconds without one.
+#[must_use]
+pub fn intrinsic_iteration_duration(
+ timeline_duration: Option<TimeValue>,
+ iteration_count: f64,
+ start_delay: TimeValue,
+ end_delay: TimeValue,
+ time_unit: TimeValueType,
+) -> TimeValue {
+ // The intrinsic iteration duration is calculated from the first matching condition from below:
+
+ // FIXME: If the animation effect is a group effect,
+ // Follow the procedure in § 2.10.3 The intrinsic iteration duration of a group effect
+
+ // FIXME: If the animation effect is a sequence effect,
+ // Follow the procedure in § 2.10.4.2 The intrinsic iteration duration of a sequence effect
+
+ match timeline_duration {
+ // If timeline duration is unresolved or iteration count is zero,
+ // Return 0
+ None => TimeValue::zero(time_unit),
+ Some(_) if iteration_count == 0.0 => TimeValue::zero(time_unit),
+ // Otherwise
+ Some(timeline_duration) => {
+ // Return(100% - start delay - end delay) / iteration count
+ // Note : Presently start and end delays are zero until such time as percentage based delays are supported.
+ // AD-HOC: An effect fills its animation's attachment range rather than the whole timeline, which is what the
+ // timeline duration is here. This matches WebKit.
+ (timeline_duration - start_delay - end_delay) / iteration_count
+ }
+ }
+}
+
+/// https://drafts.csswg.org/web-animations-2/#time-based-animation-to-a-proportional-animation
+/// `timeline_duration` is resolved, and in the unit of the associated timeline's times, `time_unit`.
+#[must_use]
+pub fn convert_a_time_based_animation_to_a_proportional_animation(
+ specified: &SpecifiedEffectTiming,
+ timeline_duration: TimeValue,
+ time_unit: TimeValueType,
+) -> AnimationEffectTiming {
+ let mut timing = specified_timing_with(specified, TimeValue::zero(time_unit));
+
+ // AD-HOC: We use the specified interation duration instead of the iteration duration here, see
+ // https://github.com/w3c/csswg-drafts/pull/13170
+ // If the iteration duration is auto, then perform the following steps.
+ let Some(specified_iteration_duration) = specified.iteration_duration.time() else {
+ // Set start delay and end delay to 0, as it is not possible to mix time and proportions.
+ // Note: Future versions may allow these properties to be assigned percentages, at which point the delays are
+ // only to be ignored if their values are expressed as times and not as percentages.
+ timing.start_delay = TimeValue::zero(time_unit);
+ timing.end_delay = TimeValue::zero(time_unit);
+
+ // AD-HOC: The spec doesn't say what to set iteration duration to in this case so we set it to the intrinsic
+ // iteration duration, see: https://github.com/w3c/csswg-drafts/issues/13220
+ timing.iteration_duration = intrinsic_iteration_duration(
+ Some(timeline_duration),
+ specified.iteration_count,
+ timing.start_delay,
+ timing.end_delay,
+ time_unit,
+ );
+ return timing;
+ };
+
+ // Otherwise:
+
+ // 1. Let total time be equal to end time
+ // AD-HOC: Using end time here only works if we haven't already converted to a proportional animation, we instead
+ // recompute the specified equivalent of "end time", see https://github.com/w3c/csswg-drafts/issues/13230
+ // NB: As for the active duration, an iteration duration or iteration count of zero makes the specified active
+ // duration zero, where infinity times zero would be NaN.
+ let specified_active_duration = if specified_iteration_duration == 0.0 || specified.iteration_count == 0.0 {
+ 0.0
+ } else {
+ specified_iteration_duration * specified.iteration_count
+ };
+ let total_time = max(
+ specified.start_delay + specified_active_duration + specified.end_delay,
+ 0.0,
+ );
+
+ // AD-HOC: Avoid a division by zero below, see https://github.com/w3c/csswg-drafts/issues/11276
+ if total_time == 0.0 {
+ return timing;
+ }
+
+ // INTEROP: An infinite iteration duration or iteration count makes the total time infinite, where the steps below
+ // would divide infinity by infinity. Like other browsers, take their limit instead: the delays, which are
+ // finite, become 0, and the iteration duration becomes timeline duration / iteration count.
+ if total_time.is_infinite() {
+ timing.iteration_duration = timeline_duration / specified.iteration_count;
+ return timing;
+ }
+
+ // 2. Set start delay to be the result of evaluating specified start delay / total time * timeline duration.
+ timing.start_delay = timeline_duration * (specified.start_delay / total_time);
+
+ // 3. Set iteration duration to be the result of evaluating specified iteration duration / total time * timeline duration.
+ timing.iteration_duration = timeline_duration * (specified_iteration_duration / total_time);
+
+ // 4. Set end delay to be the result of evaluating specified end delay / total time * timeline duration.
+ timing.end_delay = timeline_duration * (specified.end_delay / total_time);
+
+ timing
+}
+
+/// The timing properties `specified` names, with every time `zero`.
+fn specified_timing_with(specified: &SpecifiedEffectTiming, zero: TimeValue) -> AnimationEffectTiming {
+ AnimationEffectTiming {
+ start_delay: zero,
+ end_delay: zero,
+ iteration_duration: zero,
+ iteration_start: specified.iteration_start,
+ iteration_count: specified.iteration_count,
+ fill_mode: specified.fill_mode,
+ playback_direction: specified.playback_direction,
+ }
+}
+
+/// https://drafts.csswg.org/web-animations-2/#normalize-specified-timing
+/// `timeline_duration` is that of the associated timeline, as an animation attached to a range of
+/// it sees it, and `time_unit` the unit of the timeline's times, milliseconds without one.
+#[must_use]
+pub fn normalize_specified_timing(
+ specified: &SpecifiedEffectTiming,
+ timeline_duration: Option<TimeValue>,
+ time_unit: TimeValueType,
+) -> AnimationEffectTiming {
+ // If timeline duration is resolved:
+ if let Some(timeline_duration) = timeline_duration {
+ // Follow the procedure to convert a time-based animation to a proportional animation
+ return convert_a_time_based_animation_to_a_proportional_animation(specified, timeline_duration, time_unit);
+ }
+
+ // Otherwise:
+ let mut timing = specified_timing_with(specified, TimeValue::zero(time_unit));
+
+ // 1. Set start delay = specified start delay
+ timing.start_delay = TimeValue::milliseconds(specified.start_delay);
+
+ // 2. Set end delay = specified end delay
+ timing.end_delay = TimeValue::milliseconds(specified.end_delay);
+
+ // 3. If iteration duration is auto:
+ // AD-HOC: We use the specified interation duration instead of the iteration duration here, see
+ // https://github.com/w3c/csswg-drafts/pull/13170
+ timing.iteration_duration = match specified.iteration_duration.time() {
+ // Set iteration duration = intrinsic iteration duration
+ None => intrinsic_iteration_duration(
+ timeline_duration,
+ specified.iteration_count,
+ timing.start_delay,
+ timing.end_delay,
+ time_unit,
+ ),
+ // Otherwise:
+ // Set iteration duration = specified iteration duration
+ Some(specified_iteration_duration) => TimeValue::milliseconds(specified_iteration_duration),
+ };
+
+ timing
+}
+
+/// https://www.w3.org/TR/web-animations-1/#animation-direction
+#[inline]
+#[must_use]
+pub fn animation_direction(animation: Option<&AnimationPlayback>) -> AnimationDirection {
+ // "backwards" if the effect is associated with an animation and the associated animation’s playback rate is less
+ // than zero; in all other cases, the animation direction is "forwards".
+ match animation {
+ Some(animation) if animation.playback_rate < 0.0 => AnimationDirection::Backwards,
+ _ => AnimationDirection::Forwards,
+ }
+}
+
+/// https://www.w3.org/TR/web-animations-1/#active-duration
+#[inline]
+#[must_use]
+pub fn active_duration(timing: &AnimationEffectTiming) -> TimeValue {
+ // The active duration is calculated as follows:
+ // active duration = iteration duration × iteration count
+ // If either the iteration duration or iteration count are zero, the active duration is zero. This clarification is
+ // needed since the result of infinity multiplied by zero is undefined according to IEEE 754-2008.
+ if timing.iteration_duration.value == 0.0 || timing.iteration_count == 0.0 {
+ return timing.zero();
+ }
+ timing.iteration_duration * timing.iteration_count
+}
+
+/// https://www.w3.org/TR/web-animations-1/#end-time
+#[inline]
+#[must_use]
+pub fn end_time(timing: &AnimationEffectTiming) -> TimeValue {
+ // 1. The end time of an animation effect is the result of evaluating
+ // max(start delay + active duration + end delay, 0).
+ max(
+ timing.start_delay + active_duration(timing) + timing.end_delay,
+ timing.zero(),
+ )
+}
+
+/// https://www.w3.org/TR/web-animations-1/#before-active-boundary-time
+#[inline]
+#[must_use]
+pub fn before_active_boundary_time(timing: &AnimationEffectTiming) -> TimeValue {
+ // max(min(start delay, end time), 0)
+ max(min(timing.start_delay, end_time(timing)), timing.zero())
+}
+
+/// https://www.w3.org/TR/web-animations-1/#active-after-boundary-time
+#[inline]
+#[must_use]
+pub fn after_active_boundary_time(timing: &AnimationEffectTiming) -> TimeValue {
+ // max(min(start delay + active duration, end time), 0)
+ max(
+ min(timing.start_delay + active_duration(timing), end_time(timing)),
+ timing.zero(),
+ )
+}
+
+/// https://drafts.csswg.org/web-animations-2/#at-timeline-boundary
+/// `timeline` is the associated animation's timeline.
+#[inline]
+#[must_use]
+pub fn is_at_timeline_boundary(timeline: Option<&TimelineSample>) -> bool {
+ let Some(timeline) = timeline else {
+ return false;
+ };
+ let Some(timeline_time) = timeline.current_time.get() else {
+ return false;
+ };
+ let matches = |time: Option<TimeValue>| {
+ time.is_some_and(|time| (timeline_time.value - time.value).abs() < PROGRESS_TIMELINE_TOLERANCE)
+ };
+
+ // Determined based on the first matching condition:
+ // If the minimum timeline time matches the timeline current time: Return true
+ // If the maximum timeline time matches the timeline current time: Return true
+ // Otherwise: Return false
+ matches(timeline.minimum_timeline_time.get()) || matches(timeline.maximum_timeline_time.get())
+}
+
+/// https://drafts.csswg.org/web-animations-1/#animation-effect-phases-and-states
+/// Furthermore, an endpoint-inclusive active interval flag may be specified when determining the phase. If not
+/// specified, it is assumed to be false.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum EndpointInclusiveActiveInterval {
+ #[default]
+ No,
+ Yes,
+}
+
+/// https://drafts.csswg.org/web-animations-2/#animation-effect-phases-and-states
+/// The phase of an animation effect at `local_time`, Idle where it is unresolved.
+#[must_use]
+pub fn phase(
+ timing: &AnimationEffectTiming,
+ local_time: Option<TimeValue>,
+ animation_direction: AnimationDirection,
+ at_timeline_boundary: bool,
+ endpoint_inclusive: EndpointInclusiveActiveInterval,
+) -> AnimationEffectPhase {
+ let Some(local_time) = local_time else {
+ return AnimationEffectPhase::Idle;
+ };
+ let endpoint_exclusive = endpoint_inclusive == EndpointInclusiveActiveInterval::No;
+
+ let before_active_boundary_time = before_active_boundary_time(timing);
+ // An animation effect is in the before phase if the animation effect’s local time is not unresolved and either of
+ // the following conditions are met:
+ // 1. the local time is less than the before-active boundary time, or
+ // 2. the animation direction is "backwards" and the local time is equal to the before-active boundary time and
+ // not at timeline boundary.
+ if local_time < before_active_boundary_time
+ || (animation_direction == AnimationDirection::Backwards
+ && local_time == before_active_boundary_time
+ && !at_timeline_boundary
+ && endpoint_exclusive)
+ {
+ return AnimationEffectPhase::Before;
+ }
+
+ let after_active_boundary_time = after_active_boundary_time(timing);
+ // An animation effect is in the after phase if the animation effect’s local time is not unresolved and either of
+ // the following conditions are met:
+ // 1. the local time is greater than the active-after boundary time, or
+ // 2. the animation direction is "forwards" and the local time is equal to the active-after boundary time and not
+ // at timeline boundary.
+ if local_time > after_active_boundary_time
+ || (animation_direction == AnimationDirection::Forwards
+ && local_time == after_active_boundary_time
+ && !at_timeline_boundary
+ && endpoint_exclusive)
+ {
+ return AnimationEffectPhase::After;
+ }
+
+ // https://www.w3.org/TR/web-animations-1/#animation-effect-active-phase
+ // An animation effect is in the active phase if the animation effect’s local time is not unresolved and it is not
+ // in either the before phase nor the after phase.
+ AnimationEffectPhase::Active
+}
+
+/// https://www.w3.org/TR/web-animations-1/#calculating-the-active-time
+#[must_use]
+pub fn active_time(
+ timing: &AnimationEffectTiming,
+ phase: AnimationEffectPhase,
+ local_time: Option<TimeValue>,
+ fill_mode: FillMode,
+) -> Option<TimeValue> {
+ // The active time is based on the local time and start delay. However, it is only defined when the animation effect
+ // should produce an output and hence depends on its fill mode and phase as follows,
+ let local_time = || local_time.expect("an effect in a phase has a resolved local time");
+
+ match phase {
+ // -> If the animation effect is in the before phase,
+ AnimationEffectPhase::Before => {
+ // The result depends on the first matching condition from the following,
+
+ // -> If the fill mode is backwards or both,
+ if matches!(fill_mode, FillMode::Backwards | FillMode::Both) {
+ // Return the result of evaluating max(local time - start delay, 0).
+ return Some(max(local_time() - timing.start_delay, timing.zero()));
+ }
+
+ // -> Otherwise,
+ // Return an unresolved time value.
+ None
+ }
+
+ // -> If the animation effect is in the active phase,
+ AnimationEffectPhase::Active => {
+ // Return the result of evaluating local time - start delay.
+ Some(local_time() - timing.start_delay)
+ }
+
+ // -> If the animation effect is in the after phase,
+ AnimationEffectPhase::After => {
+ // The result depends on the first matching condition from the following,
+
+ // -> If the fill mode is forwards or both,
+ if matches!(fill_mode, FillMode::Forwards | FillMode::Both) {
+ // Return the result of evaluating max(min(local time - start delay, active duration), 0).
+ return Some(max(
+ min(local_time() - timing.start_delay, active_duration(timing)),
+ timing.zero(),
+ ));
+ }
+
+ // -> Otherwise,
+ // Return an unresolved time value.
+ None
+ }
+
+ // -> Otherwise (the local time is unresolved),
+ // Return an unresolved time value.
+ AnimationEffectPhase::Idle => None,
+ }
+}
+
+/// https://www.w3.org/TR/web-animations-1/#overall-progress
+#[must_use]
+pub fn overall_progress(
+ timing: &AnimationEffectTiming,
+ phase: AnimationEffectPhase,
+ active_time: Option<TimeValue>,
+) -> Option<f64> {
+ // 1. If the active time is unresolved, return unresolved.
+ let active_time = active_time?;
+
+ // 2. Calculate an initial value for overall progress based on the first matching condition from below,
+ // -> If the iteration duration is zero,
+ let overall_progress = if timing.iteration_duration.value == 0.0 {
+ // If the animation effect is in the before phase, let overall progress be zero, otherwise, let it be equal to
+ // the iteration count.
+ match phase {
+ AnimationEffectPhase::Before => 0.0,
+ _ => timing.iteration_count,
+ }
+ }
+ // Otherwise,
+ else {
+ // Let overall progress be the result of calculating active time / iteration duration.
+ active_time / timing.iteration_duration
+ };
+
+ // 3. Return the result of calculating overall progress + iteration start.
+ Some(overall_progress + timing.iteration_start)
+}
+
+/// The phase, active time and overall progress of an effect at `local_time`, with the effect's fill
+/// mode. `animation` is the associated animation, if any, and `timeline` its timeline.
+#[must_use]
+pub fn resolve_timing(
+ timing: &AnimationEffectTiming,
+ local_time: Option<TimeValue>,
+ animation: Option<&AnimationPlayback>,
+ timeline: Option<&TimelineSample>,
+) -> ResolvedEffectTiming {
+ resolve_timing_using_fill(timing, local_time, animation, timeline, timing.fill_mode)
+}
+
+/// `resolve_timing()` with the fill mode `fill_mode` in place of the effect's own.
+#[must_use]
+pub fn resolve_timing_using_fill(
+ timing: &AnimationEffectTiming,
+ local_time: Option<TimeValue>,
+ animation: Option<&AnimationPlayback>,
+ timeline: Option<&TimelineSample>,
+ fill_mode: FillMode,
+) -> ResolvedEffectTiming {
+ resolve_timing_with(
+ timing,
+ local_time,
+ animation,
+ timeline,
+ fill_mode,
+ EndpointInclusiveActiveInterval::No,
+ )
+}
+
+/// `resolve_timing()` with the fill mode `fill_mode` in place of the effect's own, determining the phase with the
+/// endpoint-inclusive active interval flag `endpoint_inclusive`.
+#[must_use]
+pub fn resolve_timing_with(
+ timing: &AnimationEffectTiming,
+ local_time: Option<TimeValue>,
+ animation: Option<&AnimationPlayback>,
+ timeline: Option<&TimelineSample>,
+ fill_mode: FillMode,
+ endpoint_inclusive: EndpointInclusiveActiveInterval,
+) -> ResolvedEffectTiming {
+ let at_timeline_boundary = local_time.is_some() && is_at_timeline_boundary(timeline);
+ let phase = phase(
+ timing,
+ local_time,
+ animation_direction(animation),
+ at_timeline_boundary,
+ endpoint_inclusive,
+ );
+ let active_time = active_time(timing, phase, local_time, fill_mode);
+ ResolvedEffectTiming {
+ phase,
+ local_time,
+ active_time,
+ overall_progress: overall_progress(timing, phase, active_time),
+ }
+}
+
+/// https://www.w3.org/TR/web-animations-1/#simple-iteration-progress
+#[must_use]
+pub fn simple_iteration_progress(timing: &AnimationEffectTiming, resolved: &ResolvedEffectTiming) -> Option<f64> {
+ // 1. If the overall progress is unresolved, return unresolved.
+ let overall_progress = resolved.overall_progress?;
+
+ // 2. If overall progress is infinity, let the simple iteration progress be iteration start % 1.0, otherwise, let
+ // the simple iteration progress be overall progress % 1.0.
+ let mut simple_iteration_progress = match overall_progress.is_infinite() {
+ true => timing.iteration_start % 1.0,
+ false => overall_progress % 1.0,
+ };
+
+ // 3. If all of the following conditions are true,
+ // - the simple iteration progress calculated above is zero, and
+ // - the animation effect is in the active phase or the after phase, and
+ // - the active time is equal to the active duration, and
+ // - the iteration count is not equal to zero.
+ if simple_iteration_progress == 0.0
+ && matches!(
+ resolved.phase,
+ AnimationEffectPhase::Active | AnimationEffectPhase::After
+ )
+ && resolved.active_time == Some(active_duration(timing))
+ && timing.iteration_count != 0.0
+ {
+ // let the simple iteration progress be 1.0.
+ simple_iteration_progress = 1.0;
+ }
+
+ // 4. Return simple iteration progress.
+ Some(simple_iteration_progress)
+}
+
+/// https://www.w3.org/TR/web-animations-1/#current-iteration
+#[must_use]
+pub fn current_iteration(timing: &AnimationEffectTiming, resolved: &ResolvedEffectTiming) -> Option<f64> {
+ current_iteration_with(timing, resolved, || simple_iteration_progress(timing, resolved))
+}
+
+/// `current_iteration()` with the simple iteration progress given by `simple_iteration_progress`.
+fn current_iteration_with(
+ timing: &AnimationEffectTiming,
+ resolved: &ResolvedEffectTiming,
+ simple_iteration_progress: impl FnOnce() -> Option<f64>,
+) -> Option<f64> {
+ // 1. If the active time is unresolved, return unresolved.
+ resolved.active_time?;
+
+ // 2. If the animation effect is in the after phase and the iteration count is infinity, return infinity.
+ if resolved.phase == AnimationEffectPhase::After && timing.iteration_count.is_infinite() {
+ return Some(timing.iteration_count);
+ }
+
+ let overall_progress = resolved
+ .overall_progress
+ .expect("a resolved active time has a resolved overall progress");
+
+ // 3. If the simple iteration progress is 1.0, return floor(overall progress) - 1.
+ if simple_iteration_progress() == Some(1.0) {
+ return Some(overall_progress.floor() - 1.0);
+ }
+
+ // 4. Otherwise, return floor(overall progress).
+ Some(overall_progress.floor())
+}
+
+/// https://www.w3.org/TR/web-animations-1/#directed-progress
+/// The current direction, which step 2 of calculating the directed progress determines.
+#[must_use]
+pub fn current_direction(timing: &AnimationEffectTiming, resolved: &ResolvedEffectTiming) -> AnimationDirection {
+ current_direction_with(timing, resolved, || simple_iteration_progress(timing, resolved))
+}
+
+/// `current_direction()` with the simple iteration progress given by `simple_iteration_progress`.
+fn current_direction_with(
+ timing: &AnimationEffectTiming,
+ resolved: &ResolvedEffectTiming,
+ simple_iteration_progress: impl FnOnce() -> Option<f64>,
+) -> AnimationDirection {
+ // 2. Calculate the current direction using the first matching condition from the following list:
+ match timing.playback_direction {
+ // -> If playback direction is normal,
+ // Let the current direction be forwards.
+ PlaybackDirection::Normal => AnimationDirection::Forwards,
+
+ // -> If playback direction is reverse,
+ // Let the current direction be reverse.
+ PlaybackDirection::Reverse => AnimationDirection::Backwards,
+
+ // -> Otherwise,
+ PlaybackDirection::Alternate | PlaybackDirection::AlternateReverse => {
+ // 1. Let d be the current iteration.
+ let mut d = current_iteration_with(timing, resolved, simple_iteration_progress)
+ .expect("an effect with a resolved simple iteration progress has a current iteration");
+
+ // 2. If playback direction is alternate-reverse increment d by 1.
+ if timing.playback_direction == PlaybackDirection::AlternateReverse {
+ d += 1.0;
+ }
+
+ // 3. If d % 2 == 0, let the current direction be forwards, otherwise let the current direction be
+ // reverse. If d is infinity, let the current direction be forwards.
+ if d.is_infinite() || d % 2.0 == 0.0 {
+ AnimationDirection::Forwards
+ } else {
+ AnimationDirection::Backwards
+ }
+ }
+ }
+}
+
+/// https://www.w3.org/TR/web-animations-1/#directed-progress
+#[must_use]
+pub fn directed_progress(timing: &AnimationEffectTiming, resolved: &ResolvedEffectTiming) -> Option<f64> {
+ directed_progress_and_current_direction(timing, resolved).map(|(directed_progress, _)| directed_progress)
+}
+
+/// https://www.w3.org/TR/web-animations-1/#directed-progress
+/// The directed progress, and the current direction it was calculated with.
+fn directed_progress_and_current_direction(
+ timing: &AnimationEffectTiming,
+ resolved: &ResolvedEffectTiming,
+) -> Option<(f64, AnimationDirection)> {
+ // 1. If the simple iteration progress is unresolved, return unresolved.
+ let simple_iteration_progress = simple_iteration_progress(timing, resolved)?;
+
+ // 2. Calculate the current direction using the first matching condition from the following list:
+ let current_direction = current_direction_with(timing, resolved, || Some(simple_iteration_progress));
+
+ // 3. If the current direction is forwards then return the simple iteration progress.
+ // Otherwise, return 1.0 - simple iteration progress.
+ let directed_progress = match current_direction {
+ AnimationDirection::Forwards => simple_iteration_progress,
+ AnimationDirection::Backwards => 1.0 - simple_iteration_progress,
+ };
+ Some((directed_progress, current_direction))
+}
+
+/// https://www.w3.org/TR/web-animations-1/#transformed-progress
+#[inline]
+#[must_use]
+pub fn transformed_progress(
+ timing: &AnimationEffectTiming,
+ resolved: &ResolvedEffectTiming,
+ timing_function: &Easing,
+) -> Option<f64> {
+ transformed_progress_with(timing, resolved, |input_progress, before_flag| {
+ timing_function.evaluate_at(input_progress, before_flag)
+ })
+}
+
+/// `transformed_progress()` with the timing function evaluated by `evaluate_timing_function`, which
+/// takes the input progress value and the before flag.
+#[must_use]
+pub fn transformed_progress_with(
+ timing: &AnimationEffectTiming,
+ resolved: &ResolvedEffectTiming,
+ evaluate_timing_function: impl FnOnce(f64, bool) -> f64,
+) -> Option<f64> {
+ // 1. If the directed progress is unresolved, return unresolved.
+ let (directed_progress, current_direction) = directed_progress_and_current_direction(timing, resolved)?;
+
+ // 2. Calculate the value of the before flag as follows:
+
+ // 1. Determine the current direction using the procedure defined in §4.9.1 Calculating the directed progress.
+ // NB: Calculating the directed progress in step 1 determined it.
+
+ // 2. If the current direction is forwards, let going forwards be true, otherwise it is false.
+ let going_forwards = current_direction == AnimationDirection::Forwards;
+
+ // 3. The before flag is set if the animation effect is in the before phase and going forwards is true; or if the
+ // animation effect is in the after phase and going forwards is false.
+ let before_flag = (resolved.phase == AnimationEffectPhase::Before && going_forwards)
+ || (resolved.phase == AnimationEffectPhase::After && !going_forwards);
+
+ // 3. Return the result of evaluating the animation effect’s timing function passing directed progress as the input
+ // progress value and before flag as the before flag.
+ Some(evaluate_timing_function(directed_progress, before_flag))
+}
+
+/// https://www.w3.org/TR/web-animations-1/#in-play
+#[inline]
+#[must_use]
+pub fn is_in_play(phase: AnimationEffectPhase, animation: Option<&AnimationPlayback>) -> bool {
+ // An animation effect is in play if all of the following conditions are met:
+ // - the animation effect is in the active phase, and
+ // - the animation effect is associated with an animation that is not finished.
+ phase == AnimationEffectPhase::Active && animation.is_some_and(|animation| !animation.is_finished)
+}
+
+/// https://www.w3.org/TR/web-animations-1/#current
+/// `animation` is the associated animation, if any, and `timeline` its timeline.
+#[must_use]
+pub fn is_current(
+ timing: &AnimationEffectTiming,
+ phase: AnimationEffectPhase,
+ animation: Option<&AnimationPlayback>,
+ timeline: Option<&TimelineSample>,
+) -> bool {
+ // An animation effect is current if any of the following conditions are true:
+
+ // - the animation effect is in play, or
+ if is_in_play(phase, animation) {
+ return true;
+ }
+
+ let Some(animation) = animation else {
+ return false;
+ };
+ let playback_rate = animation.playback_rate;
+
+ // - the animation effect is associated with an animation with a playback rate > 0 and the animation effect is
+ // in the before phase, or
+ if playback_rate > 0.0 && phase == AnimationEffectPhase::Before {
+ return true;
+ }
+
+ // - the animation effect is associated with an animation with a playback rate < 0 and the animation effect is
+ // in the after phase, or
+ if playback_rate < 0.0 && phase == AnimationEffectPhase::After {
+ return true;
+ }
+
+ // - the animation effect is associated with an animation not in the idle play state with a non-null associated
+ // timeline that is not monotonically increasing.
+ let current_time = current_time_at(animation, timeline.and_then(|timeline| timeline.current_time.get()));
+ play_state_at(animation, current_time, end_time(timing)) != AnimationPlayState::Idle
+ && timeline.is_some_and(|timeline| !timeline.is_monotonically_increasing)
+}
+
+/// https://www.w3.org/TR/web-animations-1/#in-effect
+#[inline]
+#[must_use]
+pub fn is_in_effect(resolved: &ResolvedEffectTiming) -> bool {
+ // An animation effect is in effect if its active time, as calculated according to the procedure in
+ // §4.8.3.1 Calculating the active time, is not unresolved.
+ resolved.active_time.is_some()
+}
+
+/// https://www.w3.org/TR/web-animations-1/#animation-current-time
+/// The current time of `animation` with its timeline at `timeline_time`, which is unresolved where
+/// the animation has no timeline.
+#[inline]
+#[must_use]
+pub fn current_time_at(animation: &AnimationPlayback, timeline_time: Option<TimeValue>) -> Option<TimeValue> {
+ // The current time is calculated from the first matching condition from below:
+
+ // -> If the animation’s hold time is resolved,
+ if let Some(hold_time) = animation.hold_time.get() {
+ // The current time is the animation’s hold time.
+ return Some(hold_time);
+ }
+
+ // -> If any of the following are true:
+ // - the animation has no associated timeline, or
+ // - the associated timeline is inactive, or
+ // - the animation’s start time is unresolved.
+ // The current time is an unresolved time value.
+ let (timeline_time, start_time) = (timeline_time?, animation.start_time.get()?);
+
+ // -> Otherwise,
+ // current time = (timeline time - start time) × playback rate
+ // Where timeline time is the current time value of the associated timeline. The playback rate value is defined
+ // in §4.4.15 Speed control.
+ Some((timeline_time - start_time) * animation.playback_rate)
+}
+
+/// https://www.w3.org/TR/web-animations-1/#play-states
+/// The play state of `animation` at its current time `current_time`, with the end time of its
+/// associated effect, or zero without one, `associated_effect_end`.
+#[must_use]
+pub fn play_state_at(
+ animation: &AnimationPlayback,
+ current_time: Option<TimeValue>,
+ associated_effect_end: TimeValue,
+) -> AnimationPlayState {
+ // The play state of animation, animation, at a given moment is the state corresponding to the first matching
+ // condition from the following:
+
+ // -> All of the following conditions are true:
+ // - The current time of animation is unresolved, and
+ // - the start time of animation is unresolved, and
+ // - animation does not have either a pending play task or a pending pause task,
+ if current_time.is_none() && animation.start_time.get().is_none() && !animation.pending() {
+ // → idle
+ return AnimationPlayState::Idle;
+ }
+
+ // -> Either of the following conditions are true:
+ // - animation has a pending pause task, or
+ // - both the start time of animation is unresolved and it does not have a pending play task,
+ if animation.has_pending_pause_task || (animation.start_time.get().is_none() && !animation.has_pending_play_task) {
+ // → paused
+ return AnimationPlayState::Paused;
+ }
+
+ // -> For animation, current time is resolved and either of the following conditions are true:
+ // - animation’s effective playback rate > 0 and current time ≥ associated effect end; or
+ // - animation’s effective playback rate < 0 and current time ≤ 0,
+ let effective_playback_rate = animation.effective_playback_rate();
+ if let Some(current_time) = current_time
+ && ((effective_playback_rate > 0.0 && current_time >= associated_effect_end)
+ || (effective_playback_rate < 0.0 && current_time.value <= 0.0))
+ {
+ // → finished
+ return AnimationPlayState::Finished;
+ }
+
+ // -> Otherwise,
+ // → running
+ AnimationPlayState::Running
+}
+
+/// https://www.w3.org/TR/web-animations-1/#animation-relevant
+/// Whether `animation`, on `timeline`, is relevant, with its associated effect, if any, of
+/// `effect_timing` at the local time `local_time`.
+#[must_use]
+pub fn is_relevant(
+ animation: &AnimationPlayback,
+ timeline: Option<&TimelineSample>,
+ effect_timing: Option<&AnimationEffectTiming>,
+ local_time: Option<TimeValue>,
+) -> bool {
+ // An animation is relevant if:
+ // - Its associated effect is current or in effect, and
+ // - Its replace state is not removed.
+ effect_timing.is_some_and(|timing| {
+ let resolved = resolve_timing(timing, local_time, Some(animation), timeline);
+ is_current(timing, resolved.phase, Some(animation), timeline) || is_in_effect(&resolved)
+ }) && animation.replace_state != AnimationReplaceState::Removed
+}
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/effect_timing.rs b/Libraries/LibCompositing/Rust/src/animation_timing/effect_timing.rs
new file mode 100644
index 00000000000..e40c279bcdb
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/effect_timing.rs
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The timing properties of an animation effect, as specified and as normalized.
+
+use super::time_value::{TimeValue, TimeValueType};
+
+/// https://www.w3.org/TR/web-animations-1/#enumdef-fillmode
+/// In IDL order.
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum FillMode {
+ None,
+ Forwards,
+ Backwards,
+ Both,
+ #[default]
+ Auto,
+}
+
+/// https://www.w3.org/TR/web-animations-1/#enumdef-playbackdirection
+/// In IDL order.
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum PlaybackDirection {
+ #[default]
+ Normal,
+ Reverse,
+ Alternate,
+ AlternateReverse,
+}
+
+impl TryFrom<u8> for FillMode {
+ type Error = u8;
+
+ /// The fill mode at `index` in IDL order.
+ fn try_from(index: u8) -> Result<Self, u8> {
+ Ok(match index {
+ 0 => Self::None,
+ 1 => Self::Forwards,
+ 2 => Self::Backwards,
+ 3 => Self::Both,
+ 4 => Self::Auto,
+ _ => return Err(index),
+ })
+ }
+}
+
+impl TryFrom<u8> for PlaybackDirection {
+ type Error = u8;
+
+ /// The playback direction at `index` in IDL order.
+ fn try_from(index: u8) -> Result<Self, u8> {
+ Ok(match index {
+ 0 => Self::Normal,
+ 1 => Self::Reverse,
+ 2 => Self::Alternate,
+ 3 => Self::AlternateReverse,
+ _ => return Err(index),
+ })
+ }
+}
+
+/// https://www.w3.org/TR/web-animations-1/#animation-direction
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum AnimationDirection {
+ Forwards,
+ Backwards,
+}
+
+/// https://www.w3.org/TR/web-animations-1/#animation-effect-phases-and-states
+/// The phase of an animation effect, with Idle for an unresolved local time.
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum AnimationEffectPhase {
+ Before,
+ Active,
+ After,
+ #[default]
+ Idle,
+}
+
+/// https://drafts.csswg.org/web-animations-2/#specified-iteration-duration
+/// The iteration duration as specified: auto, or a time in milliseconds.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct SpecifiedIterationDuration {
+ pub is_auto: bool,
+ pub milliseconds: f64,
+}
+
+impl SpecifiedIterationDuration {
+ pub const AUTO: Self = Self {
+ is_auto: true,
+ milliseconds: 0.0,
+ };
+
+ #[inline]
+ #[must_use]
+ pub const fn milliseconds(milliseconds: f64) -> Self {
+ Self {
+ is_auto: false,
+ milliseconds,
+ }
+ }
+
+ /// The duration in milliseconds, or none for auto.
+ #[inline]
+ #[must_use]
+ pub fn time(self) -> Option<f64> {
+ (!self.is_auto).then_some(self.milliseconds)
+ }
+}
+
+impl Default for SpecifiedIterationDuration {
+ fn default() -> Self {
+ Self::AUTO
+ }
+}
+
+/// The timing properties of an animation effect as specified, which normalizing against the
+/// effect's timeline turns into `AnimationEffectTiming`.
+/// https://www.w3.org/TR/web-animations-1/#the-effecttiming-dictionaries
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct SpecifiedEffectTiming {
+ /// https://drafts.csswg.org/web-animations-2/#specified-start-delay
+ pub start_delay: f64,
+ /// https://drafts.csswg.org/web-animations-2/#specified-end-delay
+ pub end_delay: f64,
+ /// https://drafts.csswg.org/web-animations-2/#specified-iteration-duration
+ pub iteration_duration: SpecifiedIterationDuration,
+ /// https://www.w3.org/TR/web-animations-1/#iteration-start
+ pub iteration_start: f64,
+ /// https://www.w3.org/TR/web-animations-1/#iteration-count
+ pub iteration_count: f64,
+ /// https://www.w3.org/TR/web-animations-1/#fill-mode
+ pub fill_mode: FillMode,
+ /// https://www.w3.org/TR/web-animations-1/#playback-direction
+ pub playback_direction: PlaybackDirection,
+}
+
+impl Default for SpecifiedEffectTiming {
+ fn default() -> Self {
+ Self {
+ start_delay: 0.0,
+ end_delay: 0.0,
+ iteration_duration: SpecifiedIterationDuration::AUTO,
+ iteration_start: 0.0,
+ iteration_count: 1.0,
+ fill_mode: FillMode::Auto,
+ playback_direction: PlaybackDirection::Normal,
+ }
+ }
+}
+
+/// The timing properties of an animation effect the timing calculations use: the specified
+/// timing normalized against the effect's timeline, every time in the timeline's unit.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct AnimationEffectTiming {
+ /// https://www.w3.org/TR/web-animations-1/#start-delay
+ pub start_delay: TimeValue,
+ /// https://www.w3.org/TR/web-animations-1/#end-delay
+ pub end_delay: TimeValue,
+ /// https://www.w3.org/TR/web-animations-1/#iteration-duration
+ pub iteration_duration: TimeValue,
+ /// https://www.w3.org/TR/web-animations-1/#iteration-start
+ pub iteration_start: f64,
+ /// https://www.w3.org/TR/web-animations-1/#iteration-count
+ pub iteration_count: f64,
+ /// https://www.w3.org/TR/web-animations-1/#fill-mode
+ pub fill_mode: FillMode,
+ /// https://www.w3.org/TR/web-animations-1/#playback-direction
+ pub playback_direction: PlaybackDirection,
+}
+
+impl AnimationEffectTiming {
+ /// The unit of the effect's times, which is that of its timeline.
+ #[inline]
+ #[must_use]
+ pub fn time_unit(&self) -> TimeValueType {
+ self.iteration_duration.r#type
+ }
+
+ /// A zero time in the effect's unit.
+ #[inline]
+ #[must_use]
+ pub fn zero(&self) -> TimeValue {
+ TimeValue::zero(self.time_unit())
+ }
+}
+
+impl Default for AnimationEffectTiming {
+ /// The timing of an effect associated with no animation, whose iteration duration is the
+ /// intrinsic iteration duration of 0ms.
+ fn default() -> Self {
+ Self {
+ start_delay: TimeValue::milliseconds(0.0),
+ end_delay: TimeValue::milliseconds(0.0),
+ iteration_duration: TimeValue::milliseconds(0.0),
+ iteration_start: 0.0,
+ iteration_count: 1.0,
+ fill_mode: FillMode::Auto,
+ playback_direction: PlaybackDirection::Normal,
+ }
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/mod.rs b/Libraries/LibCompositing/Rust/src/animation_timing/mod.rs
new file mode 100644
index 00000000000..ea12bd0ec15
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/mod.rs
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The timing model of Web Animations: how far along an animation effect is, from its timing
+//! properties and the state of its animation and timeline.
+//! https://www.w3.org/TR/web-animations-1/#timing-model
+
+pub mod calculations;
+pub mod effect_timing;
+pub mod playback;
+pub mod time_value;
+
+pub use calculations::*;
+pub use effect_timing::*;
+pub use playback::*;
+pub use time_value::{OptionalNumber, OptionalTimeValue, TimeValue, TimeValueType};
+
+#[cfg(test)]
+mod tests;
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/playback.rs b/Libraries/LibCompositing/Rust/src/animation_timing/playback.rs
new file mode 100644
index 00000000000..6a153a885d6
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/playback.rs
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the timing of an animation effect reads of its animation and the animation's timeline.
+
+use super::time_value::{OptionalNumber, OptionalTimeValue};
+
+/// https://www.w3.org/TR/web-animations-1/#enumdef-animationplaystate
+/// In IDL order.
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum AnimationPlayState {
+ Idle,
+ Running,
+ Paused,
+ Finished,
+}
+
+/// https://www.w3.org/TR/web-animations-1/#enumdef-animationreplacestate
+/// In IDL order.
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum AnimationReplaceState {
+ #[default]
+ Active,
+ Removed,
+ Persisted,
+}
+
+/// The playback state of an animation.
+/// https://www.w3.org/TR/web-animations-1/#animations
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct AnimationPlayback {
+ /// https://www.w3.org/TR/web-animations-1/#animation-start-time
+ pub start_time: OptionalTimeValue,
+ /// https://www.w3.org/TR/web-animations-1/#animation-hold-time
+ pub hold_time: OptionalTimeValue,
+ /// https://www.w3.org/TR/web-animations-1/#playback-rate
+ pub playback_rate: f64,
+ /// https://www.w3.org/TR/web-animations-1/#pending-playback-rate
+ pub pending_playback_rate: OptionalNumber,
+ /// https://www.w3.org/TR/web-animations-1/#pending-play-task
+ pub has_pending_play_task: bool,
+ /// https://www.w3.org/TR/web-animations-1/#pending-pause-task
+ pub has_pending_pause_task: bool,
+ /// Whether the animation was last found finished when its finished state was updated.
+ /// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state
+ pub is_finished: bool,
+ /// https://www.w3.org/TR/web-animations-1/#animation-replace-state
+ pub replace_state: AnimationReplaceState,
+}
+
+impl AnimationPlayback {
+ /// https://www.w3.org/TR/web-animations-1/#pending
+ #[inline]
+ #[must_use]
+ pub fn pending(&self) -> bool {
+ self.has_pending_play_task || self.has_pending_pause_task
+ }
+
+ /// https://www.w3.org/TR/web-animations-1/#effective-playback-rate
+ #[inline]
+ #[must_use]
+ pub fn effective_playback_rate(&self) -> f64 {
+ // The effective playback rate of an animation is its pending playback rate, if set, otherwise it is the
+ // animation’s playback rate.
+ self.pending_playback_rate.get().unwrap_or(self.playback_rate)
+ }
+}
+
+impl Default for AnimationPlayback {
+ /// An idle animation.
+ fn default() -> Self {
+ Self {
+ start_time: OptionalTimeValue::UNRESOLVED,
+ hold_time: OptionalTimeValue::UNRESOLVED,
+ playback_rate: 1.0,
+ pending_playback_rate: OptionalNumber::default(),
+ has_pending_play_task: false,
+ has_pending_pause_task: false,
+ is_finished: false,
+ replace_state: AnimationReplaceState::Active,
+ }
+ }
+}
+
+/// What the timing calculations read of an animation's timeline at one moment.
+/// https://www.w3.org/TR/web-animations-1/#timelines
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct TimelineSample {
+ /// https://www.w3.org/TR/web-animations-1/#timeline-current-time
+ pub current_time: OptionalTimeValue,
+ /// https://drafts.csswg.org/web-animations-2/#minimum-timeline-time
+ pub minimum_timeline_time: OptionalTimeValue,
+ /// https://drafts.csswg.org/web-animations-2/#maximum-timeline-time
+ pub maximum_timeline_time: OptionalTimeValue,
+ /// https://www.w3.org/TR/web-animations-1/#monotonically-increasing-timeline
+ pub is_monotonically_increasing: bool,
+}
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/tests.rs b/Libraries/LibCompositing/Rust/src/animation_timing/tests.rs
new file mode 100644
index 00000000000..f85d28574c7
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/tests.rs
@@ -0,0 +1,521 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+use crate::easing::{Easing, STEP_POSITION_JUMP_START};
+
+fn ms(value: f64) -> TimeValue {
+ TimeValue::milliseconds(value)
+}
+
+fn percent(value: f64) -> TimeValue {
+ TimeValue::percentage(value)
+}
+
+/// A one-second effect on a document timeline.
+fn one_second() -> AnimationEffectTiming {
+ normalize_specified_timing(
+ &SpecifiedEffectTiming {
+ iteration_duration: SpecifiedIterationDuration::milliseconds(1000.0),
+ ..SpecifiedEffectTiming::default()
+ },
+ None,
+ TimeValueType::Milliseconds,
+ )
+}
+
+/// An animation that started at zero and plays at `playback_rate`.
+fn playing(playback_rate: f64) -> AnimationPlayback {
+ AnimationPlayback {
+ start_time: Some(ms(0.0)).into(),
+ playback_rate,
+ ..AnimationPlayback::default()
+ }
+}
+
+fn document_timeline(time: f64) -> TimelineSample {
+ TimelineSample {
+ current_time: Some(ms(time)).into(),
+ is_monotonically_increasing: true,
+ ..TimelineSample::default()
+ }
+}
+
+fn scroll_timeline(progress: f64) -> TimelineSample {
+ TimelineSample {
+ current_time: Some(percent(progress)).into(),
+ minimum_timeline_time: Some(percent(0.0)).into(),
+ maximum_timeline_time: Some(percent(100.0)).into(),
+ is_monotonically_increasing: false,
+ }
+}
+
+/// The resolved timing of `timing` played by `animation` with its timeline at `timeline`.
+fn resolved_at(
+ timing: &AnimationEffectTiming,
+ animation: &AnimationPlayback,
+ timeline: &TimelineSample,
+) -> ResolvedEffectTiming {
+ let local_time = current_time_at(animation, timeline.current_time.get());
+ resolve_timing(timing, local_time, Some(animation), Some(timeline))
+}
+
+/// The transformed progress of `timing` played at rate one from zero, at `time`.
+fn progress_at(timing: &AnimationEffectTiming, time: f64) -> Option<f64> {
+ let resolved = resolved_at(timing, &playing(1.0), &document_timeline(time));
+ transformed_progress(timing, &resolved, &Easing::default())
+}
+
+#[test]
+fn normalizing_without_a_timeline_duration_keeps_the_specified_times() {
+ let specified = SpecifiedEffectTiming {
+ start_delay: 100.0,
+ end_delay: 50.0,
+ iteration_duration: SpecifiedIterationDuration::milliseconds(1000.0),
+ iteration_count: 2.0,
+ ..SpecifiedEffectTiming::default()
+ };
+ let timing = normalize_specified_timing(&specified, None, TimeValueType::Milliseconds);
+ assert_eq!(timing.start_delay, ms(100.0));
+ assert_eq!(timing.end_delay, ms(50.0));
+ assert_eq!(timing.iteration_duration, ms(1000.0));
+ assert_eq!(active_duration(&timing), ms(2000.0));
+ assert_eq!(end_time(&timing), ms(2150.0));
+
+ let auto = SpecifiedEffectTiming {
+ iteration_duration: SpecifiedIterationDuration::AUTO,
+ ..specified
+ };
+ let timing = normalize_specified_timing(&auto, None, TimeValueType::Milliseconds);
+ assert_eq!(
+ timing.iteration_duration,
+ ms(0.0),
+ "auto is the intrinsic iteration duration"
+ );
+}
+
+#[test]
+fn normalizing_against_a_timeline_duration_makes_the_times_proportional() {
+ let specified = SpecifiedEffectTiming {
+ start_delay: 250.0,
+ end_delay: 250.0,
+ iteration_duration: SpecifiedIterationDuration::milliseconds(500.0),
+ ..SpecifiedEffectTiming::default()
+ };
+ let timing = normalize_specified_timing(&specified, Some(percent(100.0)), TimeValueType::Percentage);
+ assert_eq!(timing.start_delay, percent(25.0));
+ assert_eq!(timing.iteration_duration, percent(50.0));
+ assert_eq!(timing.end_delay, percent(25.0));
+
+ let auto = SpecifiedEffectTiming {
+ iteration_duration: SpecifiedIterationDuration::AUTO,
+ iteration_count: 4.0,
+ ..specified
+ };
+ let timing = normalize_specified_timing(&auto, Some(percent(100.0)), TimeValueType::Percentage);
+ assert_eq!(timing.start_delay, percent(0.0), "auto drops the delays");
+ assert_eq!(timing.iteration_duration, percent(25.0));
+
+ let empty = SpecifiedEffectTiming {
+ start_delay: 0.0,
+ end_delay: 0.0,
+ iteration_duration: SpecifiedIterationDuration::milliseconds(0.0),
+ ..SpecifiedEffectTiming::default()
+ };
+ let timing = normalize_specified_timing(&empty, Some(percent(100.0)), TimeValueType::Percentage);
+ assert_eq!(
+ timing.iteration_duration,
+ percent(0.0),
+ "no division by a zero total time"
+ );
+ assert_eq!(timing.start_delay, percent(0.0));
+}
+
+#[test]
+fn normalizing_infinite_factors_against_a_timeline_duration_stays_finite() {
+ let zero_duration_repeating_forever = SpecifiedEffectTiming {
+ iteration_duration: SpecifiedIterationDuration::milliseconds(0.0),
+ iteration_count: f64::INFINITY,
+ ..SpecifiedEffectTiming::default()
+ };
+ let timing = normalize_specified_timing(
+ &zero_duration_repeating_forever,
+ Some(percent(100.0)),
+ TimeValueType::Percentage,
+ );
+ assert_eq!(timing.iteration_duration, percent(0.0));
+ assert_eq!(end_time(&timing), percent(0.0));
+
+ let infinite_duration = SpecifiedEffectTiming {
+ start_delay: 100.0,
+ iteration_duration: SpecifiedIterationDuration::milliseconds(f64::INFINITY),
+ ..SpecifiedEffectTiming::default()
+ };
+ let timing = normalize_specified_timing(&infinite_duration, Some(percent(100.0)), TimeValueType::Percentage);
+ assert_eq!(timing.start_delay, percent(0.0));
+ assert_eq!(timing.iteration_duration, percent(100.0));
+ let animation = AnimationPlayback {
+ start_time: Some(percent(0.0)).into(),
+ ..playing(1.0)
+ };
+ let resolved = resolved_at(&timing, &animation, &scroll_timeline(50.0));
+ assert_eq!(transformed_progress(&timing, &resolved, &Easing::default()), Some(0.5));
+
+ let repeating_forever = SpecifiedEffectTiming {
+ iteration_duration: SpecifiedIterationDuration::milliseconds(1000.0),
+ iteration_count: f64::INFINITY,
+ ..SpecifiedEffectTiming::default()
+ };
+ let timing = normalize_specified_timing(&repeating_forever, Some(percent(100.0)), TimeValueType::Percentage);
+ assert_eq!(timing.iteration_duration, percent(0.0));
+}
+
+#[test]
+fn an_infinite_duration_never_iterated_has_no_active_duration() {
+ let timing = AnimationEffectTiming {
+ iteration_duration: ms(f64::INFINITY),
+ iteration_count: 0.0,
+ ..AnimationEffectTiming::default()
+ };
+ assert_eq!(active_duration(&timing), ms(0.0));
+}
+
+#[test]
+fn the_phase_follows_the_boundary_times_and_the_direction() {
+ let timing = AnimationEffectTiming {
+ start_delay: ms(100.0),
+ ..one_second()
+ };
+ assert_eq!(before_active_boundary_time(&timing), ms(100.0));
+ assert_eq!(after_active_boundary_time(&timing), ms(1100.0));
+ let phase_at = |time: f64, direction| {
+ phase(
+ &timing,
+ Some(ms(time)),
+ direction,
+ false,
+ EndpointInclusiveActiveInterval::No,
+ )
+ };
+ assert_eq!(
+ phase(
+ &timing,
+ None,
+ AnimationDirection::Forwards,
+ false,
+ EndpointInclusiveActiveInterval::No
+ ),
+ AnimationEffectPhase::Idle
+ );
+ assert_eq!(
+ phase_at(50.0, AnimationDirection::Forwards),
+ AnimationEffectPhase::Before
+ );
+ assert_eq!(
+ phase_at(100.0, AnimationDirection::Forwards),
+ AnimationEffectPhase::Active
+ );
+ assert_eq!(
+ phase_at(100.0, AnimationDirection::Backwards),
+ AnimationEffectPhase::Before
+ );
+ assert_eq!(
+ phase_at(1100.0, AnimationDirection::Forwards),
+ AnimationEffectPhase::After
+ );
+ assert_eq!(
+ phase_at(1100.0, AnimationDirection::Backwards),
+ AnimationEffectPhase::Active
+ );
+ assert_eq!(
+ phase(
+ &timing,
+ Some(ms(1100.0)),
+ AnimationDirection::Forwards,
+ true,
+ EndpointInclusiveActiveInterval::No
+ ),
+ AnimationEffectPhase::Active,
+ "an effect at the timeline boundary stays active"
+ );
+ for (time, direction) in [
+ (100.0, AnimationDirection::Backwards),
+ (1100.0, AnimationDirection::Forwards),
+ ] {
+ assert_eq!(
+ phase(
+ &timing,
+ Some(ms(time)),
+ direction,
+ false,
+ EndpointInclusiveActiveInterval::Yes
+ ),
+ AnimationEffectPhase::Active,
+ "an endpoint-inclusive active interval includes its endpoints"
+ );
+ }
+}
+
+#[test]
+fn a_progress_based_timeline_is_at_its_boundary_within_tolerance() {
+ assert!(is_at_timeline_boundary(Some(&scroll_timeline(100.0 - 1e-7))));
+ assert!(is_at_timeline_boundary(Some(&scroll_timeline(0.0))));
+ assert!(!is_at_timeline_boundary(Some(&scroll_timeline(50.0))));
+ assert!(!is_at_timeline_boundary(Some(&document_timeline(0.0))));
+ assert!(!is_at_timeline_boundary(None));
+
+ let timing = normalize_specified_timing(
+ &SpecifiedEffectTiming {
+ fill_mode: FillMode::None,
+ ..SpecifiedEffectTiming::default()
+ },
+ Some(percent(100.0)),
+ TimeValueType::Percentage,
+ );
+ let animation = AnimationPlayback {
+ start_time: Some(percent(0.0)).into(),
+ ..playing(1.0)
+ };
+ let resolved = resolved_at(&timing, &animation, &scroll_timeline(100.0));
+ assert_eq!(resolved.phase, AnimationEffectPhase::Active);
+ assert_eq!(transformed_progress(&timing, &resolved, &Easing::default()), Some(1.0));
+}
+
+#[test]
+fn the_active_time_fills_as_the_fill_mode_says() {
+ let timing = AnimationEffectTiming {
+ start_delay: ms(100.0),
+ ..one_second()
+ };
+ let at = |time: f64, fill_mode| {
+ let local_time = Some(ms(time));
+ let phase = phase(
+ &timing,
+ local_time,
+ AnimationDirection::Forwards,
+ false,
+ EndpointInclusiveActiveInterval::No,
+ );
+ active_time(&timing, phase, local_time, fill_mode)
+ };
+ assert_eq!(at(50.0, FillMode::None), None);
+ assert_eq!(at(50.0, FillMode::Auto), None);
+ assert_eq!(at(50.0, FillMode::Forwards), None);
+ assert_eq!(at(50.0, FillMode::Backwards), Some(ms(0.0)));
+ assert_eq!(at(600.0, FillMode::None), Some(ms(500.0)));
+ assert_eq!(at(1500.0, FillMode::Backwards), None);
+ assert_eq!(at(1500.0, FillMode::Both), Some(ms(1000.0)));
+}
+
+#[test]
+fn progress_follows_the_timeline_through_the_active_phase() {
+ let timing = one_second();
+ assert_eq!(progress_at(&timing, 250.0), Some(0.25));
+ assert_eq!(progress_at(&timing, 0.0), Some(0.0));
+ assert_eq!(progress_at(&timing, 1500.0), None, "no fill after the end");
+ assert_eq!(progress_at(&timing, -1.0), None, "no fill before the start");
+}
+
+#[test]
+fn progress_fills_at_the_ends() {
+ let timing = AnimationEffectTiming {
+ fill_mode: FillMode::Both,
+ ..one_second()
+ };
+ assert_eq!(progress_at(&timing, 1500.0), Some(1.0));
+ assert_eq!(progress_at(&timing, -500.0), Some(0.0));
+
+ let resolved = resolved_at(&timing, &playing(1.0), &document_timeline(1500.0));
+ assert_eq!(simple_iteration_progress(&timing, &resolved), Some(1.0));
+ assert_eq!(
+ current_iteration(&timing, &resolved),
+ Some(0.0),
+ "the last iteration ends at 1.0"
+ );
+}
+
+#[test]
+fn a_hold_time_wins_over_the_timeline() {
+ let animation = AnimationPlayback {
+ hold_time: Some(ms(500.0)).into(),
+ ..playing(1.0)
+ };
+ assert_eq!(current_time_at(&animation, Some(ms(1500.0))), Some(ms(500.0)));
+ assert_eq!(current_time_at(&playing(2.0), Some(ms(1500.0))), Some(ms(3000.0)));
+ assert_eq!(current_time_at(&playing(1.0), None), None);
+ assert_eq!(current_time_at(&AnimationPlayback::default(), Some(ms(1500.0))), None);
+}
+
+#[test]
+fn each_iteration_runs_in_its_direction() {
+ let mut timing = AnimationEffectTiming {
+ iteration_count: f64::INFINITY,
+ ..one_second()
+ };
+ assert_eq!(progress_at(&timing, 1250.0), Some(0.25));
+ timing.playback_direction = PlaybackDirection::Alternate;
+ assert_eq!(
+ progress_at(&timing, 1250.0),
+ Some(0.75),
+ "an alternate second iteration runs backwards"
+ );
+ timing.playback_direction = PlaybackDirection::AlternateReverse;
+ assert_eq!(progress_at(&timing, 1250.0), Some(0.25));
+ timing.playback_direction = PlaybackDirection::Reverse;
+ assert_eq!(progress_at(&timing, 1250.0), Some(0.75));
+}
+
+#[test]
+fn an_infinitely_iterating_effect_after_its_end_is_in_its_last_iteration() {
+ let timing = AnimationEffectTiming {
+ iteration_count: f64::INFINITY,
+ fill_mode: FillMode::Forwards,
+ playback_direction: PlaybackDirection::Alternate,
+ ..one_second()
+ };
+ let resolved = resolve_timing(&timing, Some(ms(-1.0)), Some(&playing(-1.0)), None);
+ assert_eq!(resolved.phase, AnimationEffectPhase::Before);
+ let after = ResolvedEffectTiming {
+ phase: AnimationEffectPhase::After,
+ local_time: Some(ms(f64::INFINITY)),
+ active_time: Some(ms(f64::INFINITY)),
+ overall_progress: Some(f64::INFINITY),
+ };
+ assert_eq!(current_iteration(&timing, &after), Some(f64::INFINITY));
+ assert_eq!(current_direction(&timing, &after), AnimationDirection::Forwards);
+}
+
+#[test]
+fn progress_is_eased_by_the_timing_function() {
+ let timing = one_second();
+ let resolved = resolved_at(&timing, &playing(1.0), &document_timeline(500.0));
+ let steps = Easing::Steps {
+ interval_count: 2,
+ position: STEP_POSITION_JUMP_START,
+ };
+ assert_eq!(transformed_progress(&timing, &resolved, &steps), Some(1.0));
+}
+
+#[test]
+fn the_before_flag_is_set_going_forwards_before_the_active_phase() {
+ let timing = AnimationEffectTiming {
+ start_delay: ms(100.0),
+ fill_mode: FillMode::Backwards,
+ ..one_second()
+ };
+ let resolved = resolved_at(&timing, &playing(1.0), &document_timeline(50.0));
+ let progress = transformed_progress_with(&timing, &resolved, |progress, before_flag| match before_flag {
+ true => -1.0,
+ false => progress,
+ });
+ assert_eq!(progress, Some(-1.0));
+}
+
+#[test]
+fn the_play_state_follows_the_playback() {
+ let end = ms(1000.0);
+ let idle = AnimationPlayback::default();
+ assert_eq!(play_state_at(&idle, None, end), AnimationPlayState::Idle);
+ let pending = AnimationPlayback {
+ has_pending_play_task: true,
+ ..idle
+ };
+ assert_eq!(play_state_at(&pending, None, end), AnimationPlayState::Running);
+ let paused = AnimationPlayback {
+ hold_time: Some(ms(500.0)).into(),
+ ..idle
+ };
+ assert_eq!(play_state_at(&paused, Some(ms(500.0)), end), AnimationPlayState::Paused);
+ assert_eq!(
+ play_state_at(&playing(1.0), Some(ms(500.0)), end),
+ AnimationPlayState::Running
+ );
+ assert_eq!(
+ play_state_at(&playing(1.0), Some(ms(1000.0)), end),
+ AnimationPlayState::Finished
+ );
+ assert_eq!(
+ play_state_at(&playing(-1.0), Some(ms(0.0)), end),
+ AnimationPlayState::Finished
+ );
+ let reversing = AnimationPlayback {
+ pending_playback_rate: Some(-1.0).into(),
+ ..playing(1.0)
+ };
+ assert_eq!(
+ play_state_at(&reversing, Some(ms(1000.0)), end),
+ AnimationPlayState::Running,
+ "the effective playback rate decides"
+ );
+}
+
+#[test]
+fn an_effect_is_current_while_it_will_play() {
+ let timing = AnimationEffectTiming {
+ start_delay: ms(1000.0),
+ ..one_second()
+ };
+ let current_at = |animation: &AnimationPlayback, timeline: &TimelineSample| {
+ let resolved = resolved_at(&timing, animation, timeline);
+ is_current(&timing, resolved.phase, Some(animation), Some(timeline))
+ };
+ assert!(
+ current_at(&playing(1.0), &document_timeline(500.0)),
+ "before, playing forwards"
+ );
+ assert!(current_at(&playing(1.0), &document_timeline(1500.0)), "in play");
+ assert!(
+ !current_at(&playing(1.0), &document_timeline(2500.0)),
+ "after, playing forwards"
+ );
+ let finished = AnimationPlayback {
+ is_finished: true,
+ ..playing(1.0)
+ };
+ assert!(!is_in_play(AnimationEffectPhase::Active, Some(&finished)));
+ assert!(!is_in_play(AnimationEffectPhase::Active, None));
+
+ let scrolled = scroll_timeline(80.0);
+ let on_scroll_timeline = normalize_specified_timing(
+ &SpecifiedEffectTiming {
+ iteration_duration: SpecifiedIterationDuration::milliseconds(1000.0),
+ end_delay: 1000.0,
+ ..SpecifiedEffectTiming::default()
+ },
+ Some(percent(100.0)),
+ TimeValueType::Percentage,
+ );
+ let animation = AnimationPlayback {
+ start_time: Some(percent(0.0)).into(),
+ ..playing(1.0)
+ };
+ let resolved = resolved_at(&on_scroll_timeline, &animation, &scrolled);
+ assert_eq!(resolved.phase, AnimationEffectPhase::After);
+ assert!(
+ is_current(&on_scroll_timeline, resolved.phase, Some(&animation), Some(&scrolled)),
+ "a running animation on a timeline that is not monotonically increasing"
+ );
+}
+
+#[test]
+fn a_relevant_animation_has_a_current_or_in_effect_effect_and_is_not_removed() {
+ let timing = one_second();
+ let timeline = document_timeline(2000.0);
+ let animation = playing(1.0);
+ let local_time = current_time_at(&animation, timeline.current_time.get());
+ assert!(!is_relevant(&animation, Some(&timeline), Some(&timing), local_time));
+ let filling = AnimationEffectTiming {
+ fill_mode: FillMode::Forwards,
+ ..timing
+ };
+ assert!(is_relevant(&animation, Some(&timeline), Some(&filling), local_time));
+ assert!(!is_relevant(&animation, Some(&timeline), None, local_time));
+ let removed = AnimationPlayback {
+ replace_state: AnimationReplaceState::Removed,
+ ..animation
+ };
+ assert!(!is_relevant(&removed, Some(&timeline), Some(&filling), local_time));
+}
diff --git a/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs b/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs
new file mode 100644
index 00000000000..cb999293e82
--- /dev/null
+++ b/Libraries/LibCompositing/Rust/src/animation_timing/time_value.rs
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Time values of the Web Animations timing model: a time in milliseconds, or a percentage of a
+//! progress-based timeline.
+
+use std::cmp::Ordering;
+use std::ops::{Add, Div, Mul, Neg, Sub};
+
+/// The unit of a time value.
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum TimeValueType {
+ #[default]
+ Milliseconds,
+ Percentage,
+}
+
+/// A time value. Arithmetic and ordering between values of different units are meaningless and
+/// panic; equality between them is false.
+///
+/// cbindgen:field-names=[type, value]
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct TimeValue {
+ pub r#type: TimeValueType,
+ pub value: f64,
+}
+
+impl TimeValue {
+ #[inline]
+ #[must_use]
+ pub const fn new(r#type: TimeValueType, value: f64) -> Self {
+ Self { r#type, value }
+ }
+
+ #[inline]
+ #[must_use]
+ pub const fn milliseconds(value: f64) -> Self {
+ Self::new(TimeValueType::Milliseconds, value)
+ }
+
+ #[inline]
+ #[must_use]
+ pub const fn percentage(value: f64) -> Self {
+ Self::new(TimeValueType::Percentage, value)
+ }
+
+ /// A zero time in `r#type`.
+ #[inline]
+ #[must_use]
+ pub const fn zero(r#type: TimeValueType) -> Self {
+ Self::new(r#type, 0.0)
+ }
+
+ #[inline]
+ fn assert_same_type(self, other: Self) {
+ assert!(
+ self.r#type == other.r#type,
+ "time values of different units: {self:?} and {other:?}"
+ );
+ }
+}
+
+impl Neg for TimeValue {
+ type Output = Self;
+ #[inline]
+ fn neg(self) -> Self {
+ Self::new(self.r#type, -self.value)
+ }
+}
+
+impl Add for TimeValue {
+ type Output = Self;
+ #[inline]
+ fn add(self, other: Self) -> Self {
+ self.assert_same_type(other);
+ Self::new(self.r#type, self.value + other.value)
+ }
+}
+
+impl Sub for TimeValue {
+ type Output = Self;
+ #[inline]
+ fn sub(self, other: Self) -> Self {
+ self.assert_same_type(other);
+ Self::new(self.r#type, self.value - other.value)
+ }
+}
+
+impl Mul<f64> for TimeValue {
+ type Output = Self;
+ #[inline]
+ fn mul(self, factor: f64) -> Self {
+ Self::new(self.r#type, self.value * factor)
+ }
+}
+
+impl Div<f64> for TimeValue {
+ type Output = Self;
+ #[inline]
+ fn div(self, divisor: f64) -> Self {
+ Self::new(self.r#type, self.value / divisor)
+ }
+}
+
+/// The ratio of two time values.
+impl Div for TimeValue {
+ type Output = f64;
+ #[inline]
+ fn div(self, other: Self) -> f64 {
+ self.assert_same_type(other);
+ self.value / other.value
+ }
+}
+
+impl PartialOrd for TimeValue {
+ /// Values neither less nor greater than each other, which includes a NaN against anything,
+ /// order equal.
+ #[inline]
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ self.assert_same_type(*other);
+ Some(if self.value < other.value {
+ Ordering::Less
+ } else if self.value > other.value {
+ Ordering::Greater
+ } else {
+ Ordering::Equal
+ })
+ }
+}
+
+/// The larger of two values, keeping `a` where neither is less.
+#[inline]
+#[must_use]
+pub fn max<T: PartialOrd>(a: T, b: T) -> T {
+ if a < b { b } else { a }
+}
+
+/// The smaller of two values, keeping `a` where neither is less.
+#[inline]
+#[must_use]
+pub fn min<T: PartialOrd>(a: T, b: T) -> T {
+ if b < a { b } else { a }
+}
+
+/// A time value that may be unresolved.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct OptionalTimeValue {
+ pub value: TimeValue,
+ pub has_value: bool,
+}
+
+impl OptionalTimeValue {
+ pub const UNRESOLVED: Self = Self {
+ value: TimeValue::milliseconds(0.0),
+ has_value: false,
+ };
+
+ #[inline]
+ #[must_use]
+ pub fn get(self) -> Option<TimeValue> {
+ self.has_value.then_some(self.value)
+ }
+}
+
+impl From<Option<TimeValue>> for OptionalTimeValue {
+ #[inline]
+ fn from(value: Option<TimeValue>) -> Self {
+ match value {
+ Some(value) => Self { value, has_value: true },
+ None => Self::UNRESOLVED,
+ }
+ }
+}
+
+impl From<OptionalTimeValue> for Option<TimeValue> {
+ #[inline]
+ fn from(value: OptionalTimeValue) -> Self {
+ value.get()
+ }
+}
+
+/// A number that may be unresolved.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct OptionalNumber {
+ pub value: f64,
+ pub has_value: bool,
+}
+
+impl OptionalNumber {
+ #[inline]
+ #[must_use]
+ pub fn get(self) -> Option<f64> {
+ self.has_value.then_some(self.value)
+ }
+}
+
+impl From<Option<f64>> for OptionalNumber {
+ #[inline]
+ fn from(value: Option<f64>) -> Self {
+ Self {
+ value: value.unwrap_or(0.0),
+ has_value: value.is_some(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn arithmetic_keeps_the_unit() {
+ let a = TimeValue::percentage(30.0);
+ let b = TimeValue::percentage(10.0);
+ assert_eq!(a + b, TimeValue::percentage(40.0));
+ assert_eq!(a - b, TimeValue::percentage(20.0));
+ assert_eq!(a * 2.0, TimeValue::percentage(60.0));
+ assert_eq!(a / 2.0, TimeValue::percentage(15.0));
+ assert_eq!(a / b, 3.0);
+ assert_eq!(-a, TimeValue::percentage(-30.0));
+ }
+
+ #[test]
+ #[should_panic(expected = "different units")]
+ fn mixed_unit_arithmetic_panics() {
+ let _ = TimeValue::percentage(30.0) + TimeValue::milliseconds(10.0);
+ }
+
+ #[test]
+ #[should_panic(expected = "different units")]
+ fn mixed_unit_ordering_panics() {
+ let _ = TimeValue::percentage(30.0) < TimeValue::milliseconds(10.0);
+ }
+
+ #[test]
+ fn mixed_unit_values_are_not_equal() {
+ assert_ne!(TimeValue::percentage(0.0), TimeValue::milliseconds(0.0));
+ }
+
+ #[test]
+ fn nan_orders_equal_and_max_keeps_the_first() {
+ let nan = TimeValue::milliseconds(f64::NAN);
+ let zero = TimeValue::milliseconds(0.0);
+ assert!(nan <= zero && nan >= zero);
+ assert!(max(nan, zero).value.is_nan());
+ assert_eq!(max(zero, nan), zero);
+ assert!(max(f64::NAN, 0.0).is_nan());
+ assert_eq!(min(1.0, 2.0), 1.0);
+ }
+
+ #[test]
+ fn optionals_round_trip() {
+ let time = TimeValue::milliseconds(5.0);
+ assert_eq!(OptionalTimeValue::from(Some(time)).get(), Some(time));
+ assert_eq!(OptionalTimeValue::from(None).get(), None);
+ assert_eq!(OptionalNumber::from(Some(2.5)).get(), Some(2.5));
+ assert_eq!(OptionalNumber::from(None).get(), None);
+ }
+}
diff --git a/Libraries/LibCompositing/Rust/src/lib.rs b/Libraries/LibCompositing/Rust/src/lib.rs
index d0f4d6aa8ac..7ad06a79922 100644
--- a/Libraries/LibCompositing/Rust/src/lib.rs
+++ b/Libraries/LibCompositing/Rust/src/lib.rs
@@ -13,6 +13,7 @@ mod rust_demangle;
#[path = "../../../RustPanic.rs"]
mod rust_panic;
+pub mod animation_timing;
pub mod css_pixels;
pub mod display_list;
pub mod easing;
diff --git a/Libraries/LibCompositing/Rust/src/visual_animation.rs b/Libraries/LibCompositing/Rust/src/visual_animation.rs
index 90b9ff462f7..4ab84e555a0 100644
--- a/Libraries/LibCompositing/Rust/src/visual_animation.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_animation.rs
@@ -9,13 +9,14 @@
//! description at a point in time, which both the compositor and the main thread's intersection
//! observations run.
+use crate::animation_timing::{
+ self, AnimationDirection, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayback, FillMode,
+ OptionalTimeValue, TimeValue, TimeValueType,
+};
use crate::easing::Easing;
use crate::filter_bytes::filter_functions_graph;
use crate::filter_bytes::{FfiFilterFunction, FfiFilterFunctionKind};
-use crate::host::{
- FfiVisualAnimationFillMode, FfiVisualAnimationPlaybackDirection, FfiVisualAnimationTargetKind,
- FfiVisualAnimationTransformOperationKind,
-};
+use crate::host::{FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind};
use ak::math;
use libgfx_rust::filter::Filter;
use libgfx_rust::{Color, ColorFilterType, FloatMatrix4x4, rotation_matrix, scale_matrix, translation_matrix};
@@ -34,28 +35,6 @@ impl FfiVisualAnimationTargetKind {
}
}
-impl FfiVisualAnimationPlaybackDirection {
- pub fn from_u8(value: u8) -> Option<Self> {
- match value {
- 0 => Some(Self::Normal),
- 1 => Some(Self::Reverse),
- 2 => Some(Self::Alternate),
- 3 => Some(Self::AlternateReverse),
- _ => None,
- }
- }
-}
-
-impl FfiVisualAnimationFillMode {
- pub fn from_u8(value: u8) -> Option<Self> {
- match value {
- 0 => Some(Self::None),
- 1 => Some(Self::Backwards),
- _ => None,
- }
- }
-}
-
impl FfiVisualAnimationTransformOperationKind {
pub fn from_u8(value: u8) -> Option<Self> {
Some(match value {
@@ -375,12 +354,8 @@ pub struct VisualAnimation {
pub monotonic_time_at_anchor_ns: i64,
pub local_time_at_anchor_ms: f64,
pub playback_rate: f64,
- pub start_delay_ms: f64,
- pub iteration_duration_ms: f64,
- pub iteration_count: f64,
- pub iteration_start: f64,
- pub playback_direction: FfiVisualAnimationPlaybackDirection,
- pub fill_mode: FfiVisualAnimationFillMode,
+ /// The effect's timing, every time in milliseconds.
+ pub timing: AnimationEffectTiming,
pub easing: Easing,
pub keyframes: Vec<VisualAnimationKeyframe>,
}
@@ -393,12 +368,11 @@ impl Default for VisualAnimation {
monotonic_time_at_anchor_ns: 0,
local_time_at_anchor_ms: 0.0,
playback_rate: 1.0,
- start_delay_ms: 0.0,
- iteration_duration_ms: 0.0,
- iteration_count: f64::INFINITY,
- iteration_start: 0.0,
- playback_direction: FfiVisualAnimationPlaybackDirection::Normal,
- fill_mode: FfiVisualAnimationFillMode::None,
+ timing: AnimationEffectTiming {
+ iteration_count: f64::INFINITY,
+ fill_mode: FillMode::None,
+ ..AnimationEffectTiming::default()
+ },
easing: Easing::default(),
keyframes: Vec::new(),
}
@@ -424,29 +398,32 @@ impl VisualAnimation {
self.local_time_ms_after(self.elapsed_since_anchor_ns(sample_time_ns))
}
- /// The local time the active phase of a finite animation ends at.
- pub fn active_end_ms(&self) -> f64 {
- self.start_delay_ms + self.iteration_duration_ms * self.iteration_count
+ /// Whether the animation runs a finite number of iterations, and so reaches an end.
+ #[inline]
+ pub fn is_finite(&self) -> bool {
+ self.timing.iteration_count.is_finite()
+ }
+
+ /// The phase of the effect at `local_time`, in milliseconds. The compositor runs an animation forwards only.
+ fn phase_at(&self, local_time: f64) -> AnimationEffectPhase {
+ animation_timing::phase(
+ &self.timing,
+ Some(TimeValue::milliseconds(local_time)),
+ AnimationDirection::Forwards,
+ false,
+ animation_timing::EndpointInclusiveActiveInterval::No,
+ )
}
/// Whether the animation is in its active phase, or its timing cannot be told.
pub fn is_active_at(&self, sample_time_ns: i64) -> bool {
let local_time = self.local_time_ms_at(sample_time_ns);
- if !local_time.is_finite() {
- return true;
- }
- if local_time < self.start_delay_ms {
- return false;
- }
- if !self.iteration_count.is_finite() {
- return true;
- }
- local_time < self.active_end_ms()
+ !local_time.is_finite() || self.phase_at(local_time) == AnimationEffectPhase::Active
}
/// Whether a finite animation has reached the end of its active phase.
pub fn has_finished_at(&self, sample_time_ns: i64) -> bool {
- self.iteration_count.is_finite() && self.local_time_ms_at(sample_time_ns) >= self.active_end_ms()
+ self.is_finite() && self.phase_at(self.local_time_ms_at(sample_time_ns)) == AnimationEffectPhase::After
}
pub fn is_valid(&self) -> bool {
@@ -459,31 +436,29 @@ impl VisualAnimation {
pub fn has_same_animation_parameters(&self, other: &Self) -> bool {
self.target_kind == other.target_kind
&& self.playback_rate == other.playback_rate
- && self.start_delay_ms == other.start_delay_ms
- && self.iteration_duration_ms == other.iteration_duration_ms
- && self.iteration_count == other.iteration_count
- && self.iteration_start == other.iteration_start
- && self.playback_direction == other.playback_direction
- && self.fill_mode == other.fill_mode
+ && self.timing == other.timing
&& self.easing == other.easing
&& self.keyframes == other.keyframes
}
- /// Whether the timing and keyframes describe an animation that can be sampled: positive
- /// durations and rates, keyframes from offset 0 to offset 1 in increasing order, and values of
- /// the target kind that interpolate with each other.
+ /// Whether the timing and keyframes describe an animation that can be sampled: times in
+ /// milliseconds, positive durations and rates, keyframes from offset 0 to offset 1 in increasing
+ /// order, and values of the target kind that interpolate with each other.
pub fn has_valid_parameters(&self) -> bool {
+ let timing = &self.timing;
+ let in_milliseconds = |time: TimeValue| time.r#type == TimeValueType::Milliseconds && time.value.is_finite();
if self.monotonic_time_at_anchor_ns < 0
|| !self.local_time_at_anchor_ms.is_finite()
|| !self.playback_rate.is_finite()
|| self.playback_rate <= 0.0
- || !self.start_delay_ms.is_finite()
- || !self.iteration_duration_ms.is_finite()
- || self.iteration_duration_ms <= 0.0
- || self.iteration_count.is_nan()
- || self.iteration_count <= 0.0
- || !self.iteration_start.is_finite()
- || self.iteration_start < 0.0
+ || !in_milliseconds(timing.start_delay)
+ || !in_milliseconds(timing.end_delay)
+ || !in_milliseconds(timing.iteration_duration)
+ || timing.iteration_duration.value <= 0.0
+ || timing.iteration_count.is_nan()
+ || timing.iteration_count <= 0.0
+ || !timing.iteration_start.is_finite()
+ || timing.iteration_start < 0.0
|| !self.easing.is_valid()
|| self.keyframes.len() < 2
{
@@ -552,53 +527,37 @@ impl VisualAnimation {
/// The value at `elapsed_ns` after the anchor, or none while the animation is dormant, once
/// its timing cannot be resolved, or when the interpolated value is not representable.
pub fn sample(&self, elapsed_ns: i64) -> Option<VisualAnimationSample> {
- if self.iteration_duration_ms <= 0.0 || self.playback_rate <= 0.0 || self.keyframes.len() < 2 {
+ if self.playback_rate <= 0.0 || self.keyframes.len() < 2 {
return None;
}
- let mut local_time = self.local_time_ms_after(elapsed_ns);
+ let local_time = self.local_time_ms_after(elapsed_ns);
if !local_time.is_finite() {
return None;
}
- let is_in_before_phase = local_time < self.start_delay_ms;
- if is_in_before_phase {
- if self.fill_mode != FfiVisualAnimationFillMode::Backwards {
- return None;
- }
- local_time = self.start_delay_ms;
- }
- let overall_progress = (local_time - self.start_delay_ms) / self.iteration_duration_ms + self.iteration_start;
- if !overall_progress.is_finite() || overall_progress < 0.0 {
- return None;
- }
-
- let active_progress = overall_progress - self.iteration_start;
- let is_at_or_after_end = self.iteration_count.is_finite() && active_progress >= self.iteration_count;
- let mut current_iteration = overall_progress.floor();
- let mut simple_iteration_progress = overall_progress % 1.0;
- if is_at_or_after_end {
- let terminal_overall_progress = self.iteration_start + self.iteration_count;
- simple_iteration_progress = terminal_overall_progress % 1.0;
- if simple_iteration_progress == 0.0 {
- simple_iteration_progress = 1.0;
- }
- current_iteration =
- terminal_overall_progress.floor() - if simple_iteration_progress == 1.0 { 1.0 } else { 0.0 };
- }
- let going_forwards = match self.playback_direction {
- FfiVisualAnimationPlaybackDirection::Normal => true,
- FfiVisualAnimationPlaybackDirection::Reverse => false,
- FfiVisualAnimationPlaybackDirection::Alternate => current_iteration % 2.0 == 0.0,
- FfiVisualAnimationPlaybackDirection::AlternateReverse => (current_iteration + 1.0) % 2.0 == 0.0,
+ // The compositor runs the animation at its playback rate from where the main thread anchored it, which holds
+ // its local time.
+ let local_time = Some(TimeValue::milliseconds(local_time));
+ let playback = AnimationPlayback {
+ hold_time: OptionalTimeValue::from(local_time),
+ playback_rate: self.playback_rate,
+ ..AnimationPlayback::default()
};
-
- let directed_progress = if going_forwards {
- simple_iteration_progress
- } else {
- 1.0 - simple_iteration_progress
+ // NB: The compositor knows nothing of the value beneath the effect, which an effect that does not fill
+ // forwards shows once it ends. The main thread takes the animation off the compositor at its end, and until
+ // its next frame shows that value, the compositor holds the value at the end.
+ let presented_fill_mode = match self.timing.fill_mode {
+ FillMode::None | FillMode::Forwards | FillMode::Auto => FillMode::Forwards,
+ FillMode::Backwards | FillMode::Both => FillMode::Both,
};
- let before_flag = (is_in_before_phase && going_forwards) || (is_at_or_after_end && !going_forwards);
- let transformed_progress = self.easing.evaluate_at(directed_progress, before_flag);
+ let resolved = animation_timing::resolve_timing_using_fill(
+ &self.timing,
+ local_time,
+ Some(&playback),
+ None,
+ presented_fill_mode,
+ );
+ let transformed_progress = animation_timing::transformed_progress(&self.timing, &resolved, &self.easing)?;
if !transformed_progress.is_finite() {
return None;
}
@@ -657,6 +616,7 @@ impl VisualAnimation {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::animation_timing::PlaybackDirection;
use crate::easing::FfiLinearEasingPoint;
use FfiVisualAnimationTransformOperationKind as TransformKind;
@@ -719,7 +679,10 @@ mod tests {
let animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 250.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.0),
opacity_keyframe(1.0, Easing::default(), 1.0),
@@ -743,7 +706,10 @@ mod tests {
let mut animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 100.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, overshooting_easing, 0.0),
opacity_keyframe(1.0, Easing::default(), 1.0),
@@ -761,8 +727,11 @@ mod tests {
let animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 250.0,
- iteration_duration_ms: 1000.0,
- playback_direction: FfiVisualAnimationPlaybackDirection::AlternateReverse,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ playback_direction: PlaybackDirection::AlternateReverse,
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, steps(4, 1), 0.0),
opacity_keyframe(1.0, Easing::default(), 1.0),
@@ -779,8 +748,11 @@ mod tests {
let mut animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 900.0,
- iteration_duration_ms: 1000.0,
- iteration_count: 1.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ iteration_count: 1.0,
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.0),
opacity_keyframe(1.0, Easing::default(), 1.0),
@@ -789,9 +761,9 @@ mod tests {
};
assert_approximately(opacity_of(animation.sample(milliseconds(200))), 1.0);
- animation.playback_direction = FfiVisualAnimationPlaybackDirection::Reverse;
+ animation.timing.playback_direction = PlaybackDirection::Reverse;
assert_approximately(opacity_of(animation.sample(milliseconds(200))), 0.0);
- animation.iteration_start = 0.5;
+ animation.timing.iteration_start = 0.5;
assert_approximately(opacity_of(animation.sample(milliseconds(200))), 0.5);
}
@@ -800,7 +772,10 @@ mod tests {
let animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 500.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.0),
opacity_keyframe(0.5, steps(4, 0), 0.5),
@@ -818,7 +793,10 @@ mod tests {
target_kind: FfiVisualAnimationTargetKind::Transform,
node_indices: vec![0],
local_time_at_anchor_ms: 500.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
keyframe(
0.0,
@@ -853,7 +831,10 @@ mod tests {
target_kind: FfiVisualAnimationTargetKind::BackgroundColor,
node_indices: vec![0],
local_time_at_anchor_ms: 500.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
keyframe(
0.0,
@@ -880,7 +861,10 @@ mod tests {
target_kind: FfiVisualAnimationTargetKind::BackgroundColor,
node_indices: vec![0],
local_time_at_anchor_ms: 750.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
easing: Easing::Linear(vec![
FfiLinearEasingPoint {
input: 0.0,
@@ -963,7 +947,10 @@ mod tests {
target_kind: FfiVisualAnimationTargetKind::Filter,
node_indices: vec![0],
local_time_at_anchor_ms: 750.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
VisualAnimationKeyframe {
offset: 0.0,
@@ -1003,7 +990,10 @@ mod tests {
target_kind: FfiVisualAnimationTargetKind::Filter,
node_indices: vec![0],
local_time_at_anchor_ms: 500.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
keyframe(0.0, VisualAnimationValue::Filter(vec![opacity(1.0)])),
keyframe(1.0, VisualAnimationValue::Filter(vec![opacity(0.0)])),
@@ -1040,8 +1030,11 @@ mod tests {
let mut animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 50.0,
- start_delay_ms: 100.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(100.0),
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.25),
opacity_keyframe(1.0, Easing::default(), 0.75),
@@ -1050,7 +1043,7 @@ mod tests {
};
assert!(animation.sample(0).is_none());
- animation.fill_mode = FfiVisualAnimationFillMode::Backwards;
+ animation.timing.fill_mode = FillMode::Backwards;
assert_approximately(opacity_of(animation.sample(0)), 0.25);
assert_approximately(opacity_of(animation.sample(milliseconds(550))), 0.5);
}
@@ -1061,9 +1054,12 @@ mod tests {
let mut animation = VisualAnimation {
node_indices: vec![0],
local_time_at_anchor_ms: 50.0,
- start_delay_ms: 100.0,
- iteration_duration_ms: 1000.0,
- fill_mode: FfiVisualAnimationFillMode::Backwards,
+ timing: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(100.0),
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ fill_mode: FillMode::Backwards,
+ ..VisualAnimation::default().timing
+ },
easing: jump_start.clone(),
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.0),
@@ -1084,9 +1080,12 @@ mod tests {
let animation = VisualAnimation {
node_indices: vec![0],
monotonic_time_at_anchor_ns: milliseconds(1000),
- start_delay_ms: 100.0,
- iteration_duration_ms: 1000.0,
- iteration_count: 2.0,
+ timing: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(100.0),
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ iteration_count: 2.0,
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.0),
opacity_keyframe(1.0, Easing::default(), 1.0),
@@ -1104,7 +1103,10 @@ mod tests {
assert!(animation.has_finished_at(milliseconds(3100)));
let endless = VisualAnimation {
- iteration_count: f64::INFINITY,
+ timing: AnimationEffectTiming {
+ iteration_count: f64::INFINITY,
+ ..animation.timing
+ },
..animation
};
assert!(endless.is_active_at(milliseconds(1_000_000)));
@@ -1115,7 +1117,10 @@ mod tests {
fn parameter_validation_covers_timing_and_keyframes() {
let valid = VisualAnimation {
node_indices: vec![0],
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
opacity_keyframe(0.0, Easing::default(), 0.0),
opacity_keyframe(0.5, Easing::default(), 0.5),
@@ -1139,11 +1144,26 @@ mod tests {
..valid.clone()
},
VisualAnimation {
- iteration_count: f64::NAN,
+ timing: AnimationEffectTiming {
+ iteration_count: f64::NAN,
+ ..valid.timing
+ },
+ ..valid.clone()
+ },
+ VisualAnimation {
+ timing: AnimationEffectTiming {
+ iteration_start: -1.0,
+ ..valid.timing
+ },
..valid.clone()
},
VisualAnimation {
- iteration_start: -1.0,
+ timing: AnimationEffectTiming {
+ start_delay: TimeValue::percentage(0.0),
+ end_delay: TimeValue::percentage(0.0),
+ iteration_duration: TimeValue::percentage(100.0),
+ ..valid.timing
+ },
..valid.clone()
},
VisualAnimation {
diff --git a/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs b/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs
index 7b03910fd27..fd5c6e5a378 100644
--- a/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_context/ffi_types.rs
@@ -34,22 +34,6 @@ pub enum FfiVisualAnimationTargetKind {
Transform,
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum FfiVisualAnimationPlaybackDirection {
- Normal,
- Reverse,
- Alternate,
- AlternateReverse,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum FfiVisualAnimationFillMode {
- None,
- Backwards,
-}
-
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum FfiVisualAnimationTransformOperationKind {
diff --git a/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs b/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs
index 5881924b775..8b8bbc725a3 100644
--- a/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_context/serialize.rs
@@ -14,13 +14,11 @@ use super::{
CompositorScrollNodeKind, CompositorScrollNodeRecord, CompositorScrollTable, CompositorSnapAreaRecord,
CompositorSnapContainerRecord,
};
+use crate::animation_timing::{AnimationEffectTiming, FillMode, PlaybackDirection, TimeValue, TimeValueType};
use crate::css_pixels::{CssPixels, FfiCssPixelPoint, FfiCssPixelRect};
use crate::easing::{Easing, FfiEasingKind, FfiLinearEasingPoint};
use crate::filter_bytes::{FfiFilterFunction, FfiFilterFunctionKind};
-use crate::host::{
- FfiVisualAnimationFillMode, FfiVisualAnimationPlaybackDirection, FfiVisualAnimationTargetKind,
- FfiVisualAnimationTransformOperationKind,
-};
+use crate::host::{FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind};
use crate::node_slot_id::NodeSlotId;
use crate::visual_animation::{
MAXIMUM_TRANSFORM_OPERATION_VALUE_COUNT, VisualAnimation, VisualAnimationKeyframe,
@@ -112,11 +110,13 @@ impl_codec_of_enum_going_as_u8!(CompositorScrollNodeKind, |value| match value {
impl_codec_of_enum_going_as_u8!(FfiEasingKind, FfiEasingKind::from_u8);
impl_codec_of_enum_going_as_u8!(FfiFilterFunctionKind, FfiFilterFunctionKind::from_u8);
impl_codec_of_enum_going_as_u8!(FfiVisualAnimationTargetKind, FfiVisualAnimationTargetKind::from_u8);
-impl_codec_of_enum_going_as_u8!(
- FfiVisualAnimationPlaybackDirection,
- FfiVisualAnimationPlaybackDirection::from_u8
-);
-impl_codec_of_enum_going_as_u8!(FfiVisualAnimationFillMode, FfiVisualAnimationFillMode::from_u8);
+impl_codec_of_enum_going_as_u8!(PlaybackDirection, |value| PlaybackDirection::try_from(value).ok());
+impl_codec_of_enum_going_as_u8!(FillMode, |value| FillMode::try_from(value).ok());
+impl_codec_of_enum_going_as_u8!(TimeValueType, |value| match value {
+ value if value == TimeValueType::Milliseconds as u8 => Some(TimeValueType::Milliseconds),
+ value if value == TimeValueType::Percentage as u8 => Some(TimeValueType::Percentage),
+ _ => None,
+});
impl_codec_of_enum_going_as_u8!(
FfiVisualAnimationTransformOperationKind,
FfiVisualAnimationTransformOperationKind::from_u8
@@ -712,6 +712,52 @@ impl Decode for VisualAnimationKeyframe {
}
}
+impl Encode for TimeValue {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.encode(&self.r#type)?;
+ encoder.encode(&self.value)
+ }
+}
+
+impl Decode for TimeValue {
+ const MIN_ENCODED_SIZE: usize = TimeValueType::MIN_ENCODED_SIZE + size_of::<f64>();
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Ok(Self::new(decoder.decode()?, decoder.decode()?))
+ }
+}
+
+impl Encode for AnimationEffectTiming {
+ fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
+ encoder.encode(&self.start_delay)?;
+ encoder.encode(&self.end_delay)?;
+ encoder.encode(&self.iteration_duration)?;
+ encoder.encode(&self.iteration_start)?;
+ encoder.encode(&self.iteration_count)?;
+ encoder.encode(&self.fill_mode)?;
+ encoder.encode(&self.playback_direction)
+ }
+}
+
+impl Decode for AnimationEffectTiming {
+ const MIN_ENCODED_SIZE: usize = 3 * TimeValue::MIN_ENCODED_SIZE
+ + 2 * size_of::<f64>()
+ + FillMode::MIN_ENCODED_SIZE
+ + PlaybackDirection::MIN_ENCODED_SIZE;
+
+ fn decode(decoder: &mut Decoder<'_>) -> Result<Self, DecodeError> {
+ Ok(Self {
+ start_delay: decoder.decode()?,
+ end_delay: decoder.decode()?,
+ iteration_duration: decoder.decode()?,
+ iteration_start: decoder.decode()?,
+ iteration_count: decoder.decode()?,
+ fill_mode: decoder.decode()?,
+ playback_direction: decoder.decode()?,
+ })
+ }
+}
+
impl Encode for VisualAnimation {
fn encode(&self, encoder: &mut Encoder) -> Result<(), EncodeError> {
encoder.encode(&self.target_kind)?;
@@ -719,12 +765,7 @@ impl Encode for VisualAnimation {
encoder.encode(&self.monotonic_time_at_anchor_ns)?;
encoder.encode(&self.local_time_at_anchor_ms)?;
encoder.encode(&self.playback_rate)?;
- encoder.encode(&self.start_delay_ms)?;
- encoder.encode(&self.iteration_duration_ms)?;
- encoder.encode(&self.iteration_count)?;
- encoder.encode(&self.iteration_start)?;
- encoder.encode(&self.playback_direction)?;
- encoder.encode(&self.fill_mode)?;
+ encoder.encode(&self.timing)?;
encoder.encode(&self.easing)?;
encoder.encode(&self.keyframes)
}
@@ -740,12 +781,7 @@ impl Decode for VisualAnimation {
monotonic_time_at_anchor_ns: decoder.decode()?,
local_time_at_anchor_ms: decoder.decode()?,
playback_rate: decoder.decode()?,
- start_delay_ms: decoder.decode()?,
- iteration_duration_ms: decoder.decode()?,
- iteration_count: decoder.decode()?,
- iteration_start: decoder.decode()?,
- playback_direction: decoder.decode()?,
- fill_mode: decoder.decode()?,
+ timing: decoder.decode()?,
easing: decoder.decode()?,
keyframes: decoder.decode()?,
})
@@ -1289,12 +1325,15 @@ mod tests {
monotonic_time_at_anchor_ns: 1_000_000,
local_time_at_anchor_ms: 2.5,
playback_rate: 1.5,
- start_delay_ms: 3.0,
- iteration_duration_ms: 400.0,
- iteration_count: f64::INFINITY,
- iteration_start: 0.25,
- playback_direction: FfiVisualAnimationPlaybackDirection::Alternate,
- fill_mode: FfiVisualAnimationFillMode::Backwards,
+ timing: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(3.0),
+ iteration_duration: TimeValue::milliseconds(400.0),
+ iteration_count: f64::INFINITY,
+ iteration_start: 0.25,
+ playback_direction: PlaybackDirection::Alternate,
+ fill_mode: FillMode::Backwards,
+ ..VisualAnimation::default().timing
+ },
easing: Easing::CubicBezier {
x1: 0.1,
y1: 0.2,
@@ -1317,8 +1356,11 @@ mod tests {
VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::BackgroundColor,
node_indices: vec![background_color_animation.0],
- iteration_duration_ms: 100.0,
- iteration_count: 2.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(100.0),
+ iteration_count: 2.0,
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
animation_keyframe(
0.0,
@@ -1336,7 +1378,10 @@ mod tests {
VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Filter,
node_indices: vec![root_effect.0],
- iteration_duration_ms: 100.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(100.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
animation_keyframe(0.0, Easing::default(), VisualAnimationValue::Filter(Vec::new())),
animation_keyframe(
@@ -1367,7 +1412,10 @@ mod tests {
VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Transform,
node_indices: vec![VISUAL_VIEWPORT_NODE_INDEX.0],
- iteration_duration_ms: 100.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(100.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
animation_keyframe(0.0, Easing::default(), translate_and_rotate(0.0, 0.0, 0.0)),
animation_keyframe(1.0, Easing::default(), translate_and_rotate(1.0, 2.0, 3.0)),
@@ -1791,7 +1839,10 @@ mod tests {
..valid.clone()
});
rejected(VisualAnimation {
- iteration_duration_ms: 0.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(0.0),
+ ..valid.timing
+ },
..valid.clone()
});
rejected(VisualAnimation {
diff --git a/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs b/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs
index e2312c63401..cf9192f64b6 100644
--- a/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs
+++ b/Libraries/LibCompositing/Rust/src/visual_context/visual_animations.rs
@@ -183,7 +183,7 @@ impl VisualContextTree {
all_running_animations_are_bounded: true,
};
for animation in self.visual_animations.iter() {
- if animation.iteration_count.is_finite() {
+ if animation.is_finite() {
if animation.has_finished_at(sample_time_ns) {
extents.has_finished_animation = true;
continue;
@@ -226,6 +226,7 @@ fn only_rotates_in_the_plane(keyframe: &crate::visual_animation::VisualAnimation
#[cfg(test)]
mod tests {
use super::*;
+ use crate::animation_timing::{AnimationEffectTiming, TimeValue};
use crate::easing::Easing;
use crate::visual_animation::{VisualAnimationKeyframe, VisualAnimationTransformOperation};
use crate::visual_context::{
@@ -287,14 +288,20 @@ mod tests {
VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Transform,
node_indices: vec![spatial.0],
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![keyframe(0.0, translate_x(0.0)), keyframe(1.0, translate_x(20.0))],
..VisualAnimation::default()
},
VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Opacity,
node_indices: vec![effect.0],
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
keyframe(0.0, VisualAnimationValue::Opacity(0.0)),
keyframe(1.0, VisualAnimationValue::Opacity(1.0)),
@@ -334,8 +341,11 @@ mod tests {
tree.set_visual_animations(vec![VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Transform,
node_indices: vec![spatial.0],
- start_delay_ms: 1000.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(1000.0),
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![keyframe(0.0, translate_x(0.0)), keyframe(1.0, translate_x(20.0))],
..VisualAnimation::default()
}]);
@@ -363,8 +373,11 @@ mod tests {
tree.set_visual_animations(vec![VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Transform,
node_indices: vec![spatial.0],
- iteration_duration_ms: 10000.0,
- iteration_count: 1.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(10000.0),
+ iteration_count: 1.0,
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![keyframe(0.0, translate_x(0.0)), keyframe(1.0, translate_x(-1500.0))],
..VisualAnimation::default()
}]);
@@ -398,7 +411,10 @@ mod tests {
node_indices: vec![spatial.0],
monotonic_time_at_anchor_ns: 10,
local_time_at_anchor_ms: 20.0,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![keyframe(0.0, translate_x(0.0)), keyframe(1.0, translate_x(20.0))],
..VisualAnimation::default()
};
@@ -447,15 +463,21 @@ mod tests {
let rotation = VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Transform,
node_indices: vec![rotated.0],
- iteration_duration_ms: 1000.0,
- iteration_count: 1.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ iteration_count: 1.0,
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![keyframe(0.0, rotate(0.0)), keyframe(1.0, rotate(1.0))],
..VisualAnimation::default()
};
let opacity = VisualAnimation {
target_kind: FfiVisualAnimationTargetKind::Opacity,
node_indices: vec![effect.0],
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
keyframe(0.0, VisualAnimationValue::Opacity(0.0)),
keyframe(1.0, VisualAnimationValue::Opacity(1.0)),
diff --git a/Libraries/LibWeb/Animations/Animation.cpp b/Libraries/LibWeb/Animations/Animation.cpp
index 006967b46fe..1805b4dc83d 100644
--- a/Libraries/LibWeb/Animations/Animation.cpp
+++ b/Libraries/LibWeb/Animations/Animation.cpp
@@ -655,30 +655,11 @@ Optional<TimeValue> Animation::current_time_for_observation() const
return current_time_at(m_timeline ? m_timeline->current_time_for_observation() : Optional<TimeValue> {});
}
+// https://www.w3.org/TR/web-animations-1/#animation-current-time
Optional<TimeValue> Animation::current_time_at(Optional<TimeValue> timeline_time) const
{
- // The current time is calculated from the first matching condition from below:
-
- // -> If the animation’s hold time is resolved,
- if (m_hold_time.has_value()) {
- // The current time is the animation’s hold time.
- return m_hold_time.value();
- }
-
- // -> If any of the following are true:
- // - the animation has no associated timeline, or
- // - the associated timeline is inactive, or
- // - the animation’s start time is unresolved.
- if (!m_timeline || !timeline_time.has_value() || !m_start_time.has_value()) {
- // The current time is an unresolved time value.
- return {};
- }
-
- // -> Otherwise,
- // current time = (timeline time - start time) × playback rate
- // Where timeline time is the current time value of the associated timeline. The playback rate value is defined
- // in §4.4.15 Speed control.
- return (timeline_time.value() - m_start_time.value()) * playback_rate();
+ auto playback = this->playback();
+ return from_ffi(RustFFI::animations_current_time_at(&playback, to_ffi(m_timeline ? timeline_time : Optional<TimeValue> {})));
}
NullableCSSNumberish Animation::current_time_for_bindings() const
@@ -771,40 +752,17 @@ AnimationPlayState Animation::play_state() const
return play_state_at(current_time());
}
+static_assert(to_underlying(AnimationPlayState::Idle) == to_underlying(RustFFI::AnimationPlayState::Idle));
+static_assert(to_underlying(AnimationPlayState::Running) == to_underlying(RustFFI::AnimationPlayState::Running));
+static_assert(to_underlying(AnimationPlayState::Paused) == to_underlying(RustFFI::AnimationPlayState::Paused));
+static_assert(to_underlying(AnimationPlayState::Finished) == to_underlying(RustFFI::AnimationPlayState::Finished));
+
+// https://www.w3.org/TR/web-animations-1/#play-states
AnimationPlayState Animation::play_state_at(Optional<TimeValue> current_time) const
{
- // The play state of animation, animation, at a given moment is the state corresponding to the first matching
- // condition from the following:
-
- // -> All of the following conditions are true:
- // - The current time of animation is unresolved, and
- // - the start time of animation is unresolved, and
- // - animation does not have either a pending play task or a pending pause task,
- if (!current_time.has_value() && !m_start_time.has_value() && !pending()) {
- // → idle
- return AnimationPlayState::Idle;
- }
-
- // -> Either of the following conditions are true:
- // - animation has a pending pause task, or
- // - both the start time of animation is unresolved and it does not have a pending play task,
- if (m_pending_pause_task == TaskState::Scheduled || (!m_start_time.has_value() && m_pending_play_task == TaskState::None)) {
- // → paused
- return AnimationPlayState::Paused;
- }
-
- // -> For animation, current time is resolved and either of the following conditions are true:
- // - animation’s effective playback rate > 0 and current time ≥ associated effect end; or
- // - animation’s effective playback rate < 0 and current time ≤ 0,
- auto effective_playback_rate = this->effective_playback_rate();
- if (current_time.has_value() && ((effective_playback_rate > 0.0 && current_time.value() >= associated_effect_end()) || (effective_playback_rate < 0.0 && current_time->value <= 0))) {
- // → finished
- return AnimationPlayState::Finished;
- }
-
- // -> Otherwise,
- // → running
- return AnimationPlayState::Running;
+ auto playback = this->playback();
+ auto play_state = RustFFI::animations_play_state_at(&playback, to_ffi(current_time), associated_effect_end());
+ return static_cast<AnimationPlayState>(to_underlying(play_state));
}
AnimationPlayState Animation::play_state_for_bindings()
@@ -845,10 +803,21 @@ GC::Ref<WebIDL::Promise> Animation::finished_for_bindings()
// https://www.w3.org/TR/web-animations-1/#animation-relevant
bool Animation::is_relevant() const
{
- // An animation is relevant if:
- // - Its associated effect is current or in effect, and
- // - Its replace state is not removed.
- return (m_effect && (m_effect->is_current() || m_effect->is_in_effect())) && replace_state() != AnimationReplaceState::Removed;
+ auto playback = this->playback();
+ Optional<RustFFI::TimelineSample> timeline_sample;
+ if (m_timeline)
+ timeline_sample = m_timeline->sample();
+ Optional<RustFFI::AnimationEffectTiming> effect_timing;
+ Optional<TimeValue> local_time;
+ if (m_effect) {
+ effect_timing = m_effect->effect_timing(m_effect->fill_mode());
+ local_time = m_effect->local_time();
+ }
+ return RustFFI::animations_is_relevant(
+ &playback,
+ timeline_sample.has_value() ? &*timeline_sample : nullptr,
+ effect_timing.has_value() ? &*effect_timing : nullptr,
+ to_ffi(local_time));
}
// https://www.w3.org/TR/web-animations-1/#replaceable-animation
@@ -1558,6 +1527,24 @@ TimeValue Animation::associated_effect_end() const
return m_effect ? m_effect->end_time() : TimeValue::create_zero(m_timeline);
}
+static_assert(to_underlying(AnimationReplaceState::Active) == to_underlying(RustFFI::AnimationReplaceState::Active));
+static_assert(to_underlying(AnimationReplaceState::Removed) == to_underlying(RustFFI::AnimationReplaceState::Removed));
+static_assert(to_underlying(AnimationReplaceState::Persisted) == to_underlying(RustFFI::AnimationReplaceState::Persisted));
+
+RustFFI::AnimationPlayback Animation::playback() const
+{
+ return {
+ .start_time = to_ffi(m_start_time),
+ .hold_time = to_ffi(m_hold_time),
+ .playback_rate = m_playback_rate,
+ .pending_playback_rate = { .value = m_pending_playback_rate.value_or(0), .has_value = m_pending_playback_rate.has_value() },
+ .has_pending_play_task = m_pending_play_task == TaskState::Scheduled,
+ .has_pending_pause_task = m_pending_pause_task == TaskState::Scheduled,
+ .is_finished = m_is_finished,
+ .replace_state = static_cast<RustFFI::AnimationReplaceState>(to_underlying(m_replace_state)),
+ };
+}
+
// https://www.w3.org/TR/web-animations-1/#effective-playback-rate
double Animation::effective_playback_rate() const
{
diff --git a/Libraries/LibWeb/Animations/Animation.h b/Libraries/LibWeb/Animations/Animation.h
index 09bcf1a2dee..3ecc34b1e7f 100644
--- a/Libraries/LibWeb/Animations/Animation.h
+++ b/Libraries/LibWeb/Animations/Animation.h
@@ -8,6 +8,7 @@
#include <LibJS/Forward.h>
#include <LibJS/Runtime/PromiseCapability.h>
+#include <LibWeb/Animations/RustFFI.h>
#include <LibWeb/Animations/TimeValue.h>
#include <LibWeb/Animations/TimelineRange.h>
#include <LibWeb/Bindings/Animation.h>
@@ -129,6 +130,9 @@ public:
GC::Ref<WebIDL::Promise> finished() const { return current_finished_promise(); }
bool is_finished() const { return m_is_finished; }
+ // The playback state the timing model reads of the animation.
+ RustFFI::AnimationPlayback playback() const;
+
bool is_idle() const { return play_state() == AnimationPlayState::Idle; }
GC::Ptr<WebIDL::CallbackType> onfinish();
diff --git a/Libraries/LibWeb/Animations/AnimationEffect.cpp b/Libraries/LibWeb/Animations/AnimationEffect.cpp
index 098f8eafe6d..31b773dc4a8 100644
--- a/Libraries/LibWeb/Animations/AnimationEffect.cpp
+++ b/Libraries/LibWeb/Animations/AnimationEffect.cpp
@@ -164,47 +164,16 @@ Bindings::ComputedEffectTiming AnimationEffect::get_computed_timing() const
computed_timing.duration = duration;
computed_timing.direction = m_playback_direction;
computed_timing.easing = m_timing_function.to_utf16_string();
- computed_timing.active_duration = active_duration().as_css_numberish();
- computed_timing.current_iteration = current_iteration();
- computed_timing.end_time = end_time().as_css_numberish();
- computed_timing.local_time = NullableCSSNumberish::from_optional_css_numberish_time(local_time());
- computed_timing.progress = transformed_progress();
+ auto local_time = this->local_time();
+ auto timing = resolve_timing_at(local_time, m_fill_mode, WithTransformedProgress::Yes);
+ computed_timing.active_duration = timing.active_duration.as_css_numberish();
+ computed_timing.current_iteration = from_ffi(timing.current_iteration);
+ computed_timing.end_time = timing.end_time.as_css_numberish();
+ computed_timing.local_time = NullableCSSNumberish::from_optional_css_numberish_time(local_time);
+ computed_timing.progress = from_ffi(timing.transformed_progress);
return computed_timing;
}
-// https://drafts.csswg.org/web-animations-2/#intrinsic-iteration-duration
-TimeValue AnimationEffect::intrinsic_iteration_duration() const
-{
- // The intrinsic iteration duration is calculated from the first matching condition from below:
-
- // FIXME: If the animation effect is a group effect,
- if (false) {
- // Follow the procedure in § 2.10.3 The intrinsic iteration duration of a group effect
- TODO();
- }
-
- // FIXME: If the animation effect is a sequence effect,
- else if (false) {
- // Follow the procedure in § 2.10.4.2 The intrinsic iteration duration of a sequence effect
- TODO();
- }
-
- // If timeline duration is unresolved or iteration count is zero,
- else if (!timeline_duration().has_value() || m_iteration_count == 0.0) {
- // Return 0
- return TimeValue::create_zero(associated_timeline());
- }
-
- // Otherwise
- else {
- // Return(100% - start delay - end delay) / iteration count
- // Note : Presently start and end delays are zero until such time as percentage based delays are supported.
- // AD-HOC: An effect fills its animation's attachment range rather than the whole timeline, which is what the
- // timeline duration is here. This matches WebKit.
- return (timeline_duration().value() - m_start_delay - m_end_delay) / m_iteration_count;
- }
-}
-
GC::Ptr<AnimationTimeline> AnimationEffect::associated_timeline() const
{
if (!m_associated_animation)
@@ -228,82 +197,37 @@ Optional<TimeValue> AnimationEffect::timeline_duration() const
return timeline->duration();
}
-// https://drafts.csswg.org/web-animations-2/#time-based-animation-to-a-proportional-animation
-void AnimationEffect::convert_a_time_based_animation_to_a_proportional_animation()
-{
- // AD-HOC: We use the specified interation duration instead of the iteration duration here, see
- // https://github.com/w3c/csswg-drafts/pull/13170
- // If the iteration duration is auto, then perform the following steps.
- if (m_specified_iteration_duration.has<Utf16String>()) {
- // Set start delay and end delay to 0, as it is not possible to mix time and proportions.
- // Note: Future versions may allow these properties to be assigned percentages, at which point the delays are
- // only to be ignored if their values are expressed as times and not as percentages.
- m_start_delay = TimeValue::create_zero(associated_timeline());
- m_end_delay = TimeValue::create_zero(associated_timeline());
-
- // AD-HOC: The spec doesn't say what to set iteration duration to in this case so we set it to the intrinsic
- // iteration duration, see: https://github.com/w3c/csswg-drafts/issues/13220
- m_iteration_duration = intrinsic_iteration_duration();
- return;
- }
-
- // Otherwise:
-
- // NB: The caller asserts that timeline duration is resolved
- auto const& timeline_duration = this->timeline_duration().value();
-
- // 1. Let total time be equal to end time
- // AD-HOC: Using end time here only works if we haven't already converted to a proportional animation, we instead
- // recompute the specified equivalent of "end time", see https://github.com/w3c/csswg-drafts/issues/13230
- auto total_time = max(m_specified_start_delay + (m_specified_iteration_duration.get<double>() * m_iteration_count) + m_specified_end_delay, 0);
-
- // AD-HOC: Avoid a division by zero below, see https://github.com/w3c/csswg-drafts/issues/11276
- if (total_time == 0) {
- m_start_delay = TimeValue::create_zero(associated_timeline());
- m_iteration_duration = TimeValue::create_zero(associated_timeline());
- m_end_delay = TimeValue::create_zero(associated_timeline());
- return;
- }
-
- // 2. Set start delay to be the result of evaluating specified start delay / total time * timeline duration.
- m_start_delay = timeline_duration * (m_specified_start_delay / total_time);
-
- // 3. Set iteration duration to be the result of evaluating specified iteration duration / total time * timeline duration.
- m_iteration_duration = timeline_duration * (m_specified_iteration_duration.get<double>() / total_time);
-
- // 4. Set end delay to be the result of evaluating specified end delay / total time * timeline duration.
- m_end_delay = timeline_duration * (m_specified_end_delay / total_time);
-}
+static_assert(sizeof(TimeValue) == 16 && offsetof(TimeValue, type) == 0 && offsetof(TimeValue, value) == 8);
+static_assert(to_underlying(TimeValue::Type::Milliseconds) == 0 && to_underlying(TimeValue::Type::Percentage) == 1);
+static_assert(to_underlying(FillMode::None) == to_underlying(RustFFI::FillMode::None));
+static_assert(to_underlying(FillMode::Forwards) == to_underlying(RustFFI::FillMode::Forwards));
+static_assert(to_underlying(FillMode::Backwards) == to_underlying(RustFFI::FillMode::Backwards));
+static_assert(to_underlying(FillMode::Both) == to_underlying(RustFFI::FillMode::Both));
+static_assert(to_underlying(FillMode::Auto) == to_underlying(RustFFI::FillMode::Auto));
+static_assert(to_underlying(PlaybackDirection::Normal) == to_underlying(RustFFI::PlaybackDirection::Normal));
+static_assert(to_underlying(PlaybackDirection::Reverse) == to_underlying(RustFFI::PlaybackDirection::Reverse));
+static_assert(to_underlying(PlaybackDirection::Alternate) == to_underlying(RustFFI::PlaybackDirection::Alternate));
+static_assert(to_underlying(PlaybackDirection::AlternateReverse) == to_underlying(RustFFI::PlaybackDirection::AlternateReverse));
// https://drafts.csswg.org/web-animations-2/#normalize-specified-timing
void AnimationEffect::normalize_specified_timing()
{
- // If timeline duration is resolved:
- if (timeline_duration().has_value()) {
- // Follow the procedure to convert a time-based animation to a proportional animation
- convert_a_time_based_animation_to_a_proportional_animation();
- }
- // Otherwise:
- else {
- // 1. Set start delay = specified start delay
- m_start_delay = TimeValue { TimeValue::Type::Milliseconds, m_specified_start_delay };
-
- // 2. Set end delay = specified end delay
- m_end_delay = TimeValue { TimeValue::Type::Milliseconds, m_specified_end_delay };
-
- // 3. If iteration duration is auto:
- // AD-HOC: We use the specified interation duration instead of the iteration duration here, see
- // https://github.com/w3c/csswg-drafts/pull/13170
- if (m_specified_iteration_duration.has<Utf16String>()) {
- // Set iteration duration = intrinsic iteration duration
- m_iteration_duration = intrinsic_iteration_duration();
- }
- // Otherwise:
- else {
- // Set iteration duration = specified iteration duration
- m_iteration_duration = TimeValue { TimeValue::Type::Milliseconds, m_specified_iteration_duration.get<double>() };
- }
- }
+ RustFFI::SpecifiedEffectTiming specified {
+ .start_delay = m_specified_start_delay,
+ .end_delay = m_specified_end_delay,
+ .iteration_duration = m_specified_iteration_duration.visit(
+ [](double duration) { return RustFFI::SpecifiedIterationDuration { .is_auto = false, .milliseconds = duration }; },
+ [](Utf16String const&) { return RustFFI::SpecifiedIterationDuration { .is_auto = true, .milliseconds = 0 }; }),
+ .iteration_start = m_iteration_start,
+ .iteration_count = m_iteration_count,
+ .fill_mode = static_cast<RustFFI::FillMode>(to_underlying(m_fill_mode)),
+ .playback_direction = static_cast<RustFFI::PlaybackDirection>(to_underlying(m_playback_direction)),
+ };
+ auto time_unit = TimeValue::create_zero(associated_timeline()).type;
+ auto timing = RustFFI::animations_normalize_specified_timing(&specified, to_ffi(timeline_duration()), time_unit);
+ m_start_delay = timing.start_delay;
+ m_end_delay = timing.end_delay;
+ m_iteration_duration = timing.iteration_duration;
}
// https://www.w3.org/TR/web-animations-1/#dom-animationeffect-updatetiming
@@ -416,24 +340,6 @@ void AnimationEffect::update_style_if_needed() const
m_associated_animation->update_style_if_needed();
}
-// https://www.w3.org/TR/web-animations-1/#animation-direction
-AnimationDirection AnimationEffect::animation_direction() const
-{
- // "backwards" if the effect is associated with an animation and the associated animation’s playback rate is less
- // than zero; in all other cases, the animation direction is "forwards".
- if (m_associated_animation && m_associated_animation->playback_rate() < 0.0)
- return AnimationDirection::Backwards;
- return AnimationDirection::Forwards;
-}
-
-// https://www.w3.org/TR/web-animations-1/#end-time
-TimeValue AnimationEffect::end_time() const
-{
- // 1. The end time of an animation effect is the result of evaluating
- // max(start delay + active duration + end delay, 0).
- return max(m_start_delay + active_duration() + m_end_delay, TimeValue::create_zero(associated_timeline()));
-}
-
// https://www.w3.org/TR/web-animations-1/#local-time
Optional<TimeValue> AnimationEffect::local_time() const
{
@@ -454,321 +360,116 @@ Optional<TimeValue> AnimationEffect::local_time() const
return {};
}
-// https://www.w3.org/TR/web-animations-1/#active-duration
-TimeValue AnimationEffect::active_duration() const
+RustFFI::AnimationEffectTiming AnimationEffect::effect_timing(Bindings::FillMode fill_mode) const
{
- // The active duration is calculated as follows:
- // active duration = iteration duration × iteration count
- // If either the iteration duration or iteration count are zero, the active duration is zero. This clarification is
- // needed since the result of infinity multiplied by zero is undefined according to IEEE 754-2008.
- if (m_iteration_duration.value == 0 || m_iteration_count == 0.0)
- return TimeValue::create_zero(associated_timeline());
-
- return m_iteration_duration * m_iteration_count;
+ return {
+ .start_delay = m_start_delay,
+ .end_delay = m_end_delay,
+ .iteration_duration = m_iteration_duration,
+ .iteration_start = m_iteration_start,
+ .iteration_count = m_iteration_count,
+ .fill_mode = static_cast<RustFFI::FillMode>(to_underlying(fill_mode)),
+ .playback_direction = static_cast<RustFFI::PlaybackDirection>(to_underlying(m_playback_direction)),
+ };
}
-Optional<TimeValue> AnimationEffect::active_time() const
+RustFFI::EffectTimingSnapshot AnimationEffect::timing_snapshot() const
{
- return active_time_using_fill(m_fill_mode);
+ VERIFY(m_associated_animation);
+ auto timeline = m_associated_animation->timeline();
+ return {
+ .effect = effect_timing(m_fill_mode),
+ .playback = m_associated_animation->playback(),
+ .timeline = timeline ? timeline->sample() : RustFFI::TimelineSample {},
+ .has_timeline = timeline != nullptr,
+ .clock = timeline ? timeline->clock() : RustFFI::TimelineClock { .source = RustFFI::TimelineClockSource::Unticked, .origin_time = 0, .scroll_timeline = 0 },
+ };
}
-Optional<TimeValue> AnimationEffect::active_time_using_fill(Bindings::FillMode fill_mode) const
+AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing_at(Optional<TimeValue> const& local_time, Bindings::FillMode fill_mode, WithTransformedProgress with_transformed_progress, EndpointInclusiveActiveInterval endpoint_inclusive) const
{
- auto local_time = this->local_time();
- return active_time_for_phase(phase(local_time), local_time, fill_mode);
+ auto timing = effect_timing(fill_mode);
+ Optional<RustFFI::AnimationPlayback> playback;
+ Optional<RustFFI::TimelineSample> timeline_sample;
+ if (m_associated_animation) {
+ playback = m_associated_animation->playback();
+ if (auto timeline = m_associated_animation->timeline())
+ timeline_sample = timeline->sample();
+ }
+ Optional<CSS::EasingFunction::Descriptor> timing_function;
+ if (with_transformed_progress == WithTransformedProgress::Yes)
+ timing_function = m_timing_function.descriptor();
+ return RustFFI::animations_resolve_effect_timing(
+ &timing,
+ to_ffi(local_time),
+ playback.has_value() ? &*playback : nullptr,
+ timeline_sample.has_value() ? &*timeline_sample : nullptr,
+ timing_function.has_value() ? &*timing_function : nullptr,
+ endpoint_inclusive == EndpointInclusiveActiveInterval::Yes);
}
-// https://www.w3.org/TR/web-animations-1/#calculating-the-active-time
-Optional<TimeValue> AnimationEffect::active_time_for_phase(Phase phase, Optional<TimeValue> const& local_time, Bindings::FillMode fill_mode) const
+// What follows from the effect's timing alone, without a local time.
+AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing_alone() const
{
- // The active time is based on the local time and start delay. However, it is only defined when the animation effect
- // should produce an output and hence depends on its fill mode and phase as follows,
-
- switch (phase) {
- // -> If the animation effect is in the before phase,
- case Phase::Before:
- // The result depends on the first matching condition from the following,
-
- // -> If the fill mode is backwards or both,
- if (fill_mode == Bindings::FillMode::Backwards || fill_mode == Bindings::FillMode::Both) {
- // Return the result of evaluating max(local time - start delay, 0).
- return max(local_time.value() - m_start_delay, TimeValue::create_zero(associated_timeline()));
- }
-
- // -> Otherwise,
- // Return an unresolved time value.
- return {};
-
- // -> If the animation effect is in the active phase,
- case Phase::Active:
- // Return the result of evaluating local time - start delay.
- return local_time.value() - m_start_delay;
-
- // -> If the animation effect is in the after phase,
- case Phase::After:
- // The result depends on the first matching condition from the following,
-
- // -> If the fill mode is forwards or both,
- if (fill_mode == Bindings::FillMode::Forwards || fill_mode == Bindings::FillMode::Both) {
- // Return the result of evaluating max(min(local time - start delay, active duration), 0).
- return max(min(local_time.value() - m_start_delay, active_duration()), TimeValue::create_zero(associated_timeline()));
- }
-
- // -> Otherwise,
- // Return an unresolved time value.
- return {};
-
- // -> Otherwise (the local time is unresolved),
- // Return an unresolved time value.
- case Phase::Idle:
- return {};
- }
-
- VERIFY_NOT_REACHED();
+ auto timing = effect_timing(m_fill_mode);
+ return RustFFI::animations_resolve_effect_timing(&timing, to_ffi({}), nullptr, nullptr, nullptr, false);
}
-// https://www.w3.org/TR/web-animations-1/#in-play
-bool AnimationEffect::is_in_play(Phase phase) const
+AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing() const
{
- // An animation effect is in play if all of the following conditions are met:
- // - the animation effect is in the active phase, and
- // - the animation effect is associated with an animation that is not finished.
- return phase == Phase::Active && m_associated_animation && !m_associated_animation->is_finished();
+ return resolve_timing_at(local_time(), m_fill_mode);
}
-// https://www.w3.org/TR/web-animations-1/#current
-bool AnimationEffect::is_current() const
+// https://www.w3.org/TR/web-animations-1/#end-time
+TimeValue AnimationEffect::end_time() const
{
- auto phase = this->phase();
-
- // An animation effect is current if any of the following conditions are true:
-
- // - the animation effect is in play, or
- if (is_in_play(phase))
- return true;
-
- if (auto animation = m_associated_animation) {
- auto playback_rate = animation->playback_rate();
-
- // - the animation effect is associated with an animation with a playback rate > 0 and the animation effect is
- // in the before phase, or
- if (playback_rate > 0.0 && phase == Phase::Before)
- return true;
-
- // - the animation effect is associated with an animation with a playback rate < 0 and the animation effect is
- // in the after phase, or
- if (playback_rate < 0.0 && phase == Phase::After)
- return true;
-
- // - the animation effect is associated with an animation not in the idle play state with a non-null associated
- // timeline that is not monotonically increasing.
- if (animation->play_state() != Bindings::AnimationPlayState::Idle && animation->timeline() && !animation->timeline()->is_monotonically_increasing())
- return true;
- }
-
- return false;
+ return resolve_timing_alone().end_time;
}
-// https://www.w3.org/TR/web-animations-1/#in-effect
-bool AnimationEffect::is_in_effect() const
+// https://www.w3.org/TR/web-animations-1/#active-duration
+TimeValue AnimationEffect::active_duration() const
{
- // An animation effect is in effect if its active time, as calculated according to the procedure in
- // §4.8.3.1 Calculating the active time, is not unresolved.
- return active_time().has_value();
+ return resolve_timing_alone().active_duration;
}
// https://www.w3.org/TR/web-animations-1/#before-active-boundary-time
TimeValue AnimationEffect::before_active_boundary_time() const
{
- // max(min(start delay, end time), 0)
- return max(min(m_start_delay, end_time()), TimeValue::create_zero(associated_timeline()));
+ return resolve_timing_alone().before_active_boundary_time;
}
// https://www.w3.org/TR/web-animations-1/#active-after-boundary-time
TimeValue AnimationEffect::after_active_boundary_time() const
{
- // max(min(start delay + active duration, end time), 0)
- return max(min(m_start_delay + active_duration(), end_time()), TimeValue::create_zero(associated_timeline()));
-}
-
-// https://drafts.csswg.org/web-animations-2/#at-timeline-boundary
-bool AnimationEffect::is_at_timeline_boundary() const
-{
- auto timeline = associated_timeline();
- if (!timeline)
- return false;
- auto timeline_time = timeline->current_time();
- if (!timeline_time.has_value())
- return false;
- auto matches = [&](Optional<TimeValue> const& time) {
- return time.has_value() && fabs(timeline_time->value - time->value) < progress_timeline_tolerance;
- };
-
- // Determined based on the first matching condition:
- // If the minimum timeline time matches the timeline current time: Return true
- // If the maximum timeline time matches the timeline current time: Return true
- // Otherwise: Return false
- return matches(timeline->minimum_timeline_time()) || matches(timeline->maximum_timeline_time());
-}
-
-AnimationEffect::Phase AnimationEffect::phase() const
-{
- return phase(local_time());
+ return resolve_timing_alone().after_active_boundary_time;
}
-AnimationEffect::Phase AnimationEffect::phase(Optional<TimeValue> const& local_time, EndpointInclusiveActiveInterval endpoint_inclusive) const
-{
- // This is a convenience method that returns the phase of the animation effect, to avoid having to call all of the
- // phase functions separately.
- if (!local_time.has_value())
- return Phase::Idle;
-
- // https://drafts.csswg.org/web-animations-1/#animation-effect-phases-and-states
- // Furthermore, an endpoint-inclusive active interval flag may be specified when determining the phase. If not
- // specified, it is assumed to be false.
- auto at_timeline_boundary = this->is_at_timeline_boundary();
-
- auto before_active_boundary_time = this->before_active_boundary_time();
- // https://drafts.csswg.org/web-animations-2/#animation-effect-phases-and-states
- // An animation effect is in the before phase if the animation effect’s local time is not unresolved and either of
- // the following conditions are met:
- // 1. the local time is less than the before-active boundary time, or
- // 2. the animation direction is "backwards" and the local time is equal to the before-active boundary time and
- // not at timeline boundary.
- if (local_time.value() < before_active_boundary_time || (animation_direction() == AnimationDirection::Backwards && local_time.value() == before_active_boundary_time && !at_timeline_boundary && endpoint_inclusive == EndpointInclusiveActiveInterval::No))
- return Phase::Before;
-
- auto after_active_boundary_time = this->after_active_boundary_time();
- // An animation effect is in the after phase if the animation effect’s local time is not unresolved and either of
- // the following conditions are met:
- // 1. the local time is greater than the active-after boundary time, or
- // 2. the animation direction is "forwards" and the local time is equal to the active-after boundary time and not
- // at timeline boundary.
- if (local_time.value() > after_active_boundary_time || (animation_direction() == AnimationDirection::Forwards && local_time.value() == after_active_boundary_time && !at_timeline_boundary && endpoint_inclusive == EndpointInclusiveActiveInterval::No))
- return Phase::After;
-
- // https://www.w3.org/TR/web-animations-1/#animation-effect-active-phase
- // An animation effect is in the active phase if the animation effect’s local time is not unresolved and it is not
- // in either the before phase nor the after phase.
- return Phase::Active;
-}
-
-AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing(EndpointInclusiveActiveInterval endpoint_inclusive) const
+// https://www.w3.org/TR/web-animations-1/#calculating-the-active-time
+Optional<TimeValue> AnimationEffect::active_time() const
{
- auto local_time = this->local_time();
- auto phase = this->phase(local_time, endpoint_inclusive);
- auto active_time = active_time_for_phase(phase, local_time, m_fill_mode);
- return {
- .phase = phase,
- .local_time = local_time,
- .active_time = active_time,
- .overall_progress = overall_progress_for_phase(phase, active_time),
- };
+ return from_ffi(resolve_timing().active_time);
}
-// https://www.w3.org/TR/web-animations-1/#overall-progress
-Optional<double> AnimationEffect::overall_progress_for_phase(Phase phase, Optional<TimeValue> const& active_time) const
+Optional<TimeValue> AnimationEffect::active_time_using_fill(Bindings::FillMode fill_mode) const
{
- // 1. If the active time is unresolved, return unresolved.
- if (!active_time.has_value())
- return {};
-
- // 2. Calculate an initial value for overall progress based on the first matching condition from below,
- double overall_progress;
-
- // -> If the iteration duration is zero,
- if (m_iteration_duration.value == 0) {
- // If the animation effect is in the before phase, let overall progress be zero, otherwise, let it be equal to
- // the iteration count.
- if (phase == Phase::Before)
- overall_progress = 0.0;
- else
- overall_progress = m_iteration_count;
- }
- // Otherwise,
- else {
- // Let overall progress be the result of calculating active time / iteration duration.
- overall_progress = active_time.value() / m_iteration_duration;
- }
-
- // 3. Return the result of calculating overall progress + iteration start.
- return overall_progress + m_iteration_start;
+ return from_ffi(resolve_timing_at(local_time(), fill_mode).active_time);
}
-// https://www.w3.org/TR/web-animations-1/#directed-progress
-Optional<double> AnimationEffect::directed_progress(ResolvedTiming const& timing) const
+// https://www.w3.org/TR/web-animations-1/#current
+bool AnimationEffect::is_current() const
{
- // 1. If the simple iteration progress is unresolved, return unresolved.
- auto simple_iteration_progress = this->simple_iteration_progress(timing);
- if (!simple_iteration_progress.has_value())
- return {};
-
- // 2. Calculate the current direction using the first matching condition from the following list:
- auto current_direction = this->current_direction(timing);
-
- // 3. If the current direction is forwards then return the simple iteration progress.
- if (current_direction == AnimationDirection::Forwards)
- return simple_iteration_progress;
-
- // Otherwise, return 1.0 - simple iteration progress.
- return 1.0 - simple_iteration_progress.value();
+ return resolve_timing().is_current;
}
-// https://www.w3.org/TR/web-animations-1/#directed-progress
-AnimationDirection AnimationEffect::current_direction(ResolvedTiming const& timing) const
+// https://www.w3.org/TR/web-animations-1/#in-effect
+bool AnimationEffect::is_in_effect() const
{
- // 2. Calculate the current direction using the first matching condition from the following list:
- // -> If playback direction is normal,
- if (m_playback_direction == Bindings::PlaybackDirection::Normal) {
- // Let the current direction be forwards.
- return AnimationDirection::Forwards;
- }
-
- // -> If playback direction is reverse,
- if (m_playback_direction == Bindings::PlaybackDirection::Reverse) {
- // Let the current direction be reverse.
- return AnimationDirection::Backwards;
- }
- // -> Otherwise,
- // 1. Let d be the current iteration.
- double d = current_iteration(timing).value();
-
- // 2. If playback direction is alternate-reverse increment d by 1.
- if (m_playback_direction == Bindings::PlaybackDirection::AlternateReverse)
- d += 1.0;
-
- // 3. If d % 2 == 0, let the current direction be forwards, otherwise let the current direction be reverse. If d
- // is infinity, let the current direction be forwards.
- if (isinf(d))
- return AnimationDirection::Forwards;
- if (fmod(d, 2.0) == 0.0)
- return AnimationDirection::Forwards;
- return AnimationDirection::Backwards;
+ return resolve_timing().is_in_effect;
}
-// https://www.w3.org/TR/web-animations-1/#simple-iteration-progress
-Optional<double> AnimationEffect::simple_iteration_progress(ResolvedTiming const& timing) const
+AnimationEffect::Phase AnimationEffect::phase() const
{
- // 1. If the overall progress is unresolved, return unresolved.
- if (!timing.overall_progress.has_value())
- return {};
-
- // 2. If overall progress is infinity, let the simple iteration progress be iteration start % 1.0, otherwise, let
- // the simple iteration progress be overall progress % 1.0.
- double simple_iteration_progress = isinf(timing.overall_progress.value()) ? fmod(m_iteration_start, 1.0) : fmod(timing.overall_progress.value(), 1.0);
-
- // 3. If all of the following conditions are true,
- // - the simple iteration progress calculated above is zero, and
- // - the animation effect is in the active phase or the after phase, and
- // - the active time is equal to the active duration, and
- // - the iteration count is not equal to zero.
- if (simple_iteration_progress == 0.0 && (timing.phase == Phase::Active || timing.phase == Phase::After) && timing.active_time.has_value() && timing.active_time.value() == active_duration() && m_iteration_count != 0.0) {
- // let the simple iteration progress be 1.0.
- simple_iteration_progress = 1.0;
- }
-
- // 4. Return simple iteration progress.
- return simple_iteration_progress;
+ return resolve_timing().phase;
}
Optional<double> AnimationEffect::current_iteration() const
@@ -779,48 +480,13 @@ Optional<double> AnimationEffect::current_iteration() const
// https://www.w3.org/TR/web-animations-1/#current-iteration
Optional<double> AnimationEffect::current_iteration(ResolvedTiming const& timing) const
{
- // 1. If the active time is unresolved, return unresolved.
- if (!timing.active_time.has_value())
- return {};
-
- // 2. If the animation effect is in the after phase and the iteration count is infinity, return infinity.
- if (timing.phase == Phase::After && isinf(m_iteration_count))
- return m_iteration_count;
-
- // 3. If the simple iteration progress is 1.0, return floor(overall progress) - 1.
- auto simple_iteration_progress = this->simple_iteration_progress(timing);
- if (simple_iteration_progress.has_value() && simple_iteration_progress.value() == 1.0)
- return floor(timing.overall_progress.value()) - 1.0;
-
- // 4. Otherwise, return floor(overall progress).
- return floor(timing.overall_progress.value());
+ return from_ffi(timing.current_iteration);
}
// https://www.w3.org/TR/web-animations-1/#transformed-progress
Optional<double> AnimationEffect::transformed_progress(EndpointInclusiveActiveInterval endpoint_inclusive) const
{
- auto timing = resolve_timing(endpoint_inclusive);
-
- // 1. If the directed progress is unresolved, return unresolved.
- auto directed_progress = this->directed_progress(timing);
- if (!directed_progress.has_value())
- return {};
-
- // 2. Calculate the value of the before flag as follows:
-
- // 1. Determine the current direction using the procedure defined in §4.9.1 Calculating the directed progress.
- auto current_direction = this->current_direction(timing);
-
- // 2. If the current direction is forwards, let going forwards be true, otherwise it is false.
- auto going_forwards = current_direction == AnimationDirection::Forwards;
-
- // 3. The before flag is set if the animation effect is in the before phase and going forwards is true; or if the animation effect
- // is in the after phase and going forwards is false.
- auto before_flag = (timing.phase == Phase::Before && going_forwards) || (timing.phase == Phase::After && !going_forwards);
-
- // 3. Return the result of evaluating the animation effect’s timing function passing directed progress as the input progress value and
- // before flag as the before flag.
- return m_timing_function.evaluate_at(directed_progress.value(), before_flag);
+ return from_ffi(resolve_timing_at(local_time(), m_fill_mode, WithTransformedProgress::Yes, endpoint_inclusive).transformed_progress);
}
Optional<CSS::EasingFunction> AnimationEffect::parse_easing_string(Utf16View value)
diff --git a/Libraries/LibWeb/Animations/AnimationEffect.h b/Libraries/LibWeb/Animations/AnimationEffect.h
index b3a5b4cb88d..a6e82b9b23c 100644
--- a/Libraries/LibWeb/Animations/AnimationEffect.h
+++ b/Libraries/LibWeb/Animations/AnimationEffect.h
@@ -12,6 +12,7 @@
#include <AK/Variant.h>
#include <LibGC/RootHashMap.h>
#include <LibGC/RootVector.h>
+#include <LibWeb/Animations/RustFFI.h>
#include <LibWeb/Animations/TimeValue.h>
#include <LibWeb/Bindings/AnimationEffect.h>
#include <LibWeb/Bindings/Wrappable.h>
@@ -28,15 +29,29 @@ using ComputedEffectTiming = Bindings::ComputedEffectTiming;
using OptionalEffectTiming = Bindings::OptionalEffectTiming;
using EffectTimingDuration = Variant<double, Utf16String>;
-enum class AnimationDirection {
- Forwards,
- Backwards,
-};
-
Bindings::FillMode css_fill_mode_to_bindings_fill_mode(CSS::AnimationFillMode mode);
Bindings::PlaybackDirection css_animation_direction_to_bindings_playback_direction(CSS::AnimationDirection direction);
Bindings::OptionalEffectTiming to_optional_effect_timing(Bindings::EffectTiming const&);
+inline RustFFI::OptionalTimeValue to_ffi(Optional<TimeValue> const& time)
+{
+ return { .value = time.value_or(TimeValue { TimeValue::Type::Milliseconds, 0 }), .has_value = time.has_value() };
+}
+
+inline Optional<TimeValue> from_ffi(RustFFI::OptionalTimeValue const& time)
+{
+ if (!time.has_value)
+ return {};
+ return time.value;
+}
+
+inline Optional<double> from_ffi(RustFFI::OptionalNumber const& number)
+{
+ if (!number.has_value)
+ return {};
+ return number.value;
+}
+
// This object lives for the duration of an animation update, and is used to store per-element data about animated CSS properties.
struct AnimationUpdateContext {
struct ElementData {
@@ -105,8 +120,6 @@ public:
GC::Ptr<Animation> associated_animation() const { return m_associated_animation; }
void set_associated_animation(GC::Ptr<Animation> value);
- AnimationDirection animation_direction() const;
-
TimeValue end_time() const;
Optional<TimeValue> local_time() const;
TimeValue active_duration() const;
@@ -115,32 +128,27 @@ public:
bool is_current() const;
bool is_in_effect() const;
- bool has_local_time_override_for_observation() const { return m_has_local_time_override_for_observation; }
TimeValue before_active_boundary_time() const;
TimeValue after_active_boundary_time() const;
// Keep this enum up to date with CSSTransition::Phase.
- enum class Phase {
- Before,
- Active,
- After,
- Idle,
- };
+ using Phase = RustFFI::AnimationEffectPhase;
Phase phase() const;
// Everything a progress calculation needs, resolved together from one local time.
- struct ResolvedTiming {
- Phase phase;
- Optional<TimeValue> local_time;
- Optional<TimeValue> active_time;
- Optional<double> overall_progress;
- };
- enum class EndpointInclusiveActiveInterval {
+ using ResolvedTiming = RustFFI::FfiResolvedEffectTiming;
+ enum class EndpointInclusiveActiveInterval : bool {
No,
Yes,
};
- ResolvedTiming resolve_timing(EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;
+ ResolvedTiming resolve_timing() const;
+
+ // The normalized timing the timing model reads of the effect, with `fill_mode` as its fill mode.
+ RustFFI::AnimationEffectTiming effect_timing(Bindings::FillMode fill_mode) const;
+
+ // The timing the style engine samples the effect with, wherever it runs. The effect has an associated animation.
+ RustFFI::EffectTimingSnapshot timing_snapshot() const;
Phase previous_phase() const { return m_previous_phase; }
void set_previous_phase(Phase value) { m_previous_phase = value; }
@@ -170,20 +178,15 @@ protected:
virtual void visit_edges(GC::Cell::Visitor&) override;
virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
- bool is_in_play(Phase) const;
-
- TimeValue intrinsic_iteration_duration() const;
- void convert_a_time_based_animation_to_a_proportional_animation();
GC::Ptr<AnimationTimeline> associated_timeline() const;
Optional<TimeValue> timeline_duration() const;
- Phase phase(Optional<TimeValue> const& local_time, EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;
- bool is_at_timeline_boundary() const;
- Optional<TimeValue> active_time_for_phase(Phase, Optional<TimeValue> const& local_time, Bindings::FillMode) const;
- Optional<double> overall_progress_for_phase(Phase, Optional<TimeValue> const& active_time) const;
- Optional<double> simple_iteration_progress(ResolvedTiming const&) const;
- Optional<double> directed_progress(ResolvedTiming const&) const;
- AnimationDirection current_direction(ResolvedTiming const&) const;
+ enum class WithTransformedProgress : bool {
+ No,
+ Yes,
+ };
+ ResolvedTiming resolve_timing_at(Optional<TimeValue> const& local_time, Bindings::FillMode, WithTransformedProgress = WithTransformedProgress::No, EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;
+ ResolvedTiming resolve_timing_alone() const;
// https://drafts.csswg.org/web-animations-2/#specified-start-delay
double m_specified_start_delay { 0.0 };
diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.cpp b/Libraries/LibWeb/Animations/AnimationTimeline.cpp
index d261af03080..56e4aaece7e 100644
--- a/Libraries/LibWeb/Animations/AnimationTimeline.cpp
+++ b/Libraries/LibWeb/Animations/AnimationTimeline.cpp
@@ -6,8 +6,10 @@
#include <LibGC/RootVector.h>
#include <LibWeb/Animations/Animation.h>
+#include <LibWeb/Animations/AnimationEffect.h>
#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/KeyframeEffect.h>
+#include <LibWeb/Animations/ScrollTimeline.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
@@ -31,6 +33,30 @@ AnimationTimeline::CurrentTimeOverrideScope::~CurrentTimeOverrideScope()
m_timeline->m_has_current_time_override_for_style_sampling = m_had_previous_current_time_override;
}
+RustFFI::TimelineSample AnimationTimeline::sample() const
+{
+ return {
+ .current_time = to_ffi(current_time()),
+ .minimum_timeline_time = to_ffi(minimum_timeline_time()),
+ .maximum_timeline_time = to_ffi(maximum_timeline_time()),
+ .is_monotonically_increasing = is_monotonically_increasing(),
+ };
+}
+
+RustFFI::TimelineClock AnimationTimeline::clock()
+{
+ // A document timeline's time is a timestamp less its origin time, which is what lets a clock tick sample it.
+ if (can_convert_a_timeline_time_to_an_origin_relative_time()) {
+ if (auto origin_time = convert_a_timeline_time_to_an_origin_relative_time(TimeValue { TimeValue::Type::Milliseconds, 0 }); origin_time.has_value())
+ return { .source = RustFFI::TimelineClockSource::Document, .origin_time = *origin_time, .scroll_timeline = 0 };
+ }
+ // A scroll timeline's time is the progress of the scroller it follows, which is what lets a clock tick sample it
+ // where the compositor has scrolled to.
+ if (auto const* scroll_timeline = as_if<ScrollTimeline>(*this); scroll_timeline && scroll_timeline->followed_scroller().has_value())
+ return { .source = RustFFI::TimelineClockSource::Scroll, .origin_time = 0, .scroll_timeline = scroll_timeline->clock_identity() };
+ return { .source = RustFFI::TimelineClockSource::Unticked, .origin_time = 0, .scroll_timeline = 0 };
+}
+
// https://drafts.csswg.org/web-animations-1/#dom-animationtimeline-currenttime
Optional<TimeValue> AnimationTimeline::current_time() const
{
diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.h b/Libraries/LibWeb/Animations/AnimationTimeline.h
index c2565422a66..d9fe31d89dc 100644
--- a/Libraries/LibWeb/Animations/AnimationTimeline.h
+++ b/Libraries/LibWeb/Animations/AnimationTimeline.h
@@ -35,6 +35,10 @@ public:
NullableCSSNumberish current_time_for_bindings();
Optional<TimeValue> current_time() const;
+ // What the timing model reads of the timeline now.
+ RustFFI::TimelineSample sample() const;
+ // What moves the timeline as a clock tick samples it.
+ RustFFI::TimelineClock clock();
Optional<TimeValue> current_time_for_observation();
// Whether script observed the timeline in the current task at a time ahead of its current time.
bool was_observed_ahead_in_current_task() const;
diff --git a/Libraries/LibWeb/Animations/TimelineRange.h b/Libraries/LibWeb/Animations/TimelineRange.h
index 5ec99b738c6..a971832549b 100644
--- a/Libraries/LibWeb/Animations/TimelineRange.h
+++ b/Libraries/LibWeb/Animations/TimelineRange.h
@@ -76,10 +76,6 @@ struct AnimationAttachmentRange {
bool operator==(AnimationAttachmentRange const&) const = default;
};
-// How far apart two progress-based timeline times, in percent, may be and still be the same but for floating point error.
-// NB: Must match PROGRESS_TOLERANCE in the style engine.
-constexpr double progress_timeline_tolerance = 1e-6;
-
// The timeline times of the start and the end of an attachment range.
struct AttachmentInterval {
TimeValue start;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index f4efd1f76ab..476b7d5674e 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1061,6 +1061,7 @@ sync_rust_crate_ffi_headers(
Layout/TreeBuilderRustFFI.h
Layout/LayoutRustFFI.h
Compositor/RenderClockRustFFI.h
+ Animations/RustFFI.h
)
add_dependencies(LibWeb libweb_rust-ffi-headers)
target_link_libraries(libweb_bindings_rust INTERFACE LibGfx LibGC LibUnicode)
diff --git a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
index 3e75fe207f2..0973555e1f6 100644
--- a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
+++ b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
@@ -48,7 +48,6 @@
#include <LibWeb/CSS/SelectorMatching.h>
#include <LibWeb/CSS/StyleComputeFFI.h>
#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/CSS/StyleEngineEffectTiming.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleProperty.h>
#include <LibWeb/CSS/StyleScope.h>
diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cpp
index 1e64d09790f..ae162de8c7d 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -51,7 +51,6 @@
#include <LibWeb/CSS/SelectorMatching.h>
#include <LibWeb/CSS/StyleComputeFFI.h>
#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/CSS/StyleEngineEffectTiming.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleProperty.h>
#include <LibWeb/CSS/StyleScope.h>
@@ -544,62 +543,6 @@ void StyleComputer::finish_animation_refresh(Layout::BegunRead const& read, DOM:
finalize_animated_box_type(read, computed_properties, abstract_element);
}
-// The engine decides the timing only where every time is in one unit: a duration, or a percentage of a scroll
-// timeline's progress.
-ComputedValuesFFI::FfiEffectTiming style_engine_effect_timing(Animations::KeyframeEffect const& effect, Animations::Animation const& animation)
-{
- ComputedValuesFFI::FfiEffectTiming timing {};
-
- timing.is_relevant = animation.is_relevant();
- timing.is_removed = animation.replace_state() == Animations::AnimationReplaceState::Removed;
-
- Optional<Animations::TimeValue::Type> unit;
- bool one_unit = true;
- auto duration = [&](Animations::TimeValue const& time) {
- one_unit &= time.type == unit.value_or(time.type);
- unit = time.type;
- return time.value;
- };
- auto optional_duration = [&](Optional<Animations::TimeValue> const& time, bool& has_time, double& value) {
- has_time = time.has_value();
- if (time.has_value())
- value = duration(*time);
- };
- if (auto timeline = animation.timeline()) {
- optional_duration(timeline->current_time(), timing.has_timeline_time, timing.timeline_time);
- // A document timeline's time is a timestamp less its origin time, which is what lets a clock tick sample it.
- if (timeline->can_convert_a_timeline_time_to_an_origin_relative_time()) {
- auto origin_time = timeline->convert_a_timeline_time_to_an_origin_relative_time(Animations::TimeValue { Animations::TimeValue::Type::Milliseconds, 0 });
- timing.has_timeline_origin_time = origin_time.has_value();
- timing.timeline_origin_time = origin_time.value_or(0);
- }
- // A scroll timeline's time is the progress of the scroller it follows, which is what lets a clock tick sample
- // it where the compositor has scrolled to.
- if (auto const* scroll_timeline = as_if<Animations::ScrollTimeline>(*timeline); scroll_timeline && scroll_timeline->followed_scroller().has_value()) {
- timing.has_timeline_scroller = true;
- timing.scroll_timeline = scroll_timeline->clock_identity();
- }
- if (auto minimum = timeline->minimum_timeline_time(), maximum = timeline->maximum_timeline_time(); minimum.has_value() && maximum.has_value()) {
- timing.has_timeline_boundaries = true;
- timing.minimum_timeline_time = minimum->value;
- timing.maximum_timeline_time = maximum->value;
- }
- }
- optional_duration(animation.start_time(), timing.has_start_time, timing.start_time);
- optional_duration(animation.hold_time(), timing.has_hold_time, timing.hold_time);
- timing.paused = animation.play_state() == Bindings::AnimationPlayState::Paused;
- timing.playback_rate = animation.playback_rate();
- timing.start_delay = duration(effect.start_delay());
- timing.end_delay = duration(effect.end_delay());
- timing.iteration_duration = duration(effect.iteration_duration());
- timing.iteration_count = effect.iteration_count();
- timing.iteration_start = effect.iteration_start();
- timing.fill_mode = static_cast<u8>(to_underlying(effect.fill_mode()));
- timing.playback_direction = static_cast<u8>(to_underlying(effect.playback_direction()));
- timing.decidable = one_unit && !effect.has_local_time_override_for_observation();
- return timing;
-}
-
void StyleComputer::collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const
{
auto sample = begin_animation_sample(read, abstract_element, effects, computed_properties);
@@ -629,8 +572,7 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam
record_element_animation_effect_descriptions(abstract_element.element(), animation_slot, effects);
// The effects and their timing are the host's; the key each samples at, and what their keyframes compute to, are
- // the engine's. The host computes endpoint-inclusive keys for committing styles, and otherwise only for a timing
- // the engine cannot decide.
+ // the engine's.
auto& sampled_effects = sample->sampled_effects;
auto& easing_points = sample->easing_points;
sampled_effects.ensure_capacity(effects.size());
@@ -639,22 +581,12 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam
auto animation = effect->associated_animation();
if (!animation)
continue;
- auto timing = style_engine_effect_timing(*effect, *animation);
- Optional<double> current_key;
- if (purpose == AnimationSamplePurpose::CommitStyles || !timing.decidable) {
- auto endpoint_inclusive = purpose == AnimationSamplePurpose::CommitStyles
- ? Animations::AnimationEffect::EndpointInclusiveActiveInterval::Yes
- : Animations::AnimationEffect::EndpointInclusiveActiveInterval::No;
- if (auto output_progress = effect->transformed_progress(endpoint_inclusive); output_progress.has_value())
- current_key = clamp(*output_progress * 100.0 * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor, static_cast<double>(NumericLimits<i64>::min()), static_cast<double>(NumericLimits<i64>::max()));
- }
easing_points.unchecked_append({});
sampled_effects.unchecked_append({
.identity = effect->animation_preparation_identity(),
.generation = effect->animation_preparation_generation(),
- .timing = timing,
+ .timing = effect->timing_snapshot(),
.easing = effect->timing_function().descriptor_with_points_in(easing_points.last()),
- .current_key = current_key,
});
}
diff --git a/Libraries/LibWeb/CSS/StyleEngineEffectTiming.h b/Libraries/LibWeb/CSS/StyleEngineEffectTiming.h
deleted file mode 100644
index 42b0fd1130e..00000000000
--- a/Libraries/LibWeb/CSS/StyleEngineEffectTiming.h
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/ComputedValuesRustFFI.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// The timing the style engine computes the key an effect samples its keyframes at from: what its animation contributes,
-// the effect's own timing, and its timeline's current time.
-ComputedValuesFFI::FfiEffectTiming style_engine_effect_timing(Animations::KeyframeEffect const&, Animations::Animation const&);
-
-}
diff --git a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp
index 7ef2cb11d52..3ab017aa39d 100644
--- a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp
+++ b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp
@@ -14,7 +14,6 @@
#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleEngineBridge.h>
-#include <LibWeb/CSS/StyleEngineEffectTiming.h>
#include <LibWeb/Compositor/RenderClock.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
@@ -299,7 +298,7 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)
Optional<Layout::RustFFI::FfiHoverPlanInputs> hover;
Vector<u32> effect_timing_nodes;
Vector<u64> effect_timing_identities;
- Vector<CSS::ComputedValuesFFI::FfiEffectTiming> effect_timings;
+ Vector<Animations::RustFFI::EffectTimingSnapshot> effect_timings;
if (hover_lane_is_enabled() && document.is_fully_active() && !document.hidden() && document.window()) {
// A hover decides over the transitions the host runs as they run, where the host runs them without
// sampling them, which leaves the timing the engine holds of them behind.
@@ -310,14 +309,14 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)
if (!effect || !target || effect->pseudo_element_type().has_value() || !target->style_node_id()
|| !effect->can_skip_per_frame_style_update())
continue;
- auto timing = CSS::style_engine_effect_timing(*effect, animation);
+ auto timing = effect->timing_snapshot();
// The compositor runs a transition whose play is still pending from the time of the style change
- // event that started it.
+ // event that started it, on the document timeline.
if (auto const* transition = as_if<CSS::CSSTransition>(animation); transition && animation.pending()
- && !animation.start_time().has_value() && effect->is_compositor_driven()) {
- timing.has_start_time = true;
- timing.start_time = transition->transition_start_time() - effect->start_delay().value;
- timing.has_hold_time = false;
+ && !animation.start_time().has_value() && effect->is_compositor_driven()
+ && timing.clock.source == Animations::RustFFI::TimelineClockSource::Document) {
+ timing.playback.start_time = Animations::to_ffi(Animations::TimeValue { Animations::TimeValue::Type::Milliseconds, transition->transition_start_time() - effect->start_delay().value });
+ timing.playback.hold_time = Animations::to_ffi({});
}
effect_timing_nodes.append(target->style_node_id().value());
effect_timing_identities.append(effect->animation_preparation_identity());
diff --git a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp
index 8718eeb68cc..7f33d3cf1a5 100644
--- a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp
+++ b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp
@@ -269,14 +269,7 @@ CompositorAnimationEffectState::BuildOutcome CompositorAnimationEffectState::bui
request.timing.monotonic_time_at_anchor_ns = static_cast<i64>(timing_anchor.monotonic_time_ms * 1'000'000.0);
request.timing.local_time_at_anchor_ms = timing_anchor.local_time_ms;
request.timing.playback_rate = data.animation->playback_rate();
- request.timing.start_delay_ms = effect.start_delay().value;
- request.timing.iteration_duration_ms = effect.iteration_duration().value;
- request.timing.iteration_count = effect.iteration_count();
- request.timing.iteration_start = effect.iteration_start();
- request.timing.playback_direction = static_cast<Compositing::RustFFI::FfiVisualAnimationPlaybackDirection>(to_underlying(effect.playback_direction()));
- request.timing.fill_mode = first_is_one_of(effect.fill_mode(), Bindings::FillMode::Backwards, Bindings::FillMode::Both)
- ? Compositing::RustFFI::FfiVisualAnimationFillMode::Backwards
- : Compositing::RustFFI::FfiVisualAnimationFillMode::None;
+ request.timing.effect = effect.effect_timing(effect.fill_mode());
request.timing.easing = effect.timing_function().descriptor_with_points_in(effect_easing_points);
CompositorAnimationBuild lent { data, read };
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index ca21846ddd0..a9e94d6bc34 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2430,8 +2430,6 @@ fn expose_compositing_types_as_cpp_types(config: &mut cbindgen::Config) {
"FfiFilterFunctionKind",
"FfiVisualContextTreeInputs",
"FfiVisualAnimationTargetKind",
- "FfiVisualAnimationPlaybackDirection",
- "FfiVisualAnimationFillMode",
"FfiVisualAnimationTransformOperationKind",
"FfiCompositorAnimationPublishOutcome",
"FfiVisualAnimationSummary",
@@ -2954,12 +2952,6 @@ fn main() -> Result<(), Box<dyn Error>> {
expose_css_pixel_types_as_web_types(&mut computed_values_config);
// An effect the host samples carries its easing as the compositing crate describes one.
expose_compositing_types_as_cpp_types(&mut computed_values_config);
- computed_values_config.export.exclude.push("OptionalF64".to_string());
- computed_values_config
- .export
- .rename
- .insert("OptionalF64".to_string(), "Optional<double>".to_string());
- computed_values_config.includes.push("AK/Optional.h".to_string());
// The custom property registry and stores, a sample's animated custom properties and a shorthand expansion are
// opaque to C++, which holds each by pointer.
for name in [
@@ -3002,6 +2994,18 @@ fn main() -> Result<(), Box<dyn Error>> {
.push_str("\nnamespace Web::CSS::StyleValueFFI { struct CssString; }");
// An animation sample and plan read the document's style engine, which the document host reaches.
declare_document_host_of_layout_header(&mut computed_values_config);
+ // An effect the host samples carries its timing as the animations header describes it.
+ computed_values_config
+ .export
+ .exclude
+ .push("EffectTimingSnapshot".to_string());
+ computed_values_config.export.rename.insert(
+ "EffectTimingSnapshot".to_string(),
+ "Web::Animations::RustFFI::EffectTimingSnapshot".to_string(),
+ );
+ computed_values_config
+ .includes
+ .push("LibWeb/Animations/RustFFI.h".to_string());
computed_values_config.export.rename.insert(
"FfiAnimationEffectDescriptions".to_string(),
@@ -3102,6 +3106,44 @@ fn main() -> Result<(), Box<dyn Error>> {
Path::new("Layout/TreeBuilderRustFFI.h"),
);
+ // The Web Animations timing model - namespace Web::Animations::RustFFI. A time value is laid out as the C++
+ // Animations::TimeValue, which C++ passes it as, and an easing descriptor is the compositing header's.
+ let mut animations_config = base_config.clone();
+ animations_config.namespaces = Some(vec!["Web".to_string(), "Animations".to_string(), "RustFFI".to_string()]);
+ for (rust_name, cpp_name) in [
+ ("TimeValue", "Web::Animations::TimeValue"),
+ ("TimeValueType", "Web::Animations::TimeValue::Type"),
+ ("FfiEasingDescriptor", "Compositing::RustFFI::FfiEasingDescriptor"),
+ ] {
+ animations_config.export.exclude.push(rust_name.to_string());
+ animations_config
+ .export
+ .rename
+ .insert(rust_name.to_string(), cpp_name.to_string());
+ }
+ animations_config
+ .includes
+ .extend(["LibCompositing/RustFFI.h", "LibWeb/Animations/TimeValue.h"].map(String::from));
+ // The timing the host publishes of an effect it samples, which no function here takes.
+ animations_config
+ .export
+ .include
+ .push("EffectTimingSnapshot".to_string());
+ let animation_timing_dir = manifest_dir.join("../../LibCompositing/Rust/src/animation_timing");
+ println!("cargo:rerun-if-changed={}", animation_timing_dir.display());
+ generate_ffi_header(
+ animations_config,
+ &[
+ animation_timing_dir.join("time_value.rs"),
+ animation_timing_dir.join("effect_timing.rs"),
+ animation_timing_dir.join("playback.rs"),
+ manifest_dir.join("src/animations/ffi.rs"),
+ manifest_dir.join("src/animations/snapshot.rs"),
+ ],
+ &out_dir,
+ Path::new("Animations/RustFFI.h"),
+ );
+
// The lanes of the render clock - namespace Web::Compositor::RustFFI, layered on the layout header for the ticks
// the lanes hand on.
let mut render_clock_config = base_config.clone();
@@ -3160,6 +3202,13 @@ fn main() -> Result<(), Box<dyn Error>> {
layout_config
.includes
.push("LibIPC/ThreadSafeMessagePoster.h".to_string());
+ // A compositor animation carries its effect's timing as the animations header describes it.
+ layout_config.export.exclude.push("AnimationEffectTiming".to_string());
+ layout_config.export.rename.insert(
+ "AnimationEffectTiming".to_string(),
+ "Web::Animations::RustFFI::AnimationEffectTiming".to_string(),
+ );
+ layout_config.includes.push("LibWeb/Animations/RustFFI.h".to_string());
// A compositor animation effect state is opaque to C++, which holds it by pointer, and so are the paint server an
// SVG paint resource callback fills and a parsed SVG path.
for name in [
diff --git a/Libraries/LibWeb/Rust/src/animations/ffi.rs b/Libraries/LibWeb/Rust/src/animations/ffi.rs
new file mode 100644
index 00000000000..abb30e63c65
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/ffi.rs
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI through which the C++ animation classes reach the timing model, until they move to Rust.
+
+use super::timing::{
+ self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, OptionalNumber,
+ OptionalTimeValue, SpecifiedEffectTiming, TimeValue, TimeValueType, TimelineSample,
+};
+use libcompositing_rust::easing::{FfiEasingDescriptor, evaluate_easing_descriptor};
+
+/// The timing of an effect specified as `specified`, normalized against its associated timeline, whose
+/// duration, as the effect's animation sees it, is `timeline_duration`, and whose times are in `time_unit`.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_normalize_specified_timing(
+ specified: &SpecifiedEffectTiming,
+ timeline_duration: OptionalTimeValue,
+ time_unit: TimeValueType,
+) -> AnimationEffectTiming {
+ timing::normalize_specified_timing(specified, timeline_duration.get(), time_unit)
+}
+
+/// The timing of an effect at one local time, and what follows from its timing alone.
+#[repr(C)]
+pub struct FfiResolvedEffectTiming {
+ pub phase: AnimationEffectPhase,
+ pub local_time: OptionalTimeValue,
+ pub active_time: OptionalTimeValue,
+ pub overall_progress: OptionalNumber,
+ pub current_iteration: OptionalNumber,
+ /// Unresolved where no timing function was given.
+ pub transformed_progress: OptionalNumber,
+ pub is_current: bool,
+ pub is_in_effect: bool,
+ pub active_duration: TimeValue,
+ pub end_time: TimeValue,
+ pub before_active_boundary_time: TimeValue,
+ pub after_active_boundary_time: TimeValue,
+}
+
+/// The timing of an effect of `timing` at `local_time`, associated with `animation`, if any, which runs on
+/// `timeline`, if any, and with its transformed progress through `timing_function`, if given, with the
+/// endpoint-inclusive active interval flag set where `endpoint_inclusive` is.
+///
+/// # Safety
+/// The control points a linear `timing_function` names must be live for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn animations_resolve_effect_timing(
+ timing: &AnimationEffectTiming,
+ local_time: OptionalTimeValue,
+ animation: Option<&AnimationPlayback>,
+ timeline: Option<&TimelineSample>,
+ timing_function: Option<&FfiEasingDescriptor>,
+ endpoint_inclusive: bool,
+) -> FfiResolvedEffectTiming {
+ let endpoint_inclusive = if endpoint_inclusive {
+ timing::EndpointInclusiveActiveInterval::Yes
+ } else {
+ timing::EndpointInclusiveActiveInterval::No
+ };
+ let resolved = timing::resolve_timing_with(
+ timing,
+ local_time.get(),
+ animation,
+ timeline,
+ timing.fill_mode,
+ endpoint_inclusive,
+ );
+ let transformed_progress = timing_function.and_then(|timing_function| {
+ timing::transformed_progress_with(timing, &resolved, |input_progress, before_flag| {
+ evaluate_easing_descriptor(timing_function, input_progress, before_flag)
+ })
+ });
+ FfiResolvedEffectTiming {
+ phase: resolved.phase,
+ local_time: resolved.local_time.into(),
+ active_time: resolved.active_time.into(),
+ overall_progress: resolved.overall_progress.into(),
+ current_iteration: timing::current_iteration(timing, &resolved).into(),
+ transformed_progress: transformed_progress.into(),
+ is_current: timing::is_current(timing, resolved.phase, animation, timeline),
+ is_in_effect: timing::is_in_effect(&resolved),
+ active_duration: timing::active_duration(timing),
+ end_time: timing::end_time(timing),
+ before_active_boundary_time: timing::before_active_boundary_time(timing),
+ after_active_boundary_time: timing::after_active_boundary_time(timing),
+ }
+}
+
+/// The current time of `animation` with its timeline at `timeline_time`, which is unresolved where the
+/// animation has no timeline.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_current_time_at(
+ animation: &AnimationPlayback,
+ timeline_time: OptionalTimeValue,
+) -> OptionalTimeValue {
+ timing::current_time_at(animation, timeline_time.get()).into()
+}
+
+/// The play state of `animation` at its current time `current_time`, with the end time of its associated
+/// effect, or zero without one, `associated_effect_end`.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_play_state_at(
+ animation: &AnimationPlayback,
+ current_time: OptionalTimeValue,
+ associated_effect_end: TimeValue,
+) -> AnimationPlayState {
+ timing::play_state_at(animation, current_time.get(), associated_effect_end)
+}
+
+/// Whether `animation`, on `timeline`, if any, is relevant, with its associated effect, if any, of
+/// `effect_timing` at the local time `local_time`.
+#[unsafe(no_mangle)]
+pub extern "C" fn animations_is_relevant(
+ animation: &AnimationPlayback,
+ timeline: Option<&TimelineSample>,
+ effect_timing: Option<&AnimationEffectTiming>,
+ local_time: OptionalTimeValue,
+) -> bool {
+ timing::is_relevant(animation, timeline, effect_timing, local_time.get())
+}
diff --git a/Libraries/LibWeb/Rust/src/animations/mod.rs b/Libraries/LibWeb/Rust/src/animations/mod.rs
new file mode 100644
index 00000000000..27819844163
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/mod.rs
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Web Animations.
+
+pub(crate) mod ffi;
+pub(crate) mod snapshot;
+
+pub(crate) use libcompositing_rust::animation_timing as timing;
diff --git a/Libraries/LibWeb/Rust/src/animations/snapshot.rs b/Libraries/LibWeb/Rust/src/animations/snapshot.rs
new file mode 100644
index 00000000000..b6069bb526a
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/animations/snapshot.rs
@@ -0,0 +1,470 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The timing of an animation effect as the host publishes it to the style engine, which samples the
+//! effect from it wherever the engine runs.
+
+use super::timing::{
+ AnimationEffectTiming, AnimationPlayback, AnimationReplaceState, FillMode, OptionalNumber, OptionalTimeValue,
+ PlaybackDirection, TimeValue, TimeValueType, TimelineSample,
+};
+
+/// The identity the host gives a scroll timeline, by which a clock tick finds the progress of the
+/// scroller the timeline follows.
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct ScrollTimelineId(pub u64);
+
+/// What moves an effect's timeline as a clock tick samples it.
+#[cfg_attr(not(test), expect(dead_code, reason = "C++ constructs the variants"))]
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum TimelineClockSource {
+ /// Nothing a tick moves: the effect's animation has no timeline, or one no tick moves.
+ #[default]
+ Unticked,
+ /// A document timeline, whose time is a timestamp less the clock's origin time, in milliseconds.
+ Document,
+ /// A scroll timeline, whose time is the progress, in percent, of the scroller the clock's scroll
+ /// timeline follows.
+ Scroll,
+}
+
+/// What moves an effect's timeline as a clock tick samples it, and where from.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct TimelineClock {
+ pub source: TimelineClockSource,
+ /// The origin time of a document timeline.
+ pub origin_time: f64,
+ /// The identity of a scroll timeline.
+ pub scroll_timeline: ScrollTimelineId,
+}
+
+/// The progress, in percent, of a scroll timeline, which is its time.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct ScrollProgress {
+ pub timeline: ScrollTimelineId,
+ pub progress: f64,
+}
+
+impl TimelineClock {
+ /// The time of the timeline at a tick at `timestamp`, which moves every scroll timeline in
+ /// `scroll_progress`, sorted by timeline, to its progress, or `None` where the tick does not move
+ /// the timeline.
+ #[inline]
+ #[must_use]
+ pub fn time_at_tick(&self, timestamp: f64, scroll_progress: &[ScrollProgress]) -> Option<TimeValue> {
+ match self.source {
+ TimelineClockSource::Unticked => None,
+ TimelineClockSource::Document => Some(TimeValue::new(
+ TimeValueType::Milliseconds,
+ timestamp - self.origin_time,
+ )),
+ TimelineClockSource::Scroll => scroll_progress
+ .binary_search_by_key(&self.scroll_timeline, |scroll| scroll.timeline)
+ .ok()
+ .map(|index| TimeValue::new(TimeValueType::Percentage, scroll_progress[index].progress)),
+ }
+ }
+}
+
+/// The timing of an animation effect as the host holds it when it samples the effect: the effect's own
+/// normalized timing, the playback state of its animation, its animation's timeline as it stood, and
+/// what moves that timeline as a clock tick samples it.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct EffectTimingSnapshot {
+ pub effect: AnimationEffectTiming,
+ pub playback: AnimationPlayback,
+ /// The animation's timeline, where `has_timeline`.
+ pub timeline: TimelineSample,
+ pub has_timeline: bool,
+ pub clock: TimelineClock,
+}
+
+/// Bits of `CompactEffectTiming`, one for each time it holds, which mark the time a percentage in `units` and the
+/// time resolved in `resolved`.
+mod time_bit {
+ pub(super) const START_DELAY: u8 = 1 << 0;
+ pub(super) const END_DELAY: u8 = 1 << 1;
+ pub(super) const ITERATION_DURATION: u8 = 1 << 2;
+ pub(super) const START_TIME: u8 = 1 << 3;
+ pub(super) const HOLD_TIME: u8 = 1 << 4;
+ pub(super) const TIMELINE_TIME: u8 = 1 << 5;
+ pub(super) const MINIMUM_TIMELINE_TIME: u8 = 1 << 6;
+ pub(super) const MAXIMUM_TIMELINE_TIME: u8 = 1 << 7;
+}
+
+/// Bits of `CompactEffectTiming::flags`.
+mod flag {
+ pub(super) const HAS_PENDING_PLAYBACK_RATE: u8 = 1 << 0;
+ pub(super) const HAS_PENDING_PLAY_TASK: u8 = 1 << 1;
+ pub(super) const HAS_PENDING_PAUSE_TASK: u8 = 1 << 2;
+ pub(super) const IS_FINISHED: u8 = 1 << 3;
+ pub(super) const HAS_TIMELINE: u8 = 1 << 4;
+ pub(super) const IS_MONOTONICALLY_INCREASING: u8 = 1 << 5;
+}
+
+/// An `EffectTimingSnapshot` as the style engine keeps it for every effect it describes: each time a bare number,
+/// with its unit and whether it is resolved in a bit each, and the origin time of a document timeline and the
+/// identity of a scroll timeline in one place, as a timeline has at most one of them. It expands to the timing
+/// model's types wherever the engine samples the effect.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct CompactEffectTiming {
+ start_delay: f64,
+ end_delay: f64,
+ iteration_duration: f64,
+ iteration_start: f64,
+ iteration_count: f64,
+ start_time: f64,
+ hold_time: f64,
+ playback_rate: f64,
+ pending_playback_rate: f64,
+ timeline_time: f64,
+ minimum_timeline_time: f64,
+ maximum_timeline_time: f64,
+ /// The origin time of a document timeline, as its bits, or the identity of a scroll timeline.
+ clock_reference: u64,
+ /// The times that are percentages, by `time_bit`; the others are milliseconds.
+ units: u8,
+ /// The optional times that are resolved, by `time_bit`.
+ resolved: u8,
+ flags: u8,
+ fill_mode: FillMode,
+ playback_direction: PlaybackDirection,
+ replace_state: AnimationReplaceState,
+ clock_source: TimelineClockSource,
+}
+
+impl CompactEffectTiming {
+ #[inline]
+ fn time(&self, value: f64, bit: u8) -> TimeValue {
+ let unit = match self.units & bit {
+ 0 => TimeValueType::Milliseconds,
+ _ => TimeValueType::Percentage,
+ };
+ TimeValue::new(unit, value)
+ }
+
+ #[inline]
+ fn optional_time(&self, value: f64, bit: u8) -> OptionalTimeValue {
+ OptionalTimeValue {
+ value: self.time(value, bit),
+ has_value: self.resolved & bit != 0,
+ }
+ }
+
+ #[inline]
+ fn has(&self, flag: u8) -> bool {
+ self.flags & flag != 0
+ }
+
+ /// The effect's own normalized timing.
+ #[inline]
+ #[must_use]
+ pub(crate) fn effect(&self) -> AnimationEffectTiming {
+ AnimationEffectTiming {
+ start_delay: self.time(self.start_delay, time_bit::START_DELAY),
+ end_delay: self.time(self.end_delay, time_bit::END_DELAY),
+ iteration_duration: self.time(self.iteration_duration, time_bit::ITERATION_DURATION),
+ iteration_start: self.iteration_start,
+ iteration_count: self.iteration_count,
+ fill_mode: self.fill_mode,
+ playback_direction: self.playback_direction,
+ }
+ }
+
+ /// The playback state of the effect's animation.
+ #[inline]
+ #[must_use]
+ pub(crate) fn playback(&self) -> AnimationPlayback {
+ AnimationPlayback {
+ start_time: self.optional_time(self.start_time, time_bit::START_TIME),
+ hold_time: self.optional_time(self.hold_time, time_bit::HOLD_TIME),
+ playback_rate: self.playback_rate,
+ pending_playback_rate: OptionalNumber {
+ value: self.pending_playback_rate,
+ has_value: self.has(flag::HAS_PENDING_PLAYBACK_RATE),
+ },
+ has_pending_play_task: self.has(flag::HAS_PENDING_PLAY_TASK),
+ has_pending_pause_task: self.has(flag::HAS_PENDING_PAUSE_TASK),
+ is_finished: self.has(flag::IS_FINISHED),
+ replace_state: self.replace_state,
+ }
+ }
+
+ /// The animation's timeline as the host sampled it, if it has one.
+ #[inline]
+ #[must_use]
+ pub(crate) fn timeline(&self) -> Option<TimelineSample> {
+ self.has(flag::HAS_TIMELINE).then(|| self.timeline_sample())
+ }
+
+ #[inline]
+ fn timeline_sample(&self) -> TimelineSample {
+ TimelineSample {
+ current_time: self.optional_time(self.timeline_time, time_bit::TIMELINE_TIME),
+ minimum_timeline_time: self.optional_time(self.minimum_timeline_time, time_bit::MINIMUM_TIMELINE_TIME),
+ maximum_timeline_time: self.optional_time(self.maximum_timeline_time, time_bit::MAXIMUM_TIMELINE_TIME),
+ is_monotonically_increasing: self.has(flag::IS_MONOTONICALLY_INCREASING),
+ }
+ }
+
+ /// The current time of the animation's timeline as the host sampled it, which is unresolved without a timeline.
+ #[inline]
+ #[must_use]
+ pub(crate) fn timeline_time(&self) -> Option<TimeValue> {
+ if !self.has(flag::HAS_TIMELINE) {
+ return None;
+ }
+ self.optional_time(self.timeline_time, time_bit::TIMELINE_TIME).get()
+ }
+
+ /// What moves the animation's timeline as a clock tick samples it, and where from.
+ #[inline]
+ #[must_use]
+ pub(crate) fn clock(&self) -> TimelineClock {
+ match self.clock_source {
+ TimelineClockSource::Unticked => TimelineClock::default(),
+ TimelineClockSource::Document => TimelineClock {
+ source: TimelineClockSource::Document,
+ origin_time: f64::from_bits(self.clock_reference),
+ scroll_timeline: ScrollTimelineId::default(),
+ },
+ TimelineClockSource::Scroll => TimelineClock {
+ source: TimelineClockSource::Scroll,
+ origin_time: 0.0,
+ scroll_timeline: ScrollTimelineId(self.clock_reference),
+ },
+ }
+ }
+
+ /// Sets the hold time of the effect's animation.
+ #[inline]
+ pub(crate) fn set_hold_time(&mut self, hold_time: Option<TimeValue>) {
+ let hold_time = OptionalTimeValue::from(hold_time);
+ self.set_time(&hold_time.value, time_bit::HOLD_TIME);
+ self.hold_time = hold_time.value.value;
+ self.set_resolved(hold_time.has_value, time_bit::HOLD_TIME);
+ }
+
+ #[inline]
+ fn set_time(&mut self, time: &TimeValue, bit: u8) {
+ match time.r#type {
+ TimeValueType::Milliseconds => self.units &= !bit,
+ TimeValueType::Percentage => self.units |= bit,
+ }
+ }
+
+ #[inline]
+ fn set_resolved(&mut self, resolved: bool, bit: u8) {
+ match resolved {
+ true => self.resolved |= bit,
+ false => self.resolved &= !bit,
+ }
+ }
+
+ /// The timing as the host published it.
+ #[cfg(test)]
+ #[must_use]
+ pub(crate) fn snapshot(&self) -> EffectTimingSnapshot {
+ EffectTimingSnapshot {
+ effect: self.effect(),
+ playback: self.playback(),
+ timeline: self.timeline_sample(),
+ has_timeline: self.has(flag::HAS_TIMELINE),
+ clock: self.clock(),
+ }
+ }
+}
+
+impl From<&EffectTimingSnapshot> for CompactEffectTiming {
+ fn from(snapshot: &EffectTimingSnapshot) -> Self {
+ let EffectTimingSnapshot {
+ effect,
+ playback,
+ timeline,
+ has_timeline,
+ clock,
+ } = snapshot;
+ let mut compact = Self {
+ start_delay: effect.start_delay.value,
+ end_delay: effect.end_delay.value,
+ iteration_duration: effect.iteration_duration.value,
+ iteration_start: effect.iteration_start,
+ iteration_count: effect.iteration_count,
+ start_time: playback.start_time.value.value,
+ hold_time: playback.hold_time.value.value,
+ playback_rate: playback.playback_rate,
+ pending_playback_rate: playback.pending_playback_rate.value,
+ timeline_time: timeline.current_time.value.value,
+ minimum_timeline_time: timeline.minimum_timeline_time.value.value,
+ maximum_timeline_time: timeline.maximum_timeline_time.value.value,
+ clock_reference: match clock.source {
+ TimelineClockSource::Unticked => 0,
+ TimelineClockSource::Document => clock.origin_time.to_bits(),
+ TimelineClockSource::Scroll => clock.scroll_timeline.0,
+ },
+ units: 0,
+ resolved: 0,
+ flags: 0,
+ fill_mode: effect.fill_mode,
+ playback_direction: effect.playback_direction,
+ replace_state: playback.replace_state,
+ clock_source: clock.source,
+ };
+ compact.set_time(&effect.start_delay, time_bit::START_DELAY);
+ compact.set_time(&effect.end_delay, time_bit::END_DELAY);
+ compact.set_time(&effect.iteration_duration, time_bit::ITERATION_DURATION);
+ for (time, bit) in [
+ (&playback.start_time, time_bit::START_TIME),
+ (&playback.hold_time, time_bit::HOLD_TIME),
+ (&timeline.current_time, time_bit::TIMELINE_TIME),
+ (&timeline.minimum_timeline_time, time_bit::MINIMUM_TIMELINE_TIME),
+ (&timeline.maximum_timeline_time, time_bit::MAXIMUM_TIMELINE_TIME),
+ ] {
+ compact.set_time(&time.value, bit);
+ compact.set_resolved(time.has_value, bit);
+ }
+ for (set, flag) in [
+ (
+ playback.pending_playback_rate.has_value,
+ flag::HAS_PENDING_PLAYBACK_RATE,
+ ),
+ (playback.has_pending_play_task, flag::HAS_PENDING_PLAY_TASK),
+ (playback.has_pending_pause_task, flag::HAS_PENDING_PAUSE_TASK),
+ (playback.is_finished, flag::IS_FINISHED),
+ (*has_timeline, flag::HAS_TIMELINE),
+ (timeline.is_monotonically_increasing, flag::IS_MONOTONICALLY_INCREASING),
+ ] {
+ if set {
+ compact.flags |= flag;
+ }
+ }
+ compact
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ms(time: f64) -> OptionalTimeValue {
+ Some(TimeValue::milliseconds(time)).into()
+ }
+
+ fn percent(time: f64) -> OptionalTimeValue {
+ Some(TimeValue::percentage(time)).into()
+ }
+
+ fn round_trip(snapshot: EffectTimingSnapshot) {
+ let compact = CompactEffectTiming::from(&snapshot);
+ assert_eq!(compact.snapshot(), snapshot);
+ assert_eq!(compact.effect(), snapshot.effect);
+ assert_eq!(compact.playback(), snapshot.playback);
+ let timeline = snapshot.has_timeline.then_some(snapshot.timeline);
+ assert_eq!(compact.timeline(), timeline);
+ assert_eq!(
+ compact.timeline_time(),
+ timeline.and_then(|timeline| timeline.current_time.get())
+ );
+ assert_eq!(compact.clock(), snapshot.clock);
+ }
+
+ #[test]
+ fn a_document_timeline_timing_round_trips() {
+ round_trip(EffectTimingSnapshot {
+ effect: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(-250.0),
+ end_delay: TimeValue::milliseconds(125.0),
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ iteration_start: 0.5,
+ iteration_count: f64::INFINITY,
+ fill_mode: FillMode::Both,
+ playback_direction: PlaybackDirection::AlternateReverse,
+ },
+ playback: AnimationPlayback {
+ start_time: ms(40.0),
+ hold_time: ms(700.0),
+ playback_rate: -2.0,
+ pending_playback_rate: Some(0.5).into(),
+ has_pending_play_task: true,
+ has_pending_pause_task: false,
+ is_finished: true,
+ replace_state: AnimationReplaceState::Persisted,
+ },
+ timeline: TimelineSample {
+ current_time: ms(1234.5),
+ is_monotonically_increasing: true,
+ ..TimelineSample::default()
+ },
+ has_timeline: true,
+ clock: TimelineClock {
+ source: TimelineClockSource::Document,
+ origin_time: 16.75,
+ scroll_timeline: ScrollTimelineId::default(),
+ },
+ });
+ }
+
+ #[test]
+ fn a_scroll_timeline_timing_round_trips() {
+ round_trip(EffectTimingSnapshot {
+ effect: AnimationEffectTiming {
+ start_delay: TimeValue::percentage(10.0),
+ end_delay: TimeValue::percentage(5.0),
+ iteration_duration: TimeValue::percentage(85.0),
+ fill_mode: FillMode::Backwards,
+ ..AnimationEffectTiming::default()
+ },
+ playback: AnimationPlayback {
+ start_time: percent(20.0),
+ has_pending_pause_task: true,
+ replace_state: AnimationReplaceState::Removed,
+ ..AnimationPlayback::default()
+ },
+ timeline: TimelineSample {
+ current_time: percent(62.5),
+ minimum_timeline_time: percent(0.0),
+ maximum_timeline_time: percent(100.0),
+ is_monotonically_increasing: false,
+ },
+ has_timeline: true,
+ clock: TimelineClock {
+ source: TimelineClockSource::Scroll,
+ origin_time: 0.0,
+ scroll_timeline: ScrollTimelineId(u64::MAX - 3),
+ },
+ });
+ }
+
+ #[test]
+ fn unresolved_times_round_trip() {
+ round_trip(EffectTimingSnapshot::default());
+ round_trip(EffectTimingSnapshot {
+ timeline: TimelineSample {
+ current_time: OptionalTimeValue::from(None),
+ minimum_timeline_time: percent(0.0),
+ maximum_timeline_time: percent(100.0),
+ is_monotonically_increasing: false,
+ },
+ has_timeline: true,
+ ..EffectTimingSnapshot::default()
+ });
+ let mut compact = CompactEffectTiming::from(&EffectTimingSnapshot {
+ playback: AnimationPlayback {
+ hold_time: percent(30.0),
+ ..AnimationPlayback::default()
+ },
+ ..EffectTimingSnapshot::default()
+ });
+ compact.set_hold_time(Some(TimeValue::milliseconds(12.0)));
+ assert_eq!(compact.playback().hold_time.get(), Some(TimeValue::milliseconds(12.0)));
+ compact.set_hold_time(None);
+ assert_eq!(compact.playback().hold_time.get(), None);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/animations.rs b/Libraries/LibWeb/Rust/src/css/style/animations.rs
index f6442bac7f0..f78fcf85a59 100644
--- a/Libraries/LibWeb/Rust/src/css/style/animations.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/animations.rs
@@ -21,8 +21,12 @@
use super::bridge::{FfiAppliedAnimationDefinition, FfiAppliedAnimationValues};
use super::tree::{StyleNodeID, TreeScopeID};
+use crate::animations::snapshot::{CompactEffectTiming, ScrollProgress};
+use crate::animations::timing::{
+ self, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, OptionalTimeValue, ResolvedEffectTiming,
+ TimeValue, TimelineSample,
+};
use crate::css::css_string::CssString;
-use crate::css::style_compute::FfiEffectTiming;
use std::collections::HashMap;
/// Which of an element's animation lists a row belongs to, in the host's own numbering: zero for
@@ -372,20 +376,6 @@ impl AnimationKeyframes {
}
}
-/// `Bindings::FillMode`, in IDL order.
-mod fill_mode {
- pub(super) const FORWARDS: u8 = 1;
- pub(super) const BACKWARDS: u8 = 2;
- pub(super) const BOTH: u8 = 3;
-}
-
-/// `Bindings::PlaybackDirection`, in IDL order.
-mod playback_direction {
- pub(super) const NORMAL: u8 = 0;
- pub(super) const REVERSE: u8 = 1;
- pub(super) const ALTERNATE_REVERSE: u8 = 3;
-}
-
/// The times the engine samples effects' timelines at: those the host sampled them at, or those a clock
/// tick at a timestamp moves the document timelines to, with the scroll timelines at the scroll progress
/// the tick samples them at.
@@ -395,13 +385,6 @@ pub(crate) struct AnimationTimelineSamples<'a> {
scroll_progress: &'a [ScrollProgress],
}
-/// The progress, in percent, of a scroll timeline, which is its time, by the identity the host gave the timeline.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub(crate) struct ScrollProgress {
- pub(crate) timeline: u64,
- pub(crate) progress: f64,
-}
-
impl<'a> AnimationTimelineSamples<'a> {
/// The times a clock tick at `timestamp` samples at, which moves every document timeline: a timestamp less its
/// timeline's origin time, and every scroll timeline in `scroll_progress`, sorted by timeline, to its progress
@@ -416,221 +399,165 @@ impl<'a> AnimationTimelineSamples<'a> {
/// The time `timing`'s timeline is sampled at, which may be unresolved, or `None` where these samples
/// do not move it.
- fn timeline_time(self, timing: &FfiEffectTiming) -> Option<Option<f64>> {
+ #[inline]
+ fn timeline_time(self, timing: &CompactEffectTiming) -> Option<Option<TimeValue>> {
match self.timestamp {
- None => Some(timing.has_timeline_time.then_some(timing.timeline_time)),
- Some(_) if timing.has_timeline_scroller => self
- .scroll_progress
- .binary_search_by_key(&timing.scroll_timeline, |scroll| scroll.timeline)
- .ok()
- .map(|index| Some(self.scroll_progress[index].progress)),
- Some(timestamp) => timing
- .has_timeline_origin_time
- .then_some(Some(timestamp - timing.timeline_origin_time)),
+ None => Some(timing.timeline_time()),
+ Some(timestamp) => timing.clock().time_at_tick(timestamp, self.scroll_progress).map(Some),
}
}
}
-/// `AnimationEffect::Phase`.
-#[derive(Clone, Copy, PartialEq)]
-enum Phase {
- Before,
- Active,
- After,
- Idle,
-}
-
-/// `AK::max` and `AK::min`, which keep the first value where neither is less.
-fn largest(a: f64, b: f64) -> f64 {
- if a < b { b } else { a }
-}
-
-fn smallest(a: f64, b: f64) -> f64 {
- if b < a { b } else { a }
-}
-
-/// Whether two progress-based timeline times, in percent, are the same but for floating point error.
-fn is_within_progress_tolerance(a: f64, b: f64) -> bool {
- (a - b).abs() < PROGRESS_TOLERANCE
-}
-
-/// Must match `Animations::progress_timeline_tolerance` in the host.
-const PROGRESS_TOLERANCE: f64 = 1e-6;
-
/// The timing the host sampled each of an element's effects with, by the effect's identity.
pub(crate) type SampledEffectTimings = Box<[(u64, EffectTiming)]>;
/// One animation effect's timing and easing, as the host last sampled the effect.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct EffectTiming {
- pub(crate) timing: FfiEffectTiming,
+ pub(crate) timing: CompactEffectTiming,
pub(crate) easing: crate::css::easing::Easing,
}
+/// What the timing calculations read of an effect at one moment: its timing, the playback state of its animation, its
+/// local time, and its timeline then.
+#[derive(Clone, Copy)]
+struct SampledEffect {
+ effect: AnimationEffectTiming,
+ playback: AnimationPlayback,
+ local_time: Option<TimeValue>,
+ timeline: Option<TimelineSample>,
+}
+
impl EffectTiming {
/// The key the effect samples its keyframes at as the host samples it: the one its timing gives at
- /// the time the host sampled its timeline, or `host_key` where the engine cannot decide the timing,
- /// or none for an unresolved progress, which samples nothing.
+ /// the time the host sampled its timeline, or none for an unresolved progress, which samples nothing.
#[must_use]
- pub(crate) fn key(&self, host_key: Option<f64>) -> Option<f64> {
- self.key_at(AnimationTimelineSamples::default()).unwrap_or(host_key)
+ pub(crate) fn key(&self) -> Option<f64> {
+ self.key_at(AnimationTimelineSamples::default())
+ .expect("the host's samples move every timeline")
}
- /// The local time of the effect with its timeline at `samples`, or none where it is unresolved or the engine cannot
- /// decide the timing.
- /// https://www.w3.org/TR/web-animations-1/#local-time
+ /// The key the effect samples its keyframes at as the host samples it, with the endpoint-inclusive active interval
+ /// flag set, as committing the computed styles of its animation samples it.
+ #[must_use]
+ pub(crate) fn endpoint_inclusive_key(&self) -> Option<f64> {
+ self.key_with(
+ AnimationTimelineSamples::default(),
+ timing::EndpointInclusiveActiveInterval::Yes,
+ )
+ .expect("the host's samples move every timeline")
+ }
+
+ /// The local time of the effect with its timeline at `samples`, in the unit of its timeline's times, or none
+ /// where it is unresolved or the samples do not move its timeline.
#[must_use]
pub(crate) fn local_time_at(&self, samples: AnimationTimelineSamples) -> Option<f64> {
- let timing = &self.timing;
- if !timing.decidable {
- return None;
- }
- match (timing.has_hold_time, samples.timeline_time(timing)?) {
- (true, _) => Some(timing.hold_time),
- (false, Some(timeline_time)) if timing.has_start_time => {
- Some((timeline_time - timing.start_time) * timing.playback_rate)
- }
- (false, _) => None,
- }
+ let timeline_time = samples.timeline_time(&self.timing)?;
+ timing::current_time_at(&self.timing.playback(), timeline_time).map(|time| time.value)
+ }
+
+ /// Whether the effect's animation is paused as the host sampled it.
+ #[must_use]
+ pub(crate) fn is_paused(&self) -> bool {
+ let playback = self.timing.playback();
+ let current_time = timing::current_time_at(&playback, self.timing.timeline_time());
+ timing::play_state_at(&playback, current_time, timing::end_time(&self.timing.effect()))
+ == AnimationPlayState::Paused
}
- fn active_time_at(&self, samples: AnimationTimelineSamples<'_>) -> Option<(Phase, Option<f64>, f64)> {
+ /// Holds the effect's animation at `local_time`, in milliseconds.
+ pub(crate) fn hold_at(&mut self, local_time: f64) {
+ self.timing.set_hold_time(Some(TimeValue::milliseconds(local_time)));
+ }
+
+ /// Whether the effect's animation has neither a start time nor a hold time, so that it runs nothing.
+ #[must_use]
+ pub(crate) fn has_no_time(&self) -> bool {
+ let playback = self.timing.playback();
+ playback.start_time.get().is_none() && playback.hold_time.get().is_none()
+ }
+
+ /// What the timing calculations read of the effect with its timeline at `samples`, or none where the samples do
+ /// not move its timeline.
+ fn sample_at(&self, samples: AnimationTimelineSamples<'_>) -> Option<SampledEffect> {
let timing = &self.timing;
- if !timing.decidable {
- return None;
- }
let timeline_time = samples.timeline_time(timing)?;
-
- // https://www.w3.org/TR/web-animations-1/#active-duration
- let active_duration = match timing.iteration_duration == 0.0 || timing.iteration_count == 0.0 {
- true => 0.0,
- false => timing.iteration_duration * timing.iteration_count,
- };
- // https://www.w3.org/TR/web-animations-1/#end-time
- let end_time = largest(timing.start_delay + active_duration + timing.end_delay, 0.0);
+ let effect = timing.effect();
+ let playback = timing.playback();
// https://www.w3.org/TR/web-animations-1/#animation-current-time
- let unconstrained_time = timeline_time
- .filter(|_| timing.has_start_time)
- .map(|timeline_time| (timeline_time - timing.start_time) * timing.playback_rate);
+ let unconstrained_time = timing::current_time_at(
+ &AnimationPlayback {
+ hold_time: OptionalTimeValue::UNRESOLVED,
+ ..playback
+ },
+ timeline_time,
+ );
// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state
// Only a finished animation holds a time with its start time resolved. A tick moves its timeline without the
- // host updating its finished state, which lets go of that hold once the timeline goes back before the end.
+ // host updating its finished state, which lets go of that hold once the timeline goes back before the end, or,
+ // for an animation that plays in reverse, after the start.
let finish_released = samples.timestamp.is_some()
- && timing.playback_rate > 0.0
- && unconstrained_time.is_some_and(|time| time < end_time);
- let local_time = match timing.has_hold_time && !finish_released {
- true => Some(timing.hold_time),
- false => unconstrained_time,
- };
-
- // https://drafts.csswg.org/web-animations-2/#at-timeline-boundary
- let at_timeline_boundary = timing.has_timeline_boundaries
- && timeline_time.is_some_and(|time| {
- is_within_progress_tolerance(time, timing.minimum_timeline_time)
- || is_within_progress_tolerance(time, timing.maximum_timeline_time)
- });
-
- // https://drafts.csswg.org/web-animations-2/#animation-effect-phases-and-states
- let backwards = timing.playback_rate < 0.0;
- let phase = match local_time {
- None => Phase::Idle,
- Some(local_time) => {
- let before_active_boundary_time = largest(smallest(timing.start_delay, end_time), 0.0);
- let after_active_boundary_time = largest(smallest(timing.start_delay + active_duration, end_time), 0.0);
- if local_time < before_active_boundary_time
- || (backwards && local_time == before_active_boundary_time && !at_timeline_boundary)
- {
- Phase::Before
- } else if local_time > after_active_boundary_time
- || (!backwards && local_time == after_active_boundary_time && !at_timeline_boundary)
- {
- Phase::After
+ && unconstrained_time.is_some_and(|time| {
+ if playback.playback_rate > 0.0 {
+ time < timing::end_time(&effect)
} else {
- Phase::Active
+ playback.playback_rate < 0.0 && time.value > 0.0
}
- }
+ });
+ let local_time = match playback.hold_time.get() {
+ Some(hold_time) if !finish_released => Some(hold_time),
+ _ => unconstrained_time,
};
+ let timeline = timing.timeline().map(|timeline| TimelineSample {
+ current_time: timeline_time.into(),
+ ..timeline
+ });
+ Some(SampledEffect {
+ effect,
+ playback,
+ local_time,
+ timeline,
+ })
+ }
- // https://www.w3.org/TR/web-animations-1/#calculating-the-active-time
- let fills = |mode| timing.fill_mode == mode || timing.fill_mode == fill_mode::BOTH;
- let active_time = match (phase, local_time) {
- (Phase::Before, Some(local_time)) if fills(fill_mode::BACKWARDS) => {
- Some(largest(local_time - timing.start_delay, 0.0))
- }
- (Phase::Active, Some(local_time)) => Some(local_time - timing.start_delay),
- (Phase::After, Some(local_time)) if fills(fill_mode::FORWARDS) => {
- Some(largest(smallest(local_time - timing.start_delay, active_duration), 0.0))
- }
- _ => None,
- };
- Some((phase, active_time, active_duration))
+ /// The effect's timing, and its phase, active time and overall progress with its timeline at `samples`, or none
+ /// where the samples do not move its timeline.
+ fn resolve_at(
+ &self,
+ samples: AnimationTimelineSamples<'_>,
+ endpoint_inclusive: timing::EndpointInclusiveActiveInterval,
+ ) -> Option<(AnimationEffectTiming, ResolvedEffectTiming)> {
+ let sampled = self.sample_at(samples)?;
+ let resolved = timing::resolve_timing_with(
+ &sampled.effect,
+ sampled.local_time,
+ Some(&sampled.playback),
+ sampled.timeline.as_ref(),
+ sampled.effect.fill_mode,
+ endpoint_inclusive,
+ );
+ Some((sampled.effect, resolved))
}
/// The key the effect's keyframes are sampled at with its timeline at `samples`, which is
/// `AnimationEffect::transformed_progress()` scaled the way the host scales it. The outer `None` is
- /// a timing the engine cannot decide; the inner one is an unresolved progress, which samples nothing.
- ///
- /// A mirror of `Animation::current_time_at()`, `AnimationEffect::resolve_timing()` and
- /// `transformed_progress()` with everything under it.
+ /// a timeline the samples do not move; the inner one is an unresolved progress, which samples nothing.
#[must_use]
pub(crate) fn key_at(&self, samples: AnimationTimelineSamples<'_>) -> Option<Option<f64>> {
- let (phase, active_time, active_duration) = self.active_time_at(samples)?;
- let Some(active_time) = active_time else {
- return Some(None);
- };
- let timing = &self.timing;
-
- // https://www.w3.org/TR/web-animations-1/#overall-progress
- let overall_progress = match timing.iteration_duration == 0.0 {
- true if phase == Phase::Before => 0.0,
- true => timing.iteration_count,
- false => active_time / timing.iteration_duration,
- } + timing.iteration_start;
-
- // https://www.w3.org/TR/web-animations-1/#simple-iteration-progress
- let mut simple_iteration_progress = match overall_progress.is_infinite() {
- true => timing.iteration_start % 1.0,
- false => overall_progress % 1.0,
- };
- if simple_iteration_progress == 0.0
- && matches!(phase, Phase::Active | Phase::After)
- && active_time == active_duration
- && timing.iteration_count != 0.0
- {
- simple_iteration_progress = 1.0;
- }
-
- // https://www.w3.org/TR/web-animations-1/#current-iteration
- let current_iteration = if phase == Phase::After && timing.iteration_count.is_infinite() {
- timing.iteration_count
- } else if simple_iteration_progress == 1.0 {
- overall_progress.floor() - 1.0
- } else {
- overall_progress.floor()
- };
+ self.key_with(samples, timing::EndpointInclusiveActiveInterval::No)
+ }
- // https://www.w3.org/TR/web-animations-1/#directed-progress
- let going_forwards = match timing.playback_direction {
- playback_direction::NORMAL => true,
- playback_direction::REVERSE => false,
- direction => {
- let iteration = match direction == playback_direction::ALTERNATE_REVERSE {
- true => current_iteration + 1.0,
- false => current_iteration,
- };
- iteration.is_infinite() || iteration % 2.0 == 0.0
- }
- };
- let directed_progress = match going_forwards {
- true => simple_iteration_progress,
- false => 1.0 - simple_iteration_progress,
+ fn key_with(
+ &self,
+ samples: AnimationTimelineSamples<'_>,
+ endpoint_inclusive: timing::EndpointInclusiveActiveInterval,
+ ) -> Option<Option<f64>> {
+ let (effect, resolved) = self.resolve_at(samples, endpoint_inclusive)?;
+ let Some(output_progress) = timing::transformed_progress(&effect, &resolved, &self.easing) else {
+ return Some(None);
};
- // https://www.w3.org/TR/web-animations-1/#transformed-progress
- let before_flag = (phase == Phase::Before && going_forwards) || (phase == Phase::After && !going_forwards);
- let output_progress = self.easing.evaluate_at(directed_progress, before_flag);
-
// `KeyframeEffect::AnimationKeyFrameKeyScaleFactor`, and the host's clamp to what a key can hold.
let key = output_progress * 100.0 * 1000.0;
Some(Some(key.clamp(i64::MIN as f64, i64::MAX as f64)))
@@ -640,26 +567,19 @@ impl EffectTiming {
/// For every property targeted by at least one animation effect that is current or in effect, and which is associated
/// with an animation whose replace state is not removed, the user agent must act as if the will-change property on
/// the effect target includes the property.
+ ///
+ /// NB: A timeline the samples do not move stands where the host sampled it.
pub(crate) fn implies_will_change(&self, samples: AnimationTimelineSamples<'_>) -> bool {
- let timing = &self.timing;
-
- if timing.is_removed {
- return false;
- }
-
- if let Some((phase, active_time, _)) = self.active_time_at(samples) {
- return active_time.is_some()
- || (timing.has_timeline_scroller && (timing.has_start_time || timing.has_hold_time))
- || match phase {
- Phase::Before => timing.playback_rate > 0.0,
- Phase::After => timing.playback_rate < 0.0,
- _ => false,
- };
- }
-
- // Use the associated animation's relevance as computed by C++ when Rust cannot resolve the effect's timing
- // or sample its timeline.
- timing.is_relevant
+ let sampled = self
+ .sample_at(samples)
+ .or_else(|| self.sample_at(AnimationTimelineSamples::default()))
+ .expect("the host's samples move every timeline");
+ timing::is_relevant(
+ &sampled.playback,
+ sampled.timeline.as_ref(),
+ Some(&sampled.effect),
+ sampled.local_time,
+ )
}
}
@@ -720,20 +640,83 @@ mod tests {
.collect()
}
- /// A one-second linear animation that started at zero, sampled with its timeline at `time`.
+ use crate::animations::snapshot::{EffectTimingSnapshot, ScrollTimelineId, TimelineClock, TimelineClockSource};
+ use crate::animations::timing::{AnimationEffectTiming, AnimationReplaceState, FillMode, PlaybackDirection};
+
+ impl EffectTiming {
+ /// Changes the timing as the host would publish it.
+ fn change(&mut self, change: impl FnOnce(&mut EffectTimingSnapshot)) {
+ let mut snapshot = self.timing.snapshot();
+ change(&mut snapshot);
+ self.timing = CompactEffectTiming::from(&snapshot);
+ }
+ }
+
+ fn ms(time: f64) -> OptionalTimeValue {
+ Some(TimeValue::milliseconds(time)).into()
+ }
+
+ fn percent(time: f64) -> OptionalTimeValue {
+ Some(TimeValue::percentage(time)).into()
+ }
+
+ /// A one-second linear animation on a document timeline that started at zero, sampled with its timeline at
+ /// `time`.
fn timing_at(time: f64) -> EffectTiming {
EffectTiming {
- timing: FfiEffectTiming {
- decidable: true,
- has_timeline_origin_time: true,
- has_timeline_time: true,
- has_start_time: true,
- timeline_time: time,
- playback_rate: 1.0,
- iteration_duration: 1000.0,
- iteration_count: 1.0,
- ..FfiEffectTiming::default()
- },
+ timing: CompactEffectTiming::from(&EffectTimingSnapshot {
+ effect: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ fill_mode: FillMode::None,
+ ..AnimationEffectTiming::default()
+ },
+ playback: AnimationPlayback {
+ start_time: ms(0.0),
+ ..AnimationPlayback::default()
+ },
+ timeline: TimelineSample {
+ current_time: ms(time),
+ is_monotonically_increasing: true,
+ ..TimelineSample::default()
+ },
+ has_timeline: true,
+ clock: TimelineClock {
+ source: TimelineClockSource::Document,
+ ..TimelineClock::default()
+ },
+ }),
+ easing: crate::css::easing::Easing::default(),
+ }
+ }
+
+ /// A linear animation over the whole of a scroll timeline, sampled with its timeline at `progress`.
+ fn scroll_timing_at(progress: f64) -> EffectTiming {
+ EffectTiming {
+ timing: CompactEffectTiming::from(&EffectTimingSnapshot {
+ effect: AnimationEffectTiming {
+ start_delay: TimeValue::percentage(0.0),
+ end_delay: TimeValue::percentage(0.0),
+ iteration_duration: TimeValue::percentage(100.0),
+ fill_mode: FillMode::None,
+ ..AnimationEffectTiming::default()
+ },
+ playback: AnimationPlayback {
+ start_time: percent(0.0),
+ ..AnimationPlayback::default()
+ },
+ timeline: TimelineSample {
+ current_time: percent(progress),
+ minimum_timeline_time: percent(0.0),
+ maximum_timeline_time: percent(100.0),
+ is_monotonically_increasing: false,
+ },
+ has_timeline: true,
+ clock: TimelineClock {
+ source: TimelineClockSource::Scroll,
+ origin_time: 0.0,
+ scroll_timeline: ScrollTimelineId(7),
+ },
+ }),
easing: crate::css::easing::Easing::default(),
}
}
@@ -744,18 +727,17 @@ mod tests {
#[test]
fn an_animation_implies_will_change_during_its_delay_and_while_filling_forwards() {
- for fill in [0, fill_mode::BACKWARDS, fill_mode::FORWARDS, fill_mode::BOTH] {
+ for fill in [FillMode::None, FillMode::Backwards, FillMode::Forwards, FillMode::Both] {
let mut animation = timing_at(0.0);
- animation.timing.is_relevant = true;
- animation.timing.start_delay = 1000.0;
- animation.timing.fill_mode = fill;
+ animation.change(|timing| timing.effect.start_delay = TimeValue::milliseconds(1000.0));
+ animation.change(|timing| timing.effect.fill_mode = fill);
for time in [0.0, 1000.0, 1500.0] {
assert!(animation.implies_will_change(AnimationTimelineSamples::at_tick(time, &[])));
}
for time in [2000.0, 3000.0] {
assert_eq!(
animation.implies_will_change(AnimationTimelineSamples::at_tick(time, &[])),
- matches!(fill, fill_mode::FORWARDS | fill_mode::BOTH),
+ matches!(fill, FillMode::Forwards | FillMode::Both),
);
}
}
@@ -764,19 +746,40 @@ mod tests {
#[test]
fn reverse_playback_implies_will_change_when_current_or_filling_backwards() {
let mut animation = timing_at(0.0);
- animation.timing.start_time = 5000.0;
- animation.timing.start_delay = 1000.0;
- animation.timing.playback_rate = -1.0;
+ animation.change(|timing| timing.playback.start_time = ms(5000.0));
+ animation.change(|timing| timing.effect.start_delay = TimeValue::milliseconds(1000.0));
+ animation.change(|timing| timing.playback.playback_rate = -1.0);
assert!(animation.implies_will_change(AnimationTimelineSamples::at_tick(2500.0, &[])));
assert!(animation.implies_will_change(AnimationTimelineSamples::at_tick(3500.0, &[])));
assert!(!animation.implies_will_change(AnimationTimelineSamples::at_tick(4500.0, &[])));
- animation.timing.fill_mode = fill_mode::BACKWARDS;
+ animation.change(|timing| timing.effect.fill_mode = FillMode::Backwards);
assert!(animation.implies_will_change(AnimationTimelineSamples::at_tick(4500.0, &[])));
- animation.timing.is_removed = true;
+ animation.change(|timing| timing.playback.replace_state = AnimationReplaceState::Removed);
assert!(!animation.implies_will_change(AnimationTimelineSamples::at_tick(2500.0, &[])));
assert!(!animation.implies_will_change(AnimationTimelineSamples::at_tick(4500.0, &[])));
}
+ #[test]
+ fn an_animation_on_a_scroll_timeline_implies_will_change_after_its_end() {
+ // An animation on a timeline that is not monotonically increasing is current whenever it is not idle, which
+ // holds for one past its end without a fill.
+ let mut animation = scroll_timing_at(80.0);
+ animation.change(|timing| timing.effect.iteration_duration = TimeValue::percentage(50.0));
+ assert_eq!(key(&animation), Some(None));
+ assert!(animation.implies_will_change(AnimationTimelineSamples::default()));
+ let mut idle = animation.clone();
+ idle.change(|timing| timing.playback = AnimationPlayback::default());
+ assert!(!idle.implies_will_change(AnimationTimelineSamples::default()));
+ }
+
+ #[test]
+ fn a_timeline_a_tick_does_not_move_implies_will_change_where_the_host_sampled_it() {
+ let mut animation = timing_at(500.0);
+ animation.change(|timing| timing.clock.source = TimelineClockSource::Unticked);
+ assert!(animation.implies_will_change(AnimationTimelineSamples::at_tick(5000.0, &[])));
+ assert_eq!(animation.key_at(AnimationTimelineSamples::at_tick(5000.0, &[])), None);
+ }
+
#[test]
fn a_key_follows_the_timeline_through_the_active_phase() {
assert_eq!(key(&timing_at(250.0)), Some(Some(25_000.0)));
@@ -788,30 +791,29 @@ mod tests {
#[test]
fn a_key_fills_and_holds() {
let mut timing = timing_at(1500.0);
- timing.timing.fill_mode = fill_mode::BOTH;
+ timing.change(|timing| timing.effect.fill_mode = FillMode::Both);
assert_eq!(key(&timing), Some(Some(100_000.0)));
- timing.timing.timeline_time = -500.0;
+ timing.change(|timing| timing.timeline.current_time = ms(-500.0));
assert_eq!(key(&timing), Some(Some(0.0)));
- timing.timing.has_hold_time = true;
- timing.timing.hold_time = 500.0;
+ timing.change(|timing| timing.playback.hold_time = ms(500.0));
assert_eq!(key(&timing), Some(Some(50_000.0)), "a hold time wins over the timeline");
}
#[test]
fn a_key_runs_each_iteration_in_its_direction() {
let mut timing = timing_at(1250.0);
- timing.timing.iteration_count = f64::INFINITY;
+ timing.change(|timing| timing.effect.iteration_count = f64::INFINITY);
assert_eq!(key(&timing), Some(Some(25_000.0)));
- timing.timing.playback_direction = 2;
+ timing.change(|timing| timing.effect.playback_direction = PlaybackDirection::Alternate);
assert_eq!(
key(&timing),
Some(Some(75_000.0)),
"an alternate second iteration runs backwards"
);
- timing.timing.playback_direction = playback_direction::REVERSE;
+ timing.change(|timing| timing.effect.playback_direction = PlaybackDirection::Reverse);
assert_eq!(key(&timing), Some(Some(75_000.0)));
- timing.timing.playback_direction = playback_direction::NORMAL;
- timing.timing.playback_rate = 2.0;
+ timing.change(|timing| timing.effect.playback_direction = PlaybackDirection::Normal);
+ timing.change(|timing| timing.playback.playback_rate = 2.0);
assert_eq!(key(&timing), Some(Some(50_000.0)));
}
@@ -826,38 +828,19 @@ mod tests {
}
#[test]
- fn an_undecidable_timing_leaves_the_key_to_the_host() {
- let mut timing = timing_at(500.0);
- timing.timing.decidable = false;
- assert_eq!(key(&timing), None);
- let unresolved = EffectTiming {
- timing: FfiEffectTiming {
- has_timeline_time: false,
- ..timing_at(500.0).timing
- },
- ..timing_at(500.0)
- };
+ fn a_key_is_where_the_host_sampled_the_timeline() {
+ assert_eq!(timing_at(500.0).key(), Some(50_000.0));
+ let mut unresolved = timing_at(500.0);
+ unresolved.change(|timing| timing.timeline.current_time = OptionalTimeValue::UNRESOLVED);
assert_eq!(key(&unresolved), Some(None), "an inactive timeline samples nothing");
}
#[test]
fn a_tick_samples_a_scroll_timeline_where_its_scroller_is_scrolled_to() {
- let on_scroll_timeline = EffectTiming {
- timing: FfiEffectTiming {
- has_timeline_origin_time: false,
- has_timeline_scroller: true,
- scroll_timeline: 7,
- has_timeline_boundaries: false,
- minimum_timeline_time: 0.0,
- maximum_timeline_time: 0.0,
- iteration_duration: 100.0,
- ..timing_at(25.0).timing
- },
- ..timing_at(25.0)
- };
+ let on_scroll_timeline = scroll_timing_at(25.0);
let scrolled = |timeline| {
[ScrollProgress {
- timeline,
+ timeline: ScrollTimelineId(timeline),
progress: 60.0,
}]
};
@@ -875,28 +858,28 @@ mod tests {
None,
"a tick that has no progress for its timeline does not move it"
);
- let finished = EffectTiming {
- timing: FfiEffectTiming {
- has_hold_time: true,
- hold_time: 100.0,
- fill_mode: fill_mode::BOTH,
- ..on_scroll_timeline.timing
- },
- ..on_scroll_timeline
- };
+ let mut finished = on_scroll_timeline.clone();
+ finished.change(|timing| timing.playback.hold_time = percent(100.0));
+ finished.change(|timing| timing.effect.fill_mode = FillMode::Both);
assert_eq!(
finished.key_at(AnimationTimelineSamples::at_tick(1000.0, &scrolled(7))),
Some(Some(60_000.0)),
"a finished animation runs again as a tick scrolls back before its end"
);
- let paused = EffectTiming {
- timing: FfiEffectTiming {
- has_start_time: false,
- hold_time: 40.0,
- ..finished.timing
- },
- ..finished
- };
+ let mut finished_in_reverse = on_scroll_timeline.clone();
+ finished_in_reverse.change(|timing| timing.playback.start_time = percent(100.0));
+ finished_in_reverse.change(|timing| timing.playback.playback_rate = -1.0);
+ finished_in_reverse.change(|timing| timing.playback.hold_time = percent(0.0));
+ finished_in_reverse.change(|timing| timing.effect.fill_mode = FillMode::Both);
+ assert_eq!(
+ finished_in_reverse.key_at(AnimationTimelineSamples::at_tick(1000.0, &scrolled(7))),
+ Some(Some(40_000.0)),
+ "an animation finished in reverse runs again as a tick scrolls back after its start"
+ );
+ let mut paused = finished.clone();
+ paused.change(|timing| timing.playback.start_time = OptionalTimeValue::UNRESOLVED);
+ paused.change(|timing| timing.playback.hold_time = percent(40.0));
+ assert!(paused.is_paused());
assert_eq!(
paused.key_at(AnimationTimelineSamples::at_tick(1000.0, &scrolled(7))),
Some(Some(40_000.0)),
@@ -904,6 +887,15 @@ mod tests {
);
}
+ #[test]
+ fn an_attachment_range_shortens_a_scroll_timeline_animation() {
+ // An animation attached to the range from 20% to 70% of its timeline.
+ let mut timing = scroll_timing_at(45.0);
+ timing.change(|timing| timing.effect.iteration_duration = TimeValue::percentage(50.0));
+ timing.change(|timing| timing.playback.start_time = percent(20.0));
+ assert_eq!(key(&timing), Some(Some(50_000.0)));
+ }
+
#[test]
fn a_list_is_replaced_per_slot_and_dropped_when_empty() {
let node = StyleNodeID::from_raw(1).unwrap();
diff --git a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs
index 6ecbd7d5c22..79e8f19b469 100644
--- a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs
@@ -20,11 +20,11 @@ use super::bridge::{
};
use super::tree::StyleNodeID;
use super::weak_pool::WeakPool;
+use crate::animations::snapshot::{CompactEffectTiming, EffectTimingSnapshot};
use crate::css::animation::{CustomPropertyInterval, FfiCompositeOperation};
use crate::css::custom_properties::CustomPropertyRegistry;
use crate::css::easing::{Easing, FfiEasingDescriptor, FfiEasingKind, FfiLinearEasingPoint};
use crate::css::retained_fly_string::RetainedUtf16FlyString;
-use crate::css::style_compute::FfiEffectTiming;
use crate::css::style_value::EasingPayload;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
use std::collections::HashMap;
@@ -360,7 +360,7 @@ pub(crate) struct PublishedEffect {
pub(crate) reversing: Option<TransitionReversing>,
}
-const _: () = assert!(size_of::<PublishedEffect>() == 224);
+const _: () = assert!(size_of::<PublishedEffect>() == 216);
/// What a transition that reverses the one an effect belongs to starts from.
/// https://drafts.csswg.org/css-transitions/#reversing-adjusted-start-value
@@ -794,8 +794,7 @@ impl AnimationEffectDescriptions {
/// Keeps `timing` and `easing`, what the host samples one of an element's described effects with, and
/// answers the key the effect samples its keyframes at as the host samples it: the one its timing
- /// gives at the time the host sampled its timeline, or `host_key` where the engine cannot decide the
- /// timing, or none for an unresolved progress, which samples nothing. An effect the list does not
+ /// gives at the time the host sampled its timeline, or none for an unresolved progress, which samples nothing. An effect the list does not
/// describe keeps nothing, and samples nothing either.
///
/// # Safety
@@ -805,9 +804,8 @@ impl AnimationEffectDescriptions {
node: StyleNodeID,
slot: AnimationSlot,
identity: u64,
- timing: &FfiEffectTiming,
+ timing: &EffectTimingSnapshot,
easing: &FfiEasingDescriptor,
- host_key: Option<f64>,
) -> Option<f64> {
let effect = self
.rows
@@ -815,18 +813,19 @@ impl AnimationEffectDescriptions {
.and_then(|lists| lists.iter_mut().find(|(list_slot, _)| *list_slot == slot))
.and_then(|(_, effects)| effects.iter_mut().find(|effect| effect.identity == identity));
let effect = effect?;
+ let timing = CompactEffectTiming::from(timing);
// A timing that has not moved keeps the easing it holds, so a sample allocates nothing.
let unchanged = effect
.timing
.as_ref()
- .is_some_and(|kept| kept.timing == *timing && unsafe { easing_is(&kept.easing, easing) });
+ .is_some_and(|kept| kept.timing == timing && unsafe { easing_is(&kept.easing, easing) });
if !unchanged {
effect.timing = Some(EffectTiming {
- timing: *timing,
+ timing,
easing: unsafe { Easing::from_descriptor(easing) },
});
}
- effect.timing.as_ref().expect("the timing was kept above").key(host_key)
+ effect.timing.as_ref().expect("the timing was kept above").key()
}
/// Keeps `timing`, what the host sampled one of an element's described effects with where it sampled
@@ -844,7 +843,7 @@ impl AnimationEffectDescriptions {
/// Has one of an element's described effects that the host sampled before take `timing`, keeping its easing: the
/// timing the host runs it on since, where it runs it without sampling it.
- pub(crate) fn refresh_timing(&mut self, node: StyleNodeID, identity: u64, timing: &FfiEffectTiming) {
+ pub(crate) fn refresh_timing(&mut self, node: StyleNodeID, identity: u64, timing: &EffectTimingSnapshot) {
if let Some(kept) = self
.rows
.get_mut(&node)
@@ -852,7 +851,7 @@ impl AnimationEffectDescriptions {
.and_then(|(_, effects)| effects.iter_mut().find(|effect| effect.identity == identity))
.and_then(|effect| effect.timing.as_mut())
{
- kept.timing = *timing;
+ kept.timing = CompactEffectTiming::from(timing);
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
index 68b47e1de93..80e8971c623 100644
--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
@@ -1531,7 +1531,7 @@ impl RetainedState {
&mut self,
node: StyleNodeID,
identity: u64,
- timing: &crate::css::style_compute::FfiEffectTiming,
+ timing: &crate::animations::snapshot::EffectTimingSnapshot,
) {
self.animation_effect_descriptions
.refresh_timing(node, identity, timing);
@@ -1548,13 +1548,12 @@ impl RetainedState {
node: StyleNodeID,
slot: animations::AnimationSlot,
identity: u64,
- timing: &crate::css::style_compute::FfiEffectTiming,
+ timing: &crate::animations::snapshot::EffectTimingSnapshot,
easing: &crate::css::easing::FfiEasingDescriptor,
- host_key: Option<f64>,
) -> Option<f64> {
unsafe {
self.animation_effect_descriptions
- .time_effect(node, slot, identity, timing, easing, host_key)
+ .time_effect(node, slot, identity, timing, easing)
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rs
index 10fec25f51a..7decf2fb937 100644
--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs
@@ -6433,79 +6433,15 @@ pub const SUBSTITUTION_MARK_IF: u8 = 1 << 2;
pub const SUBSTITUTION_MARK_INHERIT: u8 = 1 << 3;
pub const SUBSTITUTION_MARK_CUSTOM_FUNCTION: u8 = 1 << 4;
-/// One animation effect's timing as the host holds it when it samples the effect: what its
-/// animation contributes, the effect's own timing, and the time its timeline was sampled at. Every
-/// time is in milliseconds. The host describes an effect whose times are not, or whose local time is
-/// overridden for observation, as one the engine cannot decide.
-///
-/// Its easing travels beside it, as a descriptor the call borrows.
-#[repr(C)]
-#[derive(Clone, Copy, Debug, Default, PartialEq)]
-pub struct FfiEffectTiming {
- pub scroll_timeline: u64,
- pub minimum_timeline_time: f64,
- pub maximum_timeline_time: f64,
- pub timeline_time: f64,
- pub timeline_origin_time: f64,
- pub start_time: f64,
- pub hold_time: f64,
- pub playback_rate: f64,
- pub start_delay: f64,
- pub end_delay: f64,
- pub iteration_duration: f64,
- pub iteration_count: f64,
- pub iteration_start: f64,
- pub decidable: bool,
- pub is_relevant: bool,
- pub is_removed: bool,
- pub has_timeline_time: bool,
- /// The effect's animation runs on a document timeline, whose time is a timestamp less this origin
- /// time.
- pub has_timeline_origin_time: bool,
- /// The effect's animation runs on the scroll timeline `scroll_timeline` names, whose time is its progress, in
- /// percent, where the scroller it follows is scrolled to.
- pub has_timeline_scroller: bool,
- /// The effect's animation runs on a progress-based timeline, whose minimum and maximum timeline times
- /// `minimum_timeline_time` and `maximum_timeline_time` are.
- pub has_timeline_boundaries: bool,
- pub has_start_time: bool,
- pub has_hold_time: bool,
- /// The effect's animation is paused, which holds its time, as one whose play is pending does too.
- pub paused: bool,
- /// `Bindings::FillMode`, in IDL order.
- pub fill_mode: u8,
- /// `Bindings::PlaybackDirection`, in IDL order.
- pub playback_direction: u8,
-}
-
-const _: () = assert!(size_of::<FfiEffectTiming>() == 120);
-
-/// ABI mirror of `AK::Optional<double>`.
-#[repr(C)]
-#[derive(Clone, Copy)]
-pub struct OptionalF64 {
- value: std::mem::MaybeUninit<f64>,
- has_value: bool,
-}
-
-impl From<OptionalF64> for Option<f64> {
- fn from(value: OptionalF64) -> Self {
- // SAFETY: The host's Optional initializes its storage whenever it has a value.
- value.has_value.then(|| unsafe { value.value.assume_init() })
- }
-}
-
/// One effect the host samples: which of the element's described effects it is, which version of
/// it, and its timing, from which the engine computes how far along it is on the scale the host keys
-/// keyframes by. Where the engine cannot decide the timing, the host computes that key itself.
+/// keyframes by.
#[repr(C)]
pub struct FfiSampledAnimationEffect {
pub identity: u64,
pub generation: u64,
- pub timing: FfiEffectTiming,
+ pub timing: crate::animations::snapshot::EffectTimingSnapshot,
pub easing: crate::css::easing::FfiEasingDescriptor,
- /// The host's key, for a timing the engine cannot decide.
- pub current_key: OptionalF64,
}
/// The length-resolution contexts keyframe values compute in: a font's, a line height's, and every
@@ -7015,7 +6951,7 @@ pub unsafe extern "C" fn rust_sample_animation_effects(
finish_sample_with_host(&sample, &mut callbacks, host, read, step)
}
-/// Sample an isolated effect list at the endpoint-inclusive keys supplied by the host.
+/// Sample an isolated effect list at the endpoint-inclusive keys of the timing the host samples each effect with.
///
/// # Safety
/// The inputs and every value in the descriptions must remain live for the call.
@@ -7043,12 +6979,17 @@ pub unsafe extern "C" fn rust_sample_animation_effects_for_commit_styles(
if description.keyframes().len() < 2 {
return None;
}
+ let timing = crate::css::style::animations::EffectTiming {
+ timing: crate::animations::snapshot::CompactEffectTiming::from(&effect.timing),
+ // SAFETY: The host's easings are live for as long as its effects are borrowed.
+ easing: unsafe { crate::css::easing::Easing::from_descriptor(&effect.easing) },
+ };
Some(anim::FfiSampledAnimationEffect {
effect: anim::FfiAnimationPreparationEffect {
identity: effect.identity,
generation: effect.generation,
},
- current_key: Option::<f64>::from(effect.current_key)?,
+ current_key: timing.endpoint_inclusive_key()?,
})
})
.collect();
@@ -7238,14 +7179,7 @@ fn host_sampled_effects(input: &AnimationSampleInput, engine: &mut crate::css::s
.filter_map(|effect| {
// SAFETY: The host's easings are live for as long as its effects are borrowed.
let key = unsafe {
- engine.time_element_animation_effect(
- node,
- slot,
- effect.identity,
- &effect.timing,
- &effect.easing,
- effect.current_key.into(),
- )
+ engine.time_element_animation_effect(node, slot, effect.identity, &effect.timing, &effect.easing)
};
let description = engine
.element_animation_effects(node, slot)
diff --git a/Libraries/LibWeb/Rust/src/css/transition.rs b/Libraries/LibWeb/Rust/src/css/transition.rs
index b1cb13da307..696acb6657c 100644
--- a/Libraries/LibWeb/Rust/src/css/transition.rs
+++ b/Libraries/LibWeb/Rust/src/css/transition.rs
@@ -782,7 +782,7 @@ fn host_transitions_at(
return Some(Err("a transition the host has not sampled"));
};
// An idle transition, one with neither a start time nor a hold time, runs nothing.
- if timing.timing.decidable && !timing.timing.has_start_time && !timing.timing.has_hold_time {
+ if timing.has_no_time() {
return None;
}
Some(host_transition_at(effect, timing, samples, at))
@@ -800,10 +800,10 @@ fn host_transition_at(
samples: crate::css::style::animations::AnimationTimelineSamples<'_>,
at: f64,
) -> Result<RunningTransitionAt, &'static str> {
- if timing.timing.paused {
+ if timing.is_paused() {
return Err("a paused transition");
}
- if timing.timing.playback_rate != 1.0 {
+ if timing.timing.playback().playback_rate != 1.0 {
return Err("a transition that runs at another rate");
}
let reversing = effect
@@ -812,10 +812,10 @@ fn host_transition_at(
.ok_or("a transition the host has not described")?;
let key = timing
.key_at(samples)
- .ok_or("a transition whose timing the engine cannot decide")?;
+ .ok_or("a transition on a timeline a tick does not move")?;
let local_time = timing
.local_time_at(samples)
- .ok_or("a transition whose timing the engine cannot decide")?;
+ .ok_or("a transition on a timeline a tick does not move")?;
let (property_id, start_value, end_value) =
transition_values(effect).ok_or("a transition the host has not described")?;
Ok(RunningTransitionAt {
@@ -1021,8 +1021,9 @@ impl RowTransitions {
let ended: smallvec::SmallVec<[u16; 4]> = running
.iter()
.filter(|transition| {
- let timing = &transition.timing.timing;
- transition.key.is_none() && transition.local_time >= timing.start_delay + timing.iteration_duration
+ let timing = transition.timing.timing.effect();
+ transition.key.is_none()
+ && transition.local_time >= timing.start_delay.value + timing.iteration_duration.value
})
.map(|transition| transition.property_id)
.collect();
@@ -1166,7 +1167,7 @@ impl FreshTransitionSample {
identity: effect.identity,
generation: 0,
},
- current_key: effect.timing.as_ref()?.key(Some(0.0))?,
+ current_key: effect.timing.as_ref()?.key()?,
});
}
if composed.is_empty() {
@@ -1224,22 +1225,18 @@ impl FreshTransitionSample {
(
effect.identity,
crate::css::style::animations::EffectTiming {
- timing: effect.timing,
+ timing: crate::animations::snapshot::CompactEffectTiming::from(&effect.timing),
// SAFETY: The host's easings are live for as long as its effects are borrowed.
easing: unsafe { crate::css::easing::Easing::from_descriptor(&effect.easing) },
},
)
})
.collect();
- let samples_alike = timings
- .iter()
- .zip(effects)
- .zip(&self.keys)
- .all(|(((_, timing), effect), key)| {
- timing
- .key(effect.current_key.into())
- .is_some_and(|host_key| host_key.to_bits() == key.to_bits())
- });
+ let samples_alike = timings.iter().zip(&self.keys).all(|((_, timing), key)| {
+ timing
+ .key()
+ .is_some_and(|sampled_key| sampled_key.to_bits() == key.to_bits())
+ });
if !samples_alike {
return None;
}
@@ -1337,35 +1334,27 @@ fn started_transition_timing(
action: &FfiTransitionAction,
easing: crate::css::easing::Easing,
) -> crate::css::style::animations::EffectTiming {
+ use crate::animations::snapshot::{CompactEffectTiming, EffectTimingSnapshot};
+ use crate::animations::timing::{
+ AnimationEffectTiming, AnimationPlayback, FillMode, OptionalTimeValue, PlaybackDirection, TimeValue,
+ };
crate::css::style::animations::EffectTiming {
- timing: crate::css::style_compute::FfiEffectTiming {
- is_relevant: true,
- is_removed: false,
- decidable: true,
- has_timeline_time: false,
- has_timeline_origin_time: false,
- has_timeline_scroller: false,
- scroll_timeline: 0,
- has_timeline_boundaries: false,
- minimum_timeline_time: 0.0,
- maximum_timeline_time: 0.0,
- has_start_time: false,
- has_hold_time: true,
- paused: false,
- // `Bindings::FillMode::Backwards` and `Bindings::PlaybackDirection::Normal`.
- fill_mode: 2,
- playback_direction: 0,
- timeline_time: 0.0,
- timeline_origin_time: 0.0,
- start_time: 0.0,
- hold_time: 0.0,
- playback_rate: 1.0,
- start_delay: action.delay,
- end_delay: 0.0,
- iteration_duration: action.active_duration,
- iteration_count: 1.0,
- iteration_start: 0.0,
- },
+ timing: CompactEffectTiming::from(&EffectTimingSnapshot {
+ effect: AnimationEffectTiming {
+ start_delay: TimeValue::milliseconds(action.delay),
+ end_delay: TimeValue::milliseconds(0.0),
+ iteration_duration: TimeValue::milliseconds(action.active_duration),
+ iteration_start: 0.0,
+ iteration_count: 1.0,
+ fill_mode: FillMode::Backwards,
+ playback_direction: PlaybackDirection::Normal,
+ },
+ playback: AnimationPlayback {
+ hold_time: OptionalTimeValue::from(Some(TimeValue::milliseconds(0.0))),
+ ..AnimationPlayback::default()
+ },
+ ..EffectTimingSnapshot::default()
+ }),
easing,
}
}
@@ -1405,7 +1394,8 @@ fn hover_transition_effects(
running.filter(|transition| transition.key.is_some() || transition.host_identity.is_none())
{
let mut timing = transition.timing.clone();
- timing.timing.has_hold_time = true;
+ let hold_time = timing.timing.playback().hold_time.value;
+ timing.timing.set_hold_time(Some(hold_time));
effects.push(PublishedEffect::transition(
identity,
action.property_id,
@@ -1520,7 +1510,10 @@ impl HoverTransitions {
}
let duration = runs
.iter()
- .map(|run| run.timing.timing.start_delay + run.timing.timing.iteration_duration - run.local_time)
+ .map(|run| {
+ let timing = run.timing.timing.effect();
+ timing.start_delay.value + timing.iteration_duration.value - run.local_time
+ })
.fold(0.0, f64::max);
let properties = effects
.iter()
@@ -1569,10 +1562,10 @@ impl HoverTransitions {
transition_values(effect).ok_or("a transition without values")?;
let local_time = run.local_time + elapsed;
let mut timing = run.timing.clone();
- timing.timing.hold_time = local_time;
+ timing.hold_at(local_time);
let key = timing
.key_at(Default::default())
- .ok_or("a transition whose timing the engine cannot decide")?;
+ .expect("the host's samples move every timeline");
Ok(RunningTransitionAt {
identity: effect.identity,
generation: 0,
@@ -1603,8 +1596,8 @@ impl HoverTransitions {
property_id,
host_identity: run.host_identity.unwrap_or(0),
start_time: run.started_at,
- delay: run.timing.timing.start_delay,
- duration: run.timing.timing.iteration_duration,
+ delay: run.timing.timing.effect().start_delay.value,
+ duration: run.timing.timing.effect().iteration_duration.value,
start_value,
end_value,
reversing_adjusted_start_value: run.reversing_adjusted_start_value.pointer(),
@@ -1672,8 +1665,11 @@ impl HoverTransitions {
let mut composed = crate::css::style_compute::SampledEffects::new();
for (effect, run) in self.effects.iter().zip(&self.runs) {
let mut timing = run.timing.clone();
- timing.timing.hold_time = run.local_time + elapsed;
- let Some(current_key) = timing.key_at(Default::default()).ok_or(NeedsHost)? else {
+ timing.hold_at(run.local_time + elapsed);
+ let Some(current_key) = timing
+ .key_at(Default::default())
+ .expect("the host's samples move every timeline")
+ else {
continue;
};
composed.push(FfiSampledAnimationEffect {
@@ -1912,7 +1908,7 @@ mod tests {
timing_function: easing.pointer(),
};
let mut timing = started_transition_timing(&action, Default::default());
- timing.timing.hold_time = local_time;
+ timing.hold_at(local_time);
let running = if kind == Kind::None {
vec![RunningTransitionAt {
identity: 1,
@@ -1955,7 +1951,7 @@ mod tests {
assert_eq!(runs[0].local_time, local_time);
assert_eq!(runs[0].timing.key_at(Default::default()), Some(Some(key)));
let mut sampled_timing = runs[0].timing.clone();
- sampled_timing.timing.hold_time = local_time + 250.0;
+ sampled_timing.hold_at(local_time + 250.0);
assert_eq!(sampled_timing.key_at(Default::default()), Some(Some(next_key)));
}
}
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index 92c3a7f9253..1f64a47afd7 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -26,6 +26,7 @@ pub(crate) mod heap_size;
mod url_test_stubs;
pub(crate) use libcompositing_rust::fast_hash;
+pub(crate) mod animations;
pub(crate) mod css;
pub(crate) mod layout;
pub(crate) mod paint_stage;
diff --git a/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs b/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs
index 45f5a90647e..2306354b6b8 100644
--- a/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs
+++ b/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs
@@ -164,12 +164,8 @@ pub struct FfiCompositorAnimationTiming {
pub monotonic_time_at_anchor_ns: i64,
pub local_time_at_anchor_ms: f64,
pub playback_rate: f64,
- pub start_delay_ms: f64,
- pub iteration_duration_ms: f64,
- pub iteration_count: f64,
- pub iteration_start: f64,
- pub playback_direction: FfiVisualAnimationPlaybackDirection,
- pub fill_mode: FfiVisualAnimationFillMode,
+ /// The effect's timing, every time in milliseconds.
+ pub effect: crate::animations::timing::AnimationEffectTiming,
pub easing: FfiEasingDescriptor,
}
diff --git a/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs b/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs
index 8e9c794eb88..5c595af835b 100644
--- a/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs
+++ b/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs
@@ -820,12 +820,7 @@ impl CompositorAnimationEffectState {
monotonic_time_at_anchor_ns: timing.monotonic_time_at_anchor_ns,
local_time_at_anchor_ms: timing.local_time_at_anchor_ms,
playback_rate: timing.playback_rate,
- start_delay_ms: timing.start_delay_ms,
- iteration_duration_ms: timing.iteration_duration_ms,
- iteration_count: timing.iteration_count,
- iteration_start: timing.iteration_start,
- playback_direction: timing.playback_direction,
- fill_mode: timing.fill_mode,
+ timing: timing.effect,
// SAFETY: The request's easing point ranges are live for the build.
easing: unsafe { Easing::from_descriptor(&timing.easing) },
keyframes,
@@ -897,12 +892,12 @@ impl CompositorAnimationEffectState {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::animations::timing::{AnimationEffectTiming, FillMode, TimeValue};
use crate::css::easing::{FfiEasingDescriptor, FfiEasingKind, FfiLinearEasingPoint};
use crate::css::style_value::{ColorBase, CssString, RetainedStyleValueDataList};
use crate::css::style_value::{ColorFunctionPayload, StyleValueBox};
use crate::css::style_value_arc::StyleValueArc;
use crate::css::table_group_builder::angle_unit_index;
- use crate::painting::host::{FfiVisualAnimationFillMode, FfiVisualAnimationPlaybackDirection};
use crate::painting::visual_context::publish_compositor_animations;
use crate::painting::visual_context::{TransformData, TransformDataRole, VisualContextState, VisualContextTree};
use FfiVisualAnimationTransformOperationKind as Kind;
@@ -1113,12 +1108,12 @@ mod tests {
monotonic_time_at_anchor_ns: 1_000,
local_time_at_anchor_ms: 0.0,
playback_rate: 1.0,
- start_delay_ms: 0.0,
- iteration_duration_ms: 1000.0,
- iteration_count: f64::INFINITY,
- iteration_start: 0.0,
- playback_direction: FfiVisualAnimationPlaybackDirection::Normal,
- fill_mode: FfiVisualAnimationFillMode::None,
+ effect: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ iteration_count: f64::INFINITY,
+ fill_mode: FillMode::None,
+ ..AnimationEffectTiming::default()
+ },
easing: linear_easing(),
}
}
@@ -1721,7 +1716,10 @@ mod tests {
VisualAnimation {
node_indices: vec![0],
monotonic_time_at_anchor_ns: anchor_ns,
- iteration_duration_ms: 1000.0,
+ timing: AnimationEffectTiming {
+ iteration_duration: TimeValue::milliseconds(1000.0),
+ ..VisualAnimation::default().timing
+ },
keyframes: vec![
VisualAnimationKeyframe {
offset: 0.0,
@@ -1753,7 +1751,7 @@ mod tests {
assert_eq!(again[0].monotonic_time_at_anchor_ns, 100);
let mut retimed = built_opacity_animation(300);
- retimed.iteration_duration_ms = 500.0;
+ retimed.timing.iteration_duration = TimeValue::milliseconds(500.0);
state.pending[target_kind_index(FfiVisualAnimationTargetKind::Opacity)] = Some(retimed);
let changed = state.publish_pending(true);
assert_eq!(changed[0].monotonic_time_at_anchor_ns, 300);
diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rs
index d0bba857014..6d17622f0d0 100644
--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs
@@ -28,9 +28,10 @@
use super::owner::DocumentId;
use super::{DocumentHost, RenderState};
+use crate::animations::snapshot::{ScrollProgress, ScrollTimelineId};
use crate::css::css_pixels::CssPixelRect;
use crate::css::ffi_support::OwnedArc;
-use crate::css::style::animations::{AnimationTimelineSamples, ScrollProgress};
+use crate::css::style::animations::AnimationTimelineSamples;
use crate::css::style::engine_sample::{DependentRestyle, NeedsHost, TickShownRecords};
use crate::css::style::tree::StyleNodeID;
use crate::css::transition::HoverTransitions;
@@ -269,7 +270,7 @@ impl ClockPlan {
.iter()
.zip(positions)
.map(|(timeline, &position)| ScrollProgress {
- timeline: timeline.timeline,
+ timeline: ScrollTimelineId(timeline.timeline),
progress: timeline.progress_at(position),
})
.collect()
diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs
index 7736b823a05..01ebe4ba48e 100644
--- a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs
@@ -14,11 +14,11 @@
//! as it handles the move. The host hovers the move in its own state as it handles it, or as the lanes' report says.
use super::{Lane, RenderState, TickRecording, WaitsForTickRecording};
+use crate::animations::snapshot::EffectTimingSnapshot;
use crate::css::css_pixels::{CssPixelPoint, CssPixels};
use crate::css::style::hover_lane::{HoverBoxRebuild, HoverInstall, hover_row_generated_for};
use crate::css::style::style_job::SealedStyleInputs;
use crate::css::style::tree::StyleNodeID;
-use crate::css::style_compute::FfiEffectTiming;
use crate::layout::node_data::{NodeFlag, NodeKind, NodeSlotId};
use crate::layout::tree_mutation::{HostCalls, OwedHostWork};
use crate::painting::ffi::FfiChromeMetrics;
@@ -40,7 +40,7 @@ pub struct FfiHoverPlanInputs {
/// What tells the document's page the link the hover is over.
pub link_reporter: FfiHoverLinkReporter,
/// The timings the host runs the effects of elements on without sampling them, as the compositor runs them: the
- /// element's style node, the effect's identity, and the timing, an `FfiEffectTiming`, by effect.
+ /// element's style node, the effect's identity, and the timing, an `EffectTimingSnapshot`, by effect.
pub effect_timing_nodes: *const u32,
pub effect_timing_identities: *const u64,
pub effect_timings: *const std::ffi::c_void,
@@ -238,7 +238,7 @@ pub(crate) struct HoverPlan {
link_reporter: Option<HoverLinkReporter>,
/// The timings the host runs effects on without sampling them, which the descriptions of their elements' effects
/// hold from before: the step a hover decides over the transitions they run reads them.
- effect_timings: Vec<(StyleNodeID, u64, FfiEffectTiming)>,
+ effect_timings: Vec<(StyleNodeID, u64, EffectTimingSnapshot)>,
/// The drag selecting text the ticks show, until the button goes up.
selection_drag: Option<super::selection::SelectionDrag>,
}
@@ -262,7 +262,7 @@ impl HoverPlan {
ak::slice_from_raw_parts(inputs.effect_timing_nodes, inputs.effect_timing_count),
ak::slice_from_raw_parts(inputs.effect_timing_identities, inputs.effect_timing_count),
ak::slice_from_raw_parts(
- inputs.effect_timings.cast::<FfiEffectTiming>(),
+ inputs.effect_timings.cast::<EffectTimingSnapshot>(),
inputs.effect_timing_count,
),
)
diff --git a/Tests/LibWeb/Crash/Animations/infinite-timing-on-scroll-timeline.html b/Tests/LibWeb/Crash/Animations/infinite-timing-on-scroll-timeline.html
new file mode 100644
index 00000000000..ab2ee0f9689
--- /dev/null
+++ b/Tests/LibWeb/Crash/Animations/infinite-timing-on-scroll-timeline.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<style>
+ #scroller {
+ width: 100px;
+ height: 100px;
+ overflow: scroll;
+ }
+ #content {
+ height: 300px;
+ }
+</style>
+<div id="scroller"><div id="target"></div><div id="content"></div></div>
+<script>
+ // Proportional timing on a progress-based timeline from an infinite iteration count or iteration duration.
+ (async () => {
+ scroller.scrollTop = 100;
+ const timeline = new ScrollTimeline({ source: scroller });
+ for (const timing of [
+ { duration: 0, iterations: Infinity },
+ { duration: Infinity, iterations: 1 },
+ { duration: Infinity, iterations: 0, delay: 100 },
+ { duration: 1000, iterations: Infinity },
+ ]) {
+ const animation = target.animate({ opacity: [0, 1] }, { ...timing, timeline });
+ await animation.ready;
+ animation.effect.getComputedTiming();
+ getComputedStyle(target).opacity;
+ animation.cancel();
+ }
+ document.documentElement.classList.remove("test-wait");
+ })();
+</script>
+</html>